entities
listlengths
1
44.6k
max_stars_repo_path
stringlengths
6
160
max_stars_repo_name
stringlengths
6
66
max_stars_count
int64
0
47.9k
content
stringlengths
18
1.04M
id
stringlengths
1
6
new_content
stringlengths
18
1.04M
modified
bool
1 class
references
stringlengths
32
1.52M
[ { "context": " \n {:doc \"set intersection testing.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-08-19\"\n :version \"2017-09-05\"}", "end": 267, "score": 0.9472653865814209, "start": 231, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/main/clojure/palisades/lakes/multix/sets/dynamap.clj
palisades-lakes/multimethod-experiments
5
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.sets.dynamap {:doc "set intersection testing." :author "palisades dot lakes at gmail dot com" :since "2017-08-19" :version "2017-09-05"} (:refer-clojure :exclude [contains?]) (:require [palisades.lakes.dynamap.core :as d]) (:import [java.util Collections] [palisades.lakes.bench.java.sets Contains Diameter Intersects Set Sets ByteInterval DoubleInterval FloatInterval IntegerInterval LongInterval ShortInterval])) ;;---------------------------------------------------------------- ;; diameter 2 methods primitive return value ;;---------------------------------------------------------------- (d/dynafun ^Double/TYPE diameter {:doc "Max distance between elements."}) ;;---------------------------------------------------------------- (d/defmethod diameter ^double [^java.util.Set s] (Diameter/diameter s)) #_(d/defmethod diameter ^double [^java.util.Set s] (if (>= 1 (.size s)) 0.0 (let [it (.iterator s) x0 (double (.doubleValue ^Number (.next it)))] (if (Double/isNaN x0) Double/NaN (loop [smin x0 smax x0] (if-not (.hasNext it) (- smax smin) (let [^Number x (.next it) xx (.doubleValue x)] (cond (Double/isNaN xx) Double/NaN (xx < smin) (recur xx smax) (xx > smax) (recur smin xx) :else (recur smin smax))))))))) ;;---------------------------------------------------------------- (d/defmethod diameter ^double [^Set s] (.diameter s)) ;(d/defmethod diameter ^double [^ByteInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^DoubleInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^FloatInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^IntegerInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^LongInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^ShortInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^ByteInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^DoubleInterval s] (- (.max s) (.min s))) ;(d/defmethod diameter ^double [^FloatInterval s] (- (.max s) (.min s))) ;(d/defmethod diameter ^double [^IntegerInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^LongInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^ShortInterval s] (double (- (.max s) (.min s)))) ;;---------------------------------------------------------------- ;; intersects? 9 methods ;;---------------------------------------------------------------- (d/dynafun intersects? {:doc "Test for general set intersection. 9 methods."}) ;;---------------------------------------------------------------- (d/defmethod intersects? [^IntegerInterval s0 ^IntegerInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^IntegerInterval s0 ^DoubleInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^IntegerInterval s0 ^java.util.Set s1] (.intersects s0 s1)) ;;---------------------------------------------------------------- (d/defmethod intersects? [^DoubleInterval s0 ^IntegerInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^DoubleInterval s0 ^DoubleInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^DoubleInterval s0 ^java.util.Set s1] (.intersects s0 s1)) ;;---------------------------------------------------------------- (d/defmethod intersects? [^java.util.Set s0 ^IntegerInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^java.util.Set s0 ^DoubleInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^java.util.Set s0 ^java.util.Set s1] (not (Collections/disjoint s0 s1))) ;;---------------------------------------------------------------- ;; contains? 43 methods ;;---------------------------------------------------------------- (d/dynafun contains? {:doc "Test for general set containment."}) ;;---------------------------------------------------------------- (d/defmethod contains? [^java.util.Set s ^Object x] (.contains s x)) ;;---------------------------------------------------------------- (d/defmethod contains? [^ByteInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^DoubleInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^FloatInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^IntegerInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^LongInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^ShortInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Object x] false) ;;----------------------------------------------------------------
47027
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.sets.dynamap {:doc "set intersection testing." :author "<EMAIL>" :since "2017-08-19" :version "2017-09-05"} (:refer-clojure :exclude [contains?]) (:require [palisades.lakes.dynamap.core :as d]) (:import [java.util Collections] [palisades.lakes.bench.java.sets Contains Diameter Intersects Set Sets ByteInterval DoubleInterval FloatInterval IntegerInterval LongInterval ShortInterval])) ;;---------------------------------------------------------------- ;; diameter 2 methods primitive return value ;;---------------------------------------------------------------- (d/dynafun ^Double/TYPE diameter {:doc "Max distance between elements."}) ;;---------------------------------------------------------------- (d/defmethod diameter ^double [^java.util.Set s] (Diameter/diameter s)) #_(d/defmethod diameter ^double [^java.util.Set s] (if (>= 1 (.size s)) 0.0 (let [it (.iterator s) x0 (double (.doubleValue ^Number (.next it)))] (if (Double/isNaN x0) Double/NaN (loop [smin x0 smax x0] (if-not (.hasNext it) (- smax smin) (let [^Number x (.next it) xx (.doubleValue x)] (cond (Double/isNaN xx) Double/NaN (xx < smin) (recur xx smax) (xx > smax) (recur smin xx) :else (recur smin smax))))))))) ;;---------------------------------------------------------------- (d/defmethod diameter ^double [^Set s] (.diameter s)) ;(d/defmethod diameter ^double [^ByteInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^DoubleInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^FloatInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^IntegerInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^LongInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^ShortInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^ByteInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^DoubleInterval s] (- (.max s) (.min s))) ;(d/defmethod diameter ^double [^FloatInterval s] (- (.max s) (.min s))) ;(d/defmethod diameter ^double [^IntegerInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^LongInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^ShortInterval s] (double (- (.max s) (.min s)))) ;;---------------------------------------------------------------- ;; intersects? 9 methods ;;---------------------------------------------------------------- (d/dynafun intersects? {:doc "Test for general set intersection. 9 methods."}) ;;---------------------------------------------------------------- (d/defmethod intersects? [^IntegerInterval s0 ^IntegerInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^IntegerInterval s0 ^DoubleInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^IntegerInterval s0 ^java.util.Set s1] (.intersects s0 s1)) ;;---------------------------------------------------------------- (d/defmethod intersects? [^DoubleInterval s0 ^IntegerInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^DoubleInterval s0 ^DoubleInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^DoubleInterval s0 ^java.util.Set s1] (.intersects s0 s1)) ;;---------------------------------------------------------------- (d/defmethod intersects? [^java.util.Set s0 ^IntegerInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^java.util.Set s0 ^DoubleInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^java.util.Set s0 ^java.util.Set s1] (not (Collections/disjoint s0 s1))) ;;---------------------------------------------------------------- ;; contains? 43 methods ;;---------------------------------------------------------------- (d/dynafun contains? {:doc "Test for general set containment."}) ;;---------------------------------------------------------------- (d/defmethod contains? [^java.util.Set s ^Object x] (.contains s x)) ;;---------------------------------------------------------------- (d/defmethod contains? [^ByteInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^DoubleInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^FloatInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^IntegerInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^LongInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^ShortInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Object x] false) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.sets.dynamap {:doc "set intersection testing." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-08-19" :version "2017-09-05"} (:refer-clojure :exclude [contains?]) (:require [palisades.lakes.dynamap.core :as d]) (:import [java.util Collections] [palisades.lakes.bench.java.sets Contains Diameter Intersects Set Sets ByteInterval DoubleInterval FloatInterval IntegerInterval LongInterval ShortInterval])) ;;---------------------------------------------------------------- ;; diameter 2 methods primitive return value ;;---------------------------------------------------------------- (d/dynafun ^Double/TYPE diameter {:doc "Max distance between elements."}) ;;---------------------------------------------------------------- (d/defmethod diameter ^double [^java.util.Set s] (Diameter/diameter s)) #_(d/defmethod diameter ^double [^java.util.Set s] (if (>= 1 (.size s)) 0.0 (let [it (.iterator s) x0 (double (.doubleValue ^Number (.next it)))] (if (Double/isNaN x0) Double/NaN (loop [smin x0 smax x0] (if-not (.hasNext it) (- smax smin) (let [^Number x (.next it) xx (.doubleValue x)] (cond (Double/isNaN xx) Double/NaN (xx < smin) (recur xx smax) (xx > smax) (recur smin xx) :else (recur smin smax))))))))) ;;---------------------------------------------------------------- (d/defmethod diameter ^double [^Set s] (.diameter s)) ;(d/defmethod diameter ^double [^ByteInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^DoubleInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^FloatInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^IntegerInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^LongInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^ShortInterval s] (.diameter s)) ;(d/defmethod diameter ^double [^ByteInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^DoubleInterval s] (- (.max s) (.min s))) ;(d/defmethod diameter ^double [^FloatInterval s] (- (.max s) (.min s))) ;(d/defmethod diameter ^double [^IntegerInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^LongInterval s] (double (- (.max s) (.min s)))) ;(d/defmethod diameter ^double [^ShortInterval s] (double (- (.max s) (.min s)))) ;;---------------------------------------------------------------- ;; intersects? 9 methods ;;---------------------------------------------------------------- (d/dynafun intersects? {:doc "Test for general set intersection. 9 methods."}) ;;---------------------------------------------------------------- (d/defmethod intersects? [^IntegerInterval s0 ^IntegerInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^IntegerInterval s0 ^DoubleInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^IntegerInterval s0 ^java.util.Set s1] (.intersects s0 s1)) ;;---------------------------------------------------------------- (d/defmethod intersects? [^DoubleInterval s0 ^IntegerInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^DoubleInterval s0 ^DoubleInterval s1] (.intersects s0 s1)) (d/defmethod intersects? [^DoubleInterval s0 ^java.util.Set s1] (.intersects s0 s1)) ;;---------------------------------------------------------------- (d/defmethod intersects? [^java.util.Set s0 ^IntegerInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^java.util.Set s0 ^DoubleInterval s1] (.intersects s1 s0)) (d/defmethod intersects? [^java.util.Set s0 ^java.util.Set s1] (not (Collections/disjoint s0 s1))) ;;---------------------------------------------------------------- ;; contains? 43 methods ;;---------------------------------------------------------------- (d/dynafun contains? {:doc "Test for general set containment."}) ;;---------------------------------------------------------------- (d/defmethod contains? [^java.util.Set s ^Object x] (.contains s x)) ;;---------------------------------------------------------------- (d/defmethod contains? [^ByteInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^ByteInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^DoubleInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^DoubleInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^FloatInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^FloatInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^IntegerInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^IntegerInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^LongInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^LongInterval s ^Object x] false) ;;---------------------------------------------------------------- (d/defmethod contains? [^ShortInterval s ^Byte x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Double x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Float x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Integer x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Long x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Short x] (.contains s x)) (d/defmethod contains? [^ShortInterval s ^Object x] false) ;;----------------------------------------------------------------
[ { "context": "ubworker-num init-data]\n (let [redis-source-key \"claronte\"\n redis-backup-key (str \"claronte-backup-\"", "end": 1117, "score": 0.9935131072998047, "start": 1109, "tag": "KEY", "value": "claronte" }, { "context": "rce-key \"claronte\"\n redis-backup-key (str \"claronte-backup-\" worker-num \"-\" subworker-num)\n rabbitmq-ex", "end": 1167, "score": 0.898095965385437, "start": 1150, "tag": "KEY", "value": "claronte-backup-\"" } ]
src/claronte/transport_redis_to_rabbitmq.clj
jordillonch/claronte
1
(ns claronte.transport-redis-to-rabbitmq (:require [claronte.workers.pool :refer :all] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all] [claronte.transport.sender.rabbitmq.sender :refer :all] [claronte.transport.sender.rabbitmq.connection-factory :refer :all] [claronte.transport.transporter :refer :all] ) ) (defn- transport-redis-to-rabbitmq-generic [id redis-source-key redis-backup-key rabbitmq-exchange-name rabbitmq-routing-key init-data] (let [ fetcher (->RedisFetcher id fetcher-redis-server-connection-parameters redis-source-key redis-backup-key) connection (create-connection-rabbitmq sender-rabbitmq-server-connection-parameters) channel (open-channel-rabbitmq connection) sender (->RabbitMqSender id channel rabbitmq-exchange-name rabbitmq-routing-key) ] (while (not (deref (init-data :stop-worker-atom))) (transport-message fetcher sender) ) ) ) (defn- transport-unit-of-work [worker-num subworker-num init-data] (let [redis-source-key "claronte" redis-backup-key (str "claronte-backup-" worker-num "-" subworker-num) rabbitmq-exchange-name "claronte" rabbitmq-routing-key "" id (+ (* worker-num 1000) subworker-num) ] (transport-redis-to-rabbitmq-generic id redis-source-key redis-backup-key rabbitmq-exchange-name rabbitmq-routing-key init-data) ) ) (defn transport-redis-to-rabbitmq [number-of-workers number-of-subworkers init-data] (pool-of-workers number-of-workers number-of-subworkers transport-unit-of-work init-data) )
118826
(ns claronte.transport-redis-to-rabbitmq (:require [claronte.workers.pool :refer :all] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all] [claronte.transport.sender.rabbitmq.sender :refer :all] [claronte.transport.sender.rabbitmq.connection-factory :refer :all] [claronte.transport.transporter :refer :all] ) ) (defn- transport-redis-to-rabbitmq-generic [id redis-source-key redis-backup-key rabbitmq-exchange-name rabbitmq-routing-key init-data] (let [ fetcher (->RedisFetcher id fetcher-redis-server-connection-parameters redis-source-key redis-backup-key) connection (create-connection-rabbitmq sender-rabbitmq-server-connection-parameters) channel (open-channel-rabbitmq connection) sender (->RabbitMqSender id channel rabbitmq-exchange-name rabbitmq-routing-key) ] (while (not (deref (init-data :stop-worker-atom))) (transport-message fetcher sender) ) ) ) (defn- transport-unit-of-work [worker-num subworker-num init-data] (let [redis-source-key "<KEY>" redis-backup-key (str "<KEY> worker-num "-" subworker-num) rabbitmq-exchange-name "claronte" rabbitmq-routing-key "" id (+ (* worker-num 1000) subworker-num) ] (transport-redis-to-rabbitmq-generic id redis-source-key redis-backup-key rabbitmq-exchange-name rabbitmq-routing-key init-data) ) ) (defn transport-redis-to-rabbitmq [number-of-workers number-of-subworkers init-data] (pool-of-workers number-of-workers number-of-subworkers transport-unit-of-work init-data) )
true
(ns claronte.transport-redis-to-rabbitmq (:require [claronte.workers.pool :refer :all] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all] [claronte.transport.sender.rabbitmq.sender :refer :all] [claronte.transport.sender.rabbitmq.connection-factory :refer :all] [claronte.transport.transporter :refer :all] ) ) (defn- transport-redis-to-rabbitmq-generic [id redis-source-key redis-backup-key rabbitmq-exchange-name rabbitmq-routing-key init-data] (let [ fetcher (->RedisFetcher id fetcher-redis-server-connection-parameters redis-source-key redis-backup-key) connection (create-connection-rabbitmq sender-rabbitmq-server-connection-parameters) channel (open-channel-rabbitmq connection) sender (->RabbitMqSender id channel rabbitmq-exchange-name rabbitmq-routing-key) ] (while (not (deref (init-data :stop-worker-atom))) (transport-message fetcher sender) ) ) ) (defn- transport-unit-of-work [worker-num subworker-num init-data] (let [redis-source-key "PI:KEY:<KEY>END_PI" redis-backup-key (str "PI:KEY:<KEY>END_PI worker-num "-" subworker-num) rabbitmq-exchange-name "claronte" rabbitmq-routing-key "" id (+ (* worker-num 1000) subworker-num) ] (transport-redis-to-rabbitmq-generic id redis-source-key redis-backup-key rabbitmq-exchange-name rabbitmq-routing-key init-data) ) ) (defn transport-redis-to-rabbitmq [number-of-workers number-of-subworkers init-data] (pool-of-workers number-of-workers number-of-subworkers transport-unit-of-work init-data) )
[ { "context": ";; Clojure 1.4.07\n\n(println \"Hello, Dcoder!\")\n\n<sys_write;collapse might.hackdude;com>r", "end": 37, "score": 0.5937342643737793, "start": 36, "tag": "USERNAME", "value": "D" }, { "context": ";; Clojure 1.4.07\n\n(println \"Hello, Dcoder!\")\n\n<sys_write;collapse might.hackdude;com>raw\n ", "end": 42, "score": 0.5841066241264343, "start": 37, "tag": "NAME", "value": "coder" } ]
dist/frk.clj
pedroxian/jeriko-source
0
;; Clojure 1.4.07 (println "Hello, Dcoder!") <sys_write;collapse might.hackdude;com>raw viel.nacht slozze.item cage.runge ;free
44692
;; Clojure 1.4.07 (println "Hello, D<NAME>!") <sys_write;collapse might.hackdude;com>raw viel.nacht slozze.item cage.runge ;free
true
;; Clojure 1.4.07 (println "Hello, DPI:NAME:<NAME>END_PI!") <sys_write;collapse might.hackdude;com>raw viel.nacht slozze.item cage.runge ;free
[ { "context": "NAPSHOT\"\n :description \"Personal clojure dojo for Stephen Sloan\"\n :url \"https://github.com/polygloton/clojure-do", "end": 97, "score": 0.9967736601829529, "start": 84, "tag": "NAME", "value": "Stephen Sloan" }, { "context": "ojo for Stephen Sloan\"\n :url \"https://github.com/polygloton/clojure-dojo\"\n :license {:name \"MIT\"\n ", "end": 136, "score": 0.9996667504310608, "start": 126, "tag": "USERNAME", "value": "polygloton" }, { "context": "e \"MIT\"\n :url \"https://raw2.github.com/polygloton/clojure-dojo/master/LICENSE.txt\"\n :dis", "end": 227, "score": 0.9996099472045898, "start": 217, "tag": "USERNAME", "value": "polygloton" } ]
project.clj
polygloton/clojure-dojo
0
(defproject clojure-dojo "0.1.0-SNAPSHOT" :description "Personal clojure dojo for Stephen Sloan" :url "https://github.com/polygloton/clojure-dojo" :license {:name "MIT" :url "https://raw2.github.com/polygloton/clojure-dojo/master/LICENSE.txt" :distribution "manual"} :min-lein-version "2.0.0" :pendantic? :warn :dependencies [[org.clojure/clojure "1.7.0-alpha5"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [org.clojure/core.logic "0.7.5"] [org.apache.commons/commons-math3 "3.0"] [lonocloud/synthread "1.0.4"] [print-foo "0.4.2"]] :test-selectors {:default (constantly false) :reasoned-schemer :reasoned-schemer :coding-the-matrix :coding-the-matrix})
21653
(defproject clojure-dojo "0.1.0-SNAPSHOT" :description "Personal clojure dojo for <NAME>" :url "https://github.com/polygloton/clojure-dojo" :license {:name "MIT" :url "https://raw2.github.com/polygloton/clojure-dojo/master/LICENSE.txt" :distribution "manual"} :min-lein-version "2.0.0" :pendantic? :warn :dependencies [[org.clojure/clojure "1.7.0-alpha5"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [org.clojure/core.logic "0.7.5"] [org.apache.commons/commons-math3 "3.0"] [lonocloud/synthread "1.0.4"] [print-foo "0.4.2"]] :test-selectors {:default (constantly false) :reasoned-schemer :reasoned-schemer :coding-the-matrix :coding-the-matrix})
true
(defproject clojure-dojo "0.1.0-SNAPSHOT" :description "Personal clojure dojo for PI:NAME:<NAME>END_PI" :url "https://github.com/polygloton/clojure-dojo" :license {:name "MIT" :url "https://raw2.github.com/polygloton/clojure-dojo/master/LICENSE.txt" :distribution "manual"} :min-lein-version "2.0.0" :pendantic? :warn :dependencies [[org.clojure/clojure "1.7.0-alpha5"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [org.clojure/core.logic "0.7.5"] [org.apache.commons/commons-math3 "3.0"] [lonocloud/synthread "1.0.4"] [print-foo "0.4.2"]] :test-selectors {:default (constantly false) :reasoned-schemer :reasoned-schemer :coding-the-matrix :coding-the-matrix})
[ { "context": " :he \"Hebrew\"\n :mrj \"Hill Mari\"\n :hi \"Hindi\"\n :hu ", "end": 2092, "score": 0.9942177534103394, "start": 2083, "tag": "NAME", "value": "Hill Mari" } ]
app/src/app/core.clj
lewismc/iPReS
5
; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns app.core (:require [app.cache :refer :all] [clojure.string :as str] [clj-xpath.core :as xpath] [clj-xpath.lib :as lib] [ring.util.codec :as codec]) (:import (org.apache.tika.language.translate YandexTranslator))) (def langs {:af "Afrikaans" :sq "Albanian" :am "Amharic" :ar "Arabic" :hy "Armenian" :az "Azerbaijan" :ba "Bashkir" :eu "Basque" :be "Belarusian" :bn "Bengali" :bs "Bosnian" :bg "Bulgarian" :my "Burmese" :ca "Catalan" :ceb "Cebuano" :zh "Chinese" :hr "Croatian" :cs "Czech" :da "Danish" :nl "Dutch" :en "English" :eo "Esperanto" :et "Estonian" :fi "Finnish" :fr "French" :gl "Galician" :ka "Georgian" :de "German" :el "Greek" :gu "Gujarati" :ht "Haitian (Creole)" :he "Hebrew" :mrj "Hill Mari" :hi "Hindi" :hu "Hungarian" :is "Icelandic" :id "Indonesian" :ga "Irish" :it "Italian" :ja "Japanese" :jv "Javanese" :kn "Kannada" :kk "Kazakh" :km "Khmer" :ko "Korean" :ky "Kyrgyz" :lo "Laotian" :la "Latin" :lv "Latvian" :lt "Lithuanian" :lb "Luxembourgish" :mk "Macedonian" :mg "Malagasy" :ms "Malay" :ml "Malayalam" :mt "Maltese" :mi "Maori" :mr "Marathi" :mhr "Mari" :mn "Mongolian" :ne "Nepali" :no "Norwegian" :pap "Papiamento" :fa "Persian" :pl "Polish" :pt "Portuguese" :pa "Punjabi" :ro "Romanian" :ru "Russian" :gd "Scottish" :sr "Serbian" :si "Sinhala" :sk "Slovakian" :sl "Slovenian" :es "Spanish" :su "Sundanese" :sw "Swahili" :sv "Swedish" :tl "Tagalog" :tg "Tajik" :ta "Tamil" :tt "Tatar" :te "Telugu" :th "Thai" :tr "Turkish" :udm "Udmurt" :uk "Ukrainian" :ur "Urdu" :uz "Uzbek" :vi "Vietnamese" :cy "Welsh" :xh "Xhosa" :yi "Yiddish"}) ;;;;;;;;;; ;; ;; Dealing with PO.DAAC region ;; ;;;;;;;;;; (def podaac-base-url "https://podaac.jpl.nasa.gov/ws/") (def source-language "en") (defn- build-url "Returns a fully-qualifies PO.DAAC route based on the given route and parameters." [route params] (str podaac-base-url route "?" (codec/form-encode params))) (defn- fetch-xml "Fetches and caches XML from a PO.DAAC route." [url] (slurp url)) (defn- build-xdoc "Builds an XPATH-accessible XML document from a given, formatted XML document." [xml] ;; Avoids [Fatal Error] :1:10: DOCTYPE is disallowed when the feature ;; "http://apache.org/xml/features/disallow-doctype-decl" set to true. ;; org.xml.sax.SAXParseException: DOCTYPE is disallowed when the feature ;; "http://apache.org/xml/features/disallow-doctype-decl" set to true. (let [opts {:disallow-doctype-decl false}] (try (xpath/xml->doc xml opts)))) (defn- extract-root "Extracts the root of the XML document using an XPATH query." [xpath-doc] (first (xpath/$x "/*" xpath-doc))) (defn- extract-relevant-text "Returns a sequence of relevant phrases from the XPATH root, split by the tab and newline delimiters." [root] (-> (get root :text) (str/split #"\t+\n+"))) (defn- format-relevant-text "Returns a sequence of chunks of relevant text, stripped of all leading and trailing whitespace." [text] (->> (map (fn [x] (str/trim x)) text) (filter (complement str/blank?)))) (defn hit-podaac "Hits the PO.DAAC web service specified by the given route, with the parameters specified by the given params." [route params] (-> (build-url route params) (fetch-xml) (build-xdoc) (extract-root) (extract-relevant-text) (format-relevant-text))) ;;;;;;;;;; ;; ;; Translation region ;; ;;;;;;;;;; (def translator (YandexTranslator.)) (defn translate-with-tika "Returns the translated dataset into the specified language using Apache Tika." [dataset lang-code] ;; Logging to console for requirements proving (println "\n\n\n\n\nDEBUG: Attempting to translate by calling tika-translate...\n\n\n\n\n") (pmap (fn [x] (.translate translator (str/replace x #"\\/" "/") source-language lang-code)) dataset)) (defn translate-to-lang "Returns PO.DAAC dataset specified by the given language." [dataset key lang] (cache-add key (translate-with-tika dataset lang)) (cache-lookup key)) ;;;;;;;;;; ;; ;; Top-level region ;; ;;;;;;;;;; (defn- route-to-key "Returns the concatenation of the given route, split by slashes, with the suppled language code." [route lang-code] (keyword (str (apply str (str/split route #"/")) lang-code))) (defn translate-request "Handles a given iPres request and returns the translated data in the specified format." [route params lang-code format] (let [cache-key (route-to-key route lang-code)] (if (cache-has? cache-key) (cache-lookup cache-key) (-> (hit-podaac route params) (translate-to-lang cache-key lang-code) ;;(convert-to-format format) ))))
34292
; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns app.core (:require [app.cache :refer :all] [clojure.string :as str] [clj-xpath.core :as xpath] [clj-xpath.lib :as lib] [ring.util.codec :as codec]) (:import (org.apache.tika.language.translate YandexTranslator))) (def langs {:af "Afrikaans" :sq "Albanian" :am "Amharic" :ar "Arabic" :hy "Armenian" :az "Azerbaijan" :ba "Bashkir" :eu "Basque" :be "Belarusian" :bn "Bengali" :bs "Bosnian" :bg "Bulgarian" :my "Burmese" :ca "Catalan" :ceb "Cebuano" :zh "Chinese" :hr "Croatian" :cs "Czech" :da "Danish" :nl "Dutch" :en "English" :eo "Esperanto" :et "Estonian" :fi "Finnish" :fr "French" :gl "Galician" :ka "Georgian" :de "German" :el "Greek" :gu "Gujarati" :ht "Haitian (Creole)" :he "Hebrew" :mrj "<NAME>" :hi "Hindi" :hu "Hungarian" :is "Icelandic" :id "Indonesian" :ga "Irish" :it "Italian" :ja "Japanese" :jv "Javanese" :kn "Kannada" :kk "Kazakh" :km "Khmer" :ko "Korean" :ky "Kyrgyz" :lo "Laotian" :la "Latin" :lv "Latvian" :lt "Lithuanian" :lb "Luxembourgish" :mk "Macedonian" :mg "Malagasy" :ms "Malay" :ml "Malayalam" :mt "Maltese" :mi "Maori" :mr "Marathi" :mhr "Mari" :mn "Mongolian" :ne "Nepali" :no "Norwegian" :pap "Papiamento" :fa "Persian" :pl "Polish" :pt "Portuguese" :pa "Punjabi" :ro "Romanian" :ru "Russian" :gd "Scottish" :sr "Serbian" :si "Sinhala" :sk "Slovakian" :sl "Slovenian" :es "Spanish" :su "Sundanese" :sw "Swahili" :sv "Swedish" :tl "Tagalog" :tg "Tajik" :ta "Tamil" :tt "Tatar" :te "Telugu" :th "Thai" :tr "Turkish" :udm "Udmurt" :uk "Ukrainian" :ur "Urdu" :uz "Uzbek" :vi "Vietnamese" :cy "Welsh" :xh "Xhosa" :yi "Yiddish"}) ;;;;;;;;;; ;; ;; Dealing with PO.DAAC region ;; ;;;;;;;;;; (def podaac-base-url "https://podaac.jpl.nasa.gov/ws/") (def source-language "en") (defn- build-url "Returns a fully-qualifies PO.DAAC route based on the given route and parameters." [route params] (str podaac-base-url route "?" (codec/form-encode params))) (defn- fetch-xml "Fetches and caches XML from a PO.DAAC route." [url] (slurp url)) (defn- build-xdoc "Builds an XPATH-accessible XML document from a given, formatted XML document." [xml] ;; Avoids [Fatal Error] :1:10: DOCTYPE is disallowed when the feature ;; "http://apache.org/xml/features/disallow-doctype-decl" set to true. ;; org.xml.sax.SAXParseException: DOCTYPE is disallowed when the feature ;; "http://apache.org/xml/features/disallow-doctype-decl" set to true. (let [opts {:disallow-doctype-decl false}] (try (xpath/xml->doc xml opts)))) (defn- extract-root "Extracts the root of the XML document using an XPATH query." [xpath-doc] (first (xpath/$x "/*" xpath-doc))) (defn- extract-relevant-text "Returns a sequence of relevant phrases from the XPATH root, split by the tab and newline delimiters." [root] (-> (get root :text) (str/split #"\t+\n+"))) (defn- format-relevant-text "Returns a sequence of chunks of relevant text, stripped of all leading and trailing whitespace." [text] (->> (map (fn [x] (str/trim x)) text) (filter (complement str/blank?)))) (defn hit-podaac "Hits the PO.DAAC web service specified by the given route, with the parameters specified by the given params." [route params] (-> (build-url route params) (fetch-xml) (build-xdoc) (extract-root) (extract-relevant-text) (format-relevant-text))) ;;;;;;;;;; ;; ;; Translation region ;; ;;;;;;;;;; (def translator (YandexTranslator.)) (defn translate-with-tika "Returns the translated dataset into the specified language using Apache Tika." [dataset lang-code] ;; Logging to console for requirements proving (println "\n\n\n\n\nDEBUG: Attempting to translate by calling tika-translate...\n\n\n\n\n") (pmap (fn [x] (.translate translator (str/replace x #"\\/" "/") source-language lang-code)) dataset)) (defn translate-to-lang "Returns PO.DAAC dataset specified by the given language." [dataset key lang] (cache-add key (translate-with-tika dataset lang)) (cache-lookup key)) ;;;;;;;;;; ;; ;; Top-level region ;; ;;;;;;;;;; (defn- route-to-key "Returns the concatenation of the given route, split by slashes, with the suppled language code." [route lang-code] (keyword (str (apply str (str/split route #"/")) lang-code))) (defn translate-request "Handles a given iPres request and returns the translated data in the specified format." [route params lang-code format] (let [cache-key (route-to-key route lang-code)] (if (cache-has? cache-key) (cache-lookup cache-key) (-> (hit-podaac route params) (translate-to-lang cache-key lang-code) ;;(convert-to-format format) ))))
true
; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns app.core (:require [app.cache :refer :all] [clojure.string :as str] [clj-xpath.core :as xpath] [clj-xpath.lib :as lib] [ring.util.codec :as codec]) (:import (org.apache.tika.language.translate YandexTranslator))) (def langs {:af "Afrikaans" :sq "Albanian" :am "Amharic" :ar "Arabic" :hy "Armenian" :az "Azerbaijan" :ba "Bashkir" :eu "Basque" :be "Belarusian" :bn "Bengali" :bs "Bosnian" :bg "Bulgarian" :my "Burmese" :ca "Catalan" :ceb "Cebuano" :zh "Chinese" :hr "Croatian" :cs "Czech" :da "Danish" :nl "Dutch" :en "English" :eo "Esperanto" :et "Estonian" :fi "Finnish" :fr "French" :gl "Galician" :ka "Georgian" :de "German" :el "Greek" :gu "Gujarati" :ht "Haitian (Creole)" :he "Hebrew" :mrj "PI:NAME:<NAME>END_PI" :hi "Hindi" :hu "Hungarian" :is "Icelandic" :id "Indonesian" :ga "Irish" :it "Italian" :ja "Japanese" :jv "Javanese" :kn "Kannada" :kk "Kazakh" :km "Khmer" :ko "Korean" :ky "Kyrgyz" :lo "Laotian" :la "Latin" :lv "Latvian" :lt "Lithuanian" :lb "Luxembourgish" :mk "Macedonian" :mg "Malagasy" :ms "Malay" :ml "Malayalam" :mt "Maltese" :mi "Maori" :mr "Marathi" :mhr "Mari" :mn "Mongolian" :ne "Nepali" :no "Norwegian" :pap "Papiamento" :fa "Persian" :pl "Polish" :pt "Portuguese" :pa "Punjabi" :ro "Romanian" :ru "Russian" :gd "Scottish" :sr "Serbian" :si "Sinhala" :sk "Slovakian" :sl "Slovenian" :es "Spanish" :su "Sundanese" :sw "Swahili" :sv "Swedish" :tl "Tagalog" :tg "Tajik" :ta "Tamil" :tt "Tatar" :te "Telugu" :th "Thai" :tr "Turkish" :udm "Udmurt" :uk "Ukrainian" :ur "Urdu" :uz "Uzbek" :vi "Vietnamese" :cy "Welsh" :xh "Xhosa" :yi "Yiddish"}) ;;;;;;;;;; ;; ;; Dealing with PO.DAAC region ;; ;;;;;;;;;; (def podaac-base-url "https://podaac.jpl.nasa.gov/ws/") (def source-language "en") (defn- build-url "Returns a fully-qualifies PO.DAAC route based on the given route and parameters." [route params] (str podaac-base-url route "?" (codec/form-encode params))) (defn- fetch-xml "Fetches and caches XML from a PO.DAAC route." [url] (slurp url)) (defn- build-xdoc "Builds an XPATH-accessible XML document from a given, formatted XML document." [xml] ;; Avoids [Fatal Error] :1:10: DOCTYPE is disallowed when the feature ;; "http://apache.org/xml/features/disallow-doctype-decl" set to true. ;; org.xml.sax.SAXParseException: DOCTYPE is disallowed when the feature ;; "http://apache.org/xml/features/disallow-doctype-decl" set to true. (let [opts {:disallow-doctype-decl false}] (try (xpath/xml->doc xml opts)))) (defn- extract-root "Extracts the root of the XML document using an XPATH query." [xpath-doc] (first (xpath/$x "/*" xpath-doc))) (defn- extract-relevant-text "Returns a sequence of relevant phrases from the XPATH root, split by the tab and newline delimiters." [root] (-> (get root :text) (str/split #"\t+\n+"))) (defn- format-relevant-text "Returns a sequence of chunks of relevant text, stripped of all leading and trailing whitespace." [text] (->> (map (fn [x] (str/trim x)) text) (filter (complement str/blank?)))) (defn hit-podaac "Hits the PO.DAAC web service specified by the given route, with the parameters specified by the given params." [route params] (-> (build-url route params) (fetch-xml) (build-xdoc) (extract-root) (extract-relevant-text) (format-relevant-text))) ;;;;;;;;;; ;; ;; Translation region ;; ;;;;;;;;;; (def translator (YandexTranslator.)) (defn translate-with-tika "Returns the translated dataset into the specified language using Apache Tika." [dataset lang-code] ;; Logging to console for requirements proving (println "\n\n\n\n\nDEBUG: Attempting to translate by calling tika-translate...\n\n\n\n\n") (pmap (fn [x] (.translate translator (str/replace x #"\\/" "/") source-language lang-code)) dataset)) (defn translate-to-lang "Returns PO.DAAC dataset specified by the given language." [dataset key lang] (cache-add key (translate-with-tika dataset lang)) (cache-lookup key)) ;;;;;;;;;; ;; ;; Top-level region ;; ;;;;;;;;;; (defn- route-to-key "Returns the concatenation of the given route, split by slashes, with the suppled language code." [route lang-code] (keyword (str (apply str (str/split route #"/")) lang-code))) (defn translate-request "Handles a given iPres request and returns the translated data in the specified format." [route params lang-code format] (let [cache-key (route-to-key route lang-code)] (if (cache-has? cache-key) (cache-lookup cache-key) (-> (hit-podaac route params) (translate-to-lang cache-key lang-code) ;;(convert-to-format format) ))))
[ { "context": "n \"Community Chat\"]]\n [:a {:href \"mailto:[email protected]\"} [:span.n \"[email protected]\"]]]]]\n [:div {:st", "end": 2395, "score": 0.999925971031189, "start": 2382, "tag": "EMAIL", "value": "[email protected]" }, { "context": " [:a {:href \"mailto:[email protected]\"} [:span.n \"[email protected]\"]]]]]\n [:div {:style {:text-align \"center\" ", "end": 2421, "score": 0.9999246597290039, "start": 2408, "tag": "EMAIL", "value": "[email protected]" } ]
crux-console/src/crux_ui_server/pages.clj
iojtaylor/crux
1
(ns crux-ui-server.pages (:require [crux-ui-server.preloader :as preloader] [page-renderer.api :as pr] [clojure.java.io :as io])) (def id #uuid "50005565-299f-4c08-86d0-b1919bf4b7a9") (def console-assets-frame {:title "Crux Console" :lang "en" :theme-color "hsl(32, 91%, 54%)" :og-image "/static/img/crux-logo.svg" :link-apple-icon "/static/img/cube-on-white-192.png" :link-apple-startup-image "/static/img/cube-on-white-512.png" :link-image-src "/static/img/cube-on-white-512.png" :service-worker "/service-worker-for-console.js" :favicon "/static/img/cube-on-white-120.png" :sw-default-url "/console" :stylesheet-async ["/static/styles/reset.css" "/static/styles/react-input-range.css" "/static/styles/react-ui-tree.css" "/static/styles/codemirror.css" "/static/styles/monokai.css" "/static/styles/eclipse.css"] :script "/static/crux-ui/compiled/main.js" :manifest "/static/manifest-console.json" :head-tags [[:style#_stylefy-constant-styles_] [:style#_stylefy-styles_] [:meta {:name "google" :content "notranslate"}]] :body [:body [:div#app preloader/root]]}) (defn gen-console-page [req] (pr/render-page console-assets-frame)) (defn gen-service-worker [req] (pr/generate-service-worker console-assets-frame)) (defn q-perf-page [req] (pr/render-page {:title "Crux Console" :lang "en" :doc-attrs {:data-scenario :perf-plot} :stylesheet-async "/static/styles/reset.css" :og-image "/static/img/crux-logo.svg" :script "/static/crux-ui/compiled/main-perf.js" :head-tags [[:script {:id "plots-data" :type "text/edn"} (slurp (io/resource "static/plots-data.edn"))]] :body [:body [:div#app preloader/root]]})) (defn gen-home-page [req] (pr/render-page {:title "Crux Standalone Demo with HTTP" :lang "en" :og-image "/static/img/crux-logo.svg" :body [:body [:header [:div.nav [:div.logo {:style {:opacity "0"}} [:a {:href "/"} [:img.logo-img {:src "/static/img/crux-logo.svg"}]]] [:div.n0 [:a {:href "https://juxt.pro/crux/docs/index.html"} [:span.n "Documentation"]] [:a {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux"} [:span.n "Community Chat"]] [:a {:href "mailto:[email protected]"} [:span.n "[email protected]"]]]]] [:div {:style {:text-align "center" :width "100%" :margin-top "6em"}} [:div.splash {:style {:max-width "25vw" :margin-left "auto" :margin-right "auto"}} [:a {:href "/"} [:img.splash-img {:src "/static/img/crux-logo.svg"}]]] [:div {:style {:height "4em"}}] [:h3 "You should now be able to access this Crux standalone demo node using the HTTP API via localhost:8080"]] [:div#app]]}))
83010
(ns crux-ui-server.pages (:require [crux-ui-server.preloader :as preloader] [page-renderer.api :as pr] [clojure.java.io :as io])) (def id #uuid "50005565-299f-4c08-86d0-b1919bf4b7a9") (def console-assets-frame {:title "Crux Console" :lang "en" :theme-color "hsl(32, 91%, 54%)" :og-image "/static/img/crux-logo.svg" :link-apple-icon "/static/img/cube-on-white-192.png" :link-apple-startup-image "/static/img/cube-on-white-512.png" :link-image-src "/static/img/cube-on-white-512.png" :service-worker "/service-worker-for-console.js" :favicon "/static/img/cube-on-white-120.png" :sw-default-url "/console" :stylesheet-async ["/static/styles/reset.css" "/static/styles/react-input-range.css" "/static/styles/react-ui-tree.css" "/static/styles/codemirror.css" "/static/styles/monokai.css" "/static/styles/eclipse.css"] :script "/static/crux-ui/compiled/main.js" :manifest "/static/manifest-console.json" :head-tags [[:style#_stylefy-constant-styles_] [:style#_stylefy-styles_] [:meta {:name "google" :content "notranslate"}]] :body [:body [:div#app preloader/root]]}) (defn gen-console-page [req] (pr/render-page console-assets-frame)) (defn gen-service-worker [req] (pr/generate-service-worker console-assets-frame)) (defn q-perf-page [req] (pr/render-page {:title "Crux Console" :lang "en" :doc-attrs {:data-scenario :perf-plot} :stylesheet-async "/static/styles/reset.css" :og-image "/static/img/crux-logo.svg" :script "/static/crux-ui/compiled/main-perf.js" :head-tags [[:script {:id "plots-data" :type "text/edn"} (slurp (io/resource "static/plots-data.edn"))]] :body [:body [:div#app preloader/root]]})) (defn gen-home-page [req] (pr/render-page {:title "Crux Standalone Demo with HTTP" :lang "en" :og-image "/static/img/crux-logo.svg" :body [:body [:header [:div.nav [:div.logo {:style {:opacity "0"}} [:a {:href "/"} [:img.logo-img {:src "/static/img/crux-logo.svg"}]]] [:div.n0 [:a {:href "https://juxt.pro/crux/docs/index.html"} [:span.n "Documentation"]] [:a {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux"} [:span.n "Community Chat"]] [:a {:href "mailto:<EMAIL>"} [:span.n "<EMAIL>"]]]]] [:div {:style {:text-align "center" :width "100%" :margin-top "6em"}} [:div.splash {:style {:max-width "25vw" :margin-left "auto" :margin-right "auto"}} [:a {:href "/"} [:img.splash-img {:src "/static/img/crux-logo.svg"}]]] [:div {:style {:height "4em"}}] [:h3 "You should now be able to access this Crux standalone demo node using the HTTP API via localhost:8080"]] [:div#app]]}))
true
(ns crux-ui-server.pages (:require [crux-ui-server.preloader :as preloader] [page-renderer.api :as pr] [clojure.java.io :as io])) (def id #uuid "50005565-299f-4c08-86d0-b1919bf4b7a9") (def console-assets-frame {:title "Crux Console" :lang "en" :theme-color "hsl(32, 91%, 54%)" :og-image "/static/img/crux-logo.svg" :link-apple-icon "/static/img/cube-on-white-192.png" :link-apple-startup-image "/static/img/cube-on-white-512.png" :link-image-src "/static/img/cube-on-white-512.png" :service-worker "/service-worker-for-console.js" :favicon "/static/img/cube-on-white-120.png" :sw-default-url "/console" :stylesheet-async ["/static/styles/reset.css" "/static/styles/react-input-range.css" "/static/styles/react-ui-tree.css" "/static/styles/codemirror.css" "/static/styles/monokai.css" "/static/styles/eclipse.css"] :script "/static/crux-ui/compiled/main.js" :manifest "/static/manifest-console.json" :head-tags [[:style#_stylefy-constant-styles_] [:style#_stylefy-styles_] [:meta {:name "google" :content "notranslate"}]] :body [:body [:div#app preloader/root]]}) (defn gen-console-page [req] (pr/render-page console-assets-frame)) (defn gen-service-worker [req] (pr/generate-service-worker console-assets-frame)) (defn q-perf-page [req] (pr/render-page {:title "Crux Console" :lang "en" :doc-attrs {:data-scenario :perf-plot} :stylesheet-async "/static/styles/reset.css" :og-image "/static/img/crux-logo.svg" :script "/static/crux-ui/compiled/main-perf.js" :head-tags [[:script {:id "plots-data" :type "text/edn"} (slurp (io/resource "static/plots-data.edn"))]] :body [:body [:div#app preloader/root]]})) (defn gen-home-page [req] (pr/render-page {:title "Crux Standalone Demo with HTTP" :lang "en" :og-image "/static/img/crux-logo.svg" :body [:body [:header [:div.nav [:div.logo {:style {:opacity "0"}} [:a {:href "/"} [:img.logo-img {:src "/static/img/crux-logo.svg"}]]] [:div.n0 [:a {:href "https://juxt.pro/crux/docs/index.html"} [:span.n "Documentation"]] [:a {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux"} [:span.n "Community Chat"]] [:a {:href "mailto:PI:EMAIL:<EMAIL>END_PI"} [:span.n "PI:EMAIL:<EMAIL>END_PI"]]]]] [:div {:style {:text-align "center" :width "100%" :margin-top "6em"}} [:div.splash {:style {:max-width "25vw" :margin-left "auto" :margin-right "auto"}} [:a {:href "/"} [:img.splash-img {:src "/static/img/crux-logo.svg"}]]] [:div {:style {:height "4em"}}] [:h3 "You should now be able to access this Crux standalone demo node using the HTTP API via localhost:8080"]] [:div#app]]}))
[ { "context": "ution\"}]}]}\n {:id 3\n :label \"Gloubi Boulga\"}])\n\n(def LEAVES\n \"Extract leaf nodes from a tre", "end": 2661, "score": 0.9686994552612305, "start": 2648, "tag": "NAME", "value": "Gloubi Boulga" } ]
src/talk_paris_clojure_meetup_specter/core.clj
DjebbZ/talk-paris-clojure-meetup-specter
0
(ns talk-paris-clojure-meetup-specter.core (:require [com.rpl.specter :as sp])) ;; Intro (def flat-numbers [1 2 3 4]) (defn inc-flat-numbers "Increment each number" [] (map inc flat-numbers)) (defn inc-flat-numbers-specter [] (sp/transform [sp/ALL] inc flat-numbers)) (def maps-numbers [{:id 1 :value 1} {:id 2 :value 2} {:id 3 :value 3}]) (defn inc-maps-numbers "Increment each :value" [] (map #(update % :value inc) maps-numbers)) (defn inc-maps-numbers-specter [] (sp/transform [sp/ALL :value] inc maps-numbers)) (def nested-numbers {:a [{:aa 1 :bb 2} {:cc 3}] :b [{:dd 4}]}) (defn inc-even-nested-numbers-specter [] (sp/transform [sp/MAP-VALS sp/ALL sp/MAP-VALS even?] inc nested-numbers) ) (defn inc-even-nested-numbers "Increment every even number nested within a map of vector of maps" [] (letfn [(map-vals [m afn] (->> m (map (fn [[k v]] [k (afn v)])) (into (empty m))))] (map-vals nested-numbers (fn [v] (mapv ;; mapv (fn [m] (map-vals m (fn [v] (if (even? v) (inc v) v)))) v))))) ;; Specter Powers (defn update-in-on-steroids [] (update-in {:a {:b {:c 1}}} [:a :b :c] #(if (even? %) (inc %) %)) (sp/transform [:a :b :c even?] inc {:a {:b {:c 1}}})) (defn precise-extraction [] (sp/select [sp/MAP-VALS sp/ALL sp/MAP-VALS even?] nested-numbers)) (defn reusable-paths [] (let [even-numbers-path [sp/MAP-VALS sp/ALL sp/MAP-VALS even?]] (sp/transform even-numbers-path inc nested-numbers) (sp/select even-numbers-path nested-numbers))) ;; Specter Super Power (def tree [{:id 1 :label "Freinage" :children [{:id 11 :label "Plaquettes" :children [{:id 111 :label "Plaquette de frein"} {:id 112 :label "Accessoires de plaquette de frein"}]} {:id 12 :label "Disques" :children [{:id 121 :label "Disque de frein"} {:id 122 :label "Flasque de frein"}]}]} {:id 2 :label "Pièces Moteur et Huile" :children [{:id 21 :label "Courroies et Distribution" :children [{:id 211 :label "Kit de distribution"} {:id 212 :label "Courroie de distribution"}]}]} {:id 3 :label "Gloubi Boulga"}]) (def LEAVES "Extract leaf nodes from a tree using schema v4 :leaf attribute" (sp/recursive-path [] p [sp/ALL (sp/if-path (sp/must :children) [:children p] sp/STAY)])) (comment (sp/select LEAVES tree) (sp/setval [LEAVES :leaf] true tree)) (def by-id "Specter navigator for trees. Retrieves the node identified by the `:id` passed in parameter. Ex: (sp/select-first (by-id 1) tree)" (sp/recursive-path [id] p [sp/ALL (sp/if-path #(= id (:id %)) sp/STAY [:children p])])) (comment (sp/select-one (by-id 211) tree)) (def by-ids "Specter navigator for trees. Retrieves the node identified by its `:id` from the ids passed in parameter. Ex: (sp/select-first (by-ids [1 2]) tree)" (sp/recursive-path [ids] p [sp/ALL (sp/if-path (fn [node] (some #(= % (:id node)) ids)) (sp/continue-then-stay :children p) [:children p])])) (comment (sp/select (by-ids [2 211]) tree)) ;; Bug with sp/STAY, can you find it ? (defn group-leaves-by-parent "Group leaves by each top level parent node of a tree" [tree] (sp/transform [sp/ALL (sp/collect :children LEAVES)] (fn group [leaves parent] (if (seq leaves) (assoc parent :children leaves) sp/NONE)) tree)) (sp/select [sp/ALL (sp/collect :children LEAVES)] tree) (comment (group-leaves-by-parent tree))
45931
(ns talk-paris-clojure-meetup-specter.core (:require [com.rpl.specter :as sp])) ;; Intro (def flat-numbers [1 2 3 4]) (defn inc-flat-numbers "Increment each number" [] (map inc flat-numbers)) (defn inc-flat-numbers-specter [] (sp/transform [sp/ALL] inc flat-numbers)) (def maps-numbers [{:id 1 :value 1} {:id 2 :value 2} {:id 3 :value 3}]) (defn inc-maps-numbers "Increment each :value" [] (map #(update % :value inc) maps-numbers)) (defn inc-maps-numbers-specter [] (sp/transform [sp/ALL :value] inc maps-numbers)) (def nested-numbers {:a [{:aa 1 :bb 2} {:cc 3}] :b [{:dd 4}]}) (defn inc-even-nested-numbers-specter [] (sp/transform [sp/MAP-VALS sp/ALL sp/MAP-VALS even?] inc nested-numbers) ) (defn inc-even-nested-numbers "Increment every even number nested within a map of vector of maps" [] (letfn [(map-vals [m afn] (->> m (map (fn [[k v]] [k (afn v)])) (into (empty m))))] (map-vals nested-numbers (fn [v] (mapv ;; mapv (fn [m] (map-vals m (fn [v] (if (even? v) (inc v) v)))) v))))) ;; Specter Powers (defn update-in-on-steroids [] (update-in {:a {:b {:c 1}}} [:a :b :c] #(if (even? %) (inc %) %)) (sp/transform [:a :b :c even?] inc {:a {:b {:c 1}}})) (defn precise-extraction [] (sp/select [sp/MAP-VALS sp/ALL sp/MAP-VALS even?] nested-numbers)) (defn reusable-paths [] (let [even-numbers-path [sp/MAP-VALS sp/ALL sp/MAP-VALS even?]] (sp/transform even-numbers-path inc nested-numbers) (sp/select even-numbers-path nested-numbers))) ;; Specter Super Power (def tree [{:id 1 :label "Freinage" :children [{:id 11 :label "Plaquettes" :children [{:id 111 :label "Plaquette de frein"} {:id 112 :label "Accessoires de plaquette de frein"}]} {:id 12 :label "Disques" :children [{:id 121 :label "Disque de frein"} {:id 122 :label "Flasque de frein"}]}]} {:id 2 :label "Pièces Moteur et Huile" :children [{:id 21 :label "Courroies et Distribution" :children [{:id 211 :label "Kit de distribution"} {:id 212 :label "Courroie de distribution"}]}]} {:id 3 :label "<NAME>"}]) (def LEAVES "Extract leaf nodes from a tree using schema v4 :leaf attribute" (sp/recursive-path [] p [sp/ALL (sp/if-path (sp/must :children) [:children p] sp/STAY)])) (comment (sp/select LEAVES tree) (sp/setval [LEAVES :leaf] true tree)) (def by-id "Specter navigator for trees. Retrieves the node identified by the `:id` passed in parameter. Ex: (sp/select-first (by-id 1) tree)" (sp/recursive-path [id] p [sp/ALL (sp/if-path #(= id (:id %)) sp/STAY [:children p])])) (comment (sp/select-one (by-id 211) tree)) (def by-ids "Specter navigator for trees. Retrieves the node identified by its `:id` from the ids passed in parameter. Ex: (sp/select-first (by-ids [1 2]) tree)" (sp/recursive-path [ids] p [sp/ALL (sp/if-path (fn [node] (some #(= % (:id node)) ids)) (sp/continue-then-stay :children p) [:children p])])) (comment (sp/select (by-ids [2 211]) tree)) ;; Bug with sp/STAY, can you find it ? (defn group-leaves-by-parent "Group leaves by each top level parent node of a tree" [tree] (sp/transform [sp/ALL (sp/collect :children LEAVES)] (fn group [leaves parent] (if (seq leaves) (assoc parent :children leaves) sp/NONE)) tree)) (sp/select [sp/ALL (sp/collect :children LEAVES)] tree) (comment (group-leaves-by-parent tree))
true
(ns talk-paris-clojure-meetup-specter.core (:require [com.rpl.specter :as sp])) ;; Intro (def flat-numbers [1 2 3 4]) (defn inc-flat-numbers "Increment each number" [] (map inc flat-numbers)) (defn inc-flat-numbers-specter [] (sp/transform [sp/ALL] inc flat-numbers)) (def maps-numbers [{:id 1 :value 1} {:id 2 :value 2} {:id 3 :value 3}]) (defn inc-maps-numbers "Increment each :value" [] (map #(update % :value inc) maps-numbers)) (defn inc-maps-numbers-specter [] (sp/transform [sp/ALL :value] inc maps-numbers)) (def nested-numbers {:a [{:aa 1 :bb 2} {:cc 3}] :b [{:dd 4}]}) (defn inc-even-nested-numbers-specter [] (sp/transform [sp/MAP-VALS sp/ALL sp/MAP-VALS even?] inc nested-numbers) ) (defn inc-even-nested-numbers "Increment every even number nested within a map of vector of maps" [] (letfn [(map-vals [m afn] (->> m (map (fn [[k v]] [k (afn v)])) (into (empty m))))] (map-vals nested-numbers (fn [v] (mapv ;; mapv (fn [m] (map-vals m (fn [v] (if (even? v) (inc v) v)))) v))))) ;; Specter Powers (defn update-in-on-steroids [] (update-in {:a {:b {:c 1}}} [:a :b :c] #(if (even? %) (inc %) %)) (sp/transform [:a :b :c even?] inc {:a {:b {:c 1}}})) (defn precise-extraction [] (sp/select [sp/MAP-VALS sp/ALL sp/MAP-VALS even?] nested-numbers)) (defn reusable-paths [] (let [even-numbers-path [sp/MAP-VALS sp/ALL sp/MAP-VALS even?]] (sp/transform even-numbers-path inc nested-numbers) (sp/select even-numbers-path nested-numbers))) ;; Specter Super Power (def tree [{:id 1 :label "Freinage" :children [{:id 11 :label "Plaquettes" :children [{:id 111 :label "Plaquette de frein"} {:id 112 :label "Accessoires de plaquette de frein"}]} {:id 12 :label "Disques" :children [{:id 121 :label "Disque de frein"} {:id 122 :label "Flasque de frein"}]}]} {:id 2 :label "Pièces Moteur et Huile" :children [{:id 21 :label "Courroies et Distribution" :children [{:id 211 :label "Kit de distribution"} {:id 212 :label "Courroie de distribution"}]}]} {:id 3 :label "PI:NAME:<NAME>END_PI"}]) (def LEAVES "Extract leaf nodes from a tree using schema v4 :leaf attribute" (sp/recursive-path [] p [sp/ALL (sp/if-path (sp/must :children) [:children p] sp/STAY)])) (comment (sp/select LEAVES tree) (sp/setval [LEAVES :leaf] true tree)) (def by-id "Specter navigator for trees. Retrieves the node identified by the `:id` passed in parameter. Ex: (sp/select-first (by-id 1) tree)" (sp/recursive-path [id] p [sp/ALL (sp/if-path #(= id (:id %)) sp/STAY [:children p])])) (comment (sp/select-one (by-id 211) tree)) (def by-ids "Specter navigator for trees. Retrieves the node identified by its `:id` from the ids passed in parameter. Ex: (sp/select-first (by-ids [1 2]) tree)" (sp/recursive-path [ids] p [sp/ALL (sp/if-path (fn [node] (some #(= % (:id node)) ids)) (sp/continue-then-stay :children p) [:children p])])) (comment (sp/select (by-ids [2 211]) tree)) ;; Bug with sp/STAY, can you find it ? (defn group-leaves-by-parent "Group leaves by each top level parent node of a tree" [tree] (sp/transform [sp/ALL (sp/collect :children LEAVES)] (fn group [leaves parent] (if (seq leaves) (assoc parent :children leaves) sp/NONE)) tree)) (sp/select [sp/ALL (sp/collect :children LEAVES)] tree) (comment (group-leaves-by-parent tree))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.test.basal.util\n", "end": 597, "score": 0.9998529553413391, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/test/clojure/czlab/test/basal/util.clj
llnek/xlib
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.test.basal.util (:require [clojure.test :as ct] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.core :refer [ensure?? ensure-thrown??] :as c]) (:import [java.net URL] [java.util List Set Map TimerTask ResourceBundle] [java.io File InputStream])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-util ;(ensure?? "try!!!" (nil? (u/try!!! (/ 1 0)))) ;(ensure?? "try!!" (== 4 (u/try!! 4 (/ 1 0)))) (ensure?? "system-time" (pos? (u/system-time))) (ensure?? "run<>;run<+>" (let [a (atom 0) _ (.run (u/run<> (reset! a 44))) ok? (== 44 @a) _ (.run (u/run<+> (reset! a 77)))] (and ok? (== 77 @a)))) (ensure?? "get-env-var" (let [s (u/get-env-var "PATH")] (and (string? s) (pos? (count s))))) (ensure?? "uuid<>" (let [s (u/uuid<>)] (and (== 36 (count s)) (cs/includes? s "-")))) (ensure?? "date<>" (instance? java.util.Date (u/date<>))) (ensure?? "set-sys-prop!;get-sys-prop" (= "a" (do (u/set-sys-prop! "hello.joe.test" "a") (u/get-sys-prop "hello.joe.test")))) (ensure?? "get-user-name" (let [s (u/get-user-name)] (and (string? s) (pos? (count s))))) (ensure?? "get-home-dir" (instance? java.io.File (u/get-user-home))) (ensure?? "get-user-dir" (instance? java.io.File (u/get-user-dir))) (ensure?? "trim-last-pathsep" (= "/tmp/abc" (u/trim-last-pathsep "/tmp/abc/"))) (ensure?? "trim-last-pathsep" (= "\\tmp\\abc" (u/trim-last-pathsep "\\tmp\\abc\\///"))) (ensure?? "mono-flop<>" (let [out (atom 0) m (u/mono-flop<>)] (dotimes [_ 10] (if (u/is-first-call? m) (swap! out inc))) (== 1 @out))) (ensure?? "watch<>;pause" (let [w (u/watch<>)] (u/pause 100) (and (pos? (u/elapsed-millis w)) (pos? (u/elapsed-nanos w)) (pos? (do (u/pause 100) (u/reset-watch! w) (u/elapsed-nanos w)))))) (ensure?? "jid<>" (let [s (u/jid<>)] (and (string? s) (pos? (count s)) (not (cs/includes? s "-")) (not (cs/includes? s ":"))))) (ensure?? "uid<>" (let [s (u/uid<>)] (and (string? s) (pos? (count s)) (not (cs/includes? s "-"))))) (ensure?? "rand<>" (some? (u/rand<>))) (ensure?? "rand-bytes" (let [b (u/rand-bytes 10)] (== 10 (count b)))) (ensure?? "emsg" (= "what!" (.getMessage (Exception. "what!")))) (ensure?? "objid??" (cs/includes? (u/objid?? (Exception. "aaa")) "@")) (ensure?? "encoding??;charset??" (= "utf-8" (cs/lower-case (u/encoding?? (u/charset?? "utf-8"))))) (ensure?? "pthreads" (pos? (u/pthreads))) (ensure?? "fpath" (= "c:/windows/win32/" (u/fpath "c:\\windows\\win32\\"))) (ensure?? "serialize;deserialize" (let [b (u/serialize {:a 1}) m (u/deserialize b)] (== 1 (:a m)))) (ensure?? "serialize;deserialize" (let [b (u/serialize (Exception. "hi")) e (u/deserialize b)] (= "hi" (.getMessage ^Exception e)))) (ensure?? "gczn" (= "String" (u/gczn "a"))) (ensure?? "get-class-name" (= "java.lang.String" (u/get-class-name "a"))) (ensure?? "is-windows?;is-macos?;is-linux?" (let [m (u/is-macos?) x (u/is-linux?) w (u/is-windows?)] (cond m (and (not x)(not w)) w (and (not m)(not x)) x (and (not w)(not m))))) (ensure?? "x->str;x->chars;x->bytes" (let [c0 (u/x->chars "hello") b0 (u/x->bytes c0) s0 (u/x->str c0) b1 (u/x->bytes s0) s1 (u/x->str b1) s2 (u/x->str b0)] (and (= s0 s1) (= s1 s2)))) (ensure?? "load-java-props" (let [p (u/load-java-props (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) p1 (.getProperty p "test") p2 (.getProperty p "test2")] (and (string? p1) (string? p2) (= p1 p2)))) (ensure?? "deflate;inflate" (let [b (u/deflate (u/x->bytes "hello joe")) s (u/x->str (u/inflate b))] (= s "hello joe"))) (ensure?? "safe-fpath" (let [s (u/safe-fpath "/tmp/abc def")] (= s "0x2ftmp0x2fabc0x20def"))) (ensure?? "fmt-file-url" (= (u/fmt-file-url "/tmp/a.txt") (u/fmt-file-url "file:/tmp/a.txt"))) (ensure?? "get-fpath" (let [u (u/fmt-file-url "file:/tmp/a.txt")] (= "/tmp/a.txt" (u/get-fpath u)))) (ensure?? "root-cause" (let [a (Exception. "a") b (Exception. a) c (Exception. b)] (identical? a (u/root-cause c)))) (ensure?? "root-cause-msg" (let [a (Exception. "a") b (Exception. a) c (Exception. b)] (= "a" (.getMessage (u/root-cause c))))) (ensure?? "pmap<>" (let [p (u/load-java-props (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) m (u/pmap<> p)] (and (string? (:test m)) (= (:test2 m) (:test m))))) (ensure?? "tmtask<>;cancel-timer-task!" (let [a (atom 0) t (u/tmtask<> #(reset! a 3))] (and (c/is? TimerTask t) (do (.run t) (u/cancel-timer-task! t) (== 3 @a))))) ;(ensure?? "prt-stk" (u/prt-stk (Exception. "e"))) (ensure?? "dump-stk" (let [s (u/dump-stk (Exception. "e"))] (and (string? s) (pos? (count s))))) (ensure?? "x->java" (let [obj (u/x->java {:a 1 :b #{1 2 3} :c [7 8 {:z 3}]}) m (c/cast? Map obj) _ (if (nil? m) (c/raise! "expect Map1")) a (.get m "a") b (c/cast? Set (.get m "b")) _ (if (nil? b) (c/raise! "expect Set")) c (c/cast? List (.get m "c")) _ (if (nil? c) (c/raise! "expect List")) z (c/cast? Map (.get c 2)) _ (if (nil? z) (c/raise! "expect Map3")) z3 (.get z "z")] (and (== 1 a) (== 3 (.size b)) (and (== 7 (.get c 0)) (== 8 (.get c 1))) (== 3 z3)))) (ensure?? "seqint" (let [old (u/seqint) a (u/seqint) b (u/seqint)] (and (= a (+ 1 old)) (= b (+ 1 a))))) (ensure?? "seqint2" (let [old (u/seqint2) a (u/seqint2) b (u/seqint2)] (and (= a (+ 1 old)) (= b (+ 1 a))))) (ensure?? "count-cpus" (pos? (u/count-cpus))) (ensure?? "sys-tmp-dir" (let [f (new File (u/sys-tmp-dir))] (.exists f))) (ensure?? "obj-eq?" (let [a (String. "a") b (String. "a")] (u/obj-eq? a b))) (ensure?? "url-encode;url-decode" (let [s (u/url-encode "a+c+b") z (u/url-decode s)] (= z "a+c+b"))) (ensure?? "sortby" (let [c [{:age 5} {:age 3} {:age 1} {:age 2}] a (u/sortby :age (c/compare-asc*) c) d (u/sortby :age (c/compare-des*) c)] (and (= [1 2 3 5] (mapv #(:age %) a)) (= [5 3 2 1] (mapv #(:age %) d))))) (ensure?? "new-memset" (let [m (u/new-memset<> 2) _ (u/ms-add m (atom {:a 1})) z0 (u/ms-count m)] (u/ms-add m (atom {:a 2})) (u/ms-add m (atom {:a 3})) (and (== 1 z0) (== 3 (u/ms-count m)) (== 4 (u/ms-capacity m))))) (ensure?? "each-set" (let [acc (atom 0) m (u/new-memset<> 2)] (u/ms-add m (atom {:a 1})) (u/ms-add m (atom {:a 2})) (u/ms-each m (fn [obj _] (swap! acc + (:a @obj)))) (== 3 @acc))) (ensure?? "drop->set!" (let [m (u/new-memset<> 2) a (atom {:a 1}) b (atom {:a 1})] (u/ms-add m a) (u/ms-add m b) (u/ms-drop m a) (u/ms-drop m b) (zero? (u/ms-count m)))) (ensure?? "get-cldr" (not (nil? (u/get-cldr)))) (ensure?? "set-cldr" (do (u/set-cldr (u/get-cldr)) true)) (ensure?? "load-resource" (= "hello joe, how is your dawg" (-> (u/load-resource (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) (u/rstr "test" "joe" "dawg" )))) (ensure?? "load-resource" (= ["hello joe, how is your dawg" "hello joe, how is your dawg"] (-> (u/load-resource (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) (u/rstr* ["test" "joe" "dawg"] ["test2" "joe" "dawg"] )))) (ensure?? "get-resource" (c/is? ResourceBundle (u/get-resource "czlab/basal/etc/Resources"))) (ensure?? "shuffle" (and (not= "abcde" (u/shuffle "abcde")) (== 3 (count (u/shuffle "abc"))))) (ensure?? "cljrt<>" (let [rt (u/cljrt<>) m (u/call* rt :czlab.basal.util/emsg [(Exception. "hello world")]) v (u/var* rt :czlab.basal.util/cljrt<>)] (and (= "hello world" m) (var? v)))) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ct/deftest ^:test-util basal-test-util (ct/is (c/clj-test?? test-util))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
70375
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.test.basal.util (:require [clojure.test :as ct] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.core :refer [ensure?? ensure-thrown??] :as c]) (:import [java.net URL] [java.util List Set Map TimerTask ResourceBundle] [java.io File InputStream])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-util ;(ensure?? "try!!!" (nil? (u/try!!! (/ 1 0)))) ;(ensure?? "try!!" (== 4 (u/try!! 4 (/ 1 0)))) (ensure?? "system-time" (pos? (u/system-time))) (ensure?? "run<>;run<+>" (let [a (atom 0) _ (.run (u/run<> (reset! a 44))) ok? (== 44 @a) _ (.run (u/run<+> (reset! a 77)))] (and ok? (== 77 @a)))) (ensure?? "get-env-var" (let [s (u/get-env-var "PATH")] (and (string? s) (pos? (count s))))) (ensure?? "uuid<>" (let [s (u/uuid<>)] (and (== 36 (count s)) (cs/includes? s "-")))) (ensure?? "date<>" (instance? java.util.Date (u/date<>))) (ensure?? "set-sys-prop!;get-sys-prop" (= "a" (do (u/set-sys-prop! "hello.joe.test" "a") (u/get-sys-prop "hello.joe.test")))) (ensure?? "get-user-name" (let [s (u/get-user-name)] (and (string? s) (pos? (count s))))) (ensure?? "get-home-dir" (instance? java.io.File (u/get-user-home))) (ensure?? "get-user-dir" (instance? java.io.File (u/get-user-dir))) (ensure?? "trim-last-pathsep" (= "/tmp/abc" (u/trim-last-pathsep "/tmp/abc/"))) (ensure?? "trim-last-pathsep" (= "\\tmp\\abc" (u/trim-last-pathsep "\\tmp\\abc\\///"))) (ensure?? "mono-flop<>" (let [out (atom 0) m (u/mono-flop<>)] (dotimes [_ 10] (if (u/is-first-call? m) (swap! out inc))) (== 1 @out))) (ensure?? "watch<>;pause" (let [w (u/watch<>)] (u/pause 100) (and (pos? (u/elapsed-millis w)) (pos? (u/elapsed-nanos w)) (pos? (do (u/pause 100) (u/reset-watch! w) (u/elapsed-nanos w)))))) (ensure?? "jid<>" (let [s (u/jid<>)] (and (string? s) (pos? (count s)) (not (cs/includes? s "-")) (not (cs/includes? s ":"))))) (ensure?? "uid<>" (let [s (u/uid<>)] (and (string? s) (pos? (count s)) (not (cs/includes? s "-"))))) (ensure?? "rand<>" (some? (u/rand<>))) (ensure?? "rand-bytes" (let [b (u/rand-bytes 10)] (== 10 (count b)))) (ensure?? "emsg" (= "what!" (.getMessage (Exception. "what!")))) (ensure?? "objid??" (cs/includes? (u/objid?? (Exception. "aaa")) "@")) (ensure?? "encoding??;charset??" (= "utf-8" (cs/lower-case (u/encoding?? (u/charset?? "utf-8"))))) (ensure?? "pthreads" (pos? (u/pthreads))) (ensure?? "fpath" (= "c:/windows/win32/" (u/fpath "c:\\windows\\win32\\"))) (ensure?? "serialize;deserialize" (let [b (u/serialize {:a 1}) m (u/deserialize b)] (== 1 (:a m)))) (ensure?? "serialize;deserialize" (let [b (u/serialize (Exception. "hi")) e (u/deserialize b)] (= "hi" (.getMessage ^Exception e)))) (ensure?? "gczn" (= "String" (u/gczn "a"))) (ensure?? "get-class-name" (= "java.lang.String" (u/get-class-name "a"))) (ensure?? "is-windows?;is-macos?;is-linux?" (let [m (u/is-macos?) x (u/is-linux?) w (u/is-windows?)] (cond m (and (not x)(not w)) w (and (not m)(not x)) x (and (not w)(not m))))) (ensure?? "x->str;x->chars;x->bytes" (let [c0 (u/x->chars "hello") b0 (u/x->bytes c0) s0 (u/x->str c0) b1 (u/x->bytes s0) s1 (u/x->str b1) s2 (u/x->str b0)] (and (= s0 s1) (= s1 s2)))) (ensure?? "load-java-props" (let [p (u/load-java-props (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) p1 (.getProperty p "test") p2 (.getProperty p "test2")] (and (string? p1) (string? p2) (= p1 p2)))) (ensure?? "deflate;inflate" (let [b (u/deflate (u/x->bytes "hello joe")) s (u/x->str (u/inflate b))] (= s "hello joe"))) (ensure?? "safe-fpath" (let [s (u/safe-fpath "/tmp/abc def")] (= s "0x2ftmp0x2fabc0x20def"))) (ensure?? "fmt-file-url" (= (u/fmt-file-url "/tmp/a.txt") (u/fmt-file-url "file:/tmp/a.txt"))) (ensure?? "get-fpath" (let [u (u/fmt-file-url "file:/tmp/a.txt")] (= "/tmp/a.txt" (u/get-fpath u)))) (ensure?? "root-cause" (let [a (Exception. "a") b (Exception. a) c (Exception. b)] (identical? a (u/root-cause c)))) (ensure?? "root-cause-msg" (let [a (Exception. "a") b (Exception. a) c (Exception. b)] (= "a" (.getMessage (u/root-cause c))))) (ensure?? "pmap<>" (let [p (u/load-java-props (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) m (u/pmap<> p)] (and (string? (:test m)) (= (:test2 m) (:test m))))) (ensure?? "tmtask<>;cancel-timer-task!" (let [a (atom 0) t (u/tmtask<> #(reset! a 3))] (and (c/is? TimerTask t) (do (.run t) (u/cancel-timer-task! t) (== 3 @a))))) ;(ensure?? "prt-stk" (u/prt-stk (Exception. "e"))) (ensure?? "dump-stk" (let [s (u/dump-stk (Exception. "e"))] (and (string? s) (pos? (count s))))) (ensure?? "x->java" (let [obj (u/x->java {:a 1 :b #{1 2 3} :c [7 8 {:z 3}]}) m (c/cast? Map obj) _ (if (nil? m) (c/raise! "expect Map1")) a (.get m "a") b (c/cast? Set (.get m "b")) _ (if (nil? b) (c/raise! "expect Set")) c (c/cast? List (.get m "c")) _ (if (nil? c) (c/raise! "expect List")) z (c/cast? Map (.get c 2)) _ (if (nil? z) (c/raise! "expect Map3")) z3 (.get z "z")] (and (== 1 a) (== 3 (.size b)) (and (== 7 (.get c 0)) (== 8 (.get c 1))) (== 3 z3)))) (ensure?? "seqint" (let [old (u/seqint) a (u/seqint) b (u/seqint)] (and (= a (+ 1 old)) (= b (+ 1 a))))) (ensure?? "seqint2" (let [old (u/seqint2) a (u/seqint2) b (u/seqint2)] (and (= a (+ 1 old)) (= b (+ 1 a))))) (ensure?? "count-cpus" (pos? (u/count-cpus))) (ensure?? "sys-tmp-dir" (let [f (new File (u/sys-tmp-dir))] (.exists f))) (ensure?? "obj-eq?" (let [a (String. "a") b (String. "a")] (u/obj-eq? a b))) (ensure?? "url-encode;url-decode" (let [s (u/url-encode "a+c+b") z (u/url-decode s)] (= z "a+c+b"))) (ensure?? "sortby" (let [c [{:age 5} {:age 3} {:age 1} {:age 2}] a (u/sortby :age (c/compare-asc*) c) d (u/sortby :age (c/compare-des*) c)] (and (= [1 2 3 5] (mapv #(:age %) a)) (= [5 3 2 1] (mapv #(:age %) d))))) (ensure?? "new-memset" (let [m (u/new-memset<> 2) _ (u/ms-add m (atom {:a 1})) z0 (u/ms-count m)] (u/ms-add m (atom {:a 2})) (u/ms-add m (atom {:a 3})) (and (== 1 z0) (== 3 (u/ms-count m)) (== 4 (u/ms-capacity m))))) (ensure?? "each-set" (let [acc (atom 0) m (u/new-memset<> 2)] (u/ms-add m (atom {:a 1})) (u/ms-add m (atom {:a 2})) (u/ms-each m (fn [obj _] (swap! acc + (:a @obj)))) (== 3 @acc))) (ensure?? "drop->set!" (let [m (u/new-memset<> 2) a (atom {:a 1}) b (atom {:a 1})] (u/ms-add m a) (u/ms-add m b) (u/ms-drop m a) (u/ms-drop m b) (zero? (u/ms-count m)))) (ensure?? "get-cldr" (not (nil? (u/get-cldr)))) (ensure?? "set-cldr" (do (u/set-cldr (u/get-cldr)) true)) (ensure?? "load-resource" (= "hello joe, how is your dawg" (-> (u/load-resource (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) (u/rstr "test" "joe" "dawg" )))) (ensure?? "load-resource" (= ["hello joe, how is your dawg" "hello joe, how is your dawg"] (-> (u/load-resource (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) (u/rstr* ["test" "joe" "dawg"] ["test2" "joe" "dawg"] )))) (ensure?? "get-resource" (c/is? ResourceBundle (u/get-resource "czlab/basal/etc/Resources"))) (ensure?? "shuffle" (and (not= "abcde" (u/shuffle "abcde")) (== 3 (count (u/shuffle "abc"))))) (ensure?? "cljrt<>" (let [rt (u/cljrt<>) m (u/call* rt :czlab.basal.util/emsg [(Exception. "hello world")]) v (u/var* rt :czlab.basal.util/cljrt<>)] (and (= "hello world" m) (var? v)))) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ct/deftest ^:test-util basal-test-util (ct/is (c/clj-test?? test-util))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.test.basal.util (:require [clojure.test :as ct] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.core :refer [ensure?? ensure-thrown??] :as c]) (:import [java.net URL] [java.util List Set Map TimerTask ResourceBundle] [java.io File InputStream])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-util ;(ensure?? "try!!!" (nil? (u/try!!! (/ 1 0)))) ;(ensure?? "try!!" (== 4 (u/try!! 4 (/ 1 0)))) (ensure?? "system-time" (pos? (u/system-time))) (ensure?? "run<>;run<+>" (let [a (atom 0) _ (.run (u/run<> (reset! a 44))) ok? (== 44 @a) _ (.run (u/run<+> (reset! a 77)))] (and ok? (== 77 @a)))) (ensure?? "get-env-var" (let [s (u/get-env-var "PATH")] (and (string? s) (pos? (count s))))) (ensure?? "uuid<>" (let [s (u/uuid<>)] (and (== 36 (count s)) (cs/includes? s "-")))) (ensure?? "date<>" (instance? java.util.Date (u/date<>))) (ensure?? "set-sys-prop!;get-sys-prop" (= "a" (do (u/set-sys-prop! "hello.joe.test" "a") (u/get-sys-prop "hello.joe.test")))) (ensure?? "get-user-name" (let [s (u/get-user-name)] (and (string? s) (pos? (count s))))) (ensure?? "get-home-dir" (instance? java.io.File (u/get-user-home))) (ensure?? "get-user-dir" (instance? java.io.File (u/get-user-dir))) (ensure?? "trim-last-pathsep" (= "/tmp/abc" (u/trim-last-pathsep "/tmp/abc/"))) (ensure?? "trim-last-pathsep" (= "\\tmp\\abc" (u/trim-last-pathsep "\\tmp\\abc\\///"))) (ensure?? "mono-flop<>" (let [out (atom 0) m (u/mono-flop<>)] (dotimes [_ 10] (if (u/is-first-call? m) (swap! out inc))) (== 1 @out))) (ensure?? "watch<>;pause" (let [w (u/watch<>)] (u/pause 100) (and (pos? (u/elapsed-millis w)) (pos? (u/elapsed-nanos w)) (pos? (do (u/pause 100) (u/reset-watch! w) (u/elapsed-nanos w)))))) (ensure?? "jid<>" (let [s (u/jid<>)] (and (string? s) (pos? (count s)) (not (cs/includes? s "-")) (not (cs/includes? s ":"))))) (ensure?? "uid<>" (let [s (u/uid<>)] (and (string? s) (pos? (count s)) (not (cs/includes? s "-"))))) (ensure?? "rand<>" (some? (u/rand<>))) (ensure?? "rand-bytes" (let [b (u/rand-bytes 10)] (== 10 (count b)))) (ensure?? "emsg" (= "what!" (.getMessage (Exception. "what!")))) (ensure?? "objid??" (cs/includes? (u/objid?? (Exception. "aaa")) "@")) (ensure?? "encoding??;charset??" (= "utf-8" (cs/lower-case (u/encoding?? (u/charset?? "utf-8"))))) (ensure?? "pthreads" (pos? (u/pthreads))) (ensure?? "fpath" (= "c:/windows/win32/" (u/fpath "c:\\windows\\win32\\"))) (ensure?? "serialize;deserialize" (let [b (u/serialize {:a 1}) m (u/deserialize b)] (== 1 (:a m)))) (ensure?? "serialize;deserialize" (let [b (u/serialize (Exception. "hi")) e (u/deserialize b)] (= "hi" (.getMessage ^Exception e)))) (ensure?? "gczn" (= "String" (u/gczn "a"))) (ensure?? "get-class-name" (= "java.lang.String" (u/get-class-name "a"))) (ensure?? "is-windows?;is-macos?;is-linux?" (let [m (u/is-macos?) x (u/is-linux?) w (u/is-windows?)] (cond m (and (not x)(not w)) w (and (not m)(not x)) x (and (not w)(not m))))) (ensure?? "x->str;x->chars;x->bytes" (let [c0 (u/x->chars "hello") b0 (u/x->bytes c0) s0 (u/x->str c0) b1 (u/x->bytes s0) s1 (u/x->str b1) s2 (u/x->str b0)] (and (= s0 s1) (= s1 s2)))) (ensure?? "load-java-props" (let [p (u/load-java-props (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) p1 (.getProperty p "test") p2 (.getProperty p "test2")] (and (string? p1) (string? p2) (= p1 p2)))) (ensure?? "deflate;inflate" (let [b (u/deflate (u/x->bytes "hello joe")) s (u/x->str (u/inflate b))] (= s "hello joe"))) (ensure?? "safe-fpath" (let [s (u/safe-fpath "/tmp/abc def")] (= s "0x2ftmp0x2fabc0x20def"))) (ensure?? "fmt-file-url" (= (u/fmt-file-url "/tmp/a.txt") (u/fmt-file-url "file:/tmp/a.txt"))) (ensure?? "get-fpath" (let [u (u/fmt-file-url "file:/tmp/a.txt")] (= "/tmp/a.txt" (u/get-fpath u)))) (ensure?? "root-cause" (let [a (Exception. "a") b (Exception. a) c (Exception. b)] (identical? a (u/root-cause c)))) (ensure?? "root-cause-msg" (let [a (Exception. "a") b (Exception. a) c (Exception. b)] (= "a" (.getMessage (u/root-cause c))))) (ensure?? "pmap<>" (let [p (u/load-java-props (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) m (u/pmap<> p)] (and (string? (:test m)) (= (:test2 m) (:test m))))) (ensure?? "tmtask<>;cancel-timer-task!" (let [a (atom 0) t (u/tmtask<> #(reset! a 3))] (and (c/is? TimerTask t) (do (.run t) (u/cancel-timer-task! t) (== 3 @a))))) ;(ensure?? "prt-stk" (u/prt-stk (Exception. "e"))) (ensure?? "dump-stk" (let [s (u/dump-stk (Exception. "e"))] (and (string? s) (pos? (count s))))) (ensure?? "x->java" (let [obj (u/x->java {:a 1 :b #{1 2 3} :c [7 8 {:z 3}]}) m (c/cast? Map obj) _ (if (nil? m) (c/raise! "expect Map1")) a (.get m "a") b (c/cast? Set (.get m "b")) _ (if (nil? b) (c/raise! "expect Set")) c (c/cast? List (.get m "c")) _ (if (nil? c) (c/raise! "expect List")) z (c/cast? Map (.get c 2)) _ (if (nil? z) (c/raise! "expect Map3")) z3 (.get z "z")] (and (== 1 a) (== 3 (.size b)) (and (== 7 (.get c 0)) (== 8 (.get c 1))) (== 3 z3)))) (ensure?? "seqint" (let [old (u/seqint) a (u/seqint) b (u/seqint)] (and (= a (+ 1 old)) (= b (+ 1 a))))) (ensure?? "seqint2" (let [old (u/seqint2) a (u/seqint2) b (u/seqint2)] (and (= a (+ 1 old)) (= b (+ 1 a))))) (ensure?? "count-cpus" (pos? (u/count-cpus))) (ensure?? "sys-tmp-dir" (let [f (new File (u/sys-tmp-dir))] (.exists f))) (ensure?? "obj-eq?" (let [a (String. "a") b (String. "a")] (u/obj-eq? a b))) (ensure?? "url-encode;url-decode" (let [s (u/url-encode "a+c+b") z (u/url-decode s)] (= z "a+c+b"))) (ensure?? "sortby" (let [c [{:age 5} {:age 3} {:age 1} {:age 2}] a (u/sortby :age (c/compare-asc*) c) d (u/sortby :age (c/compare-des*) c)] (and (= [1 2 3 5] (mapv #(:age %) a)) (= [5 3 2 1] (mapv #(:age %) d))))) (ensure?? "new-memset" (let [m (u/new-memset<> 2) _ (u/ms-add m (atom {:a 1})) z0 (u/ms-count m)] (u/ms-add m (atom {:a 2})) (u/ms-add m (atom {:a 3})) (and (== 1 z0) (== 3 (u/ms-count m)) (== 4 (u/ms-capacity m))))) (ensure?? "each-set" (let [acc (atom 0) m (u/new-memset<> 2)] (u/ms-add m (atom {:a 1})) (u/ms-add m (atom {:a 2})) (u/ms-each m (fn [obj _] (swap! acc + (:a @obj)))) (== 3 @acc))) (ensure?? "drop->set!" (let [m (u/new-memset<> 2) a (atom {:a 1}) b (atom {:a 1})] (u/ms-add m a) (u/ms-add m b) (u/ms-drop m a) (u/ms-drop m b) (zero? (u/ms-count m)))) (ensure?? "get-cldr" (not (nil? (u/get-cldr)))) (ensure?? "set-cldr" (do (u/set-cldr (u/get-cldr)) true)) (ensure?? "load-resource" (= "hello joe, how is your dawg" (-> (u/load-resource (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) (u/rstr "test" "joe" "dawg" )))) (ensure?? "load-resource" (= ["hello joe, how is your dawg" "hello joe, how is your dawg"] (-> (u/load-resource (-> (u/get-cldr) (.getResource "czlab/basal/etc/Resources_en.properties"))) (u/rstr* ["test" "joe" "dawg"] ["test2" "joe" "dawg"] )))) (ensure?? "get-resource" (c/is? ResourceBundle (u/get-resource "czlab/basal/etc/Resources"))) (ensure?? "shuffle" (and (not= "abcde" (u/shuffle "abcde")) (== 3 (count (u/shuffle "abc"))))) (ensure?? "cljrt<>" (let [rt (u/cljrt<>) m (u/call* rt :czlab.basal.util/emsg [(Exception. "hello world")]) v (u/var* rt :czlab.basal.util/cljrt<>)] (and (= "hello world" m) (var? v)))) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ct/deftest ^:test-util basal-test-util (ct/is (c/clj-test?? test-util))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": ";;; singleton.clj: singleton functions\n\n;; by Stuart Sierra, http://stuartsierra.com/\n;; April 14, 2009\n\n;; C", "end": 59, "score": 0.9999000430107117, "start": 46, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "artsierra.com/\n;; April 14, 2009\n\n;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use\n;; and distr", "end": 135, "score": 0.9998947381973267, "start": 122, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "ril 9, 2009: initial version\n\n\n(ns \n #^{:author \"Stuart Sierra\",\n :doc \"Singleton functions\"}\n clojure.cont", "end": 751, "score": 0.9996652603149414, "start": 738, "tag": "NAME", "value": "Stuart Sierra" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/singleton.clj
allertonm/Couverjure
3
;;; singleton.clj: singleton functions ;; by Stuart Sierra, http://stuartsierra.com/ ;; April 14, 2009 ;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; Change Log: ;; ;; April 14, 2009: added per-thread-singleton, renamed singleton to ;; global-singleton ;; ;; April 9, 2009: initial version (ns #^{:author "Stuart Sierra", :doc "Singleton functions"} clojure.contrib.singleton) (defn global-singleton "Returns a global singleton function. f is a function of no arguments that creates and returns some object. The singleton function will call f just once, the first time it is needed, and cache the value for all subsequent calls. Warning: global singletons are often unsafe in multi-threaded code. Consider per-thread-singleton instead." [f] (let [instance (atom nil) make-instance (fn [_] (f))] (fn [] (or @instance (swap! instance make-instance))))) (defn per-thread-singleton "Returns a per-thread singleton function. f is a function of no arguments that creates and returns some object. The singleton function will call f only once for each thread, and cache its value for subsequent calls from the same thread. This allows you to safely and lazily initialize shared objects on a per-thread basis. Warning: due to a bug in JDK 5, it may not be safe to use a per-thread-singleton in the initialization function for another per-thread-singleton. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230" [f] (let [thread-local (proxy [ThreadLocal] [] (initialValue [] (f)))] (fn [] (.get thread-local))))
105328
;;; singleton.clj: singleton functions ;; by <NAME>, http://stuartsierra.com/ ;; April 14, 2009 ;; Copyright (c) <NAME>, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; Change Log: ;; ;; April 14, 2009: added per-thread-singleton, renamed singleton to ;; global-singleton ;; ;; April 9, 2009: initial version (ns #^{:author "<NAME>", :doc "Singleton functions"} clojure.contrib.singleton) (defn global-singleton "Returns a global singleton function. f is a function of no arguments that creates and returns some object. The singleton function will call f just once, the first time it is needed, and cache the value for all subsequent calls. Warning: global singletons are often unsafe in multi-threaded code. Consider per-thread-singleton instead." [f] (let [instance (atom nil) make-instance (fn [_] (f))] (fn [] (or @instance (swap! instance make-instance))))) (defn per-thread-singleton "Returns a per-thread singleton function. f is a function of no arguments that creates and returns some object. The singleton function will call f only once for each thread, and cache its value for subsequent calls from the same thread. This allows you to safely and lazily initialize shared objects on a per-thread basis. Warning: due to a bug in JDK 5, it may not be safe to use a per-thread-singleton in the initialization function for another per-thread-singleton. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230" [f] (let [thread-local (proxy [ThreadLocal] [] (initialValue [] (f)))] (fn [] (.get thread-local))))
true
;;; singleton.clj: singleton functions ;; by PI:NAME:<NAME>END_PI, http://stuartsierra.com/ ;; April 14, 2009 ;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; Change Log: ;; ;; April 14, 2009: added per-thread-singleton, renamed singleton to ;; global-singleton ;; ;; April 9, 2009: initial version (ns #^{:author "PI:NAME:<NAME>END_PI", :doc "Singleton functions"} clojure.contrib.singleton) (defn global-singleton "Returns a global singleton function. f is a function of no arguments that creates and returns some object. The singleton function will call f just once, the first time it is needed, and cache the value for all subsequent calls. Warning: global singletons are often unsafe in multi-threaded code. Consider per-thread-singleton instead." [f] (let [instance (atom nil) make-instance (fn [_] (f))] (fn [] (or @instance (swap! instance make-instance))))) (defn per-thread-singleton "Returns a per-thread singleton function. f is a function of no arguments that creates and returns some object. The singleton function will call f only once for each thread, and cache its value for subsequent calls from the same thread. This allows you to safely and lazily initialize shared objects on a per-thread basis. Warning: due to a bug in JDK 5, it may not be safe to use a per-thread-singleton in the initialization function for another per-thread-singleton. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230" [f] (let [thread-local (proxy [ThreadLocal] [] (initialValue [] (f)))] (fn [] (.get thread-local))))
[ { "context": "et-initial-state\n (fn []\n {:file-input-key (gensym \"file-input-\")})\n :render\n (fn [{:keys [state", "end": 503, "score": 0.9225755929946899, "start": 497, "tag": "KEY", "value": "gensym" }, { "context": "al-state\n (fn []\n {:file-input-key (gensym \"file-input-\")})\n :render\n (fn [{:keys [state refs this]}]", "end": 516, "score": 0.9587728977203369, "start": 505, "tag": "KEY", "value": "file-input-" }, { "context": " :file-input-key (gensym \"file-input-\")))\n ", "end": 1865, "score": 0.8369988799095154, "start": 1859, "tag": "KEY", "value": "gensym" }, { "context": " :file-input-key (gensym \"file-input-\")))\n (.readAsText", "end": 1878, "score": 0.9380658864974976, "start": 1867, "tag": "KEY", "value": "file-input-" } ]
src/cljs/main/broadfcui/page/workspace/data/import_data.cljs
epam/firecloud-ui
0
(ns broadfcui.page.workspace.data.import-data (:require [dmohs.react :as react] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.style :as style] [broadfcui.components.buttons :as buttons] [broadfcui.endpoints :as endpoints] [broadfcui.page.workspace.workspace-common :as ws-common] [broadfcui.utils :as utils] )) (def ^:private preview-limit 4096) (react/defc Page {:get-initial-state (fn [] {:file-input-key (gensym "file-input-")}) :render (fn [{:keys [state refs this]}] (let [{:keys [loading? file-input-key file-contents file upload-result]} @state] [:div {:style {:textAlign "center"} :data-test-id "data-upload-container"} (when loading? [comps/Blocker {:banner "Uploading file..."}]) ;; This key is changed every time a file is selected causing React to completely replace the ;; element. Otherwise, if a user selects the same file (even after having modified it), the ;; browser will not fire the onChange event. [:input {:key file-input-key :data-test-id "data-upload-input" :type "file" :name "entities" :ref "entities" :style {:display "none"} :onChange (fn [e] (let [file (-> e .-target .-files (aget 0)) reader (js/FileReader.)] (when file (swap! state dissoc :upload-result) (set! (.-onload reader) #(swap! state assoc :file file :file-contents (.-result reader) :file-input-key (gensym "file-input-"))) (.readAsText reader (.slice file 0 preview-limit)))))}] ws-common/PHI-warning [buttons/Button {:data-test-id "choose-file-button" :text (if (:upload-result @state) "Choose another file..." "Choose file...") :onClick #(-> (@refs "entities") .click)}] (when file-contents [:div {:style {:margin "0.5em 2em" :padding "0.5em" :border style/standard-line}} (str "Previewing '" (.. (:file @state) -name) "':") [:div {:style {:overflow "auto" :maxHeight 200 :paddingBottom "0.5em" :textAlign "left"}} [:pre {} file-contents] (when (> (.-size file) preview-limit) [:em {} "(file truncated for preview)"])]]) (when (and file (not upload-result)) [buttons/Button {:data-test-id "confirm-upload-metadata-button" :text "Upload" :onClick #(this :do-upload)}]) (when upload-result (if (:success? upload-result) (style/create-flexbox {:style {:justifyContent "center" :paddingTop "1em"}} (icons/render-icon {:style {:fontSize "200%" :color (:success-state style/colors)}} :done) [:span {:style {:marginLeft "1em"} :data-test-id "upload-success-message"} "Success!"]) [:div {:style {:paddingTop "1em"}} [comps/ErrorViewer {:error (:error upload-result)}]]))])) :do-upload (fn [{:keys [props state]}] (swap! state assoc :loading? true) (endpoints/call-ajax-orch {:endpoint ((if (= "data" (:import-type props)) endpoints/import-entities endpoints/import-attributes) (:workspace-id props)) :raw-data (utils/generate-form-data {(if (= "data" (:import-type props)) :entities :attributes) (:file @state)}) :encType "multipart/form-data" :on-done (fn [{:keys [success? get-parsed-response]}] (swap! state dissoc :loading? :file :file-contents) (if success? (do (swap! state assoc :upload-result {:success? true}) ((:on-data-imported props))) (swap! state assoc :upload-result {:success? false :error (get-parsed-response false)})))}))})
25922
(ns broadfcui.page.workspace.data.import-data (:require [dmohs.react :as react] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.style :as style] [broadfcui.components.buttons :as buttons] [broadfcui.endpoints :as endpoints] [broadfcui.page.workspace.workspace-common :as ws-common] [broadfcui.utils :as utils] )) (def ^:private preview-limit 4096) (react/defc Page {:get-initial-state (fn [] {:file-input-key (<KEY> "<KEY>")}) :render (fn [{:keys [state refs this]}] (let [{:keys [loading? file-input-key file-contents file upload-result]} @state] [:div {:style {:textAlign "center"} :data-test-id "data-upload-container"} (when loading? [comps/Blocker {:banner "Uploading file..."}]) ;; This key is changed every time a file is selected causing React to completely replace the ;; element. Otherwise, if a user selects the same file (even after having modified it), the ;; browser will not fire the onChange event. [:input {:key file-input-key :data-test-id "data-upload-input" :type "file" :name "entities" :ref "entities" :style {:display "none"} :onChange (fn [e] (let [file (-> e .-target .-files (aget 0)) reader (js/FileReader.)] (when file (swap! state dissoc :upload-result) (set! (.-onload reader) #(swap! state assoc :file file :file-contents (.-result reader) :file-input-key (<KEY> "<KEY>"))) (.readAsText reader (.slice file 0 preview-limit)))))}] ws-common/PHI-warning [buttons/Button {:data-test-id "choose-file-button" :text (if (:upload-result @state) "Choose another file..." "Choose file...") :onClick #(-> (@refs "entities") .click)}] (when file-contents [:div {:style {:margin "0.5em 2em" :padding "0.5em" :border style/standard-line}} (str "Previewing '" (.. (:file @state) -name) "':") [:div {:style {:overflow "auto" :maxHeight 200 :paddingBottom "0.5em" :textAlign "left"}} [:pre {} file-contents] (when (> (.-size file) preview-limit) [:em {} "(file truncated for preview)"])]]) (when (and file (not upload-result)) [buttons/Button {:data-test-id "confirm-upload-metadata-button" :text "Upload" :onClick #(this :do-upload)}]) (when upload-result (if (:success? upload-result) (style/create-flexbox {:style {:justifyContent "center" :paddingTop "1em"}} (icons/render-icon {:style {:fontSize "200%" :color (:success-state style/colors)}} :done) [:span {:style {:marginLeft "1em"} :data-test-id "upload-success-message"} "Success!"]) [:div {:style {:paddingTop "1em"}} [comps/ErrorViewer {:error (:error upload-result)}]]))])) :do-upload (fn [{:keys [props state]}] (swap! state assoc :loading? true) (endpoints/call-ajax-orch {:endpoint ((if (= "data" (:import-type props)) endpoints/import-entities endpoints/import-attributes) (:workspace-id props)) :raw-data (utils/generate-form-data {(if (= "data" (:import-type props)) :entities :attributes) (:file @state)}) :encType "multipart/form-data" :on-done (fn [{:keys [success? get-parsed-response]}] (swap! state dissoc :loading? :file :file-contents) (if success? (do (swap! state assoc :upload-result {:success? true}) ((:on-data-imported props))) (swap! state assoc :upload-result {:success? false :error (get-parsed-response false)})))}))})
true
(ns broadfcui.page.workspace.data.import-data (:require [dmohs.react :as react] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.style :as style] [broadfcui.components.buttons :as buttons] [broadfcui.endpoints :as endpoints] [broadfcui.page.workspace.workspace-common :as ws-common] [broadfcui.utils :as utils] )) (def ^:private preview-limit 4096) (react/defc Page {:get-initial-state (fn [] {:file-input-key (PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI")}) :render (fn [{:keys [state refs this]}] (let [{:keys [loading? file-input-key file-contents file upload-result]} @state] [:div {:style {:textAlign "center"} :data-test-id "data-upload-container"} (when loading? [comps/Blocker {:banner "Uploading file..."}]) ;; This key is changed every time a file is selected causing React to completely replace the ;; element. Otherwise, if a user selects the same file (even after having modified it), the ;; browser will not fire the onChange event. [:input {:key file-input-key :data-test-id "data-upload-input" :type "file" :name "entities" :ref "entities" :style {:display "none"} :onChange (fn [e] (let [file (-> e .-target .-files (aget 0)) reader (js/FileReader.)] (when file (swap! state dissoc :upload-result) (set! (.-onload reader) #(swap! state assoc :file file :file-contents (.-result reader) :file-input-key (PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"))) (.readAsText reader (.slice file 0 preview-limit)))))}] ws-common/PHI-warning [buttons/Button {:data-test-id "choose-file-button" :text (if (:upload-result @state) "Choose another file..." "Choose file...") :onClick #(-> (@refs "entities") .click)}] (when file-contents [:div {:style {:margin "0.5em 2em" :padding "0.5em" :border style/standard-line}} (str "Previewing '" (.. (:file @state) -name) "':") [:div {:style {:overflow "auto" :maxHeight 200 :paddingBottom "0.5em" :textAlign "left"}} [:pre {} file-contents] (when (> (.-size file) preview-limit) [:em {} "(file truncated for preview)"])]]) (when (and file (not upload-result)) [buttons/Button {:data-test-id "confirm-upload-metadata-button" :text "Upload" :onClick #(this :do-upload)}]) (when upload-result (if (:success? upload-result) (style/create-flexbox {:style {:justifyContent "center" :paddingTop "1em"}} (icons/render-icon {:style {:fontSize "200%" :color (:success-state style/colors)}} :done) [:span {:style {:marginLeft "1em"} :data-test-id "upload-success-message"} "Success!"]) [:div {:style {:paddingTop "1em"}} [comps/ErrorViewer {:error (:error upload-result)}]]))])) :do-upload (fn [{:keys [props state]}] (swap! state assoc :loading? true) (endpoints/call-ajax-orch {:endpoint ((if (= "data" (:import-type props)) endpoints/import-entities endpoints/import-attributes) (:workspace-id props)) :raw-data (utils/generate-form-data {(if (= "data" (:import-type props)) :entities :attributes) (:file @state)}) :encType "multipart/form-data" :on-done (fn [{:keys [success? get-parsed-response]}] (swap! state dissoc :loading? :file :file-contents) (if success? (do (swap! state assoc :upload-result {:success? true}) ((:on-data-imported props))) (swap! state assoc :upload-result {:success? false :error (get-parsed-response false)})))}))})
[ { "context": "lly based on the ACL SNePS 3 implementation by Dr. Stuart C. Shapiro.\n\n(in-ns 'zinc.core.build)\n\n(declare structurally", "end": 77, "score": 0.9998753666877747, "start": 60, "tag": "NAME", "value": "Stuart C. Shapiro" } ]
src/clj/zinc/core/build_substitution.clj
martinodb/Zinc
0
; Originally based on the ACL SNePS 3 implementation by Dr. Stuart C. Shapiro. (in-ns 'zinc.core.build) (declare structurally-subsumes-varterm parse-vars-and-rsts check-and-build-variables notsames pre-build-vars build-vars build-quantterm-channels) (defn apply-sub-to-term ([term subst] (apply-sub-to-term term subst nil)) ([term subst ignore-type] (if (or (= (:type term) :zinc.core/Atom) (= subst {})) term (binding [zinc.core.printer/PRINTED-VARIABLES (hash-set) zinc.core.printer/PRINTED-VARIABLE-LABELS (hash-map)] (let [expr (read-string (zinc.core.printer/print-unnamed-molecular-term term)) [new-expr arb-rsts ind-dep-rsts qvar-rsts] (dosync (parse-vars-and-rsts expr {} {} {})) [new-expr built-vars substitution] (dosync (check-and-build-variables expr :reuse-inds true)) ;; expr is something like: (Carries (every x (Owns x (every y (Isa y Dog))) (Isa x Person)) y) ;; new-expr is something like: (Carries x y) ;; arb-rsts is something like: {x [[Isa x Person] [Owns x y]], y [[Isa y Dog]]} ;; subst contains something like: {arb1 Toto} ;; substitution contains something like: {y arb1} ;; by combining these we can know which vars we wanted to replace in new-expr and the rsts. replace-subst (into {} (for [[k v] substitution :when (and (subst v) (not (variableTerm? (subst v))))] [k (subst v)])) new-expr (postwalk-replace replace-subst new-expr) arb-rsts (into {} (for [[k v] arb-rsts :when (not (replace-subst k))] [k (postwalk-replace replace-subst v)])) qvar-rsts (into {} (for [[k v] qvar-rsts :when (not (replace-subst k))] [k (postwalk-replace replace-subst v)])) ind-dep-rsts (into {} (for [[k v] ind-dep-rsts :when (not (replace-subst k)) :let [[dep expr] v]] [k (list (remove (set (keys replace-subst)) dep) (postwalk-replace replace-subst expr))])) [arb-rsts qvar-rsts ind-dep-rsts notsames] (notsames arb-rsts qvar-rsts ind-dep-rsts) substitution (dosync (pre-build-vars arb-rsts ind-dep-rsts qvar-rsts notsames :reuse-inds true)) substitution (into {} (for [[k v] substitution] (if (and (subst v) (variableTerm? (subst v))) [k (subst v)] [k v]))) built-vars (dosync (build-vars arb-rsts ind-dep-rsts qvar-rsts substitution notsames))] (doseq [v (seq built-vars)] (doseq [rst (seq (@restriction-set v))] (when-not (whquestion-term? rst) ;; It doesn't make sense to assert a WhQuestion. (assert rst (ct/find-context 'BaseCT)))) (build-quantterm-channels v)) (build new-expr (if ignore-type :Entity (semantic-type-of term)) substitution #{})))))) ;; Ex: subs1: {arb2: (every x (Isa x Cat)) arb1: (every x (Isa x Entity))} ;; subs2: {arb1: (every x (Isa x Entity)) cat!} ;; Result: {arb2: (every x (Isa x Cat)) cat!, arb1: (every x (Isa x Entity)) cat!} (defn substitution-application "Apples the substitution subs2 to subs1" [subs1 subs2] (let [compose (map (fn [[k v]] [k (apply-sub-to-term v subs2)]) subs1)] (into subs2 compose))) ;(clojure.core/merge subs2 (into {} compose)))) ;; Ex: subs2: {arb1: (every x (Isa x Cat)) cat} ;; subs1: {arb2: (every x (Isa x BlahBlah)) arb1: (every x (Isa x Cat))} ;; Result: {arb2: (every x (Isa x BlahBlah)) cat} (defn substitution-application-nomerge [subs1 subs2] (into {} (map (fn [[k v]] [k (apply-sub-to-term v subs2)]) subs1))) (defn subst-occurs-helper "Returns true if when compare-subst contains a substitution for any variable inside var, it also binds var, unless there's an identical binding already in var-subst." ;; TODO: Must it bind ALL of the inner vars? [var var-subs compare-subs] (let [inner-vars (get-vars var :inner-vars? true) binds (set (keys compare-subs)) shared-binds (set/intersection binds inner-vars)] (if-not (empty? shared-binds) (or (binds var) (every? #(= (var-subs %) (compare-subs %)) shared-binds)) true))) (defn substitution-occurs-check "Ensures that whenever a variable is used in a substitution, the substitution it is combined with does not contain bindings for inner variables without a binding for the parent, or, if it does, that the inner variable binding isn't identical between the two substitutions." [subs1 subs2] (and (every? #(subst-occurs-helper % subs2 subs1) (keys subs2)) (every? #(subst-occurs-helper % subs1 subs2) (keys subs1)))) (defn compatible-substitutions? "Returns true if no variable is bound to two different terms." [subs1 subs2] ;; Verify no single variable is bound to different terms, and ;; no notSame variables are assigned the same term. (and (every? #(or (= (subs1 %) (subs2 %)) (nil? (subs2 %))) (keys subs1)) (substitution-occurs-check subs1 subs2) (every? true? (for [var (set/union (keys subs1) (keys subs2)) :let [notsames @(:not-same-as var) binding (or (subs1 var) (subs2 var))]] (every? #(not= binding (or (subs1 %) (subs2 %))) notsames))))) (defn subsumption-compatible? "Returns true if: 1) No variable is bound to two different terms. 2) A variable is bound by two different terms, of which one of them is a variable, and they are compatible by structural subsumption." [subs1 subs2] (every? #(or (= (% subs1) (% subs2)) (nil? (% subs2)) (and (variable? (% subs1)) (structurally-subsumes-varterm (% subs1) (% subs2))) (and (variable? (% subs2)) (structurally-subsumes-varterm (% subs2) (% subs1)))) (keys subs1))) ;(defn subset? ; "Returns true if subs1 is a subset of subs2" ; [subs1 subs2] ; (every? #(= (subs1 %) (subs2 %)) (keys subs1))) (defn expand-substitution "Given a term and a substitution, examines the term for embedded vars which use terms in the substitution. Builds a new substitution with those terms substituted for." [term subst] (let [term-vars (set/difference (get-vars term) (set (keys subst)))] (if-not (empty? term-vars) (into {} (map #(vector % (apply-sub-to-term % subst)) term-vars)))))
42953
; Originally based on the ACL SNePS 3 implementation by Dr. <NAME>. (in-ns 'zinc.core.build) (declare structurally-subsumes-varterm parse-vars-and-rsts check-and-build-variables notsames pre-build-vars build-vars build-quantterm-channels) (defn apply-sub-to-term ([term subst] (apply-sub-to-term term subst nil)) ([term subst ignore-type] (if (or (= (:type term) :zinc.core/Atom) (= subst {})) term (binding [zinc.core.printer/PRINTED-VARIABLES (hash-set) zinc.core.printer/PRINTED-VARIABLE-LABELS (hash-map)] (let [expr (read-string (zinc.core.printer/print-unnamed-molecular-term term)) [new-expr arb-rsts ind-dep-rsts qvar-rsts] (dosync (parse-vars-and-rsts expr {} {} {})) [new-expr built-vars substitution] (dosync (check-and-build-variables expr :reuse-inds true)) ;; expr is something like: (Carries (every x (Owns x (every y (Isa y Dog))) (Isa x Person)) y) ;; new-expr is something like: (Carries x y) ;; arb-rsts is something like: {x [[Isa x Person] [Owns x y]], y [[Isa y Dog]]} ;; subst contains something like: {arb1 Toto} ;; substitution contains something like: {y arb1} ;; by combining these we can know which vars we wanted to replace in new-expr and the rsts. replace-subst (into {} (for [[k v] substitution :when (and (subst v) (not (variableTerm? (subst v))))] [k (subst v)])) new-expr (postwalk-replace replace-subst new-expr) arb-rsts (into {} (for [[k v] arb-rsts :when (not (replace-subst k))] [k (postwalk-replace replace-subst v)])) qvar-rsts (into {} (for [[k v] qvar-rsts :when (not (replace-subst k))] [k (postwalk-replace replace-subst v)])) ind-dep-rsts (into {} (for [[k v] ind-dep-rsts :when (not (replace-subst k)) :let [[dep expr] v]] [k (list (remove (set (keys replace-subst)) dep) (postwalk-replace replace-subst expr))])) [arb-rsts qvar-rsts ind-dep-rsts notsames] (notsames arb-rsts qvar-rsts ind-dep-rsts) substitution (dosync (pre-build-vars arb-rsts ind-dep-rsts qvar-rsts notsames :reuse-inds true)) substitution (into {} (for [[k v] substitution] (if (and (subst v) (variableTerm? (subst v))) [k (subst v)] [k v]))) built-vars (dosync (build-vars arb-rsts ind-dep-rsts qvar-rsts substitution notsames))] (doseq [v (seq built-vars)] (doseq [rst (seq (@restriction-set v))] (when-not (whquestion-term? rst) ;; It doesn't make sense to assert a WhQuestion. (assert rst (ct/find-context 'BaseCT)))) (build-quantterm-channels v)) (build new-expr (if ignore-type :Entity (semantic-type-of term)) substitution #{})))))) ;; Ex: subs1: {arb2: (every x (Isa x Cat)) arb1: (every x (Isa x Entity))} ;; subs2: {arb1: (every x (Isa x Entity)) cat!} ;; Result: {arb2: (every x (Isa x Cat)) cat!, arb1: (every x (Isa x Entity)) cat!} (defn substitution-application "Apples the substitution subs2 to subs1" [subs1 subs2] (let [compose (map (fn [[k v]] [k (apply-sub-to-term v subs2)]) subs1)] (into subs2 compose))) ;(clojure.core/merge subs2 (into {} compose)))) ;; Ex: subs2: {arb1: (every x (Isa x Cat)) cat} ;; subs1: {arb2: (every x (Isa x BlahBlah)) arb1: (every x (Isa x Cat))} ;; Result: {arb2: (every x (Isa x BlahBlah)) cat} (defn substitution-application-nomerge [subs1 subs2] (into {} (map (fn [[k v]] [k (apply-sub-to-term v subs2)]) subs1))) (defn subst-occurs-helper "Returns true if when compare-subst contains a substitution for any variable inside var, it also binds var, unless there's an identical binding already in var-subst." ;; TODO: Must it bind ALL of the inner vars? [var var-subs compare-subs] (let [inner-vars (get-vars var :inner-vars? true) binds (set (keys compare-subs)) shared-binds (set/intersection binds inner-vars)] (if-not (empty? shared-binds) (or (binds var) (every? #(= (var-subs %) (compare-subs %)) shared-binds)) true))) (defn substitution-occurs-check "Ensures that whenever a variable is used in a substitution, the substitution it is combined with does not contain bindings for inner variables without a binding for the parent, or, if it does, that the inner variable binding isn't identical between the two substitutions." [subs1 subs2] (and (every? #(subst-occurs-helper % subs2 subs1) (keys subs2)) (every? #(subst-occurs-helper % subs1 subs2) (keys subs1)))) (defn compatible-substitutions? "Returns true if no variable is bound to two different terms." [subs1 subs2] ;; Verify no single variable is bound to different terms, and ;; no notSame variables are assigned the same term. (and (every? #(or (= (subs1 %) (subs2 %)) (nil? (subs2 %))) (keys subs1)) (substitution-occurs-check subs1 subs2) (every? true? (for [var (set/union (keys subs1) (keys subs2)) :let [notsames @(:not-same-as var) binding (or (subs1 var) (subs2 var))]] (every? #(not= binding (or (subs1 %) (subs2 %))) notsames))))) (defn subsumption-compatible? "Returns true if: 1) No variable is bound to two different terms. 2) A variable is bound by two different terms, of which one of them is a variable, and they are compatible by structural subsumption." [subs1 subs2] (every? #(or (= (% subs1) (% subs2)) (nil? (% subs2)) (and (variable? (% subs1)) (structurally-subsumes-varterm (% subs1) (% subs2))) (and (variable? (% subs2)) (structurally-subsumes-varterm (% subs2) (% subs1)))) (keys subs1))) ;(defn subset? ; "Returns true if subs1 is a subset of subs2" ; [subs1 subs2] ; (every? #(= (subs1 %) (subs2 %)) (keys subs1))) (defn expand-substitution "Given a term and a substitution, examines the term for embedded vars which use terms in the substitution. Builds a new substitution with those terms substituted for." [term subst] (let [term-vars (set/difference (get-vars term) (set (keys subst)))] (if-not (empty? term-vars) (into {} (map #(vector % (apply-sub-to-term % subst)) term-vars)))))
true
; Originally based on the ACL SNePS 3 implementation by Dr. PI:NAME:<NAME>END_PI. (in-ns 'zinc.core.build) (declare structurally-subsumes-varterm parse-vars-and-rsts check-and-build-variables notsames pre-build-vars build-vars build-quantterm-channels) (defn apply-sub-to-term ([term subst] (apply-sub-to-term term subst nil)) ([term subst ignore-type] (if (or (= (:type term) :zinc.core/Atom) (= subst {})) term (binding [zinc.core.printer/PRINTED-VARIABLES (hash-set) zinc.core.printer/PRINTED-VARIABLE-LABELS (hash-map)] (let [expr (read-string (zinc.core.printer/print-unnamed-molecular-term term)) [new-expr arb-rsts ind-dep-rsts qvar-rsts] (dosync (parse-vars-and-rsts expr {} {} {})) [new-expr built-vars substitution] (dosync (check-and-build-variables expr :reuse-inds true)) ;; expr is something like: (Carries (every x (Owns x (every y (Isa y Dog))) (Isa x Person)) y) ;; new-expr is something like: (Carries x y) ;; arb-rsts is something like: {x [[Isa x Person] [Owns x y]], y [[Isa y Dog]]} ;; subst contains something like: {arb1 Toto} ;; substitution contains something like: {y arb1} ;; by combining these we can know which vars we wanted to replace in new-expr and the rsts. replace-subst (into {} (for [[k v] substitution :when (and (subst v) (not (variableTerm? (subst v))))] [k (subst v)])) new-expr (postwalk-replace replace-subst new-expr) arb-rsts (into {} (for [[k v] arb-rsts :when (not (replace-subst k))] [k (postwalk-replace replace-subst v)])) qvar-rsts (into {} (for [[k v] qvar-rsts :when (not (replace-subst k))] [k (postwalk-replace replace-subst v)])) ind-dep-rsts (into {} (for [[k v] ind-dep-rsts :when (not (replace-subst k)) :let [[dep expr] v]] [k (list (remove (set (keys replace-subst)) dep) (postwalk-replace replace-subst expr))])) [arb-rsts qvar-rsts ind-dep-rsts notsames] (notsames arb-rsts qvar-rsts ind-dep-rsts) substitution (dosync (pre-build-vars arb-rsts ind-dep-rsts qvar-rsts notsames :reuse-inds true)) substitution (into {} (for [[k v] substitution] (if (and (subst v) (variableTerm? (subst v))) [k (subst v)] [k v]))) built-vars (dosync (build-vars arb-rsts ind-dep-rsts qvar-rsts substitution notsames))] (doseq [v (seq built-vars)] (doseq [rst (seq (@restriction-set v))] (when-not (whquestion-term? rst) ;; It doesn't make sense to assert a WhQuestion. (assert rst (ct/find-context 'BaseCT)))) (build-quantterm-channels v)) (build new-expr (if ignore-type :Entity (semantic-type-of term)) substitution #{})))))) ;; Ex: subs1: {arb2: (every x (Isa x Cat)) arb1: (every x (Isa x Entity))} ;; subs2: {arb1: (every x (Isa x Entity)) cat!} ;; Result: {arb2: (every x (Isa x Cat)) cat!, arb1: (every x (Isa x Entity)) cat!} (defn substitution-application "Apples the substitution subs2 to subs1" [subs1 subs2] (let [compose (map (fn [[k v]] [k (apply-sub-to-term v subs2)]) subs1)] (into subs2 compose))) ;(clojure.core/merge subs2 (into {} compose)))) ;; Ex: subs2: {arb1: (every x (Isa x Cat)) cat} ;; subs1: {arb2: (every x (Isa x BlahBlah)) arb1: (every x (Isa x Cat))} ;; Result: {arb2: (every x (Isa x BlahBlah)) cat} (defn substitution-application-nomerge [subs1 subs2] (into {} (map (fn [[k v]] [k (apply-sub-to-term v subs2)]) subs1))) (defn subst-occurs-helper "Returns true if when compare-subst contains a substitution for any variable inside var, it also binds var, unless there's an identical binding already in var-subst." ;; TODO: Must it bind ALL of the inner vars? [var var-subs compare-subs] (let [inner-vars (get-vars var :inner-vars? true) binds (set (keys compare-subs)) shared-binds (set/intersection binds inner-vars)] (if-not (empty? shared-binds) (or (binds var) (every? #(= (var-subs %) (compare-subs %)) shared-binds)) true))) (defn substitution-occurs-check "Ensures that whenever a variable is used in a substitution, the substitution it is combined with does not contain bindings for inner variables without a binding for the parent, or, if it does, that the inner variable binding isn't identical between the two substitutions." [subs1 subs2] (and (every? #(subst-occurs-helper % subs2 subs1) (keys subs2)) (every? #(subst-occurs-helper % subs1 subs2) (keys subs1)))) (defn compatible-substitutions? "Returns true if no variable is bound to two different terms." [subs1 subs2] ;; Verify no single variable is bound to different terms, and ;; no notSame variables are assigned the same term. (and (every? #(or (= (subs1 %) (subs2 %)) (nil? (subs2 %))) (keys subs1)) (substitution-occurs-check subs1 subs2) (every? true? (for [var (set/union (keys subs1) (keys subs2)) :let [notsames @(:not-same-as var) binding (or (subs1 var) (subs2 var))]] (every? #(not= binding (or (subs1 %) (subs2 %))) notsames))))) (defn subsumption-compatible? "Returns true if: 1) No variable is bound to two different terms. 2) A variable is bound by two different terms, of which one of them is a variable, and they are compatible by structural subsumption." [subs1 subs2] (every? #(or (= (% subs1) (% subs2)) (nil? (% subs2)) (and (variable? (% subs1)) (structurally-subsumes-varterm (% subs1) (% subs2))) (and (variable? (% subs2)) (structurally-subsumes-varterm (% subs2) (% subs1)))) (keys subs1))) ;(defn subset? ; "Returns true if subs1 is a subset of subs2" ; [subs1 subs2] ; (every? #(= (subs1 %) (subs2 %)) (keys subs1))) (defn expand-substitution "Given a term and a substitution, examines the term for embedded vars which use terms in the substitution. Builds a new substitution with those terms substituted for." [term subst] (let [term-vars (set/difference (get-vars term) (set (keys subst)))] (if-not (empty? term-vars) (into {} (map #(vector % (apply-sub-to-term % subst)) term-vars)))))
[ { "context": "))\n\n(def ^:private elb-account-id\n {\"us-east-1\"\"127311923021\"\n \"us-east-2\" \"033677994240\"\n \"us-west-1\" ", "end": 285, "score": 0.7689497470855713, "start": 277, "tag": "KEY", "value": "27311923" }, { "context": "oPort 0\n :cidrBlocks [\"0.0.0.0/0\"]}]\n :ingress [{:protocol \"tcp\"", "end": 5658, "score": 0.8395267128944397, "start": 5653, "tag": "IP_ADDRESS", "value": "0.0.0" } ]
src/pulumi_cljs/aws/ecs.cljs
modern-energy/pulumi-cljs
20
(ns pulumi-cljs.aws.ecs "Utilities for building ECS Fargate tasks" (:require ["@pulumi/pulumi" :as pulumi] ["@pulumi/aws" :as aws] [pulumi-cljs.core :as p] [pulumi-cljs.aws :as aws-utils])) (def ^:private elb-account-id {"us-east-1""127311923021" "us-east-2" "033677994240" "us-west-1" "027434742980" "us-west-2" "797873946194" "af-south-1" "098369216593" "ca-central-1" "985666609251" "eu-central-1" "054676820928" "eu-west-1" "156460612806" "eu-west-2" "652711504416" "eu-south-1" "635631232127" "eu-west-3" "009996457667" "eu-north-1" "897822967062" "ap-east-1" "754344448648" "ap-northeast-1" "582318560864" "ap-northeast-2" "600734575887" "ap-northeast-3" "383597477331" "ap-southeast-1" "114774131450" "ap-southeast-2" "783225319266" "ap-south-1" "718504428378" "me-south-1" "076674570225" "sa-east-1" "507241528517" "us-gov-west-1" "048591011584" "us-gov-east-1" "190560391635" "cn-north-1" "638102146993" "cn-northwest-1" "037604701340"}) (defn- access-log-bucket-policy "Generate a JSON bucket policy for access logs. See https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-logging-bucket-permissions" [provider bucket] (let [bucket-contents-arn (str "arn:aws:s3:::" bucket "/*")] (p/json {:Version "2012-10-17" :Statement [{:Effect "Allow" :Principal {:AWS (p/all [region (:region provider)] (str "arn:aws:iam::" (get elb-account-id region) ":root"))} :Action "s3:PutObject" :Resource bucket-contents-arn} {:Effect "Allow" :Principal {:Service "delivery.logs.amazonaws.com"} :Action "s3:PutObject" :Resource bucket-contents-arn} {:Effect "Allow" :Principal {:Service "delivery.logs.amazonaws.com"} :Action "s3:GetBucketAcl" :Resource (str "arn:aws:s3:::" bucket)}]}))) (defn- configure-dns "Configure A DNS entry for the load balancer using Route53" [provider name alb zone domain] (let [zone-name (str zone ".") ; Route53 wants a trailing period. zone-id (p/all [response (p/invoke aws/route53.getZone {:name zone-name} {:provider provider})] (.-id response))] (p/resource aws/route53.Record (str name "-dns") alb {:zoneId zone-id :name domain :type "A" :aliases [{:name (:dnsName alb) :zoneId (:zoneId alb) :evaluateTargetHealth true}]}) (p/resource aws/route53.Record (str name "-dns-wildcard") alb {:zoneId zone-id :name (str "*." domain) :type "A" :aliases [{:name (:dnsName alb) :zoneId (:zoneId alb) :evaluateTargetHealth true}]}))) (defn service "Build a multi-az AWS Fargate Service, with an optional load balancer for serving HTTPs traffic. Config properties: :vpc-id - The VPC to use :container-port - The port on the Container that listens for inbound traffic :cluster-id - ECS cluster to use :task-count - The number of tasks to run :zone - The hosted zone in which to create a DNS entry. :subdomain - The subdomain to use for the DNS entry. May be null or an empty string if no subdomain is desired. :certificate-arn - The ARN of a SSL certificate stored in ACM :lb - Map of properties for the load balancer :ingress-cidrs - IP ranges that can access the service via the load balancer :subnets - Collection of Subnet ids in which to run the listener(s) :health-check - Health check configuration block :task - Map of properties for the task :container-definitions - A collection of container definition maps. :cpu - CPU units for the task :memory - Memory units for the task :volumes - Collection of ECS Volume configurations :iam-statements - A collection of AWS IAM policy statements (maps with :Resource, :Effect & :Action keys) to add to the task's role. :subnets - Collection of subnet IDs in which to run the service :disconnect-lb - IF true, won't connect the service to the load balancer. Useful for debugging services failing their health check. Documentation for these values is available at (see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html). By default, runs one instance of the service in each subnet. If multiple container definitions are provided, the load balancer will be configured to connect to the first one." [parent provider name {:keys [zone subdomain certificate-arn vpc-id container-port cluster-id task-count lb task disconnect-lb]}] (let [group (p/group name {:providers [provider] :parent parent}) lb-sg (p/resource aws/ec2.SecurityGroup (str name "-lb") group {:vpcId vpc-id :egress [{:protocol "-1" :fromPort 0 :toPort 0 :cidrBlocks ["0.0.0.0/0"]}] :ingress [{:protocol "tcp" :fromPort 80 :toPort 80 :cidrBlocks (:ingress-cidrs lb)} {:protocol "tcp" :fromPort 443 :toPort 443 :cidrBlocks (:ingress-cidrs lb)}]}) domain (if (empty? subdomain) zone (str subdomain "." zone)) log-bucket-name (str "access-logs." domain) log-bucket (p/resource aws/s3.Bucket (str name "-access-logs") group {:bucket log-bucket-name :policy (access-log-bucket-policy provider log-bucket-name)}) alb (p/resource aws/lb.LoadBalancer name group {:loadBalancerType "application" :securityGroups [(:id lb-sg)] :subnets (:subnets lb) :idleTimeout (or (:timeout lb) 60) :accessLogs {:bucket (:bucket log-bucket) :enabled true}}) target-group (p/resource aws/lb.TargetGroup name alb {:port container-port :healthCheck (:health-check lb) :protocol "HTTP" :targetType "ip" :vpcId vpc-id}) http-listener (p/resource aws/lb.Listener (str name "-http") alb {:loadBalancerArn (:arn alb) :port 80 :defaultActions [{:type "redirect" :redirect {:port 443 :protocol "HTTPS" :statusCode "HTTP_301"}}]}) https-listener (p/resource aws/lb.Listener (str name "-https") alb {:loadBalancerArn (:arn alb) :certificateArn certificate-arn :port 443 :protocol "HTTPS" :sslPolicy "ELBSecurityPolicy-FS-1-1-2019-08" :defaultActions [{:type "forward" :targetGroupArn (:arn target-group)}]}) log-group (p/resource aws/cloudwatch.LogGroup name group {:name (str "/" name "/" (pulumi/getStack) "/ecs-logs")}) role (aws-utils/role (str name "-task") group {:services ["ecs-tasks.amazonaws.com"] :policies ["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"] :statements (:iam-statements task)}) container-definitions (for [d (:container-definitions task)] (assoc d :logConfiguration {:logDriver "awslogs" :options {"awslogs-group" (:name log-group) "awslogs-region" (:region provider) "awslogs-stream-prefix" (str (:name d) "-")}})) task-definition (p/resource aws/ecs.TaskDefinition name group {:family (str name "-" (pulumi/getStack)) :executionRoleArn (:arn role) :taskRoleArn (:arn role) :networkMode "awsvpc" :requiresCompatibilities ["FARGATE"] :cpu (:cpu task) :memory (:memory task) :containerDefinitions (p/json container-definitions) :volumes (:volumes task)}) sg (p/resource aws/ec2.SecurityGroup (str name "-task") group {:vpcId vpc-id :ingress [{:protocol "tcp" :fromPort container-port :toPort container-port :securityGroups [(:id lb-sg)]}] :egress [{:protocol "-1" :fromPort 0 :toPort 0 :cidrBlocks ["0.0.0.0/0"]}]}) service (p/resource aws/ecs.Service name group {:cluster cluster-id :launchType "FARGATE" :taskDefinition (:arn task-definition) :desiredCount task-count :loadBalancers (when-not disconnect-lb [{:targetGroupArn (:arn target-group) :containerName (:name (first container-definitions)) :containerPort container-port}]) :healthCheckGracePeriod 300 :deploymentMaximumPercent 200 :deploymentMinimumHealthyPercent 50 :networkConfiguration {:subnets (:subnets task) :securityGroups [(:id sg)]}})] (configure-dns provider name alb zone domain) {:dns (:dnsName alb) :security-group sg}))
95284
(ns pulumi-cljs.aws.ecs "Utilities for building ECS Fargate tasks" (:require ["@pulumi/pulumi" :as pulumi] ["@pulumi/aws" :as aws] [pulumi-cljs.core :as p] [pulumi-cljs.aws :as aws-utils])) (def ^:private elb-account-id {"us-east-1""1<KEY>021" "us-east-2" "033677994240" "us-west-1" "027434742980" "us-west-2" "797873946194" "af-south-1" "098369216593" "ca-central-1" "985666609251" "eu-central-1" "054676820928" "eu-west-1" "156460612806" "eu-west-2" "652711504416" "eu-south-1" "635631232127" "eu-west-3" "009996457667" "eu-north-1" "897822967062" "ap-east-1" "754344448648" "ap-northeast-1" "582318560864" "ap-northeast-2" "600734575887" "ap-northeast-3" "383597477331" "ap-southeast-1" "114774131450" "ap-southeast-2" "783225319266" "ap-south-1" "718504428378" "me-south-1" "076674570225" "sa-east-1" "507241528517" "us-gov-west-1" "048591011584" "us-gov-east-1" "190560391635" "cn-north-1" "638102146993" "cn-northwest-1" "037604701340"}) (defn- access-log-bucket-policy "Generate a JSON bucket policy for access logs. See https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-logging-bucket-permissions" [provider bucket] (let [bucket-contents-arn (str "arn:aws:s3:::" bucket "/*")] (p/json {:Version "2012-10-17" :Statement [{:Effect "Allow" :Principal {:AWS (p/all [region (:region provider)] (str "arn:aws:iam::" (get elb-account-id region) ":root"))} :Action "s3:PutObject" :Resource bucket-contents-arn} {:Effect "Allow" :Principal {:Service "delivery.logs.amazonaws.com"} :Action "s3:PutObject" :Resource bucket-contents-arn} {:Effect "Allow" :Principal {:Service "delivery.logs.amazonaws.com"} :Action "s3:GetBucketAcl" :Resource (str "arn:aws:s3:::" bucket)}]}))) (defn- configure-dns "Configure A DNS entry for the load balancer using Route53" [provider name alb zone domain] (let [zone-name (str zone ".") ; Route53 wants a trailing period. zone-id (p/all [response (p/invoke aws/route53.getZone {:name zone-name} {:provider provider})] (.-id response))] (p/resource aws/route53.Record (str name "-dns") alb {:zoneId zone-id :name domain :type "A" :aliases [{:name (:dnsName alb) :zoneId (:zoneId alb) :evaluateTargetHealth true}]}) (p/resource aws/route53.Record (str name "-dns-wildcard") alb {:zoneId zone-id :name (str "*." domain) :type "A" :aliases [{:name (:dnsName alb) :zoneId (:zoneId alb) :evaluateTargetHealth true}]}))) (defn service "Build a multi-az AWS Fargate Service, with an optional load balancer for serving HTTPs traffic. Config properties: :vpc-id - The VPC to use :container-port - The port on the Container that listens for inbound traffic :cluster-id - ECS cluster to use :task-count - The number of tasks to run :zone - The hosted zone in which to create a DNS entry. :subdomain - The subdomain to use for the DNS entry. May be null or an empty string if no subdomain is desired. :certificate-arn - The ARN of a SSL certificate stored in ACM :lb - Map of properties for the load balancer :ingress-cidrs - IP ranges that can access the service via the load balancer :subnets - Collection of Subnet ids in which to run the listener(s) :health-check - Health check configuration block :task - Map of properties for the task :container-definitions - A collection of container definition maps. :cpu - CPU units for the task :memory - Memory units for the task :volumes - Collection of ECS Volume configurations :iam-statements - A collection of AWS IAM policy statements (maps with :Resource, :Effect & :Action keys) to add to the task's role. :subnets - Collection of subnet IDs in which to run the service :disconnect-lb - IF true, won't connect the service to the load balancer. Useful for debugging services failing their health check. Documentation for these values is available at (see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html). By default, runs one instance of the service in each subnet. If multiple container definitions are provided, the load balancer will be configured to connect to the first one." [parent provider name {:keys [zone subdomain certificate-arn vpc-id container-port cluster-id task-count lb task disconnect-lb]}] (let [group (p/group name {:providers [provider] :parent parent}) lb-sg (p/resource aws/ec2.SecurityGroup (str name "-lb") group {:vpcId vpc-id :egress [{:protocol "-1" :fromPort 0 :toPort 0 :cidrBlocks ["0.0.0.0/0"]}] :ingress [{:protocol "tcp" :fromPort 80 :toPort 80 :cidrBlocks (:ingress-cidrs lb)} {:protocol "tcp" :fromPort 443 :toPort 443 :cidrBlocks (:ingress-cidrs lb)}]}) domain (if (empty? subdomain) zone (str subdomain "." zone)) log-bucket-name (str "access-logs." domain) log-bucket (p/resource aws/s3.Bucket (str name "-access-logs") group {:bucket log-bucket-name :policy (access-log-bucket-policy provider log-bucket-name)}) alb (p/resource aws/lb.LoadBalancer name group {:loadBalancerType "application" :securityGroups [(:id lb-sg)] :subnets (:subnets lb) :idleTimeout (or (:timeout lb) 60) :accessLogs {:bucket (:bucket log-bucket) :enabled true}}) target-group (p/resource aws/lb.TargetGroup name alb {:port container-port :healthCheck (:health-check lb) :protocol "HTTP" :targetType "ip" :vpcId vpc-id}) http-listener (p/resource aws/lb.Listener (str name "-http") alb {:loadBalancerArn (:arn alb) :port 80 :defaultActions [{:type "redirect" :redirect {:port 443 :protocol "HTTPS" :statusCode "HTTP_301"}}]}) https-listener (p/resource aws/lb.Listener (str name "-https") alb {:loadBalancerArn (:arn alb) :certificateArn certificate-arn :port 443 :protocol "HTTPS" :sslPolicy "ELBSecurityPolicy-FS-1-1-2019-08" :defaultActions [{:type "forward" :targetGroupArn (:arn target-group)}]}) log-group (p/resource aws/cloudwatch.LogGroup name group {:name (str "/" name "/" (pulumi/getStack) "/ecs-logs")}) role (aws-utils/role (str name "-task") group {:services ["ecs-tasks.amazonaws.com"] :policies ["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"] :statements (:iam-statements task)}) container-definitions (for [d (:container-definitions task)] (assoc d :logConfiguration {:logDriver "awslogs" :options {"awslogs-group" (:name log-group) "awslogs-region" (:region provider) "awslogs-stream-prefix" (str (:name d) "-")}})) task-definition (p/resource aws/ecs.TaskDefinition name group {:family (str name "-" (pulumi/getStack)) :executionRoleArn (:arn role) :taskRoleArn (:arn role) :networkMode "awsvpc" :requiresCompatibilities ["FARGATE"] :cpu (:cpu task) :memory (:memory task) :containerDefinitions (p/json container-definitions) :volumes (:volumes task)}) sg (p/resource aws/ec2.SecurityGroup (str name "-task") group {:vpcId vpc-id :ingress [{:protocol "tcp" :fromPort container-port :toPort container-port :securityGroups [(:id lb-sg)]}] :egress [{:protocol "-1" :fromPort 0 :toPort 0 :cidrBlocks ["0.0.0.0/0"]}]}) service (p/resource aws/ecs.Service name group {:cluster cluster-id :launchType "FARGATE" :taskDefinition (:arn task-definition) :desiredCount task-count :loadBalancers (when-not disconnect-lb [{:targetGroupArn (:arn target-group) :containerName (:name (first container-definitions)) :containerPort container-port}]) :healthCheckGracePeriod 300 :deploymentMaximumPercent 200 :deploymentMinimumHealthyPercent 50 :networkConfiguration {:subnets (:subnets task) :securityGroups [(:id sg)]}})] (configure-dns provider name alb zone domain) {:dns (:dnsName alb) :security-group sg}))
true
(ns pulumi-cljs.aws.ecs "Utilities for building ECS Fargate tasks" (:require ["@pulumi/pulumi" :as pulumi] ["@pulumi/aws" :as aws] [pulumi-cljs.core :as p] [pulumi-cljs.aws :as aws-utils])) (def ^:private elb-account-id {"us-east-1""1PI:KEY:<KEY>END_PI021" "us-east-2" "033677994240" "us-west-1" "027434742980" "us-west-2" "797873946194" "af-south-1" "098369216593" "ca-central-1" "985666609251" "eu-central-1" "054676820928" "eu-west-1" "156460612806" "eu-west-2" "652711504416" "eu-south-1" "635631232127" "eu-west-3" "009996457667" "eu-north-1" "897822967062" "ap-east-1" "754344448648" "ap-northeast-1" "582318560864" "ap-northeast-2" "600734575887" "ap-northeast-3" "383597477331" "ap-southeast-1" "114774131450" "ap-southeast-2" "783225319266" "ap-south-1" "718504428378" "me-south-1" "076674570225" "sa-east-1" "507241528517" "us-gov-west-1" "048591011584" "us-gov-east-1" "190560391635" "cn-north-1" "638102146993" "cn-northwest-1" "037604701340"}) (defn- access-log-bucket-policy "Generate a JSON bucket policy for access logs. See https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html#access-logging-bucket-permissions" [provider bucket] (let [bucket-contents-arn (str "arn:aws:s3:::" bucket "/*")] (p/json {:Version "2012-10-17" :Statement [{:Effect "Allow" :Principal {:AWS (p/all [region (:region provider)] (str "arn:aws:iam::" (get elb-account-id region) ":root"))} :Action "s3:PutObject" :Resource bucket-contents-arn} {:Effect "Allow" :Principal {:Service "delivery.logs.amazonaws.com"} :Action "s3:PutObject" :Resource bucket-contents-arn} {:Effect "Allow" :Principal {:Service "delivery.logs.amazonaws.com"} :Action "s3:GetBucketAcl" :Resource (str "arn:aws:s3:::" bucket)}]}))) (defn- configure-dns "Configure A DNS entry for the load balancer using Route53" [provider name alb zone domain] (let [zone-name (str zone ".") ; Route53 wants a trailing period. zone-id (p/all [response (p/invoke aws/route53.getZone {:name zone-name} {:provider provider})] (.-id response))] (p/resource aws/route53.Record (str name "-dns") alb {:zoneId zone-id :name domain :type "A" :aliases [{:name (:dnsName alb) :zoneId (:zoneId alb) :evaluateTargetHealth true}]}) (p/resource aws/route53.Record (str name "-dns-wildcard") alb {:zoneId zone-id :name (str "*." domain) :type "A" :aliases [{:name (:dnsName alb) :zoneId (:zoneId alb) :evaluateTargetHealth true}]}))) (defn service "Build a multi-az AWS Fargate Service, with an optional load balancer for serving HTTPs traffic. Config properties: :vpc-id - The VPC to use :container-port - The port on the Container that listens for inbound traffic :cluster-id - ECS cluster to use :task-count - The number of tasks to run :zone - The hosted zone in which to create a DNS entry. :subdomain - The subdomain to use for the DNS entry. May be null or an empty string if no subdomain is desired. :certificate-arn - The ARN of a SSL certificate stored in ACM :lb - Map of properties for the load balancer :ingress-cidrs - IP ranges that can access the service via the load balancer :subnets - Collection of Subnet ids in which to run the listener(s) :health-check - Health check configuration block :task - Map of properties for the task :container-definitions - A collection of container definition maps. :cpu - CPU units for the task :memory - Memory units for the task :volumes - Collection of ECS Volume configurations :iam-statements - A collection of AWS IAM policy statements (maps with :Resource, :Effect & :Action keys) to add to the task's role. :subnets - Collection of subnet IDs in which to run the service :disconnect-lb - IF true, won't connect the service to the load balancer. Useful for debugging services failing their health check. Documentation for these values is available at (see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html). By default, runs one instance of the service in each subnet. If multiple container definitions are provided, the load balancer will be configured to connect to the first one." [parent provider name {:keys [zone subdomain certificate-arn vpc-id container-port cluster-id task-count lb task disconnect-lb]}] (let [group (p/group name {:providers [provider] :parent parent}) lb-sg (p/resource aws/ec2.SecurityGroup (str name "-lb") group {:vpcId vpc-id :egress [{:protocol "-1" :fromPort 0 :toPort 0 :cidrBlocks ["0.0.0.0/0"]}] :ingress [{:protocol "tcp" :fromPort 80 :toPort 80 :cidrBlocks (:ingress-cidrs lb)} {:protocol "tcp" :fromPort 443 :toPort 443 :cidrBlocks (:ingress-cidrs lb)}]}) domain (if (empty? subdomain) zone (str subdomain "." zone)) log-bucket-name (str "access-logs." domain) log-bucket (p/resource aws/s3.Bucket (str name "-access-logs") group {:bucket log-bucket-name :policy (access-log-bucket-policy provider log-bucket-name)}) alb (p/resource aws/lb.LoadBalancer name group {:loadBalancerType "application" :securityGroups [(:id lb-sg)] :subnets (:subnets lb) :idleTimeout (or (:timeout lb) 60) :accessLogs {:bucket (:bucket log-bucket) :enabled true}}) target-group (p/resource aws/lb.TargetGroup name alb {:port container-port :healthCheck (:health-check lb) :protocol "HTTP" :targetType "ip" :vpcId vpc-id}) http-listener (p/resource aws/lb.Listener (str name "-http") alb {:loadBalancerArn (:arn alb) :port 80 :defaultActions [{:type "redirect" :redirect {:port 443 :protocol "HTTPS" :statusCode "HTTP_301"}}]}) https-listener (p/resource aws/lb.Listener (str name "-https") alb {:loadBalancerArn (:arn alb) :certificateArn certificate-arn :port 443 :protocol "HTTPS" :sslPolicy "ELBSecurityPolicy-FS-1-1-2019-08" :defaultActions [{:type "forward" :targetGroupArn (:arn target-group)}]}) log-group (p/resource aws/cloudwatch.LogGroup name group {:name (str "/" name "/" (pulumi/getStack) "/ecs-logs")}) role (aws-utils/role (str name "-task") group {:services ["ecs-tasks.amazonaws.com"] :policies ["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"] :statements (:iam-statements task)}) container-definitions (for [d (:container-definitions task)] (assoc d :logConfiguration {:logDriver "awslogs" :options {"awslogs-group" (:name log-group) "awslogs-region" (:region provider) "awslogs-stream-prefix" (str (:name d) "-")}})) task-definition (p/resource aws/ecs.TaskDefinition name group {:family (str name "-" (pulumi/getStack)) :executionRoleArn (:arn role) :taskRoleArn (:arn role) :networkMode "awsvpc" :requiresCompatibilities ["FARGATE"] :cpu (:cpu task) :memory (:memory task) :containerDefinitions (p/json container-definitions) :volumes (:volumes task)}) sg (p/resource aws/ec2.SecurityGroup (str name "-task") group {:vpcId vpc-id :ingress [{:protocol "tcp" :fromPort container-port :toPort container-port :securityGroups [(:id lb-sg)]}] :egress [{:protocol "-1" :fromPort 0 :toPort 0 :cidrBlocks ["0.0.0.0/0"]}]}) service (p/resource aws/ecs.Service name group {:cluster cluster-id :launchType "FARGATE" :taskDefinition (:arn task-definition) :desiredCount task-count :loadBalancers (when-not disconnect-lb [{:targetGroupArn (:arn target-group) :containerName (:name (first container-definitions)) :containerPort container-port}]) :healthCheckGracePeriod 300 :deploymentMaximumPercent 200 :deploymentMinimumHealthyPercent 50 :networkConfiguration {:subnets (:subnets task) :securityGroups [(:id sg)]}})] (configure-dns provider name alb zone domain) {:dns (:dnsName alb) :security-group sg}))
[ { "context": "t-gray-500 :text-xs)}\n [:small \"Copyright © 2021 Kyle Erhabor\"]\n ;; TODO: Use images instead of text.\n [:ul", "end": 658, "score": 0.9998968839645386, "start": 646, "tag": "NAME", "value": "Kyle Erhabor" }, { "context": "space-x-2)}\n [:li>a {:href \"https://github.com/KyleErhabor\"\n :target \"_blank\"}\n [pages/github", "end": 789, "score": 0.9979445338249207, "start": 778, "tag": "USERNAME", "value": "KyleErhabor" }, { "context": "\"}\n [pages/github]]\n [:li>a {:href \"mailto:[email protected]\"}\n [pages/email]]]])\n\n(defn app []\n [:div {:", "end": 889, "score": 0.9999271035194397, "start": 868, "tag": "EMAIL", "value": "[email protected]" } ]
src/treehouse/core.cljs
KyleErhabor/treehouse
0
(ns treehouse.core (:require [treehouse.pages :as pages] [treehouse.router :as router] [treehouse.storage :as store] [treehouse.tailwind :refer [tw]] [goog.dom :as gdom] [reagent.dom :as rdom])) (def container [:container :mx-auto :p-2]) (defn header [] [:header {:class (tw container)} [:ul {:class (tw :flex :space-x-2 :text-gray-500)} [:li>a {:href (router/home)} "Home"] [:li>a {:href (router/about)} "About"]]]) (defn footer [] [:footer {:class (tw container :flex :items-center :justify-between :text-gray-500 :text-xs)} [:small "Copyright © 2021 Kyle Erhabor"] ;; TODO: Use images instead of text. [:ul {:class (tw :flex :space-x-2)} [:li>a {:href "https://github.com/KyleErhabor" :target "_blank"} [pages/github]] [:li>a {:href "mailto:[email protected]"} [pages/email]]]]) (defn app [] [:div {:class (case @store/dark? true :dark false nil nil (if (.-matches (.matchMedia js/window "(prefers-color-scheme: dark)")) :dark))} [header] [:main {:class (tw container :h-screen)} @router/route] [:hr] [footer]]) (rdom/render [app] (gdom/getElement "app"))
22048
(ns treehouse.core (:require [treehouse.pages :as pages] [treehouse.router :as router] [treehouse.storage :as store] [treehouse.tailwind :refer [tw]] [goog.dom :as gdom] [reagent.dom :as rdom])) (def container [:container :mx-auto :p-2]) (defn header [] [:header {:class (tw container)} [:ul {:class (tw :flex :space-x-2 :text-gray-500)} [:li>a {:href (router/home)} "Home"] [:li>a {:href (router/about)} "About"]]]) (defn footer [] [:footer {:class (tw container :flex :items-center :justify-between :text-gray-500 :text-xs)} [:small "Copyright © 2021 <NAME>"] ;; TODO: Use images instead of text. [:ul {:class (tw :flex :space-x-2)} [:li>a {:href "https://github.com/KyleErhabor" :target "_blank"} [pages/github]] [:li>a {:href "mailto:<EMAIL>"} [pages/email]]]]) (defn app [] [:div {:class (case @store/dark? true :dark false nil nil (if (.-matches (.matchMedia js/window "(prefers-color-scheme: dark)")) :dark))} [header] [:main {:class (tw container :h-screen)} @router/route] [:hr] [footer]]) (rdom/render [app] (gdom/getElement "app"))
true
(ns treehouse.core (:require [treehouse.pages :as pages] [treehouse.router :as router] [treehouse.storage :as store] [treehouse.tailwind :refer [tw]] [goog.dom :as gdom] [reagent.dom :as rdom])) (def container [:container :mx-auto :p-2]) (defn header [] [:header {:class (tw container)} [:ul {:class (tw :flex :space-x-2 :text-gray-500)} [:li>a {:href (router/home)} "Home"] [:li>a {:href (router/about)} "About"]]]) (defn footer [] [:footer {:class (tw container :flex :items-center :justify-between :text-gray-500 :text-xs)} [:small "Copyright © 2021 PI:NAME:<NAME>END_PI"] ;; TODO: Use images instead of text. [:ul {:class (tw :flex :space-x-2)} [:li>a {:href "https://github.com/KyleErhabor" :target "_blank"} [pages/github]] [:li>a {:href "mailto:PI:EMAIL:<EMAIL>END_PI"} [pages/email]]]]) (defn app [] [:div {:class (case @store/dark? true :dark false nil nil (if (.-matches (.matchMedia js/window "(prefers-color-scheme: dark)")) :dark))} [header] [:main {:class (tw container :h-screen)} @router/route] [:hr] [footer]]) (rdom/render [app] (gdom/getElement "app"))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998680353164673, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ce, or any other, from this software.\n\n; Authors: Stuart Halloway, Frantisek Sodomka\n\n(ns clojure.test-clojure.meta", "end": 491, "score": 0.9998778104782104, "start": 476, "tag": "NAME", "value": "Stuart Halloway" }, { "context": " from this software.\n\n; Authors: Stuart Halloway, Frantisek Sodomka\n\n(ns clojure.test-clojure.metadata\n (:use clojur", "end": 510, "score": 0.9998783469200134, "start": 493, "tag": "NAME", "value": "Frantisek Sodomka" }, { "context": "etsy cow\"}\n cow1 (with-meta {:name \"betsy\" :id 33} cow1m)\n cow2m {:what \"panda co", "end": 6111, "score": 0.42741337418556213, "start": 6110, "tag": "NAME", "value": "y" } ]
Source/clojure/test_clojure/metadata.clj
etherny/Arcadia
1,447
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Authors: Stuart Halloway, Frantisek Sodomka (ns clojure.test-clojure.metadata (:use clojure.test [clojure.test-helper :only (eval-in-temp-ns)]) (:require [clojure.set :as set])) (def public-namespaces '[clojure.core clojure.pprint ;clojure.inspector clojure.set clojure.stacktrace clojure.test clojure.walk ;clojure.xml clojure.zip clojure.clr.io ;;; clojure.java.io ;clojure.java.browse ;clojure.java.javadoc ;clojure.java.shell clojure.string clojure.data]) (doseq [ns public-namespaces] (require ns)) (def public-vars (mapcat #(vals (ns-publics %)) public-namespaces)) (def public-vars-with-docstrings (filter (comp :doc meta) public-vars)) (def public-vars-with-docstrings-not-generated (remove #(re-find #"^->[A-Z]" (name (.sym %))) public-vars-with-docstrings)) (deftest public-vars-with-docstrings-have-added (is (= [] (remove (comp :added meta) public-vars-with-docstrings-not-generated)))) (deftest interaction-of-def-with-metadata (testing "initial def sets metadata" (let [v (eval-in-temp-ns (def ^{:a 1} foo 0) #'foo)] (is (= 1 (-> v meta :a))))) #_(testing "subsequent declare doesn't overwrite metadata" (let [v (eval-in-temp-ns (def ^{:b 2} bar 0) (declare bar) #'bar)] (is (= 2 (-> v meta :b)))) (testing "when compiled" (let [v (eval-in-temp-ns (def ^{:c 3} bar 0) (defn declare-bar [] (declare bar)) (declare-bar) #'bar)] (is (= 3 (-> v meta :c)))))) (testing "subsequent def with init-expr *does* overwrite metadata" (let [v (eval-in-temp-ns (def ^{:d 4} quux 0) (def quux 1) #'quux)] (is (nil? (-> v meta :d)))) (testing "when compiled" (let [v (eval-in-temp-ns (def ^{:e 5} quux 0) (defn def-quux [] (def quux 1)) (def-quux) #'quux)] (is (nil? (-> v meta :e)))))) (testing "IllegalArgumentException should not be thrown" (testing "when defining var whose value is calculated with a primitive fn." (testing "This case fails without a fix for CLJ-852" (is (eval-in-temp-ns (defn foo ^long [^long x] x) (def x (inc (foo 10)))))) (testing "This case should pass even without a fix for CLJ-852" (is (eval-in-temp-ns (defn foo ^long [^long x] x) (def x (foo (inc 10))))))))) (deftest fns-preserve-metadata-on-maps (let [xm {:a 1 :b -7} x (with-meta {:foo 1 :bar 2} xm) ym {:c "foo"} y (with-meta {:baz 4 :guh x} ym)] (is (= xm (meta (:guh y)))) (is (= xm (meta (reduce #(assoc %1 %2 (inc %2)) x (range 1000))))) (is (= xm (meta (-> x (dissoc :foo) (dissoc :bar))))) (let [z (assoc-in y [:guh :la] 18)] (is (= ym (meta z))) (is (= xm (meta (:guh z))))) (let [z (update-in y [:guh :bar] inc)] (is (= ym (meta z))) (is (= xm (meta (:guh z))))) (is (= xm (meta (get-in y [:guh])))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (merge x y)))) (is (= ym (meta (merge y x)))) (is (= xm (meta (merge-with + x y)))) (is (= ym (meta (merge-with + y x)))) (is (= xm (meta (select-keys x [:bar])))) (is (= xm (meta (set/rename-keys x {:foo :new-foo})))) ;; replace returns a seq when given a set. Can seqs have ;; metadata? ;; TBD: rseq, subseq, and rsubseq returns seqs. If it is even ;; possible to put metadata on a seq, does it make sense that the ;; seqs returned by these functions should have the same metadata ;; as the sorted collection on which they are called? )) (deftest fns-preserve-metadata-on-vectors (let [xm {:a 1 :b -7} x (with-meta [1 2 3] xm) ym {:c "foo"} y (with-meta [4 x 6] ym)] (is (= xm (meta (y 1)))) (is (= xm (meta (assoc x 1 "one")))) (is (= xm (meta (reduce #(conj %1 %2) x (range 1000))))) (is (= xm (meta (pop (pop (pop x)))))) (let [z (assoc-in y [1 2] 18)] (is (= ym (meta z))) (is (= xm (meta (z 1))))) (let [z (update-in y [1 2] inc)] (is (= ym (meta z))) (is (= xm (meta (z 1))))) (is (= xm (meta (get-in y [1])))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (replace {2 "two"} x)))) (is (= [1 "two" 3] (replace {2 "two"} x))) ;; TBD: Currently subvec drops metadata. Should it preserve it? ;;(is (= xm (meta (subvec x 2 3)))) ;; TBD: rseq returns a seq. If it is even possible to put ;; metadata on a seq, does it make sense that the seqs returned by ;; these functions should have the same metadata as the sorted ;; collection on which they are called? )) (deftest fns-preserve-metadata-on-sets ;; TBD: Do tests independently for set, hash-set, and sorted-set, ;; perhaps with a loop here. (let [xm {:a 1 :b -7} x (with-meta #{1 2 3} xm) ym {:c "foo"} y (with-meta #{4 x 6} ym)] (is (= xm (meta (y #{3 2 1})))) (is (= xm (meta (reduce #(conj %1 %2) x (range 1000))))) (is (= xm (meta (-> x (disj 1) (disj 2) (disj 3))))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (set/select even? x)))) (let [cow1m {:what "betsy cow"} cow1 (with-meta {:name "betsy" :id 33} cow1m) cow2m {:what "panda cow"} cow2 (with-meta {:name "panda" :id 34} cow2m) cowsm {:what "all the cows"} cows (with-meta #{cow1 cow2} cowsm) cow-names (set/project cows [:name]) renamed (set/rename cows {:id :number})] (is (= cowsm (meta cow-names))) (is (= cow1m (meta (first (filter #(= "betsy" (:name %)) cow-names))))) (is (= cow2m (meta (first (filter #(= "panda" (:name %)) cow-names))))) (is (= cowsm (meta renamed))) (is (= cow1m (meta (first (filter #(= "betsy" (:name %)) renamed))))) (is (= cow2m (meta (first (filter #(= "panda" (:name %)) renamed)))))) ;; replace returns a seq when given a set. Can seqs have ;; metadata? ;; union: Currently returns the metadata of the largest input set. ;; This is an artifact of union's current implementation. I doubt ;; any explicit design decision was made to do so. Like join, ;; there doesn't seem to be much reason to prefer the metadata of ;; one input set over another, if at least two input sets are ;; given, but perhaps defining it to always return a set with the ;; metadata of the first input set would be reasonable? ;; intersection: Returns metadata of the smallest input set. ;; Otherwise similar to union. ;; difference: Seems to always return a set with metadata of first ;; input set. Seems reasonable. Not sure we want to add a test ;; for it, if it is an accident of the current implementation. ;; join, index, map-invert: Currently always returns a value with ;; no metadata. This seems reasonable. )) (deftest defn-primitive-args (testing "Hinting the arg vector of a primitive-taking fn with a non-primitive type should not result in AbstractMethodError when invoked." (testing "CLJ-850 is fixed when this case passes." (is (= "foo" (eval-in-temp-ns (defn f ^String [^String s ^long i] s) (f "foo" 1))))) (testing "These cases should pass, even without a fix for CLJ-850." (is (= "foo" (eval-in-temp-ns (defn f ^String [^String s] s) (f "foo")))) (is (= 1 (eval-in-temp-ns (defn f ^long [^String s ^long i] i) (f "foo" 1)))) (is (= 1 (eval-in-temp-ns (defn f ^long [^long i] i) (f 1)))))))
16601
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Authors: <NAME>, <NAME> (ns clojure.test-clojure.metadata (:use clojure.test [clojure.test-helper :only (eval-in-temp-ns)]) (:require [clojure.set :as set])) (def public-namespaces '[clojure.core clojure.pprint ;clojure.inspector clojure.set clojure.stacktrace clojure.test clojure.walk ;clojure.xml clojure.zip clojure.clr.io ;;; clojure.java.io ;clojure.java.browse ;clojure.java.javadoc ;clojure.java.shell clojure.string clojure.data]) (doseq [ns public-namespaces] (require ns)) (def public-vars (mapcat #(vals (ns-publics %)) public-namespaces)) (def public-vars-with-docstrings (filter (comp :doc meta) public-vars)) (def public-vars-with-docstrings-not-generated (remove #(re-find #"^->[A-Z]" (name (.sym %))) public-vars-with-docstrings)) (deftest public-vars-with-docstrings-have-added (is (= [] (remove (comp :added meta) public-vars-with-docstrings-not-generated)))) (deftest interaction-of-def-with-metadata (testing "initial def sets metadata" (let [v (eval-in-temp-ns (def ^{:a 1} foo 0) #'foo)] (is (= 1 (-> v meta :a))))) #_(testing "subsequent declare doesn't overwrite metadata" (let [v (eval-in-temp-ns (def ^{:b 2} bar 0) (declare bar) #'bar)] (is (= 2 (-> v meta :b)))) (testing "when compiled" (let [v (eval-in-temp-ns (def ^{:c 3} bar 0) (defn declare-bar [] (declare bar)) (declare-bar) #'bar)] (is (= 3 (-> v meta :c)))))) (testing "subsequent def with init-expr *does* overwrite metadata" (let [v (eval-in-temp-ns (def ^{:d 4} quux 0) (def quux 1) #'quux)] (is (nil? (-> v meta :d)))) (testing "when compiled" (let [v (eval-in-temp-ns (def ^{:e 5} quux 0) (defn def-quux [] (def quux 1)) (def-quux) #'quux)] (is (nil? (-> v meta :e)))))) (testing "IllegalArgumentException should not be thrown" (testing "when defining var whose value is calculated with a primitive fn." (testing "This case fails without a fix for CLJ-852" (is (eval-in-temp-ns (defn foo ^long [^long x] x) (def x (inc (foo 10)))))) (testing "This case should pass even without a fix for CLJ-852" (is (eval-in-temp-ns (defn foo ^long [^long x] x) (def x (foo (inc 10))))))))) (deftest fns-preserve-metadata-on-maps (let [xm {:a 1 :b -7} x (with-meta {:foo 1 :bar 2} xm) ym {:c "foo"} y (with-meta {:baz 4 :guh x} ym)] (is (= xm (meta (:guh y)))) (is (= xm (meta (reduce #(assoc %1 %2 (inc %2)) x (range 1000))))) (is (= xm (meta (-> x (dissoc :foo) (dissoc :bar))))) (let [z (assoc-in y [:guh :la] 18)] (is (= ym (meta z))) (is (= xm (meta (:guh z))))) (let [z (update-in y [:guh :bar] inc)] (is (= ym (meta z))) (is (= xm (meta (:guh z))))) (is (= xm (meta (get-in y [:guh])))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (merge x y)))) (is (= ym (meta (merge y x)))) (is (= xm (meta (merge-with + x y)))) (is (= ym (meta (merge-with + y x)))) (is (= xm (meta (select-keys x [:bar])))) (is (= xm (meta (set/rename-keys x {:foo :new-foo})))) ;; replace returns a seq when given a set. Can seqs have ;; metadata? ;; TBD: rseq, subseq, and rsubseq returns seqs. If it is even ;; possible to put metadata on a seq, does it make sense that the ;; seqs returned by these functions should have the same metadata ;; as the sorted collection on which they are called? )) (deftest fns-preserve-metadata-on-vectors (let [xm {:a 1 :b -7} x (with-meta [1 2 3] xm) ym {:c "foo"} y (with-meta [4 x 6] ym)] (is (= xm (meta (y 1)))) (is (= xm (meta (assoc x 1 "one")))) (is (= xm (meta (reduce #(conj %1 %2) x (range 1000))))) (is (= xm (meta (pop (pop (pop x)))))) (let [z (assoc-in y [1 2] 18)] (is (= ym (meta z))) (is (= xm (meta (z 1))))) (let [z (update-in y [1 2] inc)] (is (= ym (meta z))) (is (= xm (meta (z 1))))) (is (= xm (meta (get-in y [1])))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (replace {2 "two"} x)))) (is (= [1 "two" 3] (replace {2 "two"} x))) ;; TBD: Currently subvec drops metadata. Should it preserve it? ;;(is (= xm (meta (subvec x 2 3)))) ;; TBD: rseq returns a seq. If it is even possible to put ;; metadata on a seq, does it make sense that the seqs returned by ;; these functions should have the same metadata as the sorted ;; collection on which they are called? )) (deftest fns-preserve-metadata-on-sets ;; TBD: Do tests independently for set, hash-set, and sorted-set, ;; perhaps with a loop here. (let [xm {:a 1 :b -7} x (with-meta #{1 2 3} xm) ym {:c "foo"} y (with-meta #{4 x 6} ym)] (is (= xm (meta (y #{3 2 1})))) (is (= xm (meta (reduce #(conj %1 %2) x (range 1000))))) (is (= xm (meta (-> x (disj 1) (disj 2) (disj 3))))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (set/select even? x)))) (let [cow1m {:what "betsy cow"} cow1 (with-meta {:name "bets<NAME>" :id 33} cow1m) cow2m {:what "panda cow"} cow2 (with-meta {:name "panda" :id 34} cow2m) cowsm {:what "all the cows"} cows (with-meta #{cow1 cow2} cowsm) cow-names (set/project cows [:name]) renamed (set/rename cows {:id :number})] (is (= cowsm (meta cow-names))) (is (= cow1m (meta (first (filter #(= "betsy" (:name %)) cow-names))))) (is (= cow2m (meta (first (filter #(= "panda" (:name %)) cow-names))))) (is (= cowsm (meta renamed))) (is (= cow1m (meta (first (filter #(= "betsy" (:name %)) renamed))))) (is (= cow2m (meta (first (filter #(= "panda" (:name %)) renamed)))))) ;; replace returns a seq when given a set. Can seqs have ;; metadata? ;; union: Currently returns the metadata of the largest input set. ;; This is an artifact of union's current implementation. I doubt ;; any explicit design decision was made to do so. Like join, ;; there doesn't seem to be much reason to prefer the metadata of ;; one input set over another, if at least two input sets are ;; given, but perhaps defining it to always return a set with the ;; metadata of the first input set would be reasonable? ;; intersection: Returns metadata of the smallest input set. ;; Otherwise similar to union. ;; difference: Seems to always return a set with metadata of first ;; input set. Seems reasonable. Not sure we want to add a test ;; for it, if it is an accident of the current implementation. ;; join, index, map-invert: Currently always returns a value with ;; no metadata. This seems reasonable. )) (deftest defn-primitive-args (testing "Hinting the arg vector of a primitive-taking fn with a non-primitive type should not result in AbstractMethodError when invoked." (testing "CLJ-850 is fixed when this case passes." (is (= "foo" (eval-in-temp-ns (defn f ^String [^String s ^long i] s) (f "foo" 1))))) (testing "These cases should pass, even without a fix for CLJ-850." (is (= "foo" (eval-in-temp-ns (defn f ^String [^String s] s) (f "foo")))) (is (= 1 (eval-in-temp-ns (defn f ^long [^String s ^long i] i) (f "foo" 1)))) (is (= 1 (eval-in-temp-ns (defn f ^long [^long i] i) (f 1)))))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Authors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI (ns clojure.test-clojure.metadata (:use clojure.test [clojure.test-helper :only (eval-in-temp-ns)]) (:require [clojure.set :as set])) (def public-namespaces '[clojure.core clojure.pprint ;clojure.inspector clojure.set clojure.stacktrace clojure.test clojure.walk ;clojure.xml clojure.zip clojure.clr.io ;;; clojure.java.io ;clojure.java.browse ;clojure.java.javadoc ;clojure.java.shell clojure.string clojure.data]) (doseq [ns public-namespaces] (require ns)) (def public-vars (mapcat #(vals (ns-publics %)) public-namespaces)) (def public-vars-with-docstrings (filter (comp :doc meta) public-vars)) (def public-vars-with-docstrings-not-generated (remove #(re-find #"^->[A-Z]" (name (.sym %))) public-vars-with-docstrings)) (deftest public-vars-with-docstrings-have-added (is (= [] (remove (comp :added meta) public-vars-with-docstrings-not-generated)))) (deftest interaction-of-def-with-metadata (testing "initial def sets metadata" (let [v (eval-in-temp-ns (def ^{:a 1} foo 0) #'foo)] (is (= 1 (-> v meta :a))))) #_(testing "subsequent declare doesn't overwrite metadata" (let [v (eval-in-temp-ns (def ^{:b 2} bar 0) (declare bar) #'bar)] (is (= 2 (-> v meta :b)))) (testing "when compiled" (let [v (eval-in-temp-ns (def ^{:c 3} bar 0) (defn declare-bar [] (declare bar)) (declare-bar) #'bar)] (is (= 3 (-> v meta :c)))))) (testing "subsequent def with init-expr *does* overwrite metadata" (let [v (eval-in-temp-ns (def ^{:d 4} quux 0) (def quux 1) #'quux)] (is (nil? (-> v meta :d)))) (testing "when compiled" (let [v (eval-in-temp-ns (def ^{:e 5} quux 0) (defn def-quux [] (def quux 1)) (def-quux) #'quux)] (is (nil? (-> v meta :e)))))) (testing "IllegalArgumentException should not be thrown" (testing "when defining var whose value is calculated with a primitive fn." (testing "This case fails without a fix for CLJ-852" (is (eval-in-temp-ns (defn foo ^long [^long x] x) (def x (inc (foo 10)))))) (testing "This case should pass even without a fix for CLJ-852" (is (eval-in-temp-ns (defn foo ^long [^long x] x) (def x (foo (inc 10))))))))) (deftest fns-preserve-metadata-on-maps (let [xm {:a 1 :b -7} x (with-meta {:foo 1 :bar 2} xm) ym {:c "foo"} y (with-meta {:baz 4 :guh x} ym)] (is (= xm (meta (:guh y)))) (is (= xm (meta (reduce #(assoc %1 %2 (inc %2)) x (range 1000))))) (is (= xm (meta (-> x (dissoc :foo) (dissoc :bar))))) (let [z (assoc-in y [:guh :la] 18)] (is (= ym (meta z))) (is (= xm (meta (:guh z))))) (let [z (update-in y [:guh :bar] inc)] (is (= ym (meta z))) (is (= xm (meta (:guh z))))) (is (= xm (meta (get-in y [:guh])))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (merge x y)))) (is (= ym (meta (merge y x)))) (is (= xm (meta (merge-with + x y)))) (is (= ym (meta (merge-with + y x)))) (is (= xm (meta (select-keys x [:bar])))) (is (= xm (meta (set/rename-keys x {:foo :new-foo})))) ;; replace returns a seq when given a set. Can seqs have ;; metadata? ;; TBD: rseq, subseq, and rsubseq returns seqs. If it is even ;; possible to put metadata on a seq, does it make sense that the ;; seqs returned by these functions should have the same metadata ;; as the sorted collection on which they are called? )) (deftest fns-preserve-metadata-on-vectors (let [xm {:a 1 :b -7} x (with-meta [1 2 3] xm) ym {:c "foo"} y (with-meta [4 x 6] ym)] (is (= xm (meta (y 1)))) (is (= xm (meta (assoc x 1 "one")))) (is (= xm (meta (reduce #(conj %1 %2) x (range 1000))))) (is (= xm (meta (pop (pop (pop x)))))) (let [z (assoc-in y [1 2] 18)] (is (= ym (meta z))) (is (= xm (meta (z 1))))) (let [z (update-in y [1 2] inc)] (is (= ym (meta z))) (is (= xm (meta (z 1))))) (is (= xm (meta (get-in y [1])))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (replace {2 "two"} x)))) (is (= [1 "two" 3] (replace {2 "two"} x))) ;; TBD: Currently subvec drops metadata. Should it preserve it? ;;(is (= xm (meta (subvec x 2 3)))) ;; TBD: rseq returns a seq. If it is even possible to put ;; metadata on a seq, does it make sense that the seqs returned by ;; these functions should have the same metadata as the sorted ;; collection on which they are called? )) (deftest fns-preserve-metadata-on-sets ;; TBD: Do tests independently for set, hash-set, and sorted-set, ;; perhaps with a loop here. (let [xm {:a 1 :b -7} x (with-meta #{1 2 3} xm) ym {:c "foo"} y (with-meta #{4 x 6} ym)] (is (= xm (meta (y #{3 2 1})))) (is (= xm (meta (reduce #(conj %1 %2) x (range 1000))))) (is (= xm (meta (-> x (disj 1) (disj 2) (disj 3))))) (is (= xm (meta (into x y)))) (is (= ym (meta (into y x)))) (is (= xm (meta (set/select even? x)))) (let [cow1m {:what "betsy cow"} cow1 (with-meta {:name "betsPI:NAME:<NAME>END_PI" :id 33} cow1m) cow2m {:what "panda cow"} cow2 (with-meta {:name "panda" :id 34} cow2m) cowsm {:what "all the cows"} cows (with-meta #{cow1 cow2} cowsm) cow-names (set/project cows [:name]) renamed (set/rename cows {:id :number})] (is (= cowsm (meta cow-names))) (is (= cow1m (meta (first (filter #(= "betsy" (:name %)) cow-names))))) (is (= cow2m (meta (first (filter #(= "panda" (:name %)) cow-names))))) (is (= cowsm (meta renamed))) (is (= cow1m (meta (first (filter #(= "betsy" (:name %)) renamed))))) (is (= cow2m (meta (first (filter #(= "panda" (:name %)) renamed)))))) ;; replace returns a seq when given a set. Can seqs have ;; metadata? ;; union: Currently returns the metadata of the largest input set. ;; This is an artifact of union's current implementation. I doubt ;; any explicit design decision was made to do so. Like join, ;; there doesn't seem to be much reason to prefer the metadata of ;; one input set over another, if at least two input sets are ;; given, but perhaps defining it to always return a set with the ;; metadata of the first input set would be reasonable? ;; intersection: Returns metadata of the smallest input set. ;; Otherwise similar to union. ;; difference: Seems to always return a set with metadata of first ;; input set. Seems reasonable. Not sure we want to add a test ;; for it, if it is an accident of the current implementation. ;; join, index, map-invert: Currently always returns a value with ;; no metadata. This seems reasonable. )) (deftest defn-primitive-args (testing "Hinting the arg vector of a primitive-taking fn with a non-primitive type should not result in AbstractMethodError when invoked." (testing "CLJ-850 is fixed when this case passes." (is (= "foo" (eval-in-temp-ns (defn f ^String [^String s ^long i] s) (f "foo" 1))))) (testing "These cases should pass, even without a fix for CLJ-850." (is (= "foo" (eval-in-temp-ns (defn f ^String [^String s] s) (f "foo")))) (is (= 1 (eval-in-temp-ns (defn f ^long [^String s ^long i] i) (f "foo" 1)))) (is (= 1 (eval-in-temp-ns (defn f ^long [^long i] i) (f 1)))))))
[ { "context": "eset-db)\n\n(def ^:private context\n {:users (->> [\"[email protected]\" \"[email protected]\"]\n (mapv #(factory :", "end": 872, "score": 0.9999106526374817, "start": 860, "tag": "EMAIL", "value": "[email protected]" }, { "context": "^:private context\n {:users (->> [\"[email protected]\" \"[email protected]\"]\n (mapv #(factory :user {:email %}", "end": 887, "score": 0.9999034404754639, "start": 875, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ities [{:name \"Personal\"\n :user-id \"[email protected]\"}\n {:name \"Business\"\n ", "end": 1010, "score": 0.9999088048934937, "start": 998, "tag": "EMAIL", "value": "[email protected]" }, { "context": " {:name \"Business\"\n :user-id \"[email protected]\"}]\n :commodities [{:name \"US Dollar\"\n ", "end": 1082, "score": 0.9998855590820312, "start": 1070, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ert-successful-count (get-a-count-of-commodities \"[email protected]\")))\n\n(deftest a-user-cannot-get-a-count-of-commod", "end": 2401, "score": 0.9999197721481323, "start": 2389, "tag": "EMAIL", "value": "[email protected]" }, { "context": "assert-blocked-count (get-a-count-of-commodities \"[email protected]\")))\n\n(defn- get-a-list-of-commodities\n [email]\n ", "end": 2541, "score": 0.999912440776825, "start": 2529, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ssert-successful-list (get-a-list-of-commodities \"[email protected]\")))\n\n(deftest a-user-cannot-get-a-list-of-commodi", "end": 3804, "score": 0.9999176263809204, "start": 3792, "tag": "EMAIL", "value": "[email protected]" }, { "context": " (assert-blocked-list (get-a-list-of-commodities \"[email protected]\")))\n\n(defn- get-a-commodity\n [email]\n (let [ctx", "end": 3941, "score": 0.9999129176139832, "start": 3929, "tag": "EMAIL", "value": "[email protected]" }, { "context": "entity\n (assert-successful-get (get-a-commodity \"[email protected]\")))\n\n(deftest a-user-cannot-get-a-commodity-in-ao", "end": 4897, "score": 0.9998979568481445, "start": 4885, "tag": "EMAIL", "value": "[email protected]" }, { "context": "rs-entity\n (assert-blocked-get (get-a-commodity \"[email protected]\")))\n\n(def ^:private commodity-attributes\n {:type", "end": 5012, "score": 0.9995859265327454, "start": 5000, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\n (assert-successful-create (create-a-commodity \"[email protected]\")))\n\n(deftest a-user-cannot-create-an-commodity-i", "end": 6739, "score": 0.9999151229858398, "start": 6727, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ity\n (assert-blocked-create (create-a-commodity \"[email protected]\")))\n\n(deftest attempt-to-create-an-invalid-commod", "end": 6865, "score": 0.9998671412467957, "start": 6853, "tag": "EMAIL", "value": "[email protected]" }, { "context": "tx (realize context)\n user (find-user ctx \"[email protected]\")\n entity (find-entity ctx \"Personal\")\n ", "end": 6990, "score": 0.999913215637207, "start": 6978, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\n (assert-successful-update (update-a-commodity \"[email protected]\")))\n\n(deftest a-user-cannot-update-a-commodity-in", "end": 8978, "score": 0.9999082684516907, "start": 8966, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ity\n (assert-blocked-update (update-a-commodity \"[email protected]\")))\n\n(defn- delete-a-commodity\n [email]\n (let [", "end": 9103, "score": 0.9998857378959656, "start": 9091, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\n (assert-successful-delete (delete-a-commodity \"[email protected]\")))\n\n(deftest a-user-cannot-delete-a-commodity-in", "end": 10003, "score": 0.9999153017997742, "start": 9991, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ity\n (assert-blocked-delete (delete-a-commodity \"[email protected]\")))\n", "end": 10128, "score": 0.9998858571052551, "start": 10116, "tag": "EMAIL", "value": "[email protected]" } ]
test/clj_money/api/commodities_test.clj
dgknght/clj-money
5
(ns clj-money.api.commodities-test (:require [clojure.test :refer [deftest use-fixtures is]] [ring.mock.request :as req] [cheshire.core :as json] [clj-factory.core :refer [factory]] [dgknght.app-lib.web :refer [path]] [dgknght.app-lib.test] [clj-money.factories.user-factory] [clj-money.test-context :refer [realize find-user find-entity find-commodity]] [clj-money.test-helpers :refer [reset-db]] [clj-money.api.test-helper :refer [add-auth]] [clj-money.models.commodities :as coms] [clj-money.web.server :refer [app]])) (use-fixtures :each reset-db) (def ^:private context {:users (->> ["[email protected]" "[email protected]"] (mapv #(factory :user {:email %}))) :entities [{:name "Personal" :user-id "[email protected]"} {:name "Business" :user-id "[email protected]"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency :entity-id "Personal"} {:name "Microsoft, Inc" :symbol "MSFT" :type :stock :exchange :nasdaq :entity-id "Personal"}]}) (defn- get-a-count-of-commodities [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :get (path :api :entities (:id entity) :commodities :count)) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-count [[response body]] (is (http-success? response)) (is (= {:count 2} body) "The body contains the count")) (defn- assert-blocked-count [[response body]] (is (http-success? response)) (is (= {:count 0} body) "The body contains a count of zero")) (deftest a-user-can-get-a-count-of-commodities-in-his-entity (assert-successful-count (get-a-count-of-commodities "[email protected]"))) (deftest a-user-cannot-get-a-count-of-commodities-in-anothers-entity (assert-blocked-count (get-a-count-of-commodities "[email protected]"))) (defn- get-a-list-of-commodities [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :get (path :api :entities (:id entity) :commodities)) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-list [[response body]] (is (http-success? response)) (is (seq-of-maps-like? [{:name "Microsoft, Inc" :symbol "MSFT" :type "stock" :exchange "nasdaq"} {:name "US Dollar" :symbol "USD" :type "currency"}] body) "The body contains the list of commodities")) (defn- assert-blocked-list [[response body]] (is (http-success? response)) (is (empty? body) "The body is empty")) (deftest a-user-can-get-a-list-of-commodities-in-his-entity (assert-successful-list (get-a-list-of-commodities "[email protected]"))) (deftest a-user-cannot-get-a-list-of-commodities-in-anothers-entity (assert-blocked-list (get-a-list-of-commodities "[email protected]"))) (defn- get-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :get (path :api :commodities (:id msft))) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-get [[response body]] (is (http-success? response)) (is (comparable? {:name "Microsoft, Inc" :symbol "MSFT" :type "stock" :exchange "nasdaq"} body) "The specified commodity is returned in the response")) (defn- assert-blocked-get [[response]] (is (http-not-found? response))) (deftest a-user-can-get-a-commodity-in-his-entity (assert-successful-get (get-a-commodity "[email protected]"))) (deftest a-user-cannot-get-a-commodity-in-aothers-entity (assert-blocked-get (get-a-commodity "[email protected]"))) (def ^:private commodity-attributes {:type "stock" :name "Apple, Inc." :symbol "AAPL" :exchange "nasdaq"}) (defn- create-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :post (path :api :entities (:id entity) :commodities)) (req/json-body commodity-attributes) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/search {:entity-id (:id entity)})] [response body retrieved])) (defn- assert-successful-create [[response body retrieved]] (is (http-created? response)) (is (comparable? commodity-attributes body) "The newly created commodity is returned in the response") (is (seq-with-map-like? (-> commodity-attributes (update-in [:type] keyword) (update-in [:exchange] keyword)) retrieved) "The new commodity can be retrieved from the database")) (defn- assert-blocked-create [[response _ retrieved]] (is (http-not-found? response)) (is (seq-with-no-map-like? (-> commodity-attributes (update-in [:type] keyword) (update-in [:exchange] keyword)) retrieved) "The commodity is not created")) (deftest a-user-can-create-a-commodity-in-his-entity (assert-successful-create (create-a-commodity "[email protected]"))) (deftest a-user-cannot-create-an-commodity-in-anothers-entity (assert-blocked-create (create-a-commodity "[email protected]"))) (deftest attempt-to-create-an-invalid-commodity (let [ctx (realize context) user (find-user ctx "[email protected]") entity (find-entity ctx "Personal") response (-> (req/request :post (path :api :entities (:id entity) :commodities)) (req/json-body (assoc commodity-attributes :exchange "notvalid")) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/search {:entity-id (:id entity)})] (is (http-bad-request? response)) (is (invalid? body [:exchange] "Exchange must be amex, nasdaq, or nyse")) (is (not-any? #(= "AAPL" (:symbol %)) retrieved) "The record is not created"))) (defn- update-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :patch (path :api :commodities (:id msft))) (req/json-body (assoc msft :name "Microsoft, Ltd.")) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/find msft)] [response body retrieved])) (defn- assert-successful-update [[response body retrieved]] (is (http-success? response)) (is (comparable? {:name "Microsoft, Ltd."} body) "The updated commodity is returned in the body") (is (comparable? {:name "Microsoft, Ltd."} retrieved) "The record is updated in the database")) (defn- assert-blocked-update [[response _ retrieved]] (is (http-not-found? response)) (is (comparable? {:name "Microsoft, Inc"} retrieved) "The record is not updated in the database")) (deftest a-user-can-update-a-commodity-in-his-entity (assert-successful-update (update-a-commodity "[email protected]"))) (deftest a-user-cannot-update-a-commodity-in-anothers-entity (assert-blocked-update (update-a-commodity "[email protected]"))) (defn- delete-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :delete (path :api :commodities (:id msft))) (add-auth user) app) retrieved (coms/find msft)] [response retrieved])) (defn- assert-successful-delete [[response retrieved]] (is (http-success? response)) (is (nil? retrieved) "The commodity cannot be retrieved after delete")) (defn- assert-blocked-delete [[response retrieved]] (is (http-not-found? response)) (is retrieved "The commodity can be retrieved after failed delete")) (deftest a-user-can-delete-a-commodity-in-his-entity (assert-successful-delete (delete-a-commodity "[email protected]"))) (deftest a-user-cannot-delete-a-commodity-in-anothers-entity (assert-blocked-delete (delete-a-commodity "[email protected]")))
17373
(ns clj-money.api.commodities-test (:require [clojure.test :refer [deftest use-fixtures is]] [ring.mock.request :as req] [cheshire.core :as json] [clj-factory.core :refer [factory]] [dgknght.app-lib.web :refer [path]] [dgknght.app-lib.test] [clj-money.factories.user-factory] [clj-money.test-context :refer [realize find-user find-entity find-commodity]] [clj-money.test-helpers :refer [reset-db]] [clj-money.api.test-helper :refer [add-auth]] [clj-money.models.commodities :as coms] [clj-money.web.server :refer [app]])) (use-fixtures :each reset-db) (def ^:private context {:users (->> ["<EMAIL>" "<EMAIL>"] (mapv #(factory :user {:email %}))) :entities [{:name "Personal" :user-id "<EMAIL>"} {:name "Business" :user-id "<EMAIL>"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency :entity-id "Personal"} {:name "Microsoft, Inc" :symbol "MSFT" :type :stock :exchange :nasdaq :entity-id "Personal"}]}) (defn- get-a-count-of-commodities [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :get (path :api :entities (:id entity) :commodities :count)) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-count [[response body]] (is (http-success? response)) (is (= {:count 2} body) "The body contains the count")) (defn- assert-blocked-count [[response body]] (is (http-success? response)) (is (= {:count 0} body) "The body contains a count of zero")) (deftest a-user-can-get-a-count-of-commodities-in-his-entity (assert-successful-count (get-a-count-of-commodities "<EMAIL>"))) (deftest a-user-cannot-get-a-count-of-commodities-in-anothers-entity (assert-blocked-count (get-a-count-of-commodities "<EMAIL>"))) (defn- get-a-list-of-commodities [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :get (path :api :entities (:id entity) :commodities)) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-list [[response body]] (is (http-success? response)) (is (seq-of-maps-like? [{:name "Microsoft, Inc" :symbol "MSFT" :type "stock" :exchange "nasdaq"} {:name "US Dollar" :symbol "USD" :type "currency"}] body) "The body contains the list of commodities")) (defn- assert-blocked-list [[response body]] (is (http-success? response)) (is (empty? body) "The body is empty")) (deftest a-user-can-get-a-list-of-commodities-in-his-entity (assert-successful-list (get-a-list-of-commodities "<EMAIL>"))) (deftest a-user-cannot-get-a-list-of-commodities-in-anothers-entity (assert-blocked-list (get-a-list-of-commodities "<EMAIL>"))) (defn- get-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :get (path :api :commodities (:id msft))) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-get [[response body]] (is (http-success? response)) (is (comparable? {:name "Microsoft, Inc" :symbol "MSFT" :type "stock" :exchange "nasdaq"} body) "The specified commodity is returned in the response")) (defn- assert-blocked-get [[response]] (is (http-not-found? response))) (deftest a-user-can-get-a-commodity-in-his-entity (assert-successful-get (get-a-commodity "<EMAIL>"))) (deftest a-user-cannot-get-a-commodity-in-aothers-entity (assert-blocked-get (get-a-commodity "<EMAIL>"))) (def ^:private commodity-attributes {:type "stock" :name "Apple, Inc." :symbol "AAPL" :exchange "nasdaq"}) (defn- create-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :post (path :api :entities (:id entity) :commodities)) (req/json-body commodity-attributes) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/search {:entity-id (:id entity)})] [response body retrieved])) (defn- assert-successful-create [[response body retrieved]] (is (http-created? response)) (is (comparable? commodity-attributes body) "The newly created commodity is returned in the response") (is (seq-with-map-like? (-> commodity-attributes (update-in [:type] keyword) (update-in [:exchange] keyword)) retrieved) "The new commodity can be retrieved from the database")) (defn- assert-blocked-create [[response _ retrieved]] (is (http-not-found? response)) (is (seq-with-no-map-like? (-> commodity-attributes (update-in [:type] keyword) (update-in [:exchange] keyword)) retrieved) "The commodity is not created")) (deftest a-user-can-create-a-commodity-in-his-entity (assert-successful-create (create-a-commodity "<EMAIL>"))) (deftest a-user-cannot-create-an-commodity-in-anothers-entity (assert-blocked-create (create-a-commodity "<EMAIL>"))) (deftest attempt-to-create-an-invalid-commodity (let [ctx (realize context) user (find-user ctx "<EMAIL>") entity (find-entity ctx "Personal") response (-> (req/request :post (path :api :entities (:id entity) :commodities)) (req/json-body (assoc commodity-attributes :exchange "notvalid")) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/search {:entity-id (:id entity)})] (is (http-bad-request? response)) (is (invalid? body [:exchange] "Exchange must be amex, nasdaq, or nyse")) (is (not-any? #(= "AAPL" (:symbol %)) retrieved) "The record is not created"))) (defn- update-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :patch (path :api :commodities (:id msft))) (req/json-body (assoc msft :name "Microsoft, Ltd.")) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/find msft)] [response body retrieved])) (defn- assert-successful-update [[response body retrieved]] (is (http-success? response)) (is (comparable? {:name "Microsoft, Ltd."} body) "The updated commodity is returned in the body") (is (comparable? {:name "Microsoft, Ltd."} retrieved) "The record is updated in the database")) (defn- assert-blocked-update [[response _ retrieved]] (is (http-not-found? response)) (is (comparable? {:name "Microsoft, Inc"} retrieved) "The record is not updated in the database")) (deftest a-user-can-update-a-commodity-in-his-entity (assert-successful-update (update-a-commodity "<EMAIL>"))) (deftest a-user-cannot-update-a-commodity-in-anothers-entity (assert-blocked-update (update-a-commodity "<EMAIL>"))) (defn- delete-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :delete (path :api :commodities (:id msft))) (add-auth user) app) retrieved (coms/find msft)] [response retrieved])) (defn- assert-successful-delete [[response retrieved]] (is (http-success? response)) (is (nil? retrieved) "The commodity cannot be retrieved after delete")) (defn- assert-blocked-delete [[response retrieved]] (is (http-not-found? response)) (is retrieved "The commodity can be retrieved after failed delete")) (deftest a-user-can-delete-a-commodity-in-his-entity (assert-successful-delete (delete-a-commodity "<EMAIL>"))) (deftest a-user-cannot-delete-a-commodity-in-anothers-entity (assert-blocked-delete (delete-a-commodity "<EMAIL>")))
true
(ns clj-money.api.commodities-test (:require [clojure.test :refer [deftest use-fixtures is]] [ring.mock.request :as req] [cheshire.core :as json] [clj-factory.core :refer [factory]] [dgknght.app-lib.web :refer [path]] [dgknght.app-lib.test] [clj-money.factories.user-factory] [clj-money.test-context :refer [realize find-user find-entity find-commodity]] [clj-money.test-helpers :refer [reset-db]] [clj-money.api.test-helper :refer [add-auth]] [clj-money.models.commodities :as coms] [clj-money.web.server :refer [app]])) (use-fixtures :each reset-db) (def ^:private context {:users (->> ["PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"] (mapv #(factory :user {:email %}))) :entities [{:name "Personal" :user-id "PI:EMAIL:<EMAIL>END_PI"} {:name "Business" :user-id "PI:EMAIL:<EMAIL>END_PI"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency :entity-id "Personal"} {:name "Microsoft, Inc" :symbol "MSFT" :type :stock :exchange :nasdaq :entity-id "Personal"}]}) (defn- get-a-count-of-commodities [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :get (path :api :entities (:id entity) :commodities :count)) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-count [[response body]] (is (http-success? response)) (is (= {:count 2} body) "The body contains the count")) (defn- assert-blocked-count [[response body]] (is (http-success? response)) (is (= {:count 0} body) "The body contains a count of zero")) (deftest a-user-can-get-a-count-of-commodities-in-his-entity (assert-successful-count (get-a-count-of-commodities "PI:EMAIL:<EMAIL>END_PI"))) (deftest a-user-cannot-get-a-count-of-commodities-in-anothers-entity (assert-blocked-count (get-a-count-of-commodities "PI:EMAIL:<EMAIL>END_PI"))) (defn- get-a-list-of-commodities [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :get (path :api :entities (:id entity) :commodities)) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-list [[response body]] (is (http-success? response)) (is (seq-of-maps-like? [{:name "Microsoft, Inc" :symbol "MSFT" :type "stock" :exchange "nasdaq"} {:name "US Dollar" :symbol "USD" :type "currency"}] body) "The body contains the list of commodities")) (defn- assert-blocked-list [[response body]] (is (http-success? response)) (is (empty? body) "The body is empty")) (deftest a-user-can-get-a-list-of-commodities-in-his-entity (assert-successful-list (get-a-list-of-commodities "PI:EMAIL:<EMAIL>END_PI"))) (deftest a-user-cannot-get-a-list-of-commodities-in-anothers-entity (assert-blocked-list (get-a-list-of-commodities "PI:EMAIL:<EMAIL>END_PI"))) (defn- get-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :get (path :api :commodities (:id msft))) (add-auth user) app) body (json/parse-string (:body response) true)] [response body])) (defn- assert-successful-get [[response body]] (is (http-success? response)) (is (comparable? {:name "Microsoft, Inc" :symbol "MSFT" :type "stock" :exchange "nasdaq"} body) "The specified commodity is returned in the response")) (defn- assert-blocked-get [[response]] (is (http-not-found? response))) (deftest a-user-can-get-a-commodity-in-his-entity (assert-successful-get (get-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (deftest a-user-cannot-get-a-commodity-in-aothers-entity (assert-blocked-get (get-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (def ^:private commodity-attributes {:type "stock" :name "Apple, Inc." :symbol "AAPL" :exchange "nasdaq"}) (defn- create-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) entity (find-entity ctx "Personal") response (-> (req/request :post (path :api :entities (:id entity) :commodities)) (req/json-body commodity-attributes) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/search {:entity-id (:id entity)})] [response body retrieved])) (defn- assert-successful-create [[response body retrieved]] (is (http-created? response)) (is (comparable? commodity-attributes body) "The newly created commodity is returned in the response") (is (seq-with-map-like? (-> commodity-attributes (update-in [:type] keyword) (update-in [:exchange] keyword)) retrieved) "The new commodity can be retrieved from the database")) (defn- assert-blocked-create [[response _ retrieved]] (is (http-not-found? response)) (is (seq-with-no-map-like? (-> commodity-attributes (update-in [:type] keyword) (update-in [:exchange] keyword)) retrieved) "The commodity is not created")) (deftest a-user-can-create-a-commodity-in-his-entity (assert-successful-create (create-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (deftest a-user-cannot-create-an-commodity-in-anothers-entity (assert-blocked-create (create-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (deftest attempt-to-create-an-invalid-commodity (let [ctx (realize context) user (find-user ctx "PI:EMAIL:<EMAIL>END_PI") entity (find-entity ctx "Personal") response (-> (req/request :post (path :api :entities (:id entity) :commodities)) (req/json-body (assoc commodity-attributes :exchange "notvalid")) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/search {:entity-id (:id entity)})] (is (http-bad-request? response)) (is (invalid? body [:exchange] "Exchange must be amex, nasdaq, or nyse")) (is (not-any? #(= "AAPL" (:symbol %)) retrieved) "The record is not created"))) (defn- update-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :patch (path :api :commodities (:id msft))) (req/json-body (assoc msft :name "Microsoft, Ltd.")) (add-auth user) app) body (json/parse-string (:body response) true) retrieved (coms/find msft)] [response body retrieved])) (defn- assert-successful-update [[response body retrieved]] (is (http-success? response)) (is (comparable? {:name "Microsoft, Ltd."} body) "The updated commodity is returned in the body") (is (comparable? {:name "Microsoft, Ltd."} retrieved) "The record is updated in the database")) (defn- assert-blocked-update [[response _ retrieved]] (is (http-not-found? response)) (is (comparable? {:name "Microsoft, Inc"} retrieved) "The record is not updated in the database")) (deftest a-user-can-update-a-commodity-in-his-entity (assert-successful-update (update-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (deftest a-user-cannot-update-a-commodity-in-anothers-entity (assert-blocked-update (update-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (defn- delete-a-commodity [email] (let [ctx (realize context) user (find-user ctx email) msft (find-commodity ctx "MSFT") response (-> (req/request :delete (path :api :commodities (:id msft))) (add-auth user) app) retrieved (coms/find msft)] [response retrieved])) (defn- assert-successful-delete [[response retrieved]] (is (http-success? response)) (is (nil? retrieved) "The commodity cannot be retrieved after delete")) (defn- assert-blocked-delete [[response retrieved]] (is (http-not-found? response)) (is retrieved "The commodity can be retrieved after failed delete")) (deftest a-user-can-delete-a-commodity-in-his-entity (assert-successful-delete (delete-a-commodity "PI:EMAIL:<EMAIL>END_PI"))) (deftest a-user-cannot-delete-a-commodity-in-anothers-entity (assert-blocked-delete (delete-a-commodity "PI:EMAIL:<EMAIL>END_PI")))
[ { "context": "ildren}))\n\n(def ^:private wrapper-key (js/Symbol \"tsers$$wrapper\"))\n(def ^:private memo-wrapper-key (js/Symbol \"ts", "end": 4963, "score": 0.9838104248046875, "start": 4949, "tag": "KEY", "value": "tsers$$wrapper" }, { "context": "er\"))\n(def ^:private memo-wrapper-key (js/Symbol \"tsers$$memo$$wrapper\"))\n\n(defn- display-name [comp]\n (or (.-displayNa", "end": 5031, "score": 0.9927310943603516, "start": 5011, "tag": "KEY", "value": "tsers$$memo$$wrapper" }, { "context": ":context user-ctx\n :value \\\"Matti\\\"}\n [application]]\n ```\"\n [{:keys [context va", "end": 13339, "score": 0.8610956072807312, "start": 13334, "tag": "NAME", "value": "Matti" } ]
src/main/tsers/react.cljs
tav10102/cljs-vanilla-react-example
0
(ns tsers.react (:require [clojure.string :as string] [goog.object :as gobj] ["react" :as reactjs] ["react-dom" :as react-dom])) ; cache for parsed hiccup tags and converted js props (def ^:private tag-cache (js/Map.)) (def ^:private js-prop-cache (doto (js/Map.) (.set "class" "className") (.set "for" "htmlFor") (.set "charset" "charSet"))) ;; Copied from reagent (originally copied from hiccup) (def ^:private re-tag #"([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?") (defn- parse-tag [hiccup-tag] (let [tag-s (if (string? hiccup-tag) hiccup-tag (name hiccup-tag))] (if-let [cached-result (.get tag-cache tag-s)] cached-result (let [[tag id class] (->> tag-s (name) (re-matches re-tag) (next)) _ (assert tag (str "Invalid tag: '" tag-s "'")) classes (some-> class (string/replace #"\." " ")) result #js {:tag tag :id id :classes classes}] (.set tag-cache tag-s result) result)))) (defn- camelize-prop-key [s] (if-not (string/starts-with? s "data-") ;; JS interrop for SPEED (let [parts (.split s "-") n (alength parts) buf (js/Array. n)] (aset buf 0 (aget parts 0)) (loop [i 1] (when (< i n) (as-> (aget parts i) p (str (.toUpperCase (.charAt p 0)) (subs p 1)) (aset buf i p)) (recur (inc i)))) (.join buf "")) s)) (declare as-element jsfy-props) (defn- primitive? [x] (or (boolean? x) (string? x) (number? x) (nil? x) (undefined? x))) (defn- fq-name [kw] (str (if-let [ns (namespace kw)] (str ns "/")) (name kw))) (defn- keyword->js-prop-name [k] (let [prop-s (name k)] (if-let [cached-result (.get js-prop-cache prop-s)] cached-result (let [res (camelize-prop-key prop-s)] (.set js-prop-cache prop-s res) res)))) (defn- jsfy-prop-key [k] (cond (keyword? k) (keyword->js-prop-name k) (string? k) k :else (throw (js/Error. (str "Invalid intrinsic property key" (pr-str k)))))) (defn- jsfy-prop-value [x] (cond (or (primitive? x) (fn? x)) x (keyword? x) (fq-name x) (symbol? x) (fq-name x) (map? x) (let [val #js {}] (doseq [[k v] x] (unchecked-set val (jsfy-prop-key k) (jsfy-prop-value v))) val) (coll? x) (let [val #js []] (doseq [v x] (.push val (jsfy-prop-value v))) val) (ifn? x) (fn [& args] (apply x args)) (satisfies? IPrintWithWriter key) (pr-str key) :else x)) (defn- jsfy-class-name [x] (cond (string? x) x (keyword? x) (name x) (symbol? x) (name x) (map? x) (->> (keep (fn [[k v]] (when v (jsfy-class-name k))) x) (string/join " ")) (coll? x) (->> (map jsfy-class-name x) (string/join " ")) :else (pr-str x))) (defn- jsfy-element-props [props] (if (some? props) (let [js-props #js {}] (doseq [[k v] props] (case k :class (unchecked-set js-props "className" (jsfy-class-name v)) :children nil (unchecked-set js-props (jsfy-prop-key k) (jsfy-prop-value v)))) js-props) #js {})) (defn- $ [type js-props cljs-children] (let [args #js [type js-props]] (doseq [child cljs-children] (.push args (as-element child))) (.apply reactjs/createElement nil args))) (defn- create-fragment [props children] ($ reactjs/Fragment (jsfy-element-props props) children)) (defn- create-intrinsic-element [parsed-tag props children] (let [js-props (jsfy-element-props props) tag-name (unchecked-get parsed-tag "tag") id (unchecked-get parsed-tag "id") classes (unchecked-get parsed-tag "classes")] (when (some? id) (assert (nil? (unchecked-get js-props "id")) (str "Id defined twice for tag " tag-name)) (unchecked-set js-props "id" id)) (when (some? classes) (if-let [class-names-from-props (unchecked-get js-props "className")] (unchecked-set js-props "className" (str class-names-from-props " " classes)) (unchecked-set js-props "className" classes))) ($ tag-name js-props children))) (defn- unwrap-delegated-children [children] (when (seq children) (if (and (empty? (next children)) (::children (meta (first children)))) (first children) children))) (defn- unwrap-props [wrapped-props] (let [children (some-> (unchecked-get wrapped-props "c") (vary-meta assoc ::children true)) props (or (unchecked-get wrapped-props "p") {})] (if children (assoc props :children children) props))) (defn- wrap-props [props children] (if-some [key (:key props)] #js {:p props :c children :key (jsfy-prop-value key)} #js {:p props :c children})) (def ^:private wrapper-key (js/Symbol "tsers$$wrapper")) (def ^:private memo-wrapper-key (js/Symbol "tsers$$memo$$wrapper")) (defn- display-name [comp] (or (.-displayName comp) (.-name comp))) (defn- wrapper-component [component] (let [wrapper (fn [react-props] (-> (unwrap-props react-props) (component) (as-element)))] (unchecked-set wrapper "displayName" (display-name component)) wrapper)) (defn- memo-eq [prev-wrapped-props next-wrapped-props] (and (some? prev-wrapped-props) (some? next-wrapped-props) (= (unwrap-props prev-wrapped-props) (unwrap-props next-wrapped-props)))) (defn- create-component-element [component props children memo?] (let [type (if memo? (or (unchecked-get component memo-wrapper-key) (let [wrapper (wrapper-component component) memo (reactjs/memo wrapper memo-eq)] (unchecked-set component memo-wrapper-key memo) memo)) (or (unchecked-get component wrapper-key) (let [wrapper (wrapper-component component)] (unchecked-set component wrapper-key wrapper) wrapper)))] (reactjs/createElement type (wrap-props props children)))) (defn- hiccup->element [[type & [props & children :as props+children] :as hiccup]] (let [props (when (map? props) props) children (if props (if (>= (count hiccup) 3) (unwrap-delegated-children children) (:children props)) (unwrap-delegated-children props+children))] (cond (= :<> type) (create-fragment props children) (or (keyword? type) (string? type)) (create-intrinsic-element (parse-tag type) props children) (or (fn? type) (ifn? type)) (create-component-element type props children (:memo (meta hiccup))) (some? (.-$$typeof type)) (create-component-element type props children false) :else (throw (js/Error. (str "Invalid hiccup tag type: " (type type))))))) (defn- array-of-elements [xs] (let [elems #js []] (doseq [x xs] (.push elems (as-element x))) elems)) (defn- ref-atom [initial-value] (let [a (atom initial-value)] (assert (identical? js/undefined (.-current a))) ; for React ref interrop (js/Object.defineProperty a "current" #js {:get (fn [] @a) :set (fn [val] (reset! a val))}) a)) (defn- jsfy-deps-array [deps] (when deps (let [js-deps #js []] (doseq [x deps] (->> (cond (keyword? x) (fq-name x) (symbol? x) (fq-name x) (uuid? x) (pr-str x) :else x) (.push js-deps))) js-deps))) (def ^:private ErrorBoundary (let [proto #js {:componentDidCatch (fn [err info] (let [this (js-this) on-error (.. this -props -onError)] (on-error err info) (.setState this #js {:latestError err}))) :shouldComponentUpdate (fn [next-props _] (not (identical? (.-props (js-this)) next-props))) :render (fn [] (.. (js-this) -props -children))} ctor (fn [props ctx] (let [this (js-this)] (.call reactjs/Component this props ctx)))] (gobj/extend (.-prototype ctor) (.-prototype reactjs/Component) proto) (set! (.-displayName ctor) "ErrorBoundary") (set! (.. ctor -prototype -constructor) ctor) ctor)) (defn- wrap-eff [eff] (fn effect-wrapper [] (let [cancel (eff)] (when (fn? cancel) cancel)))) ;; (defn as-element "Converts ClojureScript styled element (e.g. hiccup) to native React element. Normally you shouldn't use this from you CLJS codebase. Main use case is JavaScript library interoperability. ```clojure ;; the following lines are equivalent (as-element [:button {:disabled true} \"tsers\"]) (create-element \"button\" #js {:disabled true} \"tsers\") ;; conversion is done for entire hiccup (def app-el (as-element [:div.app [sidebar {:version 123 :title \"tsers\"] [main {}]])) ```" [x] (cond (vector? x) (hiccup->element x) (primitive? x) x (seq? x) (array-of-elements x) (keyword? x) (fq-name x) (symbol? x) (fq-name x) (satisfies? IPrintWithWriter x) (pr-str x) :else x)) (def create-element "Native React.createElement. Does **not** perform any conversions, see [[as-element]] if you need to convert hiccup elements to native React elements." reactjs/createElement) (defn render [element container] (react-dom/render (as-element element) container)) (defn use-state "Wrapper for React `useState` hook. Uses ClojureScript's value equality for detecting state changes, e.g. ```clojure (let [[state set-state] (use-state {:foo 12}) ... (set-state {:foo 12}) ;; wont trigger state change ...) ```" [initial] (let [xs (reactjs/useState initial) state (aget xs 0) js-set-state (aget xs 1) set-state (or (unchecked-get js-set-state wrapper-key) (let [f (fn [next] (js-set-state (fn [v'] (let [v (if (fn? next) (next v') next)] (if (= v v') v' v)))))] (unchecked-set js-set-state wrapper-key f) f))] [state set-state])) (defn use-ref "Wrapper for React `useRef` hook. Returns ClojureScript atom instead of mutable JS object. Ref atom can be used as :ref in intrinsic elements." [initial] (let [ref (reactjs/useRef nil)] (or (unchecked-get ref "current") (let [a (ref-atom initial)] (unchecked-set ref "current" a) a)))) (defn use-effect "Wrapper for React `useEffect` hook. Uses reference equality for dependency change detection but treats the following types as 'value' types: keywords, symbols, uuids. For rest (e.g. collections), use ClojureScript's [[hash]] function. ```clojure (let [[status set-status] (use-state :initial) _ (use-effect (fn [] (let [title (case status :initial \"Odottaa\" :loading \"Ladataan..\" \"...\") (set! js/document -title title))) [status]) ...) (let [[nums set-nums] (use-state [1 2 3 4]) _ (use-effect (fn [] ...) [(hash nums)])] ...) ```" [eff deps] {:pre [(fn? eff) (or (vector? deps) (nil? deps))]} (reactjs/useEffect (wrap-eff eff) (jsfy-deps-array deps))) (defn use-layout-effect "Wrapper for React `useLayoutEffect` hook. Has same dependency semantics as [[use-effect]] hook." [eff deps] {:pre [(fn? eff) (or (vector? deps) (nil? deps))]} (reactjs/useEffect (wrap-eff eff) (jsfy-deps-array deps))) (defn use-memo "Wrapper for React `useMemo` hook. Has same dependency semantics as [[use-effect]] hook." [f deps] {:pre [(fn? f) (or (vector? deps) (nil? deps))]} (reactjs/useMemo f (jsfy-deps-array deps))) (defn use-callback "Wrapper for React `useCallback` hook. Has same dependency semantics as [[use-effect]] hook." [cb deps] {:pre [(fn? cb) (or (vector? deps) (nil? deps))]} (reactjs/useCallback cb (jsfy-deps-array deps))) (defn create-context "Creates a new React context that can be used with [[context-provider]] component and [[use-context]] hook." [default-value] (reactjs/createContext default-value)) (defn use-context "Wrapper for React `useContext` hook. Accepts context created with [[create-context]] function." [context] {:pre [(some? context) (some? (.-Provider context))]} (reactjs/useContext context)) (defn context-provider "Wrapper for React's context provider component. ```clojure (def user-ctx (create-context nil)) [context-provider {:context user-ctx :value \"Matti\"} [application]] ```" [{:keys [context value children]}] {:pre [(some? context) (some? (.-Provider context))]} ($ (.-Provider context) #js {:value value} children)) (defn suspense "Wrapper for `React.Suspense` component ```clojure [suspense {:fallback [spinner]} ...] ```" [{:keys [fallback children]}] ($ reactjs/Suspense #js {:fallback (as-element fallback)} children)) (defn lazy "Wrapper for `React.lazy`. Expects promise to import a valid **cljs** react component (component that accepts persistent map as props and returns hiccup)." [loader-f] (let [type (reactjs/lazy (fn [] (.then (loader-f) (fn [import] (let [component (unchecked-get import "default") wrapper (fn [js-props] (-> (unchecked-get js-props "p") (component) (as-element)))] #js {:default wrapper})))))] (fn lazy-wrapper [props] ($ type #js {:p props} [])))) (defn error-boundary "Wrapper for `React.ErrorBoundary` component ```clojure (let [[error set-error] (use-state nil)] (if (nil? error) [error-boundary {:on-error set-error} [app]] [error-screen {:error error}])) ```" [{:keys [on-error children]}] {:pre [(fn? on-error)]} ($ ErrorBoundary #js {:onError on-error} children))
73460
(ns tsers.react (:require [clojure.string :as string] [goog.object :as gobj] ["react" :as reactjs] ["react-dom" :as react-dom])) ; cache for parsed hiccup tags and converted js props (def ^:private tag-cache (js/Map.)) (def ^:private js-prop-cache (doto (js/Map.) (.set "class" "className") (.set "for" "htmlFor") (.set "charset" "charSet"))) ;; Copied from reagent (originally copied from hiccup) (def ^:private re-tag #"([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?") (defn- parse-tag [hiccup-tag] (let [tag-s (if (string? hiccup-tag) hiccup-tag (name hiccup-tag))] (if-let [cached-result (.get tag-cache tag-s)] cached-result (let [[tag id class] (->> tag-s (name) (re-matches re-tag) (next)) _ (assert tag (str "Invalid tag: '" tag-s "'")) classes (some-> class (string/replace #"\." " ")) result #js {:tag tag :id id :classes classes}] (.set tag-cache tag-s result) result)))) (defn- camelize-prop-key [s] (if-not (string/starts-with? s "data-") ;; JS interrop for SPEED (let [parts (.split s "-") n (alength parts) buf (js/Array. n)] (aset buf 0 (aget parts 0)) (loop [i 1] (when (< i n) (as-> (aget parts i) p (str (.toUpperCase (.charAt p 0)) (subs p 1)) (aset buf i p)) (recur (inc i)))) (.join buf "")) s)) (declare as-element jsfy-props) (defn- primitive? [x] (or (boolean? x) (string? x) (number? x) (nil? x) (undefined? x))) (defn- fq-name [kw] (str (if-let [ns (namespace kw)] (str ns "/")) (name kw))) (defn- keyword->js-prop-name [k] (let [prop-s (name k)] (if-let [cached-result (.get js-prop-cache prop-s)] cached-result (let [res (camelize-prop-key prop-s)] (.set js-prop-cache prop-s res) res)))) (defn- jsfy-prop-key [k] (cond (keyword? k) (keyword->js-prop-name k) (string? k) k :else (throw (js/Error. (str "Invalid intrinsic property key" (pr-str k)))))) (defn- jsfy-prop-value [x] (cond (or (primitive? x) (fn? x)) x (keyword? x) (fq-name x) (symbol? x) (fq-name x) (map? x) (let [val #js {}] (doseq [[k v] x] (unchecked-set val (jsfy-prop-key k) (jsfy-prop-value v))) val) (coll? x) (let [val #js []] (doseq [v x] (.push val (jsfy-prop-value v))) val) (ifn? x) (fn [& args] (apply x args)) (satisfies? IPrintWithWriter key) (pr-str key) :else x)) (defn- jsfy-class-name [x] (cond (string? x) x (keyword? x) (name x) (symbol? x) (name x) (map? x) (->> (keep (fn [[k v]] (when v (jsfy-class-name k))) x) (string/join " ")) (coll? x) (->> (map jsfy-class-name x) (string/join " ")) :else (pr-str x))) (defn- jsfy-element-props [props] (if (some? props) (let [js-props #js {}] (doseq [[k v] props] (case k :class (unchecked-set js-props "className" (jsfy-class-name v)) :children nil (unchecked-set js-props (jsfy-prop-key k) (jsfy-prop-value v)))) js-props) #js {})) (defn- $ [type js-props cljs-children] (let [args #js [type js-props]] (doseq [child cljs-children] (.push args (as-element child))) (.apply reactjs/createElement nil args))) (defn- create-fragment [props children] ($ reactjs/Fragment (jsfy-element-props props) children)) (defn- create-intrinsic-element [parsed-tag props children] (let [js-props (jsfy-element-props props) tag-name (unchecked-get parsed-tag "tag") id (unchecked-get parsed-tag "id") classes (unchecked-get parsed-tag "classes")] (when (some? id) (assert (nil? (unchecked-get js-props "id")) (str "Id defined twice for tag " tag-name)) (unchecked-set js-props "id" id)) (when (some? classes) (if-let [class-names-from-props (unchecked-get js-props "className")] (unchecked-set js-props "className" (str class-names-from-props " " classes)) (unchecked-set js-props "className" classes))) ($ tag-name js-props children))) (defn- unwrap-delegated-children [children] (when (seq children) (if (and (empty? (next children)) (::children (meta (first children)))) (first children) children))) (defn- unwrap-props [wrapped-props] (let [children (some-> (unchecked-get wrapped-props "c") (vary-meta assoc ::children true)) props (or (unchecked-get wrapped-props "p") {})] (if children (assoc props :children children) props))) (defn- wrap-props [props children] (if-some [key (:key props)] #js {:p props :c children :key (jsfy-prop-value key)} #js {:p props :c children})) (def ^:private wrapper-key (js/Symbol "<KEY>")) (def ^:private memo-wrapper-key (js/Symbol "<KEY>")) (defn- display-name [comp] (or (.-displayName comp) (.-name comp))) (defn- wrapper-component [component] (let [wrapper (fn [react-props] (-> (unwrap-props react-props) (component) (as-element)))] (unchecked-set wrapper "displayName" (display-name component)) wrapper)) (defn- memo-eq [prev-wrapped-props next-wrapped-props] (and (some? prev-wrapped-props) (some? next-wrapped-props) (= (unwrap-props prev-wrapped-props) (unwrap-props next-wrapped-props)))) (defn- create-component-element [component props children memo?] (let [type (if memo? (or (unchecked-get component memo-wrapper-key) (let [wrapper (wrapper-component component) memo (reactjs/memo wrapper memo-eq)] (unchecked-set component memo-wrapper-key memo) memo)) (or (unchecked-get component wrapper-key) (let [wrapper (wrapper-component component)] (unchecked-set component wrapper-key wrapper) wrapper)))] (reactjs/createElement type (wrap-props props children)))) (defn- hiccup->element [[type & [props & children :as props+children] :as hiccup]] (let [props (when (map? props) props) children (if props (if (>= (count hiccup) 3) (unwrap-delegated-children children) (:children props)) (unwrap-delegated-children props+children))] (cond (= :<> type) (create-fragment props children) (or (keyword? type) (string? type)) (create-intrinsic-element (parse-tag type) props children) (or (fn? type) (ifn? type)) (create-component-element type props children (:memo (meta hiccup))) (some? (.-$$typeof type)) (create-component-element type props children false) :else (throw (js/Error. (str "Invalid hiccup tag type: " (type type))))))) (defn- array-of-elements [xs] (let [elems #js []] (doseq [x xs] (.push elems (as-element x))) elems)) (defn- ref-atom [initial-value] (let [a (atom initial-value)] (assert (identical? js/undefined (.-current a))) ; for React ref interrop (js/Object.defineProperty a "current" #js {:get (fn [] @a) :set (fn [val] (reset! a val))}) a)) (defn- jsfy-deps-array [deps] (when deps (let [js-deps #js []] (doseq [x deps] (->> (cond (keyword? x) (fq-name x) (symbol? x) (fq-name x) (uuid? x) (pr-str x) :else x) (.push js-deps))) js-deps))) (def ^:private ErrorBoundary (let [proto #js {:componentDidCatch (fn [err info] (let [this (js-this) on-error (.. this -props -onError)] (on-error err info) (.setState this #js {:latestError err}))) :shouldComponentUpdate (fn [next-props _] (not (identical? (.-props (js-this)) next-props))) :render (fn [] (.. (js-this) -props -children))} ctor (fn [props ctx] (let [this (js-this)] (.call reactjs/Component this props ctx)))] (gobj/extend (.-prototype ctor) (.-prototype reactjs/Component) proto) (set! (.-displayName ctor) "ErrorBoundary") (set! (.. ctor -prototype -constructor) ctor) ctor)) (defn- wrap-eff [eff] (fn effect-wrapper [] (let [cancel (eff)] (when (fn? cancel) cancel)))) ;; (defn as-element "Converts ClojureScript styled element (e.g. hiccup) to native React element. Normally you shouldn't use this from you CLJS codebase. Main use case is JavaScript library interoperability. ```clojure ;; the following lines are equivalent (as-element [:button {:disabled true} \"tsers\"]) (create-element \"button\" #js {:disabled true} \"tsers\") ;; conversion is done for entire hiccup (def app-el (as-element [:div.app [sidebar {:version 123 :title \"tsers\"] [main {}]])) ```" [x] (cond (vector? x) (hiccup->element x) (primitive? x) x (seq? x) (array-of-elements x) (keyword? x) (fq-name x) (symbol? x) (fq-name x) (satisfies? IPrintWithWriter x) (pr-str x) :else x)) (def create-element "Native React.createElement. Does **not** perform any conversions, see [[as-element]] if you need to convert hiccup elements to native React elements." reactjs/createElement) (defn render [element container] (react-dom/render (as-element element) container)) (defn use-state "Wrapper for React `useState` hook. Uses ClojureScript's value equality for detecting state changes, e.g. ```clojure (let [[state set-state] (use-state {:foo 12}) ... (set-state {:foo 12}) ;; wont trigger state change ...) ```" [initial] (let [xs (reactjs/useState initial) state (aget xs 0) js-set-state (aget xs 1) set-state (or (unchecked-get js-set-state wrapper-key) (let [f (fn [next] (js-set-state (fn [v'] (let [v (if (fn? next) (next v') next)] (if (= v v') v' v)))))] (unchecked-set js-set-state wrapper-key f) f))] [state set-state])) (defn use-ref "Wrapper for React `useRef` hook. Returns ClojureScript atom instead of mutable JS object. Ref atom can be used as :ref in intrinsic elements." [initial] (let [ref (reactjs/useRef nil)] (or (unchecked-get ref "current") (let [a (ref-atom initial)] (unchecked-set ref "current" a) a)))) (defn use-effect "Wrapper for React `useEffect` hook. Uses reference equality for dependency change detection but treats the following types as 'value' types: keywords, symbols, uuids. For rest (e.g. collections), use ClojureScript's [[hash]] function. ```clojure (let [[status set-status] (use-state :initial) _ (use-effect (fn [] (let [title (case status :initial \"Odottaa\" :loading \"Ladataan..\" \"...\") (set! js/document -title title))) [status]) ...) (let [[nums set-nums] (use-state [1 2 3 4]) _ (use-effect (fn [] ...) [(hash nums)])] ...) ```" [eff deps] {:pre [(fn? eff) (or (vector? deps) (nil? deps))]} (reactjs/useEffect (wrap-eff eff) (jsfy-deps-array deps))) (defn use-layout-effect "Wrapper for React `useLayoutEffect` hook. Has same dependency semantics as [[use-effect]] hook." [eff deps] {:pre [(fn? eff) (or (vector? deps) (nil? deps))]} (reactjs/useEffect (wrap-eff eff) (jsfy-deps-array deps))) (defn use-memo "Wrapper for React `useMemo` hook. Has same dependency semantics as [[use-effect]] hook." [f deps] {:pre [(fn? f) (or (vector? deps) (nil? deps))]} (reactjs/useMemo f (jsfy-deps-array deps))) (defn use-callback "Wrapper for React `useCallback` hook. Has same dependency semantics as [[use-effect]] hook." [cb deps] {:pre [(fn? cb) (or (vector? deps) (nil? deps))]} (reactjs/useCallback cb (jsfy-deps-array deps))) (defn create-context "Creates a new React context that can be used with [[context-provider]] component and [[use-context]] hook." [default-value] (reactjs/createContext default-value)) (defn use-context "Wrapper for React `useContext` hook. Accepts context created with [[create-context]] function." [context] {:pre [(some? context) (some? (.-Provider context))]} (reactjs/useContext context)) (defn context-provider "Wrapper for React's context provider component. ```clojure (def user-ctx (create-context nil)) [context-provider {:context user-ctx :value \"<NAME>\"} [application]] ```" [{:keys [context value children]}] {:pre [(some? context) (some? (.-Provider context))]} ($ (.-Provider context) #js {:value value} children)) (defn suspense "Wrapper for `React.Suspense` component ```clojure [suspense {:fallback [spinner]} ...] ```" [{:keys [fallback children]}] ($ reactjs/Suspense #js {:fallback (as-element fallback)} children)) (defn lazy "Wrapper for `React.lazy`. Expects promise to import a valid **cljs** react component (component that accepts persistent map as props and returns hiccup)." [loader-f] (let [type (reactjs/lazy (fn [] (.then (loader-f) (fn [import] (let [component (unchecked-get import "default") wrapper (fn [js-props] (-> (unchecked-get js-props "p") (component) (as-element)))] #js {:default wrapper})))))] (fn lazy-wrapper [props] ($ type #js {:p props} [])))) (defn error-boundary "Wrapper for `React.ErrorBoundary` component ```clojure (let [[error set-error] (use-state nil)] (if (nil? error) [error-boundary {:on-error set-error} [app]] [error-screen {:error error}])) ```" [{:keys [on-error children]}] {:pre [(fn? on-error)]} ($ ErrorBoundary #js {:onError on-error} children))
true
(ns tsers.react (:require [clojure.string :as string] [goog.object :as gobj] ["react" :as reactjs] ["react-dom" :as react-dom])) ; cache for parsed hiccup tags and converted js props (def ^:private tag-cache (js/Map.)) (def ^:private js-prop-cache (doto (js/Map.) (.set "class" "className") (.set "for" "htmlFor") (.set "charset" "charSet"))) ;; Copied from reagent (originally copied from hiccup) (def ^:private re-tag #"([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?") (defn- parse-tag [hiccup-tag] (let [tag-s (if (string? hiccup-tag) hiccup-tag (name hiccup-tag))] (if-let [cached-result (.get tag-cache tag-s)] cached-result (let [[tag id class] (->> tag-s (name) (re-matches re-tag) (next)) _ (assert tag (str "Invalid tag: '" tag-s "'")) classes (some-> class (string/replace #"\." " ")) result #js {:tag tag :id id :classes classes}] (.set tag-cache tag-s result) result)))) (defn- camelize-prop-key [s] (if-not (string/starts-with? s "data-") ;; JS interrop for SPEED (let [parts (.split s "-") n (alength parts) buf (js/Array. n)] (aset buf 0 (aget parts 0)) (loop [i 1] (when (< i n) (as-> (aget parts i) p (str (.toUpperCase (.charAt p 0)) (subs p 1)) (aset buf i p)) (recur (inc i)))) (.join buf "")) s)) (declare as-element jsfy-props) (defn- primitive? [x] (or (boolean? x) (string? x) (number? x) (nil? x) (undefined? x))) (defn- fq-name [kw] (str (if-let [ns (namespace kw)] (str ns "/")) (name kw))) (defn- keyword->js-prop-name [k] (let [prop-s (name k)] (if-let [cached-result (.get js-prop-cache prop-s)] cached-result (let [res (camelize-prop-key prop-s)] (.set js-prop-cache prop-s res) res)))) (defn- jsfy-prop-key [k] (cond (keyword? k) (keyword->js-prop-name k) (string? k) k :else (throw (js/Error. (str "Invalid intrinsic property key" (pr-str k)))))) (defn- jsfy-prop-value [x] (cond (or (primitive? x) (fn? x)) x (keyword? x) (fq-name x) (symbol? x) (fq-name x) (map? x) (let [val #js {}] (doseq [[k v] x] (unchecked-set val (jsfy-prop-key k) (jsfy-prop-value v))) val) (coll? x) (let [val #js []] (doseq [v x] (.push val (jsfy-prop-value v))) val) (ifn? x) (fn [& args] (apply x args)) (satisfies? IPrintWithWriter key) (pr-str key) :else x)) (defn- jsfy-class-name [x] (cond (string? x) x (keyword? x) (name x) (symbol? x) (name x) (map? x) (->> (keep (fn [[k v]] (when v (jsfy-class-name k))) x) (string/join " ")) (coll? x) (->> (map jsfy-class-name x) (string/join " ")) :else (pr-str x))) (defn- jsfy-element-props [props] (if (some? props) (let [js-props #js {}] (doseq [[k v] props] (case k :class (unchecked-set js-props "className" (jsfy-class-name v)) :children nil (unchecked-set js-props (jsfy-prop-key k) (jsfy-prop-value v)))) js-props) #js {})) (defn- $ [type js-props cljs-children] (let [args #js [type js-props]] (doseq [child cljs-children] (.push args (as-element child))) (.apply reactjs/createElement nil args))) (defn- create-fragment [props children] ($ reactjs/Fragment (jsfy-element-props props) children)) (defn- create-intrinsic-element [parsed-tag props children] (let [js-props (jsfy-element-props props) tag-name (unchecked-get parsed-tag "tag") id (unchecked-get parsed-tag "id") classes (unchecked-get parsed-tag "classes")] (when (some? id) (assert (nil? (unchecked-get js-props "id")) (str "Id defined twice for tag " tag-name)) (unchecked-set js-props "id" id)) (when (some? classes) (if-let [class-names-from-props (unchecked-get js-props "className")] (unchecked-set js-props "className" (str class-names-from-props " " classes)) (unchecked-set js-props "className" classes))) ($ tag-name js-props children))) (defn- unwrap-delegated-children [children] (when (seq children) (if (and (empty? (next children)) (::children (meta (first children)))) (first children) children))) (defn- unwrap-props [wrapped-props] (let [children (some-> (unchecked-get wrapped-props "c") (vary-meta assoc ::children true)) props (or (unchecked-get wrapped-props "p") {})] (if children (assoc props :children children) props))) (defn- wrap-props [props children] (if-some [key (:key props)] #js {:p props :c children :key (jsfy-prop-value key)} #js {:p props :c children})) (def ^:private wrapper-key (js/Symbol "PI:KEY:<KEY>END_PI")) (def ^:private memo-wrapper-key (js/Symbol "PI:KEY:<KEY>END_PI")) (defn- display-name [comp] (or (.-displayName comp) (.-name comp))) (defn- wrapper-component [component] (let [wrapper (fn [react-props] (-> (unwrap-props react-props) (component) (as-element)))] (unchecked-set wrapper "displayName" (display-name component)) wrapper)) (defn- memo-eq [prev-wrapped-props next-wrapped-props] (and (some? prev-wrapped-props) (some? next-wrapped-props) (= (unwrap-props prev-wrapped-props) (unwrap-props next-wrapped-props)))) (defn- create-component-element [component props children memo?] (let [type (if memo? (or (unchecked-get component memo-wrapper-key) (let [wrapper (wrapper-component component) memo (reactjs/memo wrapper memo-eq)] (unchecked-set component memo-wrapper-key memo) memo)) (or (unchecked-get component wrapper-key) (let [wrapper (wrapper-component component)] (unchecked-set component wrapper-key wrapper) wrapper)))] (reactjs/createElement type (wrap-props props children)))) (defn- hiccup->element [[type & [props & children :as props+children] :as hiccup]] (let [props (when (map? props) props) children (if props (if (>= (count hiccup) 3) (unwrap-delegated-children children) (:children props)) (unwrap-delegated-children props+children))] (cond (= :<> type) (create-fragment props children) (or (keyword? type) (string? type)) (create-intrinsic-element (parse-tag type) props children) (or (fn? type) (ifn? type)) (create-component-element type props children (:memo (meta hiccup))) (some? (.-$$typeof type)) (create-component-element type props children false) :else (throw (js/Error. (str "Invalid hiccup tag type: " (type type))))))) (defn- array-of-elements [xs] (let [elems #js []] (doseq [x xs] (.push elems (as-element x))) elems)) (defn- ref-atom [initial-value] (let [a (atom initial-value)] (assert (identical? js/undefined (.-current a))) ; for React ref interrop (js/Object.defineProperty a "current" #js {:get (fn [] @a) :set (fn [val] (reset! a val))}) a)) (defn- jsfy-deps-array [deps] (when deps (let [js-deps #js []] (doseq [x deps] (->> (cond (keyword? x) (fq-name x) (symbol? x) (fq-name x) (uuid? x) (pr-str x) :else x) (.push js-deps))) js-deps))) (def ^:private ErrorBoundary (let [proto #js {:componentDidCatch (fn [err info] (let [this (js-this) on-error (.. this -props -onError)] (on-error err info) (.setState this #js {:latestError err}))) :shouldComponentUpdate (fn [next-props _] (not (identical? (.-props (js-this)) next-props))) :render (fn [] (.. (js-this) -props -children))} ctor (fn [props ctx] (let [this (js-this)] (.call reactjs/Component this props ctx)))] (gobj/extend (.-prototype ctor) (.-prototype reactjs/Component) proto) (set! (.-displayName ctor) "ErrorBoundary") (set! (.. ctor -prototype -constructor) ctor) ctor)) (defn- wrap-eff [eff] (fn effect-wrapper [] (let [cancel (eff)] (when (fn? cancel) cancel)))) ;; (defn as-element "Converts ClojureScript styled element (e.g. hiccup) to native React element. Normally you shouldn't use this from you CLJS codebase. Main use case is JavaScript library interoperability. ```clojure ;; the following lines are equivalent (as-element [:button {:disabled true} \"tsers\"]) (create-element \"button\" #js {:disabled true} \"tsers\") ;; conversion is done for entire hiccup (def app-el (as-element [:div.app [sidebar {:version 123 :title \"tsers\"] [main {}]])) ```" [x] (cond (vector? x) (hiccup->element x) (primitive? x) x (seq? x) (array-of-elements x) (keyword? x) (fq-name x) (symbol? x) (fq-name x) (satisfies? IPrintWithWriter x) (pr-str x) :else x)) (def create-element "Native React.createElement. Does **not** perform any conversions, see [[as-element]] if you need to convert hiccup elements to native React elements." reactjs/createElement) (defn render [element container] (react-dom/render (as-element element) container)) (defn use-state "Wrapper for React `useState` hook. Uses ClojureScript's value equality for detecting state changes, e.g. ```clojure (let [[state set-state] (use-state {:foo 12}) ... (set-state {:foo 12}) ;; wont trigger state change ...) ```" [initial] (let [xs (reactjs/useState initial) state (aget xs 0) js-set-state (aget xs 1) set-state (or (unchecked-get js-set-state wrapper-key) (let [f (fn [next] (js-set-state (fn [v'] (let [v (if (fn? next) (next v') next)] (if (= v v') v' v)))))] (unchecked-set js-set-state wrapper-key f) f))] [state set-state])) (defn use-ref "Wrapper for React `useRef` hook. Returns ClojureScript atom instead of mutable JS object. Ref atom can be used as :ref in intrinsic elements." [initial] (let [ref (reactjs/useRef nil)] (or (unchecked-get ref "current") (let [a (ref-atom initial)] (unchecked-set ref "current" a) a)))) (defn use-effect "Wrapper for React `useEffect` hook. Uses reference equality for dependency change detection but treats the following types as 'value' types: keywords, symbols, uuids. For rest (e.g. collections), use ClojureScript's [[hash]] function. ```clojure (let [[status set-status] (use-state :initial) _ (use-effect (fn [] (let [title (case status :initial \"Odottaa\" :loading \"Ladataan..\" \"...\") (set! js/document -title title))) [status]) ...) (let [[nums set-nums] (use-state [1 2 3 4]) _ (use-effect (fn [] ...) [(hash nums)])] ...) ```" [eff deps] {:pre [(fn? eff) (or (vector? deps) (nil? deps))]} (reactjs/useEffect (wrap-eff eff) (jsfy-deps-array deps))) (defn use-layout-effect "Wrapper for React `useLayoutEffect` hook. Has same dependency semantics as [[use-effect]] hook." [eff deps] {:pre [(fn? eff) (or (vector? deps) (nil? deps))]} (reactjs/useEffect (wrap-eff eff) (jsfy-deps-array deps))) (defn use-memo "Wrapper for React `useMemo` hook. Has same dependency semantics as [[use-effect]] hook." [f deps] {:pre [(fn? f) (or (vector? deps) (nil? deps))]} (reactjs/useMemo f (jsfy-deps-array deps))) (defn use-callback "Wrapper for React `useCallback` hook. Has same dependency semantics as [[use-effect]] hook." [cb deps] {:pre [(fn? cb) (or (vector? deps) (nil? deps))]} (reactjs/useCallback cb (jsfy-deps-array deps))) (defn create-context "Creates a new React context that can be used with [[context-provider]] component and [[use-context]] hook." [default-value] (reactjs/createContext default-value)) (defn use-context "Wrapper for React `useContext` hook. Accepts context created with [[create-context]] function." [context] {:pre [(some? context) (some? (.-Provider context))]} (reactjs/useContext context)) (defn context-provider "Wrapper for React's context provider component. ```clojure (def user-ctx (create-context nil)) [context-provider {:context user-ctx :value \"PI:NAME:<NAME>END_PI\"} [application]] ```" [{:keys [context value children]}] {:pre [(some? context) (some? (.-Provider context))]} ($ (.-Provider context) #js {:value value} children)) (defn suspense "Wrapper for `React.Suspense` component ```clojure [suspense {:fallback [spinner]} ...] ```" [{:keys [fallback children]}] ($ reactjs/Suspense #js {:fallback (as-element fallback)} children)) (defn lazy "Wrapper for `React.lazy`. Expects promise to import a valid **cljs** react component (component that accepts persistent map as props and returns hiccup)." [loader-f] (let [type (reactjs/lazy (fn [] (.then (loader-f) (fn [import] (let [component (unchecked-get import "default") wrapper (fn [js-props] (-> (unchecked-get js-props "p") (component) (as-element)))] #js {:default wrapper})))))] (fn lazy-wrapper [props] ($ type #js {:p props} [])))) (defn error-boundary "Wrapper for `React.ErrorBoundary` component ```clojure (let [[error set-error] (use-state nil)] (if (nil? error) [error-boundary {:on-error set-error} [app]] [error-screen {:error error}])) ```" [{:keys [on-error children]}] {:pre [(fn? on-error)]} ($ ErrorBoundary #js {:onError on-error} children))
[ { "context": ":owner owner\n :passwd passwd\n :test test\n ", "end": 3475, "score": 0.9963271617889404, "start": 3469, "tag": "PASSWORD", "value": "passwd" } ]
src/cayenne/data/deposit.clj
CrossRef/cayenne
11
(ns cayenne.data.deposit (:import [java.util Date]) (:require [clojure.data.json :as json] [metrics.gauges :refer [defgauge]] [somnium.congomongo :as m] [cayenne.conf :as conf] [cayenne.api.v1.response :as r] [cayenne.api.v1.query :as q] [cayenne.api.v1.filter :as f] [metrics.meters :refer [defmeter] :as meter] [metrics.histograms :refer [defhistogram] :as hist])) (defhistogram [cayenne data deposit-size]) (defmeter [cayenne data deposits-received] "deposits-received") (defgauge [cayenne data deposit-count] (m/with-mongo (conf/get-service :mongo) (m/fetch-count :deposits))) (defn ensure-deposit-indexes! [collection-name] (m/add-index! collection-name [:batch-id]) (m/add-index! collection-name [:owner :batch-id]) (m/add-index! collection-name [:owner :submitted-at]) (m/add-index! collection-name [:owner :dois]) (m/add-index! collection-name [:owner :status])) (defn id->s [doc] (-> doc (:_id) (.toString))) (defn ->response-doc [deposit-doc & {:keys [length summary] :or {length false summary false}}] (let [clean-doc (-> deposit-doc (dissoc :data-id) (dissoc :passwd) (dissoc :_id)) with-length-doc (if length (m/with-mongo (conf/get-service :mongo) (let [deposit-file (m/fetch-one-file :deposits :where {:_id (:data-id deposit-doc)})] (assoc clean-doc :length (:length deposit-file)))) clean-doc)] (if summary (-> with-length-doc (dissoc :citations) (assoc :citation-count (-> with-length-doc :citations count)) (assoc :matched-citation-count (->> with-length-doc :citations (filter :match) count))) with-length-doc))) (defn set-on-deposit! [batch-id k v] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {(name k) v}}))) (defn append! [batch-id k v] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$push" {(name k) v}}))) ;; for now there is only one modification operation - altering ;; citations of a pdf deposit (defn modify! [batch-id data] (let [citations (json/read-str data :key-fn keyword)] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {"citations" citations}})))) (defn create! [deposit-data type batch-id dois owner passwd test pingback-url filename parent] (meter/mark! deposits-received) (m/with-mongo (conf/get-service :mongo) (ensure-deposit-indexes! :deposits) (let [new-file (m/insert-file! :deposits deposit-data) new-doc (m/insert! :deposits {:content-type type :data-id (:_id new-file) :batch-id batch-id :parent parent :dois dois :owner owner :passwd passwd :test test :pingback-url pingback-url :filename filename :status :submitted :handoff {:status :incomplete :timestamp 0 :try-count 0 :delay-millis 0} :submitted-at (Date.)})] (hist/update! deposit-size (:length new-file)) (let [new-doc-id (id->s new-doc)] (when parent (append! parent :children batch-id)) new-doc-id)))) (defn begin-handoff! "Call to begin hand-off or a hand-off try." [batch-id & {:keys [delay-fn] :or {delay-fn (fn [_ x] x)}}] (m/with-mongo (conf/get-service :mongo) (let [deposit-data (m/fetch-one :deposits :where {:batch-id batch-id}) curr-try-count (get-in deposit-data [:handoff :try-count]) curr-delay-millis (get-in deposit-data [:handoff :delay-millis]) next-delay-millis (delay-fn curr-delay-millis (inc curr-try-count))] (set-on-deposit! batch-id :handoff {:timestamp (System/currentTimeMillis) :try-count (inc curr-try-count) :delay-millis next-delay-millis}) next-delay-millis))) (defn end-handoff! "Call to indicate successful hand-off process." [batch-id] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {"handoff.status" :completed}}))) (defn complete! [batch-id] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {:status :completed}}))) (defn failed! [batch-id & {:keys [exception] :or {exception nil}}] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {:status :failed :exception (if exception (.toString exception) nil)}}))) (defn fetch-data [query-context] (m/with-mongo (conf/get-service :mongo) (let [where-clause (-> query-context (q/->mongo-query :filters f/deposit-filters :id-field :batch-id) second)] (when-let [deposit (m/fetch-one :deposits :where where-clause)] (m/stream-from :deposits (m/fetch-one-file :deposits :where {:_id (:data-id deposit)})))))) (defn fetch-one [query-context] (m/with-mongo (conf/get-service :mongo) (let [where-clause (-> query-context (q/->mongo-query :filters f/deposit-filters :id-field :batch-id) second)] (when-let [deposit (m/fetch-one :deposits :where where-clause)] (r/api-response :deposit :content (->response-doc deposit :length true)))))) (defn fetch [query-context] (m/with-mongo (conf/get-service :mongo) (let [query (q/->mongo-query query-context :filters f/deposit-filters) deposits (if (and (:rows query-context) (zero? (:rows query-context))) [] (apply m/fetch :deposits query)) deposits-count (apply m/fetch-count :deposits query)] (-> (r/api-response :deposit-list) (r/with-query-context-info query-context) (r/with-result-items deposits-count (map #(->response-doc % :length true :summary true) deposits))))))
16972
(ns cayenne.data.deposit (:import [java.util Date]) (:require [clojure.data.json :as json] [metrics.gauges :refer [defgauge]] [somnium.congomongo :as m] [cayenne.conf :as conf] [cayenne.api.v1.response :as r] [cayenne.api.v1.query :as q] [cayenne.api.v1.filter :as f] [metrics.meters :refer [defmeter] :as meter] [metrics.histograms :refer [defhistogram] :as hist])) (defhistogram [cayenne data deposit-size]) (defmeter [cayenne data deposits-received] "deposits-received") (defgauge [cayenne data deposit-count] (m/with-mongo (conf/get-service :mongo) (m/fetch-count :deposits))) (defn ensure-deposit-indexes! [collection-name] (m/add-index! collection-name [:batch-id]) (m/add-index! collection-name [:owner :batch-id]) (m/add-index! collection-name [:owner :submitted-at]) (m/add-index! collection-name [:owner :dois]) (m/add-index! collection-name [:owner :status])) (defn id->s [doc] (-> doc (:_id) (.toString))) (defn ->response-doc [deposit-doc & {:keys [length summary] :or {length false summary false}}] (let [clean-doc (-> deposit-doc (dissoc :data-id) (dissoc :passwd) (dissoc :_id)) with-length-doc (if length (m/with-mongo (conf/get-service :mongo) (let [deposit-file (m/fetch-one-file :deposits :where {:_id (:data-id deposit-doc)})] (assoc clean-doc :length (:length deposit-file)))) clean-doc)] (if summary (-> with-length-doc (dissoc :citations) (assoc :citation-count (-> with-length-doc :citations count)) (assoc :matched-citation-count (->> with-length-doc :citations (filter :match) count))) with-length-doc))) (defn set-on-deposit! [batch-id k v] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {(name k) v}}))) (defn append! [batch-id k v] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$push" {(name k) v}}))) ;; for now there is only one modification operation - altering ;; citations of a pdf deposit (defn modify! [batch-id data] (let [citations (json/read-str data :key-fn keyword)] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {"citations" citations}})))) (defn create! [deposit-data type batch-id dois owner passwd test pingback-url filename parent] (meter/mark! deposits-received) (m/with-mongo (conf/get-service :mongo) (ensure-deposit-indexes! :deposits) (let [new-file (m/insert-file! :deposits deposit-data) new-doc (m/insert! :deposits {:content-type type :data-id (:_id new-file) :batch-id batch-id :parent parent :dois dois :owner owner :passwd <PASSWORD> :test test :pingback-url pingback-url :filename filename :status :submitted :handoff {:status :incomplete :timestamp 0 :try-count 0 :delay-millis 0} :submitted-at (Date.)})] (hist/update! deposit-size (:length new-file)) (let [new-doc-id (id->s new-doc)] (when parent (append! parent :children batch-id)) new-doc-id)))) (defn begin-handoff! "Call to begin hand-off or a hand-off try." [batch-id & {:keys [delay-fn] :or {delay-fn (fn [_ x] x)}}] (m/with-mongo (conf/get-service :mongo) (let [deposit-data (m/fetch-one :deposits :where {:batch-id batch-id}) curr-try-count (get-in deposit-data [:handoff :try-count]) curr-delay-millis (get-in deposit-data [:handoff :delay-millis]) next-delay-millis (delay-fn curr-delay-millis (inc curr-try-count))] (set-on-deposit! batch-id :handoff {:timestamp (System/currentTimeMillis) :try-count (inc curr-try-count) :delay-millis next-delay-millis}) next-delay-millis))) (defn end-handoff! "Call to indicate successful hand-off process." [batch-id] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {"handoff.status" :completed}}))) (defn complete! [batch-id] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {:status :completed}}))) (defn failed! [batch-id & {:keys [exception] :or {exception nil}}] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {:status :failed :exception (if exception (.toString exception) nil)}}))) (defn fetch-data [query-context] (m/with-mongo (conf/get-service :mongo) (let [where-clause (-> query-context (q/->mongo-query :filters f/deposit-filters :id-field :batch-id) second)] (when-let [deposit (m/fetch-one :deposits :where where-clause)] (m/stream-from :deposits (m/fetch-one-file :deposits :where {:_id (:data-id deposit)})))))) (defn fetch-one [query-context] (m/with-mongo (conf/get-service :mongo) (let [where-clause (-> query-context (q/->mongo-query :filters f/deposit-filters :id-field :batch-id) second)] (when-let [deposit (m/fetch-one :deposits :where where-clause)] (r/api-response :deposit :content (->response-doc deposit :length true)))))) (defn fetch [query-context] (m/with-mongo (conf/get-service :mongo) (let [query (q/->mongo-query query-context :filters f/deposit-filters) deposits (if (and (:rows query-context) (zero? (:rows query-context))) [] (apply m/fetch :deposits query)) deposits-count (apply m/fetch-count :deposits query)] (-> (r/api-response :deposit-list) (r/with-query-context-info query-context) (r/with-result-items deposits-count (map #(->response-doc % :length true :summary true) deposits))))))
true
(ns cayenne.data.deposit (:import [java.util Date]) (:require [clojure.data.json :as json] [metrics.gauges :refer [defgauge]] [somnium.congomongo :as m] [cayenne.conf :as conf] [cayenne.api.v1.response :as r] [cayenne.api.v1.query :as q] [cayenne.api.v1.filter :as f] [metrics.meters :refer [defmeter] :as meter] [metrics.histograms :refer [defhistogram] :as hist])) (defhistogram [cayenne data deposit-size]) (defmeter [cayenne data deposits-received] "deposits-received") (defgauge [cayenne data deposit-count] (m/with-mongo (conf/get-service :mongo) (m/fetch-count :deposits))) (defn ensure-deposit-indexes! [collection-name] (m/add-index! collection-name [:batch-id]) (m/add-index! collection-name [:owner :batch-id]) (m/add-index! collection-name [:owner :submitted-at]) (m/add-index! collection-name [:owner :dois]) (m/add-index! collection-name [:owner :status])) (defn id->s [doc] (-> doc (:_id) (.toString))) (defn ->response-doc [deposit-doc & {:keys [length summary] :or {length false summary false}}] (let [clean-doc (-> deposit-doc (dissoc :data-id) (dissoc :passwd) (dissoc :_id)) with-length-doc (if length (m/with-mongo (conf/get-service :mongo) (let [deposit-file (m/fetch-one-file :deposits :where {:_id (:data-id deposit-doc)})] (assoc clean-doc :length (:length deposit-file)))) clean-doc)] (if summary (-> with-length-doc (dissoc :citations) (assoc :citation-count (-> with-length-doc :citations count)) (assoc :matched-citation-count (->> with-length-doc :citations (filter :match) count))) with-length-doc))) (defn set-on-deposit! [batch-id k v] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {(name k) v}}))) (defn append! [batch-id k v] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$push" {(name k) v}}))) ;; for now there is only one modification operation - altering ;; citations of a pdf deposit (defn modify! [batch-id data] (let [citations (json/read-str data :key-fn keyword)] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {"citations" citations}})))) (defn create! [deposit-data type batch-id dois owner passwd test pingback-url filename parent] (meter/mark! deposits-received) (m/with-mongo (conf/get-service :mongo) (ensure-deposit-indexes! :deposits) (let [new-file (m/insert-file! :deposits deposit-data) new-doc (m/insert! :deposits {:content-type type :data-id (:_id new-file) :batch-id batch-id :parent parent :dois dois :owner owner :passwd PI:PASSWORD:<PASSWORD>END_PI :test test :pingback-url pingback-url :filename filename :status :submitted :handoff {:status :incomplete :timestamp 0 :try-count 0 :delay-millis 0} :submitted-at (Date.)})] (hist/update! deposit-size (:length new-file)) (let [new-doc-id (id->s new-doc)] (when parent (append! parent :children batch-id)) new-doc-id)))) (defn begin-handoff! "Call to begin hand-off or a hand-off try." [batch-id & {:keys [delay-fn] :or {delay-fn (fn [_ x] x)}}] (m/with-mongo (conf/get-service :mongo) (let [deposit-data (m/fetch-one :deposits :where {:batch-id batch-id}) curr-try-count (get-in deposit-data [:handoff :try-count]) curr-delay-millis (get-in deposit-data [:handoff :delay-millis]) next-delay-millis (delay-fn curr-delay-millis (inc curr-try-count))] (set-on-deposit! batch-id :handoff {:timestamp (System/currentTimeMillis) :try-count (inc curr-try-count) :delay-millis next-delay-millis}) next-delay-millis))) (defn end-handoff! "Call to indicate successful hand-off process." [batch-id] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {"handoff.status" :completed}}))) (defn complete! [batch-id] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {:status :completed}}))) (defn failed! [batch-id & {:keys [exception] :or {exception nil}}] (m/with-mongo (conf/get-service :mongo) (m/update! :deposits {:batch-id batch-id} {"$set" {:status :failed :exception (if exception (.toString exception) nil)}}))) (defn fetch-data [query-context] (m/with-mongo (conf/get-service :mongo) (let [where-clause (-> query-context (q/->mongo-query :filters f/deposit-filters :id-field :batch-id) second)] (when-let [deposit (m/fetch-one :deposits :where where-clause)] (m/stream-from :deposits (m/fetch-one-file :deposits :where {:_id (:data-id deposit)})))))) (defn fetch-one [query-context] (m/with-mongo (conf/get-service :mongo) (let [where-clause (-> query-context (q/->mongo-query :filters f/deposit-filters :id-field :batch-id) second)] (when-let [deposit (m/fetch-one :deposits :where where-clause)] (r/api-response :deposit :content (->response-doc deposit :length true)))))) (defn fetch [query-context] (m/with-mongo (conf/get-service :mongo) (let [query (q/->mongo-query query-context :filters f/deposit-filters) deposits (if (and (:rows query-context) (zero? (:rows query-context))) [] (apply m/fetch :deposits query)) deposits-count (apply m/fetch-count :deposits query)] (-> (r/api-response :deposit-list) (r/with-query-context-info query-context) (r/with-result-items deposits-count (map #(->response-doc % :length true :summary true) deposits))))))
[ { "context": " [:copyright \"&#x2117; &amp; &#xA9; 2005 John Doe &amp; Family\"]\n [:itunes:subtitle \"ePubを", "end": 1638, "score": 0.9998683333396912, "start": 1630, "tag": "NAME", "value": "John Doe" }, { "context": "bをPodcastで配信するサーバの実験\"]\n [:itunes:author \"deltam\"]\n [:itunes:summary \"実験中デース\"]\n ", "end": 1742, "score": 0.909316897392273, "start": 1736, "tag": "USERNAME", "value": "deltam" } ]
src/epubcast/core.clj
deltam/ePubcast
1
(ns epubcast.core "experiment server for publishing ePub on Podcast RSS." (:gen-class) (:use [clojure.java.io :only (file)] [clojure.contrib.io :only (reader writer)] [clojure.contrib.seq :only (rand-elt)] [compojure.core] [hiccup.core] [hiccup.form-helpers] [ring.middleware [session :only (wrap-session)] [file :only (wrap-file)]] [ring.adapter jetty] [ring.util.response :only (file-response)] [ring.middleware params stacktrace file file-info session])) (defn static-files "./static 内のファイルの名前、サイズのMapシーケンスを返す" [] (let [epub-seq (seq (. (file "./static") listFiles))] (for [ep epub-seq] {:name (. ep getName) :length (. ep length)}))) (defn main-html "assembling stub html" [] (html [:h1 "ePubcast"] [:div {:align "right"} [:a {:href "/epub"} "epub feeds"] [:a {:href "itpc://localhost:8080/epub"} "[add iTunes]"]] [:div {:align "left"} [:blockquote {:style "border-style:solid"} [:p "list of ./static"] (for [ep (static-files)] [:p [:a {:href (str "file/" (:name ep))} (:name ep)]])]])) (defn epub-rss "./staticに入っているファイルを返すためのPodcastRSSを返す" [] (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" (html [:rss {:xmlns:itunes "http://www.itunes.com/dtds/podcast-1.0.dtd" :version "2.0"} [:channel [:title "ePubcast exp"] [:link "http://www.example.com/podcasts/everything/index.html"] [:language "ja"] ; [:copyright "&#x2117; &amp; &#xA9; 2005 John Doe &amp; Family"] [:itunes:subtitle "ePubをPodcastで配信するサーバの実験"] [:itunes:author "deltam"] [:itunes:summary "実験中デース"] [:description "実験実験!!!"] [:itunes:owner [:itunes:name "test"] [:itunes:email "test"]] ; [:itunes:image {:href "http://example.com/podcasts/everything/AllAboutEverything.jpg"}] [:itunes:category {:text "Technology"} [:itunes:category {:text "Gadgets"}]] [:itunes:category {:text "TV &amp; Film"}] ;; items (for [ep (static-files)] (let [fullpath (str "http://localhost:8080/file/" (:name ep))] [:item [:title (:name ep)] [:itunes:author "Nobody"] [:itunes:subtitle "./static" [:itunes:summary "./static"] [:enclosure {:url fullpath :length (str (:length ep)) :type "application/epub+zip"}] [:guid fullpath] [:pubDate "Mon, 4 Oct 2010 19:00:00 GMT"] [:itunes:duration "7:04"] [:itunes:keywords "test"]]])) ]]))) (defroutes main-routes "routing main page, podcast rss, static file link." ; defaultで表示するHTML (GET "/" [] (main-html)) ; Podcast RSSを返す (GET "/epub" [] (epub-rss)) ; 静的ファイルをstaticフォルダから探して返す (GET ["/file/:filename" :filename #".*"] [filename] (file-response filename {:root "./static"})) (ANY "*" [] {:status 404, :body "<h1>Page not found</h1>"})) ; temporary solution ; http://groups.google.com/group/compojure/browse_thread/thread/44a25e10c37f3b1b/d4a17cb99f84814f?pli=1 (defn wrap-charset [handler charset] (fn [request] (if-let [response (handler request)] (if-let [content-type (get-in response [:headers "Content-Type"])] (if (.contains content-type "charset") response (assoc-in response [:headers "Content-Type"] (str content-type "; charset=" charset))) response)))) (wrap! main-routes (:charset "utf8")) (defn -main "run jetty with port 8080" [& args] (run-jetty main-routes {:port 8080}))
4612
(ns epubcast.core "experiment server for publishing ePub on Podcast RSS." (:gen-class) (:use [clojure.java.io :only (file)] [clojure.contrib.io :only (reader writer)] [clojure.contrib.seq :only (rand-elt)] [compojure.core] [hiccup.core] [hiccup.form-helpers] [ring.middleware [session :only (wrap-session)] [file :only (wrap-file)]] [ring.adapter jetty] [ring.util.response :only (file-response)] [ring.middleware params stacktrace file file-info session])) (defn static-files "./static 内のファイルの名前、サイズのMapシーケンスを返す" [] (let [epub-seq (seq (. (file "./static") listFiles))] (for [ep epub-seq] {:name (. ep getName) :length (. ep length)}))) (defn main-html "assembling stub html" [] (html [:h1 "ePubcast"] [:div {:align "right"} [:a {:href "/epub"} "epub feeds"] [:a {:href "itpc://localhost:8080/epub"} "[add iTunes]"]] [:div {:align "left"} [:blockquote {:style "border-style:solid"} [:p "list of ./static"] (for [ep (static-files)] [:p [:a {:href (str "file/" (:name ep))} (:name ep)]])]])) (defn epub-rss "./staticに入っているファイルを返すためのPodcastRSSを返す" [] (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" (html [:rss {:xmlns:itunes "http://www.itunes.com/dtds/podcast-1.0.dtd" :version "2.0"} [:channel [:title "ePubcast exp"] [:link "http://www.example.com/podcasts/everything/index.html"] [:language "ja"] ; [:copyright "&#x2117; &amp; &#xA9; 2005 <NAME> &amp; Family"] [:itunes:subtitle "ePubをPodcastで配信するサーバの実験"] [:itunes:author "deltam"] [:itunes:summary "実験中デース"] [:description "実験実験!!!"] [:itunes:owner [:itunes:name "test"] [:itunes:email "test"]] ; [:itunes:image {:href "http://example.com/podcasts/everything/AllAboutEverything.jpg"}] [:itunes:category {:text "Technology"} [:itunes:category {:text "Gadgets"}]] [:itunes:category {:text "TV &amp; Film"}] ;; items (for [ep (static-files)] (let [fullpath (str "http://localhost:8080/file/" (:name ep))] [:item [:title (:name ep)] [:itunes:author "Nobody"] [:itunes:subtitle "./static" [:itunes:summary "./static"] [:enclosure {:url fullpath :length (str (:length ep)) :type "application/epub+zip"}] [:guid fullpath] [:pubDate "Mon, 4 Oct 2010 19:00:00 GMT"] [:itunes:duration "7:04"] [:itunes:keywords "test"]]])) ]]))) (defroutes main-routes "routing main page, podcast rss, static file link." ; defaultで表示するHTML (GET "/" [] (main-html)) ; Podcast RSSを返す (GET "/epub" [] (epub-rss)) ; 静的ファイルをstaticフォルダから探して返す (GET ["/file/:filename" :filename #".*"] [filename] (file-response filename {:root "./static"})) (ANY "*" [] {:status 404, :body "<h1>Page not found</h1>"})) ; temporary solution ; http://groups.google.com/group/compojure/browse_thread/thread/44a25e10c37f3b1b/d4a17cb99f84814f?pli=1 (defn wrap-charset [handler charset] (fn [request] (if-let [response (handler request)] (if-let [content-type (get-in response [:headers "Content-Type"])] (if (.contains content-type "charset") response (assoc-in response [:headers "Content-Type"] (str content-type "; charset=" charset))) response)))) (wrap! main-routes (:charset "utf8")) (defn -main "run jetty with port 8080" [& args] (run-jetty main-routes {:port 8080}))
true
(ns epubcast.core "experiment server for publishing ePub on Podcast RSS." (:gen-class) (:use [clojure.java.io :only (file)] [clojure.contrib.io :only (reader writer)] [clojure.contrib.seq :only (rand-elt)] [compojure.core] [hiccup.core] [hiccup.form-helpers] [ring.middleware [session :only (wrap-session)] [file :only (wrap-file)]] [ring.adapter jetty] [ring.util.response :only (file-response)] [ring.middleware params stacktrace file file-info session])) (defn static-files "./static 内のファイルの名前、サイズのMapシーケンスを返す" [] (let [epub-seq (seq (. (file "./static") listFiles))] (for [ep epub-seq] {:name (. ep getName) :length (. ep length)}))) (defn main-html "assembling stub html" [] (html [:h1 "ePubcast"] [:div {:align "right"} [:a {:href "/epub"} "epub feeds"] [:a {:href "itpc://localhost:8080/epub"} "[add iTunes]"]] [:div {:align "left"} [:blockquote {:style "border-style:solid"} [:p "list of ./static"] (for [ep (static-files)] [:p [:a {:href (str "file/" (:name ep))} (:name ep)]])]])) (defn epub-rss "./staticに入っているファイルを返すためのPodcastRSSを返す" [] (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" (html [:rss {:xmlns:itunes "http://www.itunes.com/dtds/podcast-1.0.dtd" :version "2.0"} [:channel [:title "ePubcast exp"] [:link "http://www.example.com/podcasts/everything/index.html"] [:language "ja"] ; [:copyright "&#x2117; &amp; &#xA9; 2005 PI:NAME:<NAME>END_PI &amp; Family"] [:itunes:subtitle "ePubをPodcastで配信するサーバの実験"] [:itunes:author "deltam"] [:itunes:summary "実験中デース"] [:description "実験実験!!!"] [:itunes:owner [:itunes:name "test"] [:itunes:email "test"]] ; [:itunes:image {:href "http://example.com/podcasts/everything/AllAboutEverything.jpg"}] [:itunes:category {:text "Technology"} [:itunes:category {:text "Gadgets"}]] [:itunes:category {:text "TV &amp; Film"}] ;; items (for [ep (static-files)] (let [fullpath (str "http://localhost:8080/file/" (:name ep))] [:item [:title (:name ep)] [:itunes:author "Nobody"] [:itunes:subtitle "./static" [:itunes:summary "./static"] [:enclosure {:url fullpath :length (str (:length ep)) :type "application/epub+zip"}] [:guid fullpath] [:pubDate "Mon, 4 Oct 2010 19:00:00 GMT"] [:itunes:duration "7:04"] [:itunes:keywords "test"]]])) ]]))) (defroutes main-routes "routing main page, podcast rss, static file link." ; defaultで表示するHTML (GET "/" [] (main-html)) ; Podcast RSSを返す (GET "/epub" [] (epub-rss)) ; 静的ファイルをstaticフォルダから探して返す (GET ["/file/:filename" :filename #".*"] [filename] (file-response filename {:root "./static"})) (ANY "*" [] {:status 404, :body "<h1>Page not found</h1>"})) ; temporary solution ; http://groups.google.com/group/compojure/browse_thread/thread/44a25e10c37f3b1b/d4a17cb99f84814f?pli=1 (defn wrap-charset [handler charset] (fn [request] (if-let [response (handler request)] (if-let [content-type (get-in response [:headers "Content-Type"])] (if (.contains content-type "charset") response (assoc-in response [:headers "Content-Type"] (str content-type "; charset=" charset))) response)))) (wrap! main-routes (:charset "utf8")) (defn -main "run jetty with port 8080" [& args] (run-jetty main-routes {:port 8080}))
[ { "context": "ch -- Predicate logic\n\n; Copyright (c) 2016 - 2018 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 84, "score": 0.9998691082000732, "start": 70, "tag": "NAME", "value": "Burkhardt Renz" }, { "context": " phi6 world-5-11)\n; => false\n\n;; Exercise 5.1 from Volker Halbach's Exercises Booklet\n\n(def ds\n {:univ #{1 2 3}\n ", "end": 2191, "score": 0.942072868347168, "start": 2177, "tag": "NAME", "value": "Volker Halbach" } ]
src/lwb/pred/examples/halbach.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Predicate logic ; Copyright (c) 2016 - 2018 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.pred.examples.halbach (:require [lwb.pred :refer (make-pred sig-from-model wff? eval-phi)])) ;; Examples from Volker Halbach: The Logic Manual Chap 5 ;; European cities ; (Q x) = city x is on continent ; (R x y) = city x is smaller than city y (def cities {:univ #{:florence :stockholm :barcelona :london} 'a [:func 0 :florence] 'b [:func 0 :london] 'Q [:pred 1 (make-pred #{[:florence] [:stockholm] [:barcelona]})] 'R [:pred 2 (make-pred #{[:florence :stockholm] [:florence :barcelona] [:florence :london] [:stockholm :barcelona] [:stockholm :london] [:barcelona :london]})] }) (def phi1 '(R a b)) (eval-phi phi1 cities) ; => true -- (R :florence :london) (eval-phi '(R b a) cities) ; => false (def phi2 '(forall [x] (impl (Q x) (R x b)))) (eval-phi phi2 cities) ; => true (def phi3 '(forall [x] (exists [y] (or (R x y) (R y x))))) (eval-phi phi3 cities) ; => true ;; world-5-9 (def world-5-9 {:univ #{1 2} 'b [:func 0 1] 'Q [:pred 1 (make-pred #{[1]})]}) (def phi4 '(impl (Q b) (forall [x] (Q x)))) (eval-phi phi4 world-5-9) ; => false ;; cosmos (def cosmos {:univ #{:sun :moon} 'R [:pred 2 (make-pred #{[:sun :sun] [:moon :moon]})]}) (def phi5 '(impl (forall [x] (exists [y] (R x y))) (exists [y] (forall [x] (R x y))))) (eval-phi phi5 cosmos) ; => false ;; world-5-11 (def world-5-11 {:univ #{1} 'a [:func 0 1] 'P [:pred 1 (make-pred #{[1]})] 'Q [:pred 1 (make-pred #{[1]})] 'R [:pred 1 (make-pred #{})]}) (def phi6 '(impl (and (forall [x] (impl (P x) (or (Q x) (R x)))) (P a)) (R a))) (eval-phi phi6 world-5-11) ; => false ;; Exercise 5.1 from Volker Halbach's Exercises Booklet (def ds {:univ #{1 2 3} 'a [:func 0 1] 'b [:func 0 3] 'P [:pred 1 (make-pred #{[2]})] 'R [:pred 2 (make-pred #{[1 2] [2 3] [1 3]})]}) ;; (i) (eval-phi '(P a) ds) ; => false; a is not in P ;; (ii) (eval-phi '(R a b) ds) ; => true; [1 3] is in R ;; (iii) (eval-phi '(R b a) ds) ; => false; [3 1] is not in R ;; (iv) (eval-phi '(equiv (R a b) (R b a)) ds) ; => false; see (ii) and (iii) ;; (v) (eval-phi '(or (R b b) (and (not (P a)) (not (R a a)))) ds) ; => true; the second part is true ;; (vi) (eval-phi '(exists [x] (R a x)) ds) ; => true; e.g. x = 2 ;; (vii) (eval-phi '(exists [x] (and (R a x) (R x b))) ds) ; => true; e.g. x = 2 ;; (viii) (eval-phi '(or (P b) (exists [x] (R x x))) ds) ; => false; 3 ist not in P, and R is not symmetric ;; (ix) (eval-phi '(forall [x] (exists [y] (R x y))) ds) ; => false; [3 ?] is not in R ;; (x) (eval-phi '(forall [x] (impl (P x) (and (exists [y] (R y x)) (exists [y] (R x y))))) ds) ; => true; x is 2, [1 2] in R and [2 3] in R ;; (xi) (eval-phi '(forall [x] (impl (P x) (exists [y] (and (R y x) (R x y))))) ds) ; => false; x is 2, but no pair and its mirrored one
48309
; lwb Logic WorkBench -- Predicate logic ; Copyright (c) 2016 - 2018 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.pred.examples.halbach (:require [lwb.pred :refer (make-pred sig-from-model wff? eval-phi)])) ;; Examples from Volker Halbach: The Logic Manual Chap 5 ;; European cities ; (Q x) = city x is on continent ; (R x y) = city x is smaller than city y (def cities {:univ #{:florence :stockholm :barcelona :london} 'a [:func 0 :florence] 'b [:func 0 :london] 'Q [:pred 1 (make-pred #{[:florence] [:stockholm] [:barcelona]})] 'R [:pred 2 (make-pred #{[:florence :stockholm] [:florence :barcelona] [:florence :london] [:stockholm :barcelona] [:stockholm :london] [:barcelona :london]})] }) (def phi1 '(R a b)) (eval-phi phi1 cities) ; => true -- (R :florence :london) (eval-phi '(R b a) cities) ; => false (def phi2 '(forall [x] (impl (Q x) (R x b)))) (eval-phi phi2 cities) ; => true (def phi3 '(forall [x] (exists [y] (or (R x y) (R y x))))) (eval-phi phi3 cities) ; => true ;; world-5-9 (def world-5-9 {:univ #{1 2} 'b [:func 0 1] 'Q [:pred 1 (make-pred #{[1]})]}) (def phi4 '(impl (Q b) (forall [x] (Q x)))) (eval-phi phi4 world-5-9) ; => false ;; cosmos (def cosmos {:univ #{:sun :moon} 'R [:pred 2 (make-pred #{[:sun :sun] [:moon :moon]})]}) (def phi5 '(impl (forall [x] (exists [y] (R x y))) (exists [y] (forall [x] (R x y))))) (eval-phi phi5 cosmos) ; => false ;; world-5-11 (def world-5-11 {:univ #{1} 'a [:func 0 1] 'P [:pred 1 (make-pred #{[1]})] 'Q [:pred 1 (make-pred #{[1]})] 'R [:pred 1 (make-pred #{})]}) (def phi6 '(impl (and (forall [x] (impl (P x) (or (Q x) (R x)))) (P a)) (R a))) (eval-phi phi6 world-5-11) ; => false ;; Exercise 5.1 from <NAME>'s Exercises Booklet (def ds {:univ #{1 2 3} 'a [:func 0 1] 'b [:func 0 3] 'P [:pred 1 (make-pred #{[2]})] 'R [:pred 2 (make-pred #{[1 2] [2 3] [1 3]})]}) ;; (i) (eval-phi '(P a) ds) ; => false; a is not in P ;; (ii) (eval-phi '(R a b) ds) ; => true; [1 3] is in R ;; (iii) (eval-phi '(R b a) ds) ; => false; [3 1] is not in R ;; (iv) (eval-phi '(equiv (R a b) (R b a)) ds) ; => false; see (ii) and (iii) ;; (v) (eval-phi '(or (R b b) (and (not (P a)) (not (R a a)))) ds) ; => true; the second part is true ;; (vi) (eval-phi '(exists [x] (R a x)) ds) ; => true; e.g. x = 2 ;; (vii) (eval-phi '(exists [x] (and (R a x) (R x b))) ds) ; => true; e.g. x = 2 ;; (viii) (eval-phi '(or (P b) (exists [x] (R x x))) ds) ; => false; 3 ist not in P, and R is not symmetric ;; (ix) (eval-phi '(forall [x] (exists [y] (R x y))) ds) ; => false; [3 ?] is not in R ;; (x) (eval-phi '(forall [x] (impl (P x) (and (exists [y] (R y x)) (exists [y] (R x y))))) ds) ; => true; x is 2, [1 2] in R and [2 3] in R ;; (xi) (eval-phi '(forall [x] (impl (P x) (exists [y] (and (R y x) (R x y))))) ds) ; => false; x is 2, but no pair and its mirrored one
true
; lwb Logic WorkBench -- Predicate logic ; Copyright (c) 2016 - 2018 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.pred.examples.halbach (:require [lwb.pred :refer (make-pred sig-from-model wff? eval-phi)])) ;; Examples from Volker Halbach: The Logic Manual Chap 5 ;; European cities ; (Q x) = city x is on continent ; (R x y) = city x is smaller than city y (def cities {:univ #{:florence :stockholm :barcelona :london} 'a [:func 0 :florence] 'b [:func 0 :london] 'Q [:pred 1 (make-pred #{[:florence] [:stockholm] [:barcelona]})] 'R [:pred 2 (make-pred #{[:florence :stockholm] [:florence :barcelona] [:florence :london] [:stockholm :barcelona] [:stockholm :london] [:barcelona :london]})] }) (def phi1 '(R a b)) (eval-phi phi1 cities) ; => true -- (R :florence :london) (eval-phi '(R b a) cities) ; => false (def phi2 '(forall [x] (impl (Q x) (R x b)))) (eval-phi phi2 cities) ; => true (def phi3 '(forall [x] (exists [y] (or (R x y) (R y x))))) (eval-phi phi3 cities) ; => true ;; world-5-9 (def world-5-9 {:univ #{1 2} 'b [:func 0 1] 'Q [:pred 1 (make-pred #{[1]})]}) (def phi4 '(impl (Q b) (forall [x] (Q x)))) (eval-phi phi4 world-5-9) ; => false ;; cosmos (def cosmos {:univ #{:sun :moon} 'R [:pred 2 (make-pred #{[:sun :sun] [:moon :moon]})]}) (def phi5 '(impl (forall [x] (exists [y] (R x y))) (exists [y] (forall [x] (R x y))))) (eval-phi phi5 cosmos) ; => false ;; world-5-11 (def world-5-11 {:univ #{1} 'a [:func 0 1] 'P [:pred 1 (make-pred #{[1]})] 'Q [:pred 1 (make-pred #{[1]})] 'R [:pred 1 (make-pred #{})]}) (def phi6 '(impl (and (forall [x] (impl (P x) (or (Q x) (R x)))) (P a)) (R a))) (eval-phi phi6 world-5-11) ; => false ;; Exercise 5.1 from PI:NAME:<NAME>END_PI's Exercises Booklet (def ds {:univ #{1 2 3} 'a [:func 0 1] 'b [:func 0 3] 'P [:pred 1 (make-pred #{[2]})] 'R [:pred 2 (make-pred #{[1 2] [2 3] [1 3]})]}) ;; (i) (eval-phi '(P a) ds) ; => false; a is not in P ;; (ii) (eval-phi '(R a b) ds) ; => true; [1 3] is in R ;; (iii) (eval-phi '(R b a) ds) ; => false; [3 1] is not in R ;; (iv) (eval-phi '(equiv (R a b) (R b a)) ds) ; => false; see (ii) and (iii) ;; (v) (eval-phi '(or (R b b) (and (not (P a)) (not (R a a)))) ds) ; => true; the second part is true ;; (vi) (eval-phi '(exists [x] (R a x)) ds) ; => true; e.g. x = 2 ;; (vii) (eval-phi '(exists [x] (and (R a x) (R x b))) ds) ; => true; e.g. x = 2 ;; (viii) (eval-phi '(or (P b) (exists [x] (R x x))) ds) ; => false; 3 ist not in P, and R is not symmetric ;; (ix) (eval-phi '(forall [x] (exists [y] (R x y))) ds) ; => false; [3 ?] is not in R ;; (x) (eval-phi '(forall [x] (impl (P x) (and (exists [y] (R y x)) (exists [y] (R x y))))) ds) ; => true; x is 2, [1 2] in R and [2 3] in R ;; (xi) (eval-phi '(forall [x] (impl (P x) (exists [y] (and (R y x) (R x y))))) ds) ; => false; x is 2, but no pair and its mirrored one
[ { "context": " (Associative Destructuring)\n(def a-name {:first \"Toto\" :last \"Mookey\" :salutation \"Mr.\"})\n\n(println a-n", "end": 75, "score": 0.9997372627258301, "start": 71, "tag": "NAME", "value": "Toto" }, { "context": " Destructuring)\n(def a-name {:first \"Toto\" :last \"Mookey\" :salutation \"Mr.\"})\n\n(println a-name)\n\n(let [{fn", "end": 90, "score": 0.9997468590736389, "start": 84, "tag": "NAME", "value": "Mookey" } ]
session/01_languages/05-dps-3.clj
DhavalDalal/destructuring-and-pattern-matching
2
; Destructuring a map (Associative Destructuring) (def a-name {:first "Toto" :last "Mookey" :salutation "Mr."}) (println a-name) (let [{fname :first lname :last} a-name] (println fname lname)) (require '[clojure.string :refer [upper-case]]) (defn capitalize [{fname :first lname :last}] (str (upper-case fname) " " (upper-case lname))) (println (capitalize a-name))
124707
; Destructuring a map (Associative Destructuring) (def a-name {:first "<NAME>" :last "<NAME>" :salutation "Mr."}) (println a-name) (let [{fname :first lname :last} a-name] (println fname lname)) (require '[clojure.string :refer [upper-case]]) (defn capitalize [{fname :first lname :last}] (str (upper-case fname) " " (upper-case lname))) (println (capitalize a-name))
true
; Destructuring a map (Associative Destructuring) (def a-name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :salutation "Mr."}) (println a-name) (let [{fname :first lname :last} a-name] (println fname lname)) (require '[clojure.string :refer [upper-case]]) (defn capitalize [{fname :first lname :last}] (str (upper-case fname) " " (upper-case lname))) (println (capitalize a-name))
[ { "context": ") (dec cnt))\n ))\n\n; destructuring\n(def names [\"Bob\" \"Joe\" \"Sam\" \"Ned\" \"Homer\" \"Bart\"])\n(let [[item1 ", "end": 380, "score": 0.9997652769088745, "start": 377, "tag": "NAME", "value": "Bob" }, { "context": " cnt))\n ))\n\n; destructuring\n(def names [\"Bob\" \"Joe\" \"Sam\" \"Ned\" \"Homer\" \"Bart\"])\n(let [[item1 & rema", "end": 386, "score": 0.9997254610061646, "start": 383, "tag": "NAME", "value": "Joe" }, { "context": "\n ))\n\n; destructuring\n(def names [\"Bob\" \"Joe\" \"Sam\" \"Ned\" \"Homer\" \"Bart\"])\n(let [[item1 & remaining]", "end": 392, "score": 0.9998449087142944, "start": 389, "tag": "NAME", "value": "Sam" }, { "context": ")\n\n; destructuring\n(def names [\"Bob\" \"Joe\" \"Sam\" \"Ned\" \"Homer\" \"Bart\"])\n(let [[item1 & remaining] names", "end": 398, "score": 0.9997634887695312, "start": 395, "tag": "NAME", "value": "Ned" }, { "context": "estructuring\n(def names [\"Bob\" \"Joe\" \"Sam\" \"Ned\" \"Homer\" \"Bart\"])\n(let [[item1 & remaining] names] ; item", "end": 406, "score": 0.9997555017471313, "start": 401, "tag": "NAME", "value": "Homer" }, { "context": "ring\n(def names [\"Bob\" \"Joe\" \"Sam\" \"Ned\" \"Homer\" \"Bart\"])\n(let [[item1 & remaining] names] ; item1 = Bob", "end": 413, "score": 0.9997673034667969, "start": 409, "tag": "NAME", "value": "Bart" }, { "context": "Bart\"])\n(let [[item1 & remaining] names] ; item1 = Bob, remaining = the rest\n (println item1)\n ", "end": 463, "score": 0.9996151924133301, "start": 460, "tag": "NAME", "value": "Bob" } ]
aoc-2020/src/aoc_2020/playground.clj
xfr3386/aoc_clojure
0
(ns playground (:require [clojure.string :as str]) (:require [clojure.edn :as edn]) (:require [clojure.math.numeric-tower :as math])) ; print 0, -1, -2, -3, -4 (loop [i 0] (when (> i -5) (println i) (recur (dec i)) )) ; sum of 10+9+8+7... (loop [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt)) )) ; destructuring (def names ["Bob" "Joe" "Sam" "Ned" "Homer" "Bart"]) (let [[item1 & remaining] names] ; item1 = Bob, remaining = the rest (println item1) (apply println remaining)) (let [sample "ecl:grn cid:315 iyr:2012 hgt:192cm eyr:2023 pid:873355140 byr:1925 hcl:#cb2c03"] (println sample) (str/replace sample "\r\n" "")) (str/split "1234abc" #"(\d[a-zA-Z])") (def birth-year 2027) (and (nil? birth-year) (<= 1920 (Integer/parseInt birth-year) 2002)) (re-find #"\d+" "183cm") (re-find #"\p{Alpha}+" "183cm") (def rows (range 128)) (def seats (range 8)) ;(def search-term "FBFBBFF") ;(println (first search-term)) ;(= (subs search-term 0 1) "F") (println rows) ; if F (first (split-at (/ (- (count rows) 1) 2) rows)) ; if B (rest (split-at (/ (- (count rows) 1) 2) rows)) (first (partition (/ (count rows) 2) rows)) (last (partition (/ (count rows) 2) rows)) (rest "FBFBBFF") (defn find-row [search-term remaining-seats comparator] (let [two-halves (partition (/ (count remaining-seats) 2) remaining-seats)] (if (= (count remaining-seats) 1) (println remaining-seats) (if (= (subs search-term 0 1) comparator) (do (println (first search-term)) (println (first two-halves)) (find-row (subs search-term 1) (first two-halves) comparator)) (do (println (first search-term)) (println (last two-halves)) (find-row (subs search-term 1) (last two-halves) comparator)) )))) (find-row "FBFBBFF" rows "F") (find-row "RLR" seats "L") ; FBFBBFF ; 0-127 ; want 0-63; split-at (127-1)/2 (defn find-position [search-term remaining-values comparator] (let [two-halves (partition (/ (count remaining-values) 2) remaining-values)] (if (= (count remaining-values) 1) (first remaining-values) (if (= (subs search-term 0 1) comparator) (find-position (subs search-term 1) (first two-halves) comparator) (find-position (subs search-term 1) (last two-halves) comparator))))) (find-position "FBFBBFB" rows "F") (find-position "RRL" seats "L") (mod 101 2) ;; a map with a term that contains a sub-map (def bag-test-map {:gold {:dull-green 3 :muted-green 1 :shiny-orange 2} :fuschia {:dim-blue 3 :dim-red 1 :dim-orange 2}}) (println bag-test-map) ;; to get an item in the submap, get-in with the m (get-in bag-test-map [:gold :dull-green]) ;; dim red bags contain 1 mirrored olive bag, 1 plaid violet bag. ;; {:dim-red {:mirrored-olive-bag 1 :plaid-violet-bag 1 :plaid-violet-bag 1}} ;; posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags. ;; NOTICE: bag vs bags ;; {:posh-salmon {:shiny-brown 1 :dark-red 2 :drab-gold 3}} ;; posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags. (def bag-test-string (str/replace "posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags." #"bags" "bag")) ;; remove contain, separate main from subs with #, replace trailing . with , (def parse-bag-test-string (str/replace bag-test-string #"^(.* bag)\scontain\s(.*)(.)" "$1#$2, ")) (println parse-bag-test-string) ;; GET MAIN BAG NAME ;; get the main bag string, with spaces replaced as - (def main-bag (str/replace (str/replace parse-bag-test-string #"(.*)#.*" "$1") #" " "-")) (println main-bag) ;; GENERATE SUB-BAG MAP WITH COUNT AS VALUE ;; get sub-bag strings in the form of #-remaining-name-words (def containing-seq (map #(str/replace % #"(\w) " "$1-") (re-seq #"\d[\w|\s]+" parse-bag-test-string))) (println containing-seq) ;; get map form string of sub-bags as ":sub-bag count" (def sub-bags-with-values (map #(str/replace % #"(\d)-(.*)" ":$2 $1") containing-seq)) (println sub-bags-with-values) ;; combine main bag and sub bag into single map form string, convert to map (def bag-and-containers-values-hash (clojure.edn/read-string (str "{:" main-bag " {" (str/join " " sub-bags-with-values) "}}"))) (println bag-and-containers-values-hash) (map #(str %) (get bag-and-containers-values-hash (keyword main-bag))) ;; GENERATE SUB-BAG LIST, DROP VALUES ;; (re-find #"\d[\w|\s]+" parse-bag-test-string) ;; (defn extract-group [n] (fn [group] (group n))) (def sub-bags (map #(str/replace % #"\d-([\w|-]+)" "$1") containing-seq)) (println sub-bags) (def bag-and-containers-hash (clojure.edn/read-string (str "{:" main-bag " (" (str/join " " sub-bags) ")}"))) (println bag-and-containers-hash) (def test-bag-1 (edn/read-string "{:posh-salmon-bag {:shiny-brown-bag 1, :dark-red-bags 2, :drab-gold-bags 3} :shiny-brown-bag {:dark-red-bags 2, :drab-gold-bags 3} :dark-red-bags {:drab-gold-bags 3}}")) (get test-bag-1 :posh-salmon-bag) (get test-bag-1 :shiny-brown-bag) (get-in test-bag-1 [:posh-salmon-bag :shiny-brown-bag]) (select-keys test-bag-1 [:posh-salmon-bag]) (def sub-bag-test (str "(drab-silver-bag dim-coral-bag drab-silver-bag dim-salmon-bag)")) (re-find #"dim-coral-bag" sub-bag-test) (into () ":shiny-gold-bag :vibrant-yellow-bag") (split-at 4 [1 2 3 4 5]) (subvec [1 2 3 4 5 6 7] 0) (nth [1 2 3 4 5 6 7] 0) (def diffs [3 1 1 1 1 3 3 1 1 1 1 3 1 1 1 1 3 1 1 3 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 3 1 1 1 3 3 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 3 1 1 3 3 3 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 3 1 3 1 1 1]) ;; (def diffs [3 1 3 1 1 3 1 1 1 3 1]) (def separated-diffs (partition-by #(= 1 %) diffs)) (println separated-diffs) (loop [index 0 two-groups 0 three-groups 0 four-groups 0] (if (= index (count separated-diffs)) (* (math/expt 2 two-groups) (math/expt 4 three-groups) (math/expt 7 four-groups)) (let [current-group (nth separated-diffs index)] (println current-group " count " (count current-group)) (if (and (some #(= 1 %) current-group) (> (count current-group) 1)) (if (= (count current-group) 2) (recur (inc index) (inc two-groups) three-groups four-groups) (if (= (count current-group) 3) (recur (inc index) two-groups (inc three-groups) four-groups) (recur (inc index) two-groups three-groups (inc four-groups)))) (recur (inc index) two-groups three-groups four-groups))))) (def test-seats "#.#L.L#.###LLL#LL.L#L.#.L..#..#L##.##.L##.#L.LL.LL#.#L#L#.##..L.L.....#L#L##L#L##.LLLLLL.L#.#L#L#.##") (count (filter #(= "#" (str %)) test-seats)) (frequencies test-seats)
97743
(ns playground (:require [clojure.string :as str]) (:require [clojure.edn :as edn]) (:require [clojure.math.numeric-tower :as math])) ; print 0, -1, -2, -3, -4 (loop [i 0] (when (> i -5) (println i) (recur (dec i)) )) ; sum of 10+9+8+7... (loop [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt)) )) ; destructuring (def names ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) (let [[item1 & remaining] names] ; item1 = <NAME>, remaining = the rest (println item1) (apply println remaining)) (let [sample "ecl:grn cid:315 iyr:2012 hgt:192cm eyr:2023 pid:873355140 byr:1925 hcl:#cb2c03"] (println sample) (str/replace sample "\r\n" "")) (str/split "1234abc" #"(\d[a-zA-Z])") (def birth-year 2027) (and (nil? birth-year) (<= 1920 (Integer/parseInt birth-year) 2002)) (re-find #"\d+" "183cm") (re-find #"\p{Alpha}+" "183cm") (def rows (range 128)) (def seats (range 8)) ;(def search-term "FBFBBFF") ;(println (first search-term)) ;(= (subs search-term 0 1) "F") (println rows) ; if F (first (split-at (/ (- (count rows) 1) 2) rows)) ; if B (rest (split-at (/ (- (count rows) 1) 2) rows)) (first (partition (/ (count rows) 2) rows)) (last (partition (/ (count rows) 2) rows)) (rest "FBFBBFF") (defn find-row [search-term remaining-seats comparator] (let [two-halves (partition (/ (count remaining-seats) 2) remaining-seats)] (if (= (count remaining-seats) 1) (println remaining-seats) (if (= (subs search-term 0 1) comparator) (do (println (first search-term)) (println (first two-halves)) (find-row (subs search-term 1) (first two-halves) comparator)) (do (println (first search-term)) (println (last two-halves)) (find-row (subs search-term 1) (last two-halves) comparator)) )))) (find-row "FBFBBFF" rows "F") (find-row "RLR" seats "L") ; FBFBBFF ; 0-127 ; want 0-63; split-at (127-1)/2 (defn find-position [search-term remaining-values comparator] (let [two-halves (partition (/ (count remaining-values) 2) remaining-values)] (if (= (count remaining-values) 1) (first remaining-values) (if (= (subs search-term 0 1) comparator) (find-position (subs search-term 1) (first two-halves) comparator) (find-position (subs search-term 1) (last two-halves) comparator))))) (find-position "FBFBBFB" rows "F") (find-position "RRL" seats "L") (mod 101 2) ;; a map with a term that contains a sub-map (def bag-test-map {:gold {:dull-green 3 :muted-green 1 :shiny-orange 2} :fuschia {:dim-blue 3 :dim-red 1 :dim-orange 2}}) (println bag-test-map) ;; to get an item in the submap, get-in with the m (get-in bag-test-map [:gold :dull-green]) ;; dim red bags contain 1 mirrored olive bag, 1 plaid violet bag. ;; {:dim-red {:mirrored-olive-bag 1 :plaid-violet-bag 1 :plaid-violet-bag 1}} ;; posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags. ;; NOTICE: bag vs bags ;; {:posh-salmon {:shiny-brown 1 :dark-red 2 :drab-gold 3}} ;; posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags. (def bag-test-string (str/replace "posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags." #"bags" "bag")) ;; remove contain, separate main from subs with #, replace trailing . with , (def parse-bag-test-string (str/replace bag-test-string #"^(.* bag)\scontain\s(.*)(.)" "$1#$2, ")) (println parse-bag-test-string) ;; GET MAIN BAG NAME ;; get the main bag string, with spaces replaced as - (def main-bag (str/replace (str/replace parse-bag-test-string #"(.*)#.*" "$1") #" " "-")) (println main-bag) ;; GENERATE SUB-BAG MAP WITH COUNT AS VALUE ;; get sub-bag strings in the form of #-remaining-name-words (def containing-seq (map #(str/replace % #"(\w) " "$1-") (re-seq #"\d[\w|\s]+" parse-bag-test-string))) (println containing-seq) ;; get map form string of sub-bags as ":sub-bag count" (def sub-bags-with-values (map #(str/replace % #"(\d)-(.*)" ":$2 $1") containing-seq)) (println sub-bags-with-values) ;; combine main bag and sub bag into single map form string, convert to map (def bag-and-containers-values-hash (clojure.edn/read-string (str "{:" main-bag " {" (str/join " " sub-bags-with-values) "}}"))) (println bag-and-containers-values-hash) (map #(str %) (get bag-and-containers-values-hash (keyword main-bag))) ;; GENERATE SUB-BAG LIST, DROP VALUES ;; (re-find #"\d[\w|\s]+" parse-bag-test-string) ;; (defn extract-group [n] (fn [group] (group n))) (def sub-bags (map #(str/replace % #"\d-([\w|-]+)" "$1") containing-seq)) (println sub-bags) (def bag-and-containers-hash (clojure.edn/read-string (str "{:" main-bag " (" (str/join " " sub-bags) ")}"))) (println bag-and-containers-hash) (def test-bag-1 (edn/read-string "{:posh-salmon-bag {:shiny-brown-bag 1, :dark-red-bags 2, :drab-gold-bags 3} :shiny-brown-bag {:dark-red-bags 2, :drab-gold-bags 3} :dark-red-bags {:drab-gold-bags 3}}")) (get test-bag-1 :posh-salmon-bag) (get test-bag-1 :shiny-brown-bag) (get-in test-bag-1 [:posh-salmon-bag :shiny-brown-bag]) (select-keys test-bag-1 [:posh-salmon-bag]) (def sub-bag-test (str "(drab-silver-bag dim-coral-bag drab-silver-bag dim-salmon-bag)")) (re-find #"dim-coral-bag" sub-bag-test) (into () ":shiny-gold-bag :vibrant-yellow-bag") (split-at 4 [1 2 3 4 5]) (subvec [1 2 3 4 5 6 7] 0) (nth [1 2 3 4 5 6 7] 0) (def diffs [3 1 1 1 1 3 3 1 1 1 1 3 1 1 1 1 3 1 1 3 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 3 1 1 1 3 3 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 3 1 1 3 3 3 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 3 1 3 1 1 1]) ;; (def diffs [3 1 3 1 1 3 1 1 1 3 1]) (def separated-diffs (partition-by #(= 1 %) diffs)) (println separated-diffs) (loop [index 0 two-groups 0 three-groups 0 four-groups 0] (if (= index (count separated-diffs)) (* (math/expt 2 two-groups) (math/expt 4 three-groups) (math/expt 7 four-groups)) (let [current-group (nth separated-diffs index)] (println current-group " count " (count current-group)) (if (and (some #(= 1 %) current-group) (> (count current-group) 1)) (if (= (count current-group) 2) (recur (inc index) (inc two-groups) three-groups four-groups) (if (= (count current-group) 3) (recur (inc index) two-groups (inc three-groups) four-groups) (recur (inc index) two-groups three-groups (inc four-groups)))) (recur (inc index) two-groups three-groups four-groups))))) (def test-seats "#.#L.L#.###LLL#LL.L#L.#.L..#..#L##.##.L##.#L.LL.LL#.#L#L#.##..L.L.....#L#L##L#L##.LLLLLL.L#.#L#L#.##") (count (filter #(= "#" (str %)) test-seats)) (frequencies test-seats)
true
(ns playground (:require [clojure.string :as str]) (:require [clojure.edn :as edn]) (:require [clojure.math.numeric-tower :as math])) ; print 0, -1, -2, -3, -4 (loop [i 0] (when (> i -5) (println i) (recur (dec i)) )) ; sum of 10+9+8+7... (loop [sum 0 cnt 10] (if (= cnt 0) sum (recur (+ cnt sum) (dec cnt)) )) ; destructuring (def names ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (let [[item1 & remaining] names] ; item1 = PI:NAME:<NAME>END_PI, remaining = the rest (println item1) (apply println remaining)) (let [sample "ecl:grn cid:315 iyr:2012 hgt:192cm eyr:2023 pid:873355140 byr:1925 hcl:#cb2c03"] (println sample) (str/replace sample "\r\n" "")) (str/split "1234abc" #"(\d[a-zA-Z])") (def birth-year 2027) (and (nil? birth-year) (<= 1920 (Integer/parseInt birth-year) 2002)) (re-find #"\d+" "183cm") (re-find #"\p{Alpha}+" "183cm") (def rows (range 128)) (def seats (range 8)) ;(def search-term "FBFBBFF") ;(println (first search-term)) ;(= (subs search-term 0 1) "F") (println rows) ; if F (first (split-at (/ (- (count rows) 1) 2) rows)) ; if B (rest (split-at (/ (- (count rows) 1) 2) rows)) (first (partition (/ (count rows) 2) rows)) (last (partition (/ (count rows) 2) rows)) (rest "FBFBBFF") (defn find-row [search-term remaining-seats comparator] (let [two-halves (partition (/ (count remaining-seats) 2) remaining-seats)] (if (= (count remaining-seats) 1) (println remaining-seats) (if (= (subs search-term 0 1) comparator) (do (println (first search-term)) (println (first two-halves)) (find-row (subs search-term 1) (first two-halves) comparator)) (do (println (first search-term)) (println (last two-halves)) (find-row (subs search-term 1) (last two-halves) comparator)) )))) (find-row "FBFBBFF" rows "F") (find-row "RLR" seats "L") ; FBFBBFF ; 0-127 ; want 0-63; split-at (127-1)/2 (defn find-position [search-term remaining-values comparator] (let [two-halves (partition (/ (count remaining-values) 2) remaining-values)] (if (= (count remaining-values) 1) (first remaining-values) (if (= (subs search-term 0 1) comparator) (find-position (subs search-term 1) (first two-halves) comparator) (find-position (subs search-term 1) (last two-halves) comparator))))) (find-position "FBFBBFB" rows "F") (find-position "RRL" seats "L") (mod 101 2) ;; a map with a term that contains a sub-map (def bag-test-map {:gold {:dull-green 3 :muted-green 1 :shiny-orange 2} :fuschia {:dim-blue 3 :dim-red 1 :dim-orange 2}}) (println bag-test-map) ;; to get an item in the submap, get-in with the m (get-in bag-test-map [:gold :dull-green]) ;; dim red bags contain 1 mirrored olive bag, 1 plaid violet bag. ;; {:dim-red {:mirrored-olive-bag 1 :plaid-violet-bag 1 :plaid-violet-bag 1}} ;; posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags. ;; NOTICE: bag vs bags ;; {:posh-salmon {:shiny-brown 1 :dark-red 2 :drab-gold 3}} ;; posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags. (def bag-test-string (str/replace "posh salmon bags contain 1 shiny brown bag, 2 dark red bags, 3 drab gold bags." #"bags" "bag")) ;; remove contain, separate main from subs with #, replace trailing . with , (def parse-bag-test-string (str/replace bag-test-string #"^(.* bag)\scontain\s(.*)(.)" "$1#$2, ")) (println parse-bag-test-string) ;; GET MAIN BAG NAME ;; get the main bag string, with spaces replaced as - (def main-bag (str/replace (str/replace parse-bag-test-string #"(.*)#.*" "$1") #" " "-")) (println main-bag) ;; GENERATE SUB-BAG MAP WITH COUNT AS VALUE ;; get sub-bag strings in the form of #-remaining-name-words (def containing-seq (map #(str/replace % #"(\w) " "$1-") (re-seq #"\d[\w|\s]+" parse-bag-test-string))) (println containing-seq) ;; get map form string of sub-bags as ":sub-bag count" (def sub-bags-with-values (map #(str/replace % #"(\d)-(.*)" ":$2 $1") containing-seq)) (println sub-bags-with-values) ;; combine main bag and sub bag into single map form string, convert to map (def bag-and-containers-values-hash (clojure.edn/read-string (str "{:" main-bag " {" (str/join " " sub-bags-with-values) "}}"))) (println bag-and-containers-values-hash) (map #(str %) (get bag-and-containers-values-hash (keyword main-bag))) ;; GENERATE SUB-BAG LIST, DROP VALUES ;; (re-find #"\d[\w|\s]+" parse-bag-test-string) ;; (defn extract-group [n] (fn [group] (group n))) (def sub-bags (map #(str/replace % #"\d-([\w|-]+)" "$1") containing-seq)) (println sub-bags) (def bag-and-containers-hash (clojure.edn/read-string (str "{:" main-bag " (" (str/join " " sub-bags) ")}"))) (println bag-and-containers-hash) (def test-bag-1 (edn/read-string "{:posh-salmon-bag {:shiny-brown-bag 1, :dark-red-bags 2, :drab-gold-bags 3} :shiny-brown-bag {:dark-red-bags 2, :drab-gold-bags 3} :dark-red-bags {:drab-gold-bags 3}}")) (get test-bag-1 :posh-salmon-bag) (get test-bag-1 :shiny-brown-bag) (get-in test-bag-1 [:posh-salmon-bag :shiny-brown-bag]) (select-keys test-bag-1 [:posh-salmon-bag]) (def sub-bag-test (str "(drab-silver-bag dim-coral-bag drab-silver-bag dim-salmon-bag)")) (re-find #"dim-coral-bag" sub-bag-test) (into () ":shiny-gold-bag :vibrant-yellow-bag") (split-at 4 [1 2 3 4 5]) (subvec [1 2 3 4 5 6 7] 0) (nth [1 2 3 4 5 6 7] 0) (def diffs [3 1 1 1 1 3 3 1 1 1 1 3 1 1 1 1 3 1 1 3 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 3 1 1 1 3 3 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 3 1 1 3 3 3 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 1 3 1 1 1 3 1 3 1 1 1]) ;; (def diffs [3 1 3 1 1 3 1 1 1 3 1]) (def separated-diffs (partition-by #(= 1 %) diffs)) (println separated-diffs) (loop [index 0 two-groups 0 three-groups 0 four-groups 0] (if (= index (count separated-diffs)) (* (math/expt 2 two-groups) (math/expt 4 three-groups) (math/expt 7 four-groups)) (let [current-group (nth separated-diffs index)] (println current-group " count " (count current-group)) (if (and (some #(= 1 %) current-group) (> (count current-group) 1)) (if (= (count current-group) 2) (recur (inc index) (inc two-groups) three-groups four-groups) (if (= (count current-group) 3) (recur (inc index) two-groups (inc three-groups) four-groups) (recur (inc index) two-groups three-groups (inc four-groups)))) (recur (inc index) two-groups three-groups four-groups))))) (def test-seats "#.#L.L#.###LLL#LL.L#L.#.L..#..#L##.##.L##.#L.LL.LL#.#L#L#.##..L.L.....#L#L##L#L##.LLLLLL.L#.#L#L#.##") (count (filter #(= "#" (str %)) test-seats)) (frequencies test-seats)
[ { "context": "wordpress.com/2016/03/hll-fig-3.png\n;;\n;; To quote Adrian: \"The end result is that for an important ran", "end": 731, "score": 0.7356041669845581, "start": 729, "tag": "NAME", "value": "Ad" } ]
src/hllsandbox/notes.clj
amontalenti/hyperloglog-sandbox
1
(ns hllsandbox.notes) ;; Notes from reading HyperLogLogPlusPlus.java from Elasticsearch: ;; ;; - Precision min/max is 4 - 18 ;; - There are also "thresholds" which provide a convenience over ;; the precision values; the set looks like [10, 20, ..., 350000] ;; and they map to the precision values. ;; - When the HLL cardinality is small, "linear counting" is used, ;; but with a small modification of using a hash table for LC. ;; - According to acoyler analysis, at p = 14, linear counting performs ;; better for cardinalities between 0 - 50k, and then HLL starts to ;; perform much better, especially with bias correction. See this: ;; https://adriancolyer.files.wordpress.com/2016/03/hll-fig-3.png ;; ;; To quote Adrian: "The end result is that for an important range ;; of cardinalities -- roughly between 18k and 61k p = 14, the ;; error is much less than that of the original HyperLogLog." ... ;; "Notice that linear counting still beats the bias-corrected estimate ;; for small n. For precision 14 (p = 14) the error curves intersect at ;; around n = 11.5k. Therefore linear counting is used below 11.5k, and ;; bias corrected raw estimates above."
38881
(ns hllsandbox.notes) ;; Notes from reading HyperLogLogPlusPlus.java from Elasticsearch: ;; ;; - Precision min/max is 4 - 18 ;; - There are also "thresholds" which provide a convenience over ;; the precision values; the set looks like [10, 20, ..., 350000] ;; and they map to the precision values. ;; - When the HLL cardinality is small, "linear counting" is used, ;; but with a small modification of using a hash table for LC. ;; - According to acoyler analysis, at p = 14, linear counting performs ;; better for cardinalities between 0 - 50k, and then HLL starts to ;; perform much better, especially with bias correction. See this: ;; https://adriancolyer.files.wordpress.com/2016/03/hll-fig-3.png ;; ;; To quote <NAME>rian: "The end result is that for an important range ;; of cardinalities -- roughly between 18k and 61k p = 14, the ;; error is much less than that of the original HyperLogLog." ... ;; "Notice that linear counting still beats the bias-corrected estimate ;; for small n. For precision 14 (p = 14) the error curves intersect at ;; around n = 11.5k. Therefore linear counting is used below 11.5k, and ;; bias corrected raw estimates above."
true
(ns hllsandbox.notes) ;; Notes from reading HyperLogLogPlusPlus.java from Elasticsearch: ;; ;; - Precision min/max is 4 - 18 ;; - There are also "thresholds" which provide a convenience over ;; the precision values; the set looks like [10, 20, ..., 350000] ;; and they map to the precision values. ;; - When the HLL cardinality is small, "linear counting" is used, ;; but with a small modification of using a hash table for LC. ;; - According to acoyler analysis, at p = 14, linear counting performs ;; better for cardinalities between 0 - 50k, and then HLL starts to ;; perform much better, especially with bias correction. See this: ;; https://adriancolyer.files.wordpress.com/2016/03/hll-fig-3.png ;; ;; To quote PI:NAME:<NAME>END_PIrian: "The end result is that for an important range ;; of cardinalities -- roughly between 18k and 61k p = 14, the ;; error is much less than that of the original HyperLogLog." ... ;; "Notice that linear counting still beats the bias-corrected estimate ;; for small n. For precision 14 (p = 14) the error curves intersect at ;; around n = 11.5k. Therefore linear counting is used below 11.5k, and ;; bias corrected raw estimates above."
[ { "context": "tegory\" \"reference\"\n \"author\" \"Nigel Rees\"\n \"title\" \"Sayings of the Cen", "end": 500, "score": 0.9998818635940552, "start": 490, "tag": "NAME", "value": "Nigel Rees" }, { "context": "category\" \"fiction\"\n \"author\" \"Evelyn Waugh\"\n \"title\" \"Sword of Honour\"}\n", "end": 638, "score": 0.9998970031738281, "start": 626, "tag": "NAME", "value": "Evelyn Waugh" }, { "context": "category\" \"fiction\"\n \"author\" \"Herman Melville\"\n \"title\" \"Moby Dick\"}\n ", "end": 772, "score": 0.9998880624771118, "start": 757, "tag": "NAME", "value": "Herman Melville" }, { "context": " \"Herman Melville\"\n \"title\" \"Moby Dick\"}\n {\"category\" \"fiction\"\n ", "end": 807, "score": 0.6902461051940918, "start": 804, "tag": "NAME", "value": "Mob" }, { "context": "category\" \"fiction\"\n \"author\" \"J.R.R. Tolkien\"\n \"title\" \"The Lord of the Ri", "end": 899, "score": 0.9998953938484192, "start": 885, "tag": "NAME", "value": "J.R.R. Tolkien" }, { "context": " [{\"category\" \"reference\" \"author\" \"Nigel Rees\" \"title\" \"Sayings of the Century\"}\n ", "end": 1462, "score": 0.9998799562454224, "start": 1452, "tag": "NAME", "value": "Nigel Rees" }, { "context": " {\"category\" \"fiction\" \"author\" \"Evelyn Waugh\" \"title\" \"Sword of Honour\"}\n ", "end": 1564, "score": 0.9998979568481445, "start": 1552, "tag": "NAME", "value": "Evelyn Waugh" }, { "context": " {\"category\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n {\"cat", "end": 1662, "score": 0.9998921155929565, "start": 1647, "tag": "NAME", "value": "Herman Melville" }, { "context": "ry\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n {\"category\" \"fictio", "end": 1676, "score": 0.8610872626304626, "start": 1673, "tag": "NAME", "value": "Mob" }, { "context": "\"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n {\"category\" \"fiction\" \"au", "end": 1682, "score": 0.5943436622619629, "start": 1678, "tag": "NAME", "value": "Dick" }, { "context": " {\"category\" \"fiction\" \"author\" \"J.R.R. Tolkien\" \"title\" \"The Lord of the Rings\"}]\n ", "end": 1753, "score": 0.9998937845230103, "start": 1739, "tag": "NAME", "value": "J.R.R. Tolkien" }, { "context": " [{\"category\" \"reference\" \"author\" \"Nigel Rees\" \"title\" \"Sayings of the Century\"}\n ", "end": 1964, "score": 0.9998573064804077, "start": 1954, "tag": "NAME", "value": "Nigel Rees" }, { "context": " {\"category\" \"fiction\" \"author\" \"Evelyn Waugh\" \"title\" \"Sword of Honour\"}\n ", "end": 2065, "score": 0.9998885989189148, "start": 2053, "tag": "NAME", "value": "Evelyn Waugh" }, { "context": " {\"category\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n {\"cate", "end": 2162, "score": 0.9998921751976013, "start": 2147, "tag": "NAME", "value": "Herman Melville" }, { "context": "ry\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n {\"category\" \"fiction\" \"aut", "end": 2182, "score": 0.9974197745323181, "start": 2173, "tag": "NAME", "value": "Moby Dick" }, { "context": " {\"category\" \"fiction\" \"author\" \"J.R.R. Tolkien\" \"title\" \"The Lord of the Rings\"}]\n ", "end": 2252, "score": 0.9998903274536133, "start": 2238, "tag": "NAME", "value": "J.R.R. Tolkien" }, { "context": " {:json [{\"category\" \"reference\" \"author\" \"Nigel Rees\" \"title\" \"Sayings of the Century\"}\n ", "end": 2440, "score": 0.9998692274093628, "start": 2430, "tag": "NAME", "value": "Nigel Rees" }, { "context": " {\"category\" \"fiction\" \"author\" \"Evelyn Waugh\" \"title\" \"Sword of Honour\"}\n {", "end": 2540, "score": 0.9998936653137207, "start": 2528, "tag": "NAME", "value": "Evelyn Waugh" }, { "context": " {\"category\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n {\"categ", "end": 2636, "score": 0.9998838305473328, "start": 2621, "tag": "NAME", "value": "Herman Melville" }, { "context": " {\"category\" \"fiction\" \"author\" \"J.R.R. Tolkien\" \"title\" \"The Lord of the Rings\"}]\n :", "end": 2725, "score": 0.9998946189880371, "start": 2711, "tag": "NAME", "value": "J.R.R. Tolkien" }, { "context": " {:json {\"category\" \"reference\" \"author\" \"Nigel Rees\" \"title\" \"Sayings of the Century\"}\n :", "end": 2861, "score": 0.9998575448989868, "start": 2851, "tag": "NAME", "value": "Nigel Rees" }, { "context": "\"store\" \"book\" 0 \"category\"]}\n {:json \"Nigel Rees\"\n :path [\"store\" \"book\" 0 \"author\"]}\n", "end": 3047, "score": 0.9960178136825562, "start": 3037, "tag": "NAME", "value": "Nigel Rees" }, { "context": " {:json {\"category\" \"fiction\" \"author\" \"Evelyn Waugh\" \"title\" \"Sword of Honour\"}\n :path [\"", "end": 3251, "score": 0.9998888969421387, "start": 3239, "tag": "NAME", "value": "Evelyn Waugh" }, { "context": "\"store\" \"book\" 1 \"category\"]}\n {:json \"Evelyn Waugh\"\n :path [\"store\" \"book\" 1 \"author\"]}\n", "end": 3430, "score": 0.9995498061180115, "start": 3418, "tag": "NAME", "value": "Evelyn Waugh" }, { "context": " {:json {\"category\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n :path [\"store\"", "end": 3630, "score": 0.9998704195022583, "start": 3615, "tag": "NAME", "value": "Herman Melville" }, { "context": "ry\" \"fiction\" \"author\" \"Herman Melville\" \"title\" \"Moby Dick\"}\n :path [\"store\" \"book\" 2]}\n ", "end": 3650, "score": 0.9994624257087708, "start": 3641, "tag": "NAME", "value": "Moby Dick" }, { "context": "\"store\" \"book\" 2 \"category\"]}\n {:json \"Herman Melville\"\n :path [\"store\" \"book\" 2 \"author\"]}\n", "end": 3806, "score": 0.999826967716217, "start": 3791, "tag": "NAME", "value": "Herman Melville" }, { "context": " [\"store\" \"book\" 2 \"author\"]}\n {:json \"Moby Dick\"\n :path [\"store\" \"book\" 2 \"title\"]}\n ", "end": 3885, "score": 0.999800443649292, "start": 3876, "tag": "NAME", "value": "Moby Dick" }, { "context": " {:json {\"category\" \"fiction\" \"author\" \"J.R.R. Tolkien\" \"title\" \"The Lord of the Rings\"}\n :p", "end": 3999, "score": 0.9998393058776855, "start": 3985, "tag": "NAME", "value": "J.R.R. Tolkien" }, { "context": "\"store\" \"book\" 3 \"category\"]}\n {:json \"J.R.R. Tolkien\"\n :path [\"store\" \"book\" 3 \"author\"]}\n", "end": 4186, "score": 0.999677836894989, "start": 4172, "tag": "NAME", "value": "J.R.R. Tolkien" } ]
src/test/com/yetanalytics/pathetic/json_test.cljc
yetanalytics/pathetic
10
(ns com.yetanalytics.pathetic.json-test (:require [clojure.test :refer [deftest testing is]] [clojure.spec.alpha :as s] [clojure.test.check] [clojure.test.check.properties] [clojure.spec.test.alpha :as stest] [com.yetanalytics.pathetic.json :as json :refer [recursive-descent jassoc jassoc-in]])) (def store-ex {"store" {"book" [{"category" "reference" "author" "Nigel Rees" "title" "Sayings of the Century"} {"category" "fiction" "author" "Evelyn Waugh" "title" "Sword of Honour"} {"category" "fiction" "author" "Herman Melville" "title" "Moby Dick"} {"category" "fiction" "author" "J.R.R. Tolkien" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}}}) (deftest spec-test (testing "json-related specs" (is (s/valid? ::json/json store-ex)) (is (s/valid? ::json/json nil)) (is (s/valid? ::json/path [1 2 3 "foo" "bar"])))) (deftest recursive-descent-test (testing "recursive-descent function - should return all JSON substructures" (is (= [{:json {"store" {"book" [{"category" "reference" "author" "Nigel Rees" "title" "Sayings of the Century"} {"category" "fiction" "author" "Evelyn Waugh" "title" "Sword of Honour"} {"category" "fiction" "author" "Herman Melville" "title" "Moby Dick"} {"category" "fiction" "author" "J.R.R. Tolkien" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}}} :path []} {:json {"book" [{"category" "reference" "author" "Nigel Rees" "title" "Sayings of the Century"} {"category" "fiction" "author" "Evelyn Waugh" "title" "Sword of Honour"} {"category" "fiction" "author" "Herman Melville" "title" "Moby Dick"} {"category" "fiction" "author" "J.R.R. Tolkien" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}} :path ["store"]} {:json [{"category" "reference" "author" "Nigel Rees" "title" "Sayings of the Century"} {"category" "fiction" "author" "Evelyn Waugh" "title" "Sword of Honour"} {"category" "fiction" "author" "Herman Melville" "title" "Moby Dick"} {"category" "fiction" "author" "J.R.R. Tolkien" "title" "The Lord of the Rings"}] :path ["store" "book"]} {:json {"category" "reference" "author" "Nigel Rees" "title" "Sayings of the Century"} :path ["store" "book" 0]} {:json "reference" :path ["store" "book" 0 "category"]} {:json "Nigel Rees" :path ["store" "book" 0 "author"]} {:json "Sayings of the Century" :path ["store" "book" 0 "title"]} {:json {"category" "fiction" "author" "Evelyn Waugh" "title" "Sword of Honour"} :path ["store" "book" 1]} {:json "fiction" :path ["store" "book" 1 "category"]} {:json "Evelyn Waugh" :path ["store" "book" 1 "author"]} {:json "Sword of Honour" :path ["store" "book" 1 "title"]} {:json {"category" "fiction" "author" "Herman Melville" "title" "Moby Dick"} :path ["store" "book" 2]} {:json "fiction" :path ["store" "book" 2 "category"]} {:json "Herman Melville" :path ["store" "book" 2 "author"]} {:json "Moby Dick" :path ["store" "book" 2 "title"]} {:json {"category" "fiction" "author" "J.R.R. Tolkien" "title" "The Lord of the Rings"} :path ["store" "book" 3]} {:json "fiction" :path ["store" "book" 3 "category"]} {:json "J.R.R. Tolkien" :path ["store" "book" 3 "author"]} {:json "The Lord of the Rings" :path ["store" "book" 3 "title"]} {:json {"color" "red" "price" 20} :path ["store" "bicycle"]} {:json "red" :path ["store" "bicycle" "color"]} {:json 20 :path ["store" "bicycle" "price"]}] (recursive-descent store-ex))))) (deftest jassoc-test (testing "jassoc function" (is (= {"0" "a"} (jassoc nil "0" "a"))) (is (= ["a"] (jassoc nil 0 "a"))) (is (= [nil "a"] (jassoc nil 1 "a"))) (is (= ["a" nil :c] (jassoc ["a"] 2 :c))) (is (= {"foo" "b"} (jassoc ["a"] "foo" "b"))))) (deftest jassoc-in-test (testing "jassoc-in function" (is (= "b" (jassoc-in nil [] "b"))) (is (= "b" (jassoc-in {} [] "b"))) (is (= "b" (jassoc-in {"foo" "bar"} [] "b"))) (is (= {"0" "a"} (jassoc-in nil ["0"] "a"))) (is (= {"foo" {"bar" "b"}} (jassoc-in {"foo" {"bar" "a"}} ["foo" "bar"] "b"))) (is (= {"foo" {"bar" "a" "baz" "b"}} (jassoc-in {"foo" {"bar" "a"}} ["foo" "baz"] "b"))) (is (= {"foo" ["b"]} (jassoc-in {"foo" {"bar" "a"}} ["foo" 0] "b"))) (is (= {"foo" "b"} (jassoc-in nil ["foo"] "b"))) (is (= [nil nil [nil nil nil 3]] (jassoc-in nil [2 3] 3))))) (deftest gen-tests (testing "Generative tests for json" (let [results (stest/check `[json/recursive-descent json/jassoc json/jassoc-in] {:clojure.spec.test.check/opts {:num-tests #?(:clj 500 :cljs 100) :seed (rand-int 2000000000)}}) {:keys [total check-passed]} (stest/summarize-results results)] (is (= total check-passed)))))
9841
(ns com.yetanalytics.pathetic.json-test (:require [clojure.test :refer [deftest testing is]] [clojure.spec.alpha :as s] [clojure.test.check] [clojure.test.check.properties] [clojure.spec.test.alpha :as stest] [com.yetanalytics.pathetic.json :as json :refer [recursive-descent jassoc jassoc-in]])) (def store-ex {"store" {"book" [{"category" "reference" "author" "<NAME>" "title" "Sayings of the Century"} {"category" "fiction" "author" "<NAME>" "title" "Sword of Honour"} {"category" "fiction" "author" "<NAME>" "title" "<NAME>y Dick"} {"category" "fiction" "author" "<NAME>" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}}}) (deftest spec-test (testing "json-related specs" (is (s/valid? ::json/json store-ex)) (is (s/valid? ::json/json nil)) (is (s/valid? ::json/path [1 2 3 "foo" "bar"])))) (deftest recursive-descent-test (testing "recursive-descent function - should return all JSON substructures" (is (= [{:json {"store" {"book" [{"category" "reference" "author" "<NAME>" "title" "Sayings of the Century"} {"category" "fiction" "author" "<NAME>" "title" "Sword of Honour"} {"category" "fiction" "author" "<NAME>" "title" "<NAME>y <NAME>"} {"category" "fiction" "author" "<NAME>" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}}} :path []} {:json {"book" [{"category" "reference" "author" "<NAME>" "title" "Sayings of the Century"} {"category" "fiction" "author" "<NAME>" "title" "Sword of Honour"} {"category" "fiction" "author" "<NAME>" "title" "<NAME>"} {"category" "fiction" "author" "<NAME>" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}} :path ["store"]} {:json [{"category" "reference" "author" "<NAME>" "title" "Sayings of the Century"} {"category" "fiction" "author" "<NAME>" "title" "Sword of Honour"} {"category" "fiction" "author" "<NAME>" "title" "Moby Dick"} {"category" "fiction" "author" "<NAME>" "title" "The Lord of the Rings"}] :path ["store" "book"]} {:json {"category" "reference" "author" "<NAME>" "title" "Sayings of the Century"} :path ["store" "book" 0]} {:json "reference" :path ["store" "book" 0 "category"]} {:json "<NAME>" :path ["store" "book" 0 "author"]} {:json "Sayings of the Century" :path ["store" "book" 0 "title"]} {:json {"category" "fiction" "author" "<NAME>" "title" "Sword of Honour"} :path ["store" "book" 1]} {:json "fiction" :path ["store" "book" 1 "category"]} {:json "<NAME>" :path ["store" "book" 1 "author"]} {:json "Sword of Honour" :path ["store" "book" 1 "title"]} {:json {"category" "fiction" "author" "<NAME>" "title" "<NAME>"} :path ["store" "book" 2]} {:json "fiction" :path ["store" "book" 2 "category"]} {:json "<NAME>" :path ["store" "book" 2 "author"]} {:json "<NAME>" :path ["store" "book" 2 "title"]} {:json {"category" "fiction" "author" "<NAME>" "title" "The Lord of the Rings"} :path ["store" "book" 3]} {:json "fiction" :path ["store" "book" 3 "category"]} {:json "<NAME>" :path ["store" "book" 3 "author"]} {:json "The Lord of the Rings" :path ["store" "book" 3 "title"]} {:json {"color" "red" "price" 20} :path ["store" "bicycle"]} {:json "red" :path ["store" "bicycle" "color"]} {:json 20 :path ["store" "bicycle" "price"]}] (recursive-descent store-ex))))) (deftest jassoc-test (testing "jassoc function" (is (= {"0" "a"} (jassoc nil "0" "a"))) (is (= ["a"] (jassoc nil 0 "a"))) (is (= [nil "a"] (jassoc nil 1 "a"))) (is (= ["a" nil :c] (jassoc ["a"] 2 :c))) (is (= {"foo" "b"} (jassoc ["a"] "foo" "b"))))) (deftest jassoc-in-test (testing "jassoc-in function" (is (= "b" (jassoc-in nil [] "b"))) (is (= "b" (jassoc-in {} [] "b"))) (is (= "b" (jassoc-in {"foo" "bar"} [] "b"))) (is (= {"0" "a"} (jassoc-in nil ["0"] "a"))) (is (= {"foo" {"bar" "b"}} (jassoc-in {"foo" {"bar" "a"}} ["foo" "bar"] "b"))) (is (= {"foo" {"bar" "a" "baz" "b"}} (jassoc-in {"foo" {"bar" "a"}} ["foo" "baz"] "b"))) (is (= {"foo" ["b"]} (jassoc-in {"foo" {"bar" "a"}} ["foo" 0] "b"))) (is (= {"foo" "b"} (jassoc-in nil ["foo"] "b"))) (is (= [nil nil [nil nil nil 3]] (jassoc-in nil [2 3] 3))))) (deftest gen-tests (testing "Generative tests for json" (let [results (stest/check `[json/recursive-descent json/jassoc json/jassoc-in] {:clojure.spec.test.check/opts {:num-tests #?(:clj 500 :cljs 100) :seed (rand-int 2000000000)}}) {:keys [total check-passed]} (stest/summarize-results results)] (is (= total check-passed)))))
true
(ns com.yetanalytics.pathetic.json-test (:require [clojure.test :refer [deftest testing is]] [clojure.spec.alpha :as s] [clojure.test.check] [clojure.test.check.properties] [clojure.spec.test.alpha :as stest] [com.yetanalytics.pathetic.json :as json :refer [recursive-descent jassoc jassoc-in]])) (def store-ex {"store" {"book" [{"category" "reference" "author" "PI:NAME:<NAME>END_PI" "title" "Sayings of the Century"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "Sword of Honour"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "PI:NAME:<NAME>END_PIy Dick"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}}}) (deftest spec-test (testing "json-related specs" (is (s/valid? ::json/json store-ex)) (is (s/valid? ::json/json nil)) (is (s/valid? ::json/path [1 2 3 "foo" "bar"])))) (deftest recursive-descent-test (testing "recursive-descent function - should return all JSON substructures" (is (= [{:json {"store" {"book" [{"category" "reference" "author" "PI:NAME:<NAME>END_PI" "title" "Sayings of the Century"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "Sword of Honour"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "PI:NAME:<NAME>END_PIy PI:NAME:<NAME>END_PI"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}}} :path []} {:json {"book" [{"category" "reference" "author" "PI:NAME:<NAME>END_PI" "title" "Sayings of the Century"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "Sword of Honour"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "PI:NAME:<NAME>END_PI"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "The Lord of the Rings"}] "bicycle" {"color" "red" "price" 20}} :path ["store"]} {:json [{"category" "reference" "author" "PI:NAME:<NAME>END_PI" "title" "Sayings of the Century"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "Sword of Honour"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "Moby Dick"} {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "The Lord of the Rings"}] :path ["store" "book"]} {:json {"category" "reference" "author" "PI:NAME:<NAME>END_PI" "title" "Sayings of the Century"} :path ["store" "book" 0]} {:json "reference" :path ["store" "book" 0 "category"]} {:json "PI:NAME:<NAME>END_PI" :path ["store" "book" 0 "author"]} {:json "Sayings of the Century" :path ["store" "book" 0 "title"]} {:json {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "Sword of Honour"} :path ["store" "book" 1]} {:json "fiction" :path ["store" "book" 1 "category"]} {:json "PI:NAME:<NAME>END_PI" :path ["store" "book" 1 "author"]} {:json "Sword of Honour" :path ["store" "book" 1 "title"]} {:json {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "PI:NAME:<NAME>END_PI"} :path ["store" "book" 2]} {:json "fiction" :path ["store" "book" 2 "category"]} {:json "PI:NAME:<NAME>END_PI" :path ["store" "book" 2 "author"]} {:json "PI:NAME:<NAME>END_PI" :path ["store" "book" 2 "title"]} {:json {"category" "fiction" "author" "PI:NAME:<NAME>END_PI" "title" "The Lord of the Rings"} :path ["store" "book" 3]} {:json "fiction" :path ["store" "book" 3 "category"]} {:json "PI:NAME:<NAME>END_PI" :path ["store" "book" 3 "author"]} {:json "The Lord of the Rings" :path ["store" "book" 3 "title"]} {:json {"color" "red" "price" 20} :path ["store" "bicycle"]} {:json "red" :path ["store" "bicycle" "color"]} {:json 20 :path ["store" "bicycle" "price"]}] (recursive-descent store-ex))))) (deftest jassoc-test (testing "jassoc function" (is (= {"0" "a"} (jassoc nil "0" "a"))) (is (= ["a"] (jassoc nil 0 "a"))) (is (= [nil "a"] (jassoc nil 1 "a"))) (is (= ["a" nil :c] (jassoc ["a"] 2 :c))) (is (= {"foo" "b"} (jassoc ["a"] "foo" "b"))))) (deftest jassoc-in-test (testing "jassoc-in function" (is (= "b" (jassoc-in nil [] "b"))) (is (= "b" (jassoc-in {} [] "b"))) (is (= "b" (jassoc-in {"foo" "bar"} [] "b"))) (is (= {"0" "a"} (jassoc-in nil ["0"] "a"))) (is (= {"foo" {"bar" "b"}} (jassoc-in {"foo" {"bar" "a"}} ["foo" "bar"] "b"))) (is (= {"foo" {"bar" "a" "baz" "b"}} (jassoc-in {"foo" {"bar" "a"}} ["foo" "baz"] "b"))) (is (= {"foo" ["b"]} (jassoc-in {"foo" {"bar" "a"}} ["foo" 0] "b"))) (is (= {"foo" "b"} (jassoc-in nil ["foo"] "b"))) (is (= [nil nil [nil nil nil 3]] (jassoc-in nil [2 3] 3))))) (deftest gen-tests (testing "Generative tests for json" (let [results (stest/check `[json/recursive-descent json/jassoc json/jassoc-in] {:clojure.spec.test.check/opts {:num-tests #?(:clj 500 :cljs 100) :seed (rand-int 2000000000)}}) {:keys [total check-passed]} (stest/summarize-results results)] (is (= total check-passed)))))
[ { "context": "intln (let [progeny\n #{[\"father\" \"son\"] [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}]\n ", "end": 736, "score": 0.8869077563285828, "start": 733, "tag": "NAME", "value": "son" }, { "context": "et [progeny\n #{[\"father\" \"son\"] [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}]\n (= (", "end": 746, "score": 0.9815228581428528, "start": 741, "tag": "NAME", "value": "uncle" }, { "context": "eny\n #{[\"father\" \"son\"] [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}]\n (= (arg proge", "end": 755, "score": 0.9833886623382568, "start": 749, "tag": "NAME", "value": "cousin" }, { "context": " #{[\"father\" \"son\"] [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}]\n (= (arg progeny)\n ", "end": 763, "score": 0.9265554547309875, "start": 760, "tag": "NAME", "value": "son" }, { "context": " #{[\"father\" \"son\"] [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}]\n (= (arg progeny)\n ", "end": 774, "score": 0.9773389101028442, "start": 766, "tag": "NAME", "value": "grandson" }, { "context": " (= (arg progeny)\n #{[\"father\" \"son\"] [\"father\" \"grandson\"]\n [\"uncle", "end": 841, "score": 0.7007786631584167, "start": 838, "tag": "NAME", "value": "son" }, { "context": "ny)\n #{[\"father\" \"son\"] [\"father\" \"grandson\"]\n [\"uncle\" \"cousin\"] [\"son\" \"gr", "end": 863, "score": 0.9405709505081177, "start": 855, "tag": "NAME", "value": "grandson" }, { "context": " \"son\"] [\"father\" \"grandson\"]\n [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}))))\n\n(transitive-c", "end": 891, "score": 0.9638715982437134, "start": 886, "tag": "NAME", "value": "uncle" }, { "context": "[\"father\" \"grandson\"]\n [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}))))\n\n(transitive-closure #(", "end": 900, "score": 0.9822127223014832, "start": 894, "tag": "NAME", "value": "cousin" }, { "context": "grandson\"]\n [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}))))\n\n(transitive-closure #(let [vv-", "end": 908, "score": 0.9683140516281128, "start": 905, "tag": "NAME", "value": "son" }, { "context": "on\"]\n [\"uncle\" \"cousin\"] [\"son\" \"grandson\"]}))))\n\n(transitive-closure #(let [vv-seq (seq %)", "end": 919, "score": 0.9790710210800171, "start": 911, "tag": "NAME", "value": "grandson" } ]
src/clojure4j/explorer/questions/$81to90/$84_set_theory_h_transitive_closure.clj
ningDr/clojure-4-me
0
(ns clojure4j.explorer.questions.$81to90.$84-set-theory-h-transitive-closure (:require [clojure.set])) (defn transitive-closure "Write a function which generates the transitive closure of a binary relation. The relation will be represented as a set of 2 item vectors." [arg] (println (let [divides #{[8 4] [9 3] [4 2] [27 9]}] (= (arg divides) #{[4 2] [8 4] [8 2] [9 3] [27 9] [27 3]}))) (println (let [more-legs #{["cat" "man"] ["man" "snake"] ["spider" "cat"]}] (= (arg more-legs) #{["cat" "man"] ["cat" "snake"] ["man" "snake"] ["spider" "cat"] ["spider" "man"] ["spider" "snake"]}))) (println (let [progeny #{["father" "son"] ["uncle" "cousin"] ["son" "grandson"]}] (= (arg progeny) #{["father" "son"] ["father" "grandson"] ["uncle" "cousin"] ["son" "grandson"]})))) (transitive-closure #(let [vv-seq (seq %) fn-seq (fn [vv-seq] (filter (complement nil?) (seq (set (apply concat ((fn [v-seq] (mapv (fn [item] (mapv (fn [s-item] (if (and (= 3 (count (clojure.set/union (set item) (set s-item)))) (= (last item) (first s-item))) (vector (first item) (last s-item)))) v-seq)) v-seq)) vv-seq))))))] (loop [l-seq (fn-seq vv-seq), res-set %, i (count res-set)] (if (= i (count l-seq)) res-set (recur (fn-seq (seq (apply conj res-set l-seq))) (apply conj res-set l-seq) (count l-seq)))))) ;; ************************************************************* (transitive-closure (fn [edges] (let [adj-list (reduce (fn [agg [x y]] (merge-with into agg {x #{y}})) {} edges) vs (into #{} (keys adj-list)) linked-cmp (fn ch [v adj-list visited] (if (empty? adj-list) visited (->> (for [v-adj (adj-list v) :when (not (visited v-adj))] (ch v-adj (dissoc adj-list v) (into visited [v v-adj]))) (reduce into visited)))) vs-cmp (for [v vs] [v (disj (linked-cmp v adj-list #{}) v)])] (reduce (fn [agg [v cmp]] (into agg (map #(vector v %) cmp))) #{} vs-cmp)))) ;; 解构用的很彻底 (transitive-closure #(loop [s %] (let [n (into s (for [[a b] s [c d] s :when (= b c)] [a d]))] (println "s=" s ";n=" n) (if (= n s) n (recur n))))) (transitive-closure (letfn [(update [e x] (let [in (for [ei e :when (= x (second ei))] (first ei)) out (for [ei e :when (= x (first ei))] (second ei))] (into e (for [v1 in v2 out] [v1 v2])))) (trans [e] (reduce update e (distinct (flatten (vec e)))))] trans))
82722
(ns clojure4j.explorer.questions.$81to90.$84-set-theory-h-transitive-closure (:require [clojure.set])) (defn transitive-closure "Write a function which generates the transitive closure of a binary relation. The relation will be represented as a set of 2 item vectors." [arg] (println (let [divides #{[8 4] [9 3] [4 2] [27 9]}] (= (arg divides) #{[4 2] [8 4] [8 2] [9 3] [27 9] [27 3]}))) (println (let [more-legs #{["cat" "man"] ["man" "snake"] ["spider" "cat"]}] (= (arg more-legs) #{["cat" "man"] ["cat" "snake"] ["man" "snake"] ["spider" "cat"] ["spider" "man"] ["spider" "snake"]}))) (println (let [progeny #{["father" "<NAME>"] ["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"]}] (= (arg progeny) #{["father" "<NAME>"] ["father" "<NAME>"] ["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"]})))) (transitive-closure #(let [vv-seq (seq %) fn-seq (fn [vv-seq] (filter (complement nil?) (seq (set (apply concat ((fn [v-seq] (mapv (fn [item] (mapv (fn [s-item] (if (and (= 3 (count (clojure.set/union (set item) (set s-item)))) (= (last item) (first s-item))) (vector (first item) (last s-item)))) v-seq)) v-seq)) vv-seq))))))] (loop [l-seq (fn-seq vv-seq), res-set %, i (count res-set)] (if (= i (count l-seq)) res-set (recur (fn-seq (seq (apply conj res-set l-seq))) (apply conj res-set l-seq) (count l-seq)))))) ;; ************************************************************* (transitive-closure (fn [edges] (let [adj-list (reduce (fn [agg [x y]] (merge-with into agg {x #{y}})) {} edges) vs (into #{} (keys adj-list)) linked-cmp (fn ch [v adj-list visited] (if (empty? adj-list) visited (->> (for [v-adj (adj-list v) :when (not (visited v-adj))] (ch v-adj (dissoc adj-list v) (into visited [v v-adj]))) (reduce into visited)))) vs-cmp (for [v vs] [v (disj (linked-cmp v adj-list #{}) v)])] (reduce (fn [agg [v cmp]] (into agg (map #(vector v %) cmp))) #{} vs-cmp)))) ;; 解构用的很彻底 (transitive-closure #(loop [s %] (let [n (into s (for [[a b] s [c d] s :when (= b c)] [a d]))] (println "s=" s ";n=" n) (if (= n s) n (recur n))))) (transitive-closure (letfn [(update [e x] (let [in (for [ei e :when (= x (second ei))] (first ei)) out (for [ei e :when (= x (first ei))] (second ei))] (into e (for [v1 in v2 out] [v1 v2])))) (trans [e] (reduce update e (distinct (flatten (vec e)))))] trans))
true
(ns clojure4j.explorer.questions.$81to90.$84-set-theory-h-transitive-closure (:require [clojure.set])) (defn transitive-closure "Write a function which generates the transitive closure of a binary relation. The relation will be represented as a set of 2 item vectors." [arg] (println (let [divides #{[8 4] [9 3] [4 2] [27 9]}] (= (arg divides) #{[4 2] [8 4] [8 2] [9 3] [27 9] [27 3]}))) (println (let [more-legs #{["cat" "man"] ["man" "snake"] ["spider" "cat"]}] (= (arg more-legs) #{["cat" "man"] ["cat" "snake"] ["man" "snake"] ["spider" "cat"] ["spider" "man"] ["spider" "snake"]}))) (println (let [progeny #{["father" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}] (= (arg progeny) #{["father" "PI:NAME:<NAME>END_PI"] ["father" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]})))) (transitive-closure #(let [vv-seq (seq %) fn-seq (fn [vv-seq] (filter (complement nil?) (seq (set (apply concat ((fn [v-seq] (mapv (fn [item] (mapv (fn [s-item] (if (and (= 3 (count (clojure.set/union (set item) (set s-item)))) (= (last item) (first s-item))) (vector (first item) (last s-item)))) v-seq)) v-seq)) vv-seq))))))] (loop [l-seq (fn-seq vv-seq), res-set %, i (count res-set)] (if (= i (count l-seq)) res-set (recur (fn-seq (seq (apply conj res-set l-seq))) (apply conj res-set l-seq) (count l-seq)))))) ;; ************************************************************* (transitive-closure (fn [edges] (let [adj-list (reduce (fn [agg [x y]] (merge-with into agg {x #{y}})) {} edges) vs (into #{} (keys adj-list)) linked-cmp (fn ch [v adj-list visited] (if (empty? adj-list) visited (->> (for [v-adj (adj-list v) :when (not (visited v-adj))] (ch v-adj (dissoc adj-list v) (into visited [v v-adj]))) (reduce into visited)))) vs-cmp (for [v vs] [v (disj (linked-cmp v adj-list #{}) v)])] (reduce (fn [agg [v cmp]] (into agg (map #(vector v %) cmp))) #{} vs-cmp)))) ;; 解构用的很彻底 (transitive-closure #(loop [s %] (let [n (into s (for [[a b] s [c d] s :when (= b c)] [a d]))] (println "s=" s ";n=" n) (if (= n s) n (recur n))))) (transitive-closure (letfn [(update [e x] (let [in (for [ei e :when (= x (second ei))] (first ei)) out (for [ei e :when (= x (first ei))] (second ei))] (into e (for [v1 in v2 out] [v1 v2])))) (trans [e] (reduce update e (distinct (flatten (vec e)))))] trans))
[ { "context": "auth-by-username-password\n conn\n \"[email protected]\"\n \"Test1234\")\n <?))\n\n(def cog-schem", "end": 752, "score": 0.999804675579071, "start": 732, "tag": "EMAIL", "value": "[email protected]" }, { "context": " conn\n \"[email protected]\"\n \"Test1234\")\n <?))\n\n(def cog-schema {:box/sync-ddb-uri", "end": 772, "score": 0.854265570640564, "start": 764, "tag": "USERNAME", "value": "Test1234" } ]
src/cljs/rx/box/sync_client_test.cljs
zk/rx-lib
0
(ns rx.box.sync-client-test (:require [rx.kitchen-sink :as ks] [rx.res :as res] [rx.anom :as anom :refer-macros [<defn <?]] [rx.aws :as aws] [rx.box.common :as com] [rx.box.auth :as auth] [rx.box.test-helpers :as th] [rx.box.sync-client :as r] [rx.box.persist-local :as pl] [rx.test :as test] [cljs.core.async :as async :refer [<! >! chan close! put! take! timeout] :refer-macros [go]])) (def creds (:dev-creds (ks/edn-read-string (ks/slurp-cljs "~/.rx-prod-secrets.edn")))) (<defn <auth [conn] (->> (auth/<auth-by-username-password conn "[email protected]" "Test1234") <?)) (def cog-schema {:box/sync-ddb-uri "https://8pg6p1yb85.execute-api.us-west-2.amazonaws.com/20191217/" :box/cog-config {:aws.cog/client-id "1em482svs0uojb8u7kmooulmmj" :aws.cog/pool-id "us-west-2_W1OuUCkYR"} :box/cog-client-creds {:aws.creds/access-id "" :aws.creds/secret-key "" :aws.creds/region "us-west-2"}}) (test/<deftest test-<sync-entities [opts] (let [conn (<? (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3} :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"} {:box.canary/id "foo2" :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"}] store-res (<? (pl/<transact conn entities)) ok-res (<? (r/<sync-idents conn [[:box.canary/id "foo1"] [:box.canary/id "foo2"]] (<? (<auth conn)))) empty-res (<! (r/<sync-entities conn [{}] (<? (<auth conn))))] [{::test/desc "Local storage of entities should succeed" ::test/passed? (not (anom/? store-res)) ::test/explain-data store-res} {::test/desc "Sync should succeed" ::test/passed? (not (anom/? ok-res)) ::test/explain-data ok-res} {::test/desc "Empty entities param should anom" ::test/passed? (anom/? empty-res) ::test/explain-data empty-res}])) #_(<defn <verify-deployment [{:keys [:rx.aws/AWS]}] (let [conn (<! (pl/<conn AWS {:box/local-db-name "verify_deployment" :box/local-data-table-name "verify_deployment_data" :box/local-refs-table-name "verify_deployment_refs" :box/ddb-data-table-name "canter-prod-pk-string" :box/attrs {:foo/id {:box.attr/ident? true}}}))] (r/<sync-entities conn {:foo/id "hello"} nil))) (test/<deftest test-<sync-imd [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] sync-res (<! (r/<sync-imd conn entities nil))] [{::test/desc "<sync ok" ::test/passed? (not (anom/? sync-res)) ::test/explain-data sync-res}])) (test/<deftest test-<sync-ack-fail [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] res (<! (r/<sync-ack conn entities {:box/cog-tokens nil})) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync-ack should fail without auth" ::test/passed? (anom/? res) ::test/explain-data res} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}])) (test/<deftest test-<sync-ack-success [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] res (<! (r/<sync-ack conn entities (<? (<auth conn)))) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync-ack should succeed" ::test/passed? (not (anom/? res)) ::test/explain-data res} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}])) #_(test/<deftest test-<sync-without-auth [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3} :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"}] sync-res (<! (r/<sync conn entities {:box/cog-tokens nil})) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync ok" ::test/passed? (not (anom/? sync-res)) ::test/explain-data sync-res} {::test/desc "Data returned by sync should be correct" ::test/explain-data sync-res ::test/passed? (and (map? sync-res) (= (-> sync-res :entities first :box.canary/id) "foo1"))} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}]))
52818
(ns rx.box.sync-client-test (:require [rx.kitchen-sink :as ks] [rx.res :as res] [rx.anom :as anom :refer-macros [<defn <?]] [rx.aws :as aws] [rx.box.common :as com] [rx.box.auth :as auth] [rx.box.test-helpers :as th] [rx.box.sync-client :as r] [rx.box.persist-local :as pl] [rx.test :as test] [cljs.core.async :as async :refer [<! >! chan close! put! take! timeout] :refer-macros [go]])) (def creds (:dev-creds (ks/edn-read-string (ks/slurp-cljs "~/.rx-prod-secrets.edn")))) (<defn <auth [conn] (->> (auth/<auth-by-username-password conn "<EMAIL>" "Test1234") <?)) (def cog-schema {:box/sync-ddb-uri "https://8pg6p1yb85.execute-api.us-west-2.amazonaws.com/20191217/" :box/cog-config {:aws.cog/client-id "1em482svs0uojb8u7kmooulmmj" :aws.cog/pool-id "us-west-2_W1OuUCkYR"} :box/cog-client-creds {:aws.creds/access-id "" :aws.creds/secret-key "" :aws.creds/region "us-west-2"}}) (test/<deftest test-<sync-entities [opts] (let [conn (<? (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3} :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"} {:box.canary/id "foo2" :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"}] store-res (<? (pl/<transact conn entities)) ok-res (<? (r/<sync-idents conn [[:box.canary/id "foo1"] [:box.canary/id "foo2"]] (<? (<auth conn)))) empty-res (<! (r/<sync-entities conn [{}] (<? (<auth conn))))] [{::test/desc "Local storage of entities should succeed" ::test/passed? (not (anom/? store-res)) ::test/explain-data store-res} {::test/desc "Sync should succeed" ::test/passed? (not (anom/? ok-res)) ::test/explain-data ok-res} {::test/desc "Empty entities param should anom" ::test/passed? (anom/? empty-res) ::test/explain-data empty-res}])) #_(<defn <verify-deployment [{:keys [:rx.aws/AWS]}] (let [conn (<! (pl/<conn AWS {:box/local-db-name "verify_deployment" :box/local-data-table-name "verify_deployment_data" :box/local-refs-table-name "verify_deployment_refs" :box/ddb-data-table-name "canter-prod-pk-string" :box/attrs {:foo/id {:box.attr/ident? true}}}))] (r/<sync-entities conn {:foo/id "hello"} nil))) (test/<deftest test-<sync-imd [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] sync-res (<! (r/<sync-imd conn entities nil))] [{::test/desc "<sync ok" ::test/passed? (not (anom/? sync-res)) ::test/explain-data sync-res}])) (test/<deftest test-<sync-ack-fail [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] res (<! (r/<sync-ack conn entities {:box/cog-tokens nil})) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync-ack should fail without auth" ::test/passed? (anom/? res) ::test/explain-data res} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}])) (test/<deftest test-<sync-ack-success [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] res (<! (r/<sync-ack conn entities (<? (<auth conn)))) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync-ack should succeed" ::test/passed? (not (anom/? res)) ::test/explain-data res} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}])) #_(test/<deftest test-<sync-without-auth [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3} :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"}] sync-res (<! (r/<sync conn entities {:box/cog-tokens nil})) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync ok" ::test/passed? (not (anom/? sync-res)) ::test/explain-data sync-res} {::test/desc "Data returned by sync should be correct" ::test/explain-data sync-res ::test/passed? (and (map? sync-res) (= (-> sync-res :entities first :box.canary/id) "foo1"))} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}]))
true
(ns rx.box.sync-client-test (:require [rx.kitchen-sink :as ks] [rx.res :as res] [rx.anom :as anom :refer-macros [<defn <?]] [rx.aws :as aws] [rx.box.common :as com] [rx.box.auth :as auth] [rx.box.test-helpers :as th] [rx.box.sync-client :as r] [rx.box.persist-local :as pl] [rx.test :as test] [cljs.core.async :as async :refer [<! >! chan close! put! take! timeout] :refer-macros [go]])) (def creds (:dev-creds (ks/edn-read-string (ks/slurp-cljs "~/.rx-prod-secrets.edn")))) (<defn <auth [conn] (->> (auth/<auth-by-username-password conn "PI:EMAIL:<EMAIL>END_PI" "Test1234") <?)) (def cog-schema {:box/sync-ddb-uri "https://8pg6p1yb85.execute-api.us-west-2.amazonaws.com/20191217/" :box/cog-config {:aws.cog/client-id "1em482svs0uojb8u7kmooulmmj" :aws.cog/pool-id "us-west-2_W1OuUCkYR"} :box/cog-client-creds {:aws.creds/access-id "" :aws.creds/secret-key "" :aws.creds/region "us-west-2"}}) (test/<deftest test-<sync-entities [opts] (let [conn (<? (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3} :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"} {:box.canary/id "foo2" :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"}] store-res (<? (pl/<transact conn entities)) ok-res (<? (r/<sync-idents conn [[:box.canary/id "foo1"] [:box.canary/id "foo2"]] (<? (<auth conn)))) empty-res (<! (r/<sync-entities conn [{}] (<? (<auth conn))))] [{::test/desc "Local storage of entities should succeed" ::test/passed? (not (anom/? store-res)) ::test/explain-data store-res} {::test/desc "Sync should succeed" ::test/passed? (not (anom/? ok-res)) ::test/explain-data ok-res} {::test/desc "Empty entities param should anom" ::test/passed? (anom/? empty-res) ::test/explain-data empty-res}])) #_(<defn <verify-deployment [{:keys [:rx.aws/AWS]}] (let [conn (<! (pl/<conn AWS {:box/local-db-name "verify_deployment" :box/local-data-table-name "verify_deployment_data" :box/local-refs-table-name "verify_deployment_refs" :box/ddb-data-table-name "canter-prod-pk-string" :box/attrs {:foo/id {:box.attr/ident? true}}}))] (r/<sync-entities conn {:foo/id "hello"} nil))) (test/<deftest test-<sync-imd [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] sync-res (<! (r/<sync-imd conn entities nil))] [{::test/desc "<sync ok" ::test/passed? (not (anom/? sync-res)) ::test/explain-data sync-res}])) (test/<deftest test-<sync-ack-fail [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] res (<! (r/<sync-ack conn entities {:box/cog-tokens nil})) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync-ack should fail without auth" ::test/passed? (anom/? res) ::test/explain-data res} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}])) (test/<deftest test-<sync-ack-success [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3}}] res (<! (r/<sync-ack conn entities (<? (<auth conn)))) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync-ack should succeed" ::test/passed? (not (anom/? res)) ::test/explain-data res} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}])) #_(test/<deftest test-<sync-without-auth [opts] (let [conn (<! (th/<test-conn opts cog-schema)) entities [{:box.canary/id "foo1" :box.example/vector [{:foo/bar "baz"}] :box.example/set #{1 2 3} :box.sync/owner-id "357b0101-eae5-481d-9217-35403ec5fb6c"}] sync-res (<! (r/<sync conn entities {:box/cog-tokens nil})) pull-res (<! (pl/<pull conn [:box.canary/id "foo1"]))] [{::test/desc "<sync ok" ::test/passed? (not (anom/? sync-res)) ::test/explain-data sync-res} {::test/desc "Data returned by sync should be correct" ::test/explain-data sync-res ::test/passed? (and (map? sync-res) (= (-> sync-res :entities first :box.canary/id) "foo1"))} {::test/desc "Data should be in local db" ::test/explain-data pull-res ::test/passed? (= (-> pull-res :box.canary/id) "foo1")}]))
[ { "context": "n matching in clojure\"\n :url \"https://github.com/justiniac/matchure\"\n :license {:name \"Copyright (c) 2011 D", "end": 156, "score": 0.992375373840332, "start": 147, "tag": "USERNAME", "value": "justiniac" }, { "context": "ac/matchure\"\n :license {:name \"Copyright (c) 2011 Drew Colthorp\"\n :url \"https://github.com/justiniac/m", "end": 218, "score": 0.9998900294303894, "start": 205, "tag": "NAME", "value": "Drew Colthorp" }, { "context": "ew Colthorp\"\n :url \"https://github.com/justiniac/matchure#license\"}\n :dependencies [[org.clojure/", "end": 266, "score": 0.892895519733429, "start": 257, "tag": "USERNAME", "value": "justiniac" } ]
project.clj
fdserr/matchure
4
(defproject org.clojars.justiniac/matchure "0.13.1" :description "Idiomatic and powerful pattern matching in clojure" :url "https://github.com/justiniac/matchure" :license {:name "Copyright (c) 2011 Drew Colthorp" :url "https://github.com/justiniac/matchure#license"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/tools.macro "0.1.2"]])
64377
(defproject org.clojars.justiniac/matchure "0.13.1" :description "Idiomatic and powerful pattern matching in clojure" :url "https://github.com/justiniac/matchure" :license {:name "Copyright (c) 2011 <NAME>" :url "https://github.com/justiniac/matchure#license"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/tools.macro "0.1.2"]])
true
(defproject org.clojars.justiniac/matchure "0.13.1" :description "Idiomatic and powerful pattern matching in clojure" :url "https://github.com/justiniac/matchure" :license {:name "Copyright (c) 2011 PI:NAME:<NAME>END_PI" :url "https://github.com/justiniac/matchure#license"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/tools.macro "0.1.2"]])
[ { "context": " managing the context stack.\"\n ;;\n ;; 2019-12-05 Klaus Harbo\n ;;\n ;; We need this because Clojupyter functio", "end": 859, "score": 0.9998895525932312, "start": 848, "tag": "NAME", "value": "Klaus Harbo" }, { "context": "for now, this is how we do it.\n ;;\n ;; 2021-8-14 Daniel Ciumberică:\n ;;\n ;; We are currently passing around the ju", "end": 2245, "score": 0.9998824000358582, "start": 2228, "tag": "NAME", "value": "Daniel Ciumberică" } ]
src/clojupyter/state.clj
nighcoder/clojupyter
2
(ns clojupyter.state (:require [clojupyter.util-actions :as u!] [io.simplect.compose :refer [p P]])) (def STATE (atom {:execute-count 1N :display-queue [] :history-session nil :zmq-context nil :halt? false :comms {} :cur-ctx () :cljsrv nil})) ;;; ------------------------------------------------------------------------------------------------------------------------ ;;; CURRENT-CONTEXT ;;; ------------------------------------------------------------------------------------------------------------------------ (defn push-context! "Pushes `ctx` to global context stack. Returns `ctx`. Note: `with-current-context` is the recommended way to managing the context stack." ;; ;; 2019-12-05 Klaus Harbo ;; ;; We need this because Clojupyter functions called by user code (in Jupyter cells) - ;; e.g. widget-creating functions - need context to generate the right side-effects. Setting a ;; value in the global state is necessary because user code is evaluated on a separate thread ;; managed by NREPL to which we have a TCP connection and thus effectively communicate with using ;; text. ;; ;; The `core.async` channels used to communicate with Jupyter cannot be encoded and sent to the ;; NREPL thread and it seems like overkill to implement a protocol enabling the two to enchange ;; the data needed for the NREPL client to perform actions on behalf of the Clojupyter functions ;; called by user code. ;; ;; It would be desirable to avoid this global state but as of now it does not seem worthwhile to ;; invest a lot in avoiding it as it seems that the interaction model between Jupyter and kernels ;; require strict serialization anyway because the client (Lab, Notebook, ...) needs `busy`/`idle` ;; signals to know when they have seen all updates. So we must finish handling one request ;; (EXECUTE-REQUEST, COMM-*, or one of the others) before we can start processing the next one ;; anyway. The notion of a 'current request' fits this model just fine. ;; ;; So, at least for now, this is how we do it. ;; ;; 2021-8-14 Daniel Ciumberică: ;; ;; We are currently passing around the jupyter channels, the terminator and the nrepl adress, ;; which all appear to be runtime constants. [ctx] (swap! STATE update :cur-ctx (p cons ctx)) ctx) (defn swap-context! [f] (swap! STATE update :cur-ctx (fn [ctx-list] (cons (f (first ctx-list)) (rest ctx-list))))) (defn pop-context! "Pops top of context stack and returns it. Throws Exception if stack is empty. Note: `with-current-context` is the recommended way to managing the context stack." [] (if-let [ctx (first (:cur-ctx @STATE))] (do (swap! STATE (P update :cur-ctx rest)) ctx) (throw (ex-info "pop-context! - empty stack" {:STATE @STATE})))) (defmacro with-current-context [[ctx] & body] `(try (push-context! ~ctx) ~@body (finally (pop-context!))))
88602
(ns clojupyter.state (:require [clojupyter.util-actions :as u!] [io.simplect.compose :refer [p P]])) (def STATE (atom {:execute-count 1N :display-queue [] :history-session nil :zmq-context nil :halt? false :comms {} :cur-ctx () :cljsrv nil})) ;;; ------------------------------------------------------------------------------------------------------------------------ ;;; CURRENT-CONTEXT ;;; ------------------------------------------------------------------------------------------------------------------------ (defn push-context! "Pushes `ctx` to global context stack. Returns `ctx`. Note: `with-current-context` is the recommended way to managing the context stack." ;; ;; 2019-12-05 <NAME> ;; ;; We need this because Clojupyter functions called by user code (in Jupyter cells) - ;; e.g. widget-creating functions - need context to generate the right side-effects. Setting a ;; value in the global state is necessary because user code is evaluated on a separate thread ;; managed by NREPL to which we have a TCP connection and thus effectively communicate with using ;; text. ;; ;; The `core.async` channels used to communicate with Jupyter cannot be encoded and sent to the ;; NREPL thread and it seems like overkill to implement a protocol enabling the two to enchange ;; the data needed for the NREPL client to perform actions on behalf of the Clojupyter functions ;; called by user code. ;; ;; It would be desirable to avoid this global state but as of now it does not seem worthwhile to ;; invest a lot in avoiding it as it seems that the interaction model between Jupyter and kernels ;; require strict serialization anyway because the client (Lab, Notebook, ...) needs `busy`/`idle` ;; signals to know when they have seen all updates. So we must finish handling one request ;; (EXECUTE-REQUEST, COMM-*, or one of the others) before we can start processing the next one ;; anyway. The notion of a 'current request' fits this model just fine. ;; ;; So, at least for now, this is how we do it. ;; ;; 2021-8-14 <NAME>: ;; ;; We are currently passing around the jupyter channels, the terminator and the nrepl adress, ;; which all appear to be runtime constants. [ctx] (swap! STATE update :cur-ctx (p cons ctx)) ctx) (defn swap-context! [f] (swap! STATE update :cur-ctx (fn [ctx-list] (cons (f (first ctx-list)) (rest ctx-list))))) (defn pop-context! "Pops top of context stack and returns it. Throws Exception if stack is empty. Note: `with-current-context` is the recommended way to managing the context stack." [] (if-let [ctx (first (:cur-ctx @STATE))] (do (swap! STATE (P update :cur-ctx rest)) ctx) (throw (ex-info "pop-context! - empty stack" {:STATE @STATE})))) (defmacro with-current-context [[ctx] & body] `(try (push-context! ~ctx) ~@body (finally (pop-context!))))
true
(ns clojupyter.state (:require [clojupyter.util-actions :as u!] [io.simplect.compose :refer [p P]])) (def STATE (atom {:execute-count 1N :display-queue [] :history-session nil :zmq-context nil :halt? false :comms {} :cur-ctx () :cljsrv nil})) ;;; ------------------------------------------------------------------------------------------------------------------------ ;;; CURRENT-CONTEXT ;;; ------------------------------------------------------------------------------------------------------------------------ (defn push-context! "Pushes `ctx` to global context stack. Returns `ctx`. Note: `with-current-context` is the recommended way to managing the context stack." ;; ;; 2019-12-05 PI:NAME:<NAME>END_PI ;; ;; We need this because Clojupyter functions called by user code (in Jupyter cells) - ;; e.g. widget-creating functions - need context to generate the right side-effects. Setting a ;; value in the global state is necessary because user code is evaluated on a separate thread ;; managed by NREPL to which we have a TCP connection and thus effectively communicate with using ;; text. ;; ;; The `core.async` channels used to communicate with Jupyter cannot be encoded and sent to the ;; NREPL thread and it seems like overkill to implement a protocol enabling the two to enchange ;; the data needed for the NREPL client to perform actions on behalf of the Clojupyter functions ;; called by user code. ;; ;; It would be desirable to avoid this global state but as of now it does not seem worthwhile to ;; invest a lot in avoiding it as it seems that the interaction model between Jupyter and kernels ;; require strict serialization anyway because the client (Lab, Notebook, ...) needs `busy`/`idle` ;; signals to know when they have seen all updates. So we must finish handling one request ;; (EXECUTE-REQUEST, COMM-*, or one of the others) before we can start processing the next one ;; anyway. The notion of a 'current request' fits this model just fine. ;; ;; So, at least for now, this is how we do it. ;; ;; 2021-8-14 PI:NAME:<NAME>END_PI: ;; ;; We are currently passing around the jupyter channels, the terminator and the nrepl adress, ;; which all appear to be runtime constants. [ctx] (swap! STATE update :cur-ctx (p cons ctx)) ctx) (defn swap-context! [f] (swap! STATE update :cur-ctx (fn [ctx-list] (cons (f (first ctx-list)) (rest ctx-list))))) (defn pop-context! "Pops top of context stack and returns it. Throws Exception if stack is empty. Note: `with-current-context` is the recommended way to managing the context stack." [] (if-let [ctx (first (:cur-ctx @STATE))] (do (swap! STATE (P update :cur-ctx rest)) ctx) (throw (ex-info "pop-context! - empty stack" {:STATE @STATE})))) (defmacro with-current-context [[ctx] & body] `(try (push-context! ~ctx) ~@body (finally (pop-context!))))
[ { "context": "noisy [] (swap! noisy (fn [n] (not n))))\n;;From Stuart Sierra's blog post, for catching otherwise \"slien", "end": 1024, "score": 0.6115736961364746, "start": 1020, "tag": "NAME", "value": "uart" }, { "context": "] (swap! noisy (fn [n] (not n))))\n;;From Stuart Sierra's blog post, for catching otherwise \"slient\" exce", "end": 1031, "score": 0.5049724578857422, "start": 1027, "tag": "NAME", "value": "erra" } ]
src/nightclub/core.clj
joinr/nightclub
6
(ns nightclub.core (:require [nightcode.customizations :as custom] [nightcode.editors :as editors] [nightcode.projects :as projects] [nightcode.utils :as utils] [nightcode.sandbox :as sandbox] [nightcode.repl :as repl] [nightcode.shortcuts :as shortcuts] [nightcode.ui :as ui] [nightcode.window :as window] [nightclub.patches] ;;temporary patches to NC [seesaw.core :as s] [cemerick.pomegranate :refer [add-dependencies]] ) (:gen-class)) ;;initial expression to eval in embedded repl (def init (atom nil)) ;;A really dumb ns for defining an event system for decoupled components ;;to communicate through (like editor -> repl interactions and the like). ;;This is not meant to be a high-throughput system; we basically ;;have an observable atom, upon which we can subscribe to events. (def noisy (atom true)) (defn toggle-noisy [] (swap! noisy (fn [n] (not n)))) ;;From Stuart Sierra's blog post, for catching otherwise "slient" exceptions ;;Since we're using multithreading and the like, and we don't want ;;exceptions to get silently swallowed (let [out *out*] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (when @noisy (binding [*out* out] (println ["Uncaught Exception on" (.getName thread) ex]))))))) ;;creates a pane with a project pane, a file-based editor tree and a ;;repl. (defn create-window-content "Returns the entire window with all panes." [args] (let [console (editors/create-console "*REPL*") one-touch! #(doto % (.setOneTouchExpandable true))] (one-touch! (s/left-right-split ;(one-touch! (projects/create-pane console) ; #_(s/top-bottom-split (projects/create-pane console) ; (repl/create-pane console) ; :divider-location 0.8 ; :resize-weight 0.5)) (one-touch! (if (= (:panel args) "horizontal") (s/left-right-split (editors/create-pane) (repl/create-pane console :interrupt (atom nil)) ;(builders/create-pane) :divider-location 0.5 :resize-weight 0.5) (s/top-bottom-split (editors/create-pane) (repl/create-pane console :interrupt (atom nil)) ;(builders/create-pane) :divider-location 0.8 :resize-weight 0.5))) :divider-location 0.32 :resize-weight 0)))) ;;note: we're not cleaning up well here, but we're also no longer ;;shutting down by default. ;;note: we now allow caller to pass in window-args... (defn create-window "Creates the main window." [& {:keys [window-args cli-args]}] (let [_ (window/set-shutdown! (= (:on-close window-args) :exit)) window-args (merge {:title (str "Nightclub Embedded REPL " #_(or (some-> "nightcode.core" utils/get-project (nth 2)) "beta")) :content (create-window-content cli-args) :width 1242 :height 768 :icon "images/logo_launcher.png" :on-close :dispose} window-args)] (doto (apply s/frame (flatten (seq window-args))) ; set various window properties window/enable-full-screen! window/add-listener!))) (defn main-window "Launches the main window." [& {:keys [window-args cli-args]}] (let [parsed-args (custom/parse-args cli-args) _ (window/set-shutdown! false) init-eval (when @init (let [res @init _ (reset! init nil)] res)) ] (window/set-icon! "images/logo_launcher.png") (window/set-theme! parsed-args) (sandbox/create-profiles-clj!) (sandbox/read-file-permissions!) (s/invoke-later ; listen for keys while modifier is down (shortcuts/listen-for-shortcuts! (fn [key-code] (case key-code ; enter 10 (projects/toggle-project-tree-selection!) ; page up 33 (editors/move-tab-selection! -1) ; page down 34 (editors/move-tab-selection! 1) ; up 38 (projects/move-project-tree-selection! -1) ; down 40 (projects/move-project-tree-selection! 1) ; Q 81 (window/confirm-exit-app!) ; W 87 (editors/close-selected-editor!) ; else false))) ; create and show the frame (s/show! (reset! ui/root (create-window :window-args window-args :cli-args parsed-args))) ; initialize the project pane (ui/update-project-tree!) ;;necessary hack to get linenumbers correct (reset! editors/font-size @editors/font-size) (when init-eval (repl/send-repl! (str init-eval))) ))) (defn ^java.io.Closeable string-push-back-reader "Creates a PushbackReader from a given string" [^String s] (java.io.PushbackReader. (java.io.StringReader. s))) (defn string->forms [txt] (let [rdr (string-push-back-reader txt)] (loop [acc []] (let [res (clojure.edn/read {:eof :end-of-file} rdr )] (if (identical? res :end-of-file) acc (recur (conj acc res))))))) (defn selected-path [] @nightcode.ui/tree-selection) (defn editor-selection [] (some->> (get @editors/editors (selected-path)) (:text-area) (.getSelectedText))) (defn editor-text [] (some->> (get @editors/editors (selected-path)) (:text-area) (.getText))) (defn editor-pane [] (some->> (get @editors/editors (selected-path)) (:view) (.getLayout) (#(.getLayoutComponent % "Center")))) (defn stringify [frm] (cond (string? frm) (str \" frm \") (char? frm) (str "\\" frm) :else (str frm))) (defn eval-selection! [] (when-let [selected (editor-selection)] (do (repl/println-repl! "") (->> (string->forms selected) (map stringify) (clojure.string/join \space) (repl/send-repl!))))) (defn eval-selected-file [] (when-let [txt (editor-text)] (repl/send-repl! txt))) (defn load-selected-file! [] (when-let [p (selected-path)] (repl/println-repl! (str [:loading-file p])) (repl/echo-repl! `(load-file ~p)))) ;;hook up the plumbing... (defn register-handlers! [] (editors/set-handler :eval-selection (fn [_] (future (eval-selection!)))) (editors/set-handler :load-in-repl (fn [_] (future (load-selected-file!)))) ) (defn resize-plaf-font [nm size] (let [fnt (javax.swing.UIManager/get nm) size (float size) newfont (.deriveFont fnt (float size))] (javax.swing.UIManager/put nm (javax.swing.plaf.FontUIResource. newfont)))) (defn update-look [] (s/invoke-now (fn [] (javax.swing.SwingUtilities/updateComponentTreeUI @ui/root)))) ;;in case we're not in a lein project, i.e. an embedded repl... (def default-repositories {"central" {:url "https://repo1.maven.org/maven2/", :snapshots false}, "clojars" {:url "https://repo.clojars.org/"}}) (defn add-dependencies! "Given a vector of clojure dependency vectors - or a single dependency vector - dynamically resolves the dependencies and adds them to the class path using alembic.still/distill. Tries to determine if the jvm session was launch local to a project, if not will use default clojure repositories by default. usage: (add-dependencies! '[incanter \"1.5.6\"]) (add-dependencies! '[[incanter \"1.5.6\"][seesaw \"1.4.5\"]])" [deps & {:keys [repositories verbose proxy] :or {verbose true} :as options}] (let [repositories (or repositories (when-not (.exists (clojure.java.io/file "project.clj")) default-repositories)) opts (assoc options :repositories repositories)] (add-dependencies :coordinates deps :repositories default-repositories))) (defn attach! "Creates a nightclub window, with project, repl, and file editor(s). Caller may supply an initial form for evaluation via :init-eval, and behavior for closing." [& {:keys [init-eval on-close window-args cli-args] :or {on-close :dispose cli-args ""}}] (let [_ (case on-close :exit (window/set-shutdown! true) (window/set-shutdown! false)) _ (reset! init (or init-eval (str "(ns " *ns* ")")))] (do (main-window :window-args window-args :cli-args cli-args) (register-handlers!) )))
11501
(ns nightclub.core (:require [nightcode.customizations :as custom] [nightcode.editors :as editors] [nightcode.projects :as projects] [nightcode.utils :as utils] [nightcode.sandbox :as sandbox] [nightcode.repl :as repl] [nightcode.shortcuts :as shortcuts] [nightcode.ui :as ui] [nightcode.window :as window] [nightclub.patches] ;;temporary patches to NC [seesaw.core :as s] [cemerick.pomegranate :refer [add-dependencies]] ) (:gen-class)) ;;initial expression to eval in embedded repl (def init (atom nil)) ;;A really dumb ns for defining an event system for decoupled components ;;to communicate through (like editor -> repl interactions and the like). ;;This is not meant to be a high-throughput system; we basically ;;have an observable atom, upon which we can subscribe to events. (def noisy (atom true)) (defn toggle-noisy [] (swap! noisy (fn [n] (not n)))) ;;From St<NAME> Si<NAME>'s blog post, for catching otherwise "slient" exceptions ;;Since we're using multithreading and the like, and we don't want ;;exceptions to get silently swallowed (let [out *out*] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (when @noisy (binding [*out* out] (println ["Uncaught Exception on" (.getName thread) ex]))))))) ;;creates a pane with a project pane, a file-based editor tree and a ;;repl. (defn create-window-content "Returns the entire window with all panes." [args] (let [console (editors/create-console "*REPL*") one-touch! #(doto % (.setOneTouchExpandable true))] (one-touch! (s/left-right-split ;(one-touch! (projects/create-pane console) ; #_(s/top-bottom-split (projects/create-pane console) ; (repl/create-pane console) ; :divider-location 0.8 ; :resize-weight 0.5)) (one-touch! (if (= (:panel args) "horizontal") (s/left-right-split (editors/create-pane) (repl/create-pane console :interrupt (atom nil)) ;(builders/create-pane) :divider-location 0.5 :resize-weight 0.5) (s/top-bottom-split (editors/create-pane) (repl/create-pane console :interrupt (atom nil)) ;(builders/create-pane) :divider-location 0.8 :resize-weight 0.5))) :divider-location 0.32 :resize-weight 0)))) ;;note: we're not cleaning up well here, but we're also no longer ;;shutting down by default. ;;note: we now allow caller to pass in window-args... (defn create-window "Creates the main window." [& {:keys [window-args cli-args]}] (let [_ (window/set-shutdown! (= (:on-close window-args) :exit)) window-args (merge {:title (str "Nightclub Embedded REPL " #_(or (some-> "nightcode.core" utils/get-project (nth 2)) "beta")) :content (create-window-content cli-args) :width 1242 :height 768 :icon "images/logo_launcher.png" :on-close :dispose} window-args)] (doto (apply s/frame (flatten (seq window-args))) ; set various window properties window/enable-full-screen! window/add-listener!))) (defn main-window "Launches the main window." [& {:keys [window-args cli-args]}] (let [parsed-args (custom/parse-args cli-args) _ (window/set-shutdown! false) init-eval (when @init (let [res @init _ (reset! init nil)] res)) ] (window/set-icon! "images/logo_launcher.png") (window/set-theme! parsed-args) (sandbox/create-profiles-clj!) (sandbox/read-file-permissions!) (s/invoke-later ; listen for keys while modifier is down (shortcuts/listen-for-shortcuts! (fn [key-code] (case key-code ; enter 10 (projects/toggle-project-tree-selection!) ; page up 33 (editors/move-tab-selection! -1) ; page down 34 (editors/move-tab-selection! 1) ; up 38 (projects/move-project-tree-selection! -1) ; down 40 (projects/move-project-tree-selection! 1) ; Q 81 (window/confirm-exit-app!) ; W 87 (editors/close-selected-editor!) ; else false))) ; create and show the frame (s/show! (reset! ui/root (create-window :window-args window-args :cli-args parsed-args))) ; initialize the project pane (ui/update-project-tree!) ;;necessary hack to get linenumbers correct (reset! editors/font-size @editors/font-size) (when init-eval (repl/send-repl! (str init-eval))) ))) (defn ^java.io.Closeable string-push-back-reader "Creates a PushbackReader from a given string" [^String s] (java.io.PushbackReader. (java.io.StringReader. s))) (defn string->forms [txt] (let [rdr (string-push-back-reader txt)] (loop [acc []] (let [res (clojure.edn/read {:eof :end-of-file} rdr )] (if (identical? res :end-of-file) acc (recur (conj acc res))))))) (defn selected-path [] @nightcode.ui/tree-selection) (defn editor-selection [] (some->> (get @editors/editors (selected-path)) (:text-area) (.getSelectedText))) (defn editor-text [] (some->> (get @editors/editors (selected-path)) (:text-area) (.getText))) (defn editor-pane [] (some->> (get @editors/editors (selected-path)) (:view) (.getLayout) (#(.getLayoutComponent % "Center")))) (defn stringify [frm] (cond (string? frm) (str \" frm \") (char? frm) (str "\\" frm) :else (str frm))) (defn eval-selection! [] (when-let [selected (editor-selection)] (do (repl/println-repl! "") (->> (string->forms selected) (map stringify) (clojure.string/join \space) (repl/send-repl!))))) (defn eval-selected-file [] (when-let [txt (editor-text)] (repl/send-repl! txt))) (defn load-selected-file! [] (when-let [p (selected-path)] (repl/println-repl! (str [:loading-file p])) (repl/echo-repl! `(load-file ~p)))) ;;hook up the plumbing... (defn register-handlers! [] (editors/set-handler :eval-selection (fn [_] (future (eval-selection!)))) (editors/set-handler :load-in-repl (fn [_] (future (load-selected-file!)))) ) (defn resize-plaf-font [nm size] (let [fnt (javax.swing.UIManager/get nm) size (float size) newfont (.deriveFont fnt (float size))] (javax.swing.UIManager/put nm (javax.swing.plaf.FontUIResource. newfont)))) (defn update-look [] (s/invoke-now (fn [] (javax.swing.SwingUtilities/updateComponentTreeUI @ui/root)))) ;;in case we're not in a lein project, i.e. an embedded repl... (def default-repositories {"central" {:url "https://repo1.maven.org/maven2/", :snapshots false}, "clojars" {:url "https://repo.clojars.org/"}}) (defn add-dependencies! "Given a vector of clojure dependency vectors - or a single dependency vector - dynamically resolves the dependencies and adds them to the class path using alembic.still/distill. Tries to determine if the jvm session was launch local to a project, if not will use default clojure repositories by default. usage: (add-dependencies! '[incanter \"1.5.6\"]) (add-dependencies! '[[incanter \"1.5.6\"][seesaw \"1.4.5\"]])" [deps & {:keys [repositories verbose proxy] :or {verbose true} :as options}] (let [repositories (or repositories (when-not (.exists (clojure.java.io/file "project.clj")) default-repositories)) opts (assoc options :repositories repositories)] (add-dependencies :coordinates deps :repositories default-repositories))) (defn attach! "Creates a nightclub window, with project, repl, and file editor(s). Caller may supply an initial form for evaluation via :init-eval, and behavior for closing." [& {:keys [init-eval on-close window-args cli-args] :or {on-close :dispose cli-args ""}}] (let [_ (case on-close :exit (window/set-shutdown! true) (window/set-shutdown! false)) _ (reset! init (or init-eval (str "(ns " *ns* ")")))] (do (main-window :window-args window-args :cli-args cli-args) (register-handlers!) )))
true
(ns nightclub.core (:require [nightcode.customizations :as custom] [nightcode.editors :as editors] [nightcode.projects :as projects] [nightcode.utils :as utils] [nightcode.sandbox :as sandbox] [nightcode.repl :as repl] [nightcode.shortcuts :as shortcuts] [nightcode.ui :as ui] [nightcode.window :as window] [nightclub.patches] ;;temporary patches to NC [seesaw.core :as s] [cemerick.pomegranate :refer [add-dependencies]] ) (:gen-class)) ;;initial expression to eval in embedded repl (def init (atom nil)) ;;A really dumb ns for defining an event system for decoupled components ;;to communicate through (like editor -> repl interactions and the like). ;;This is not meant to be a high-throughput system; we basically ;;have an observable atom, upon which we can subscribe to events. (def noisy (atom true)) (defn toggle-noisy [] (swap! noisy (fn [n] (not n)))) ;;From StPI:NAME:<NAME>END_PI SiPI:NAME:<NAME>END_PI's blog post, for catching otherwise "slient" exceptions ;;Since we're using multithreading and the like, and we don't want ;;exceptions to get silently swallowed (let [out *out*] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (when @noisy (binding [*out* out] (println ["Uncaught Exception on" (.getName thread) ex]))))))) ;;creates a pane with a project pane, a file-based editor tree and a ;;repl. (defn create-window-content "Returns the entire window with all panes." [args] (let [console (editors/create-console "*REPL*") one-touch! #(doto % (.setOneTouchExpandable true))] (one-touch! (s/left-right-split ;(one-touch! (projects/create-pane console) ; #_(s/top-bottom-split (projects/create-pane console) ; (repl/create-pane console) ; :divider-location 0.8 ; :resize-weight 0.5)) (one-touch! (if (= (:panel args) "horizontal") (s/left-right-split (editors/create-pane) (repl/create-pane console :interrupt (atom nil)) ;(builders/create-pane) :divider-location 0.5 :resize-weight 0.5) (s/top-bottom-split (editors/create-pane) (repl/create-pane console :interrupt (atom nil)) ;(builders/create-pane) :divider-location 0.8 :resize-weight 0.5))) :divider-location 0.32 :resize-weight 0)))) ;;note: we're not cleaning up well here, but we're also no longer ;;shutting down by default. ;;note: we now allow caller to pass in window-args... (defn create-window "Creates the main window." [& {:keys [window-args cli-args]}] (let [_ (window/set-shutdown! (= (:on-close window-args) :exit)) window-args (merge {:title (str "Nightclub Embedded REPL " #_(or (some-> "nightcode.core" utils/get-project (nth 2)) "beta")) :content (create-window-content cli-args) :width 1242 :height 768 :icon "images/logo_launcher.png" :on-close :dispose} window-args)] (doto (apply s/frame (flatten (seq window-args))) ; set various window properties window/enable-full-screen! window/add-listener!))) (defn main-window "Launches the main window." [& {:keys [window-args cli-args]}] (let [parsed-args (custom/parse-args cli-args) _ (window/set-shutdown! false) init-eval (when @init (let [res @init _ (reset! init nil)] res)) ] (window/set-icon! "images/logo_launcher.png") (window/set-theme! parsed-args) (sandbox/create-profiles-clj!) (sandbox/read-file-permissions!) (s/invoke-later ; listen for keys while modifier is down (shortcuts/listen-for-shortcuts! (fn [key-code] (case key-code ; enter 10 (projects/toggle-project-tree-selection!) ; page up 33 (editors/move-tab-selection! -1) ; page down 34 (editors/move-tab-selection! 1) ; up 38 (projects/move-project-tree-selection! -1) ; down 40 (projects/move-project-tree-selection! 1) ; Q 81 (window/confirm-exit-app!) ; W 87 (editors/close-selected-editor!) ; else false))) ; create and show the frame (s/show! (reset! ui/root (create-window :window-args window-args :cli-args parsed-args))) ; initialize the project pane (ui/update-project-tree!) ;;necessary hack to get linenumbers correct (reset! editors/font-size @editors/font-size) (when init-eval (repl/send-repl! (str init-eval))) ))) (defn ^java.io.Closeable string-push-back-reader "Creates a PushbackReader from a given string" [^String s] (java.io.PushbackReader. (java.io.StringReader. s))) (defn string->forms [txt] (let [rdr (string-push-back-reader txt)] (loop [acc []] (let [res (clojure.edn/read {:eof :end-of-file} rdr )] (if (identical? res :end-of-file) acc (recur (conj acc res))))))) (defn selected-path [] @nightcode.ui/tree-selection) (defn editor-selection [] (some->> (get @editors/editors (selected-path)) (:text-area) (.getSelectedText))) (defn editor-text [] (some->> (get @editors/editors (selected-path)) (:text-area) (.getText))) (defn editor-pane [] (some->> (get @editors/editors (selected-path)) (:view) (.getLayout) (#(.getLayoutComponent % "Center")))) (defn stringify [frm] (cond (string? frm) (str \" frm \") (char? frm) (str "\\" frm) :else (str frm))) (defn eval-selection! [] (when-let [selected (editor-selection)] (do (repl/println-repl! "") (->> (string->forms selected) (map stringify) (clojure.string/join \space) (repl/send-repl!))))) (defn eval-selected-file [] (when-let [txt (editor-text)] (repl/send-repl! txt))) (defn load-selected-file! [] (when-let [p (selected-path)] (repl/println-repl! (str [:loading-file p])) (repl/echo-repl! `(load-file ~p)))) ;;hook up the plumbing... (defn register-handlers! [] (editors/set-handler :eval-selection (fn [_] (future (eval-selection!)))) (editors/set-handler :load-in-repl (fn [_] (future (load-selected-file!)))) ) (defn resize-plaf-font [nm size] (let [fnt (javax.swing.UIManager/get nm) size (float size) newfont (.deriveFont fnt (float size))] (javax.swing.UIManager/put nm (javax.swing.plaf.FontUIResource. newfont)))) (defn update-look [] (s/invoke-now (fn [] (javax.swing.SwingUtilities/updateComponentTreeUI @ui/root)))) ;;in case we're not in a lein project, i.e. an embedded repl... (def default-repositories {"central" {:url "https://repo1.maven.org/maven2/", :snapshots false}, "clojars" {:url "https://repo.clojars.org/"}}) (defn add-dependencies! "Given a vector of clojure dependency vectors - or a single dependency vector - dynamically resolves the dependencies and adds them to the class path using alembic.still/distill. Tries to determine if the jvm session was launch local to a project, if not will use default clojure repositories by default. usage: (add-dependencies! '[incanter \"1.5.6\"]) (add-dependencies! '[[incanter \"1.5.6\"][seesaw \"1.4.5\"]])" [deps & {:keys [repositories verbose proxy] :or {verbose true} :as options}] (let [repositories (or repositories (when-not (.exists (clojure.java.io/file "project.clj")) default-repositories)) opts (assoc options :repositories repositories)] (add-dependencies :coordinates deps :repositories default-repositories))) (defn attach! "Creates a nightclub window, with project, repl, and file editor(s). Caller may supply an initial form for evaluation via :init-eval, and behavior for closing." [& {:keys [init-eval on-close window-args cli-args] :or {on-close :dispose cli-args ""}}] (let [_ (case on-close :exit (window/set-shutdown! true) (window/set-shutdown! false)) _ (reset! init (or init-eval (str "(ns " *ns* ")")))] (do (main-window :window-args window-args :cli-args cli-args) (register-handlers!) )))
[ { "context": "file is part of gorilla-repl. Copyright (C) 2014-, Jony Hudson.\n;;;;\n;;;; gorilla-repl is licenced to you under ", "end": 72, "score": 0.9997404217720032, "start": 61, "tag": "NAME", "value": "Jony Hudson" }, { "context": "n the notebook style.\"\n :url \"https://github.com/benfb/gorilla-repl\"\n :license {:name \"MIT\"}\n :depende", "end": 330, "score": 0.9988561868667603, "start": 325, "tag": "USERNAME", "value": "benfb" }, { "context": "ies {\"releases\" {:url \"https://repo.clojars.org\" :username :env :password :env :sign-releases false}})\n", "end": 1894, "score": 0.8852436542510986, "start": 1886, "tag": "USERNAME", "value": "username" } ]
project.clj
benfb/gorilla-repl
39
;;;; This file is part of gorilla-repl. Copyright (C) 2014-, Jony Hudson. ;;;; ;;;; gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details. (defproject org.clojars.benfb/gorilla-repl "0.7.0" :description "A rich REPL for Clojure in the notebook style." :url "https://github.com/benfb/gorilla-repl" :license {:name "MIT"} :dependencies ^:replace [[org.clojure/clojure "1.10.1"] [http-kit "2.4.0-alpha6" :exclusions [ring/ring-core]] [ring/ring-json "0.5.0" :exclusions [org.clojure/clojure]] [cheshire "5.9.0"] [compojure "1.6.1" :exclusions [ring/ring-core ring/ring-json]] [gorilla-renderable "2.0.0"] [gorilla-plot "0.1.4" :exclusions [org.clojure/clojure]] [grimradical/clj-semver "0.2.0" :exclusions [org.clojure/clojure]] [cider/cider-nrepl "0.25.2" :exclusions [org.clojure/clojure]] [nrepl/nrepl "0.7.0"]] :main ^:skip-aot gorilla-repl.core :target-path "target/%s" :jvm-opts ~(let [version (System/getProperty "java.version") [major _ _] (clojure.string/split version #"\.")] (if (>= (java.lang.Integer/parseInt major) 9) ["--add-modules" "java.xml.bind"] [])) :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "v" "--no-sign"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :deploy-repositories {"releases" {:url "https://repo.clojars.org" :username :env :password :env :sign-releases false}})
5305
;;;; This file is part of gorilla-repl. Copyright (C) 2014-, <NAME>. ;;;; ;;;; gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details. (defproject org.clojars.benfb/gorilla-repl "0.7.0" :description "A rich REPL for Clojure in the notebook style." :url "https://github.com/benfb/gorilla-repl" :license {:name "MIT"} :dependencies ^:replace [[org.clojure/clojure "1.10.1"] [http-kit "2.4.0-alpha6" :exclusions [ring/ring-core]] [ring/ring-json "0.5.0" :exclusions [org.clojure/clojure]] [cheshire "5.9.0"] [compojure "1.6.1" :exclusions [ring/ring-core ring/ring-json]] [gorilla-renderable "2.0.0"] [gorilla-plot "0.1.4" :exclusions [org.clojure/clojure]] [grimradical/clj-semver "0.2.0" :exclusions [org.clojure/clojure]] [cider/cider-nrepl "0.25.2" :exclusions [org.clojure/clojure]] [nrepl/nrepl "0.7.0"]] :main ^:skip-aot gorilla-repl.core :target-path "target/%s" :jvm-opts ~(let [version (System/getProperty "java.version") [major _ _] (clojure.string/split version #"\.")] (if (>= (java.lang.Integer/parseInt major) 9) ["--add-modules" "java.xml.bind"] [])) :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "v" "--no-sign"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :deploy-repositories {"releases" {:url "https://repo.clojars.org" :username :env :password :env :sign-releases false}})
true
;;;; This file is part of gorilla-repl. Copyright (C) 2014-, PI:NAME:<NAME>END_PI. ;;;; ;;;; gorilla-repl is licenced to you under the MIT licence. See the file LICENCE.txt for full details. (defproject org.clojars.benfb/gorilla-repl "0.7.0" :description "A rich REPL for Clojure in the notebook style." :url "https://github.com/benfb/gorilla-repl" :license {:name "MIT"} :dependencies ^:replace [[org.clojure/clojure "1.10.1"] [http-kit "2.4.0-alpha6" :exclusions [ring/ring-core]] [ring/ring-json "0.5.0" :exclusions [org.clojure/clojure]] [cheshire "5.9.0"] [compojure "1.6.1" :exclusions [ring/ring-core ring/ring-json]] [gorilla-renderable "2.0.0"] [gorilla-plot "0.1.4" :exclusions [org.clojure/clojure]] [grimradical/clj-semver "0.2.0" :exclusions [org.clojure/clojure]] [cider/cider-nrepl "0.25.2" :exclusions [org.clojure/clojure]] [nrepl/nrepl "0.7.0"]] :main ^:skip-aot gorilla-repl.core :target-path "target/%s" :jvm-opts ~(let [version (System/getProperty "java.version") [major _ _] (clojure.string/split version #"\.")] (if (>= (java.lang.Integer/parseInt major) 9) ["--add-modules" "java.xml.bind"] [])) :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "v" "--no-sign"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :deploy-repositories {"releases" {:url "https://repo.clojars.org" :username :env :password :env :sign-releases false}})
[ { "context": " :dbpedia.resource/Pablo-Picasso ; id\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"", "end": 544, "score": 0.9996162056922913, "start": 539, "tag": "NAME", "value": "Pablo" }, { "context": "-Picasso ; id\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"}\n #inst \"1881-10-25T09", "end": 570, "score": 0.9995145797729492, "start": 563, "tag": "NAME", "value": "Picasso" }, { "context": " :dbpedia.resource/Pablo-Picasso ; id\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Sain2\"", "end": 727, "score": 0.9995157718658447, "start": 722, "tag": "NAME", "value": "Pablo" }, { "context": "-Picasso ; id\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Sain2\"}\n #inst \"1881-10-25T09", "end": 753, "score": 0.9996031522750854, "start": 746, "tag": "NAME", "value": "Picasso" }, { "context": "db/id :dbpedia.resource/Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"", "end": 1066, "score": 0.9995379447937012, "start": 1061, "tag": "NAME", "value": "Pablo" }, { "context": "Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"}\n #inst \"1973-04-08T09", "end": 1092, "score": 0.9996683597564697, "start": 1085, "tag": "NAME", "value": "Picasso" }, { "context": "db/id :dbpedia.resource/Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n ", "end": 1276, "score": 0.9995023012161255, "start": 1271, "tag": "NAME", "value": "Pablo" }, { "context": "Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n :location \"France\"}\n #", "end": 1302, "score": 0.9995080232620239, "start": 1295, "tag": "NAME", "value": "Picasso" }, { "context": "crux/db node)\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true}) ; using `:full-resul", "end": 1871, "score": 0.9995280504226685, "start": 1866, "tag": "NAME", "value": "Pablo" }, { "context": "db/id :dbpedia.resource/Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n ", "end": 2110, "score": 0.9996061325073242, "start": 2105, "tag": "NAME", "value": "Pablo" }, { "context": "Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n :location \"France\"}\n #", "end": 2136, "score": 0.9995706081390381, "start": 2129, "tag": "NAME", "value": "Picasso" }, { "context": "crux/db node)\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true})\n\n\n;; again, query th", "end": 2329, "score": 0.9995149374008179, "start": 2324, "tag": "NAME", "value": "Pablo" }, { "context": "7.966-00:00\")\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true})\n", "end": 2545, "score": 0.9995039701461792, "start": 2540, "tag": "NAME", "value": "Pablo" } ]
docs/example/repl-walkthrough/walkthrough.clj
deobald/crux
0
;; load a repl with the latest crux-core dependency, e.g. using clj: ;; $ clj -Sdeps '{:deps {juxt/crux-core {:mvn/version "RELEASE"}}}' (ns walkthrough.crux-standalone (:require [crux.api :as crux]) (:import (crux.api ICruxAPI))) ;; this in-memory configuration is the easiest way to try Crux, no Kafka needed (def node (crux/start-node {})) ;; transaction containing a `put` operation, optionally specifying a valid time (crux/submit-tx node [[:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso ; id :name "Pablo" :last-name "Picasso" :location "Spain"} #inst "1881-10-25T09:20:27.966-00:00"] [:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso ; id :name "Pablo" :last-name "Picasso" :location "Sain2"} #inst "1881-10-25T09:20:27.966-00:00"]]) ; valid time, Picasso's birth ;; transaction containing a `match` operation (crux/submit-tx node [[:crux.tx/match ; check old version :dbpedia.resource/Pablo-Picasso {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "Pablo" :last-name "Picasso" :location "Spain"} #inst "1973-04-08T09:20:27.966-00:00"] [:crux.tx/put ; put new version if it matches {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "Pablo" :last-name "Picasso" :height 1.63 :location "France"} #inst "1973-04-08T09:20:27.966-00:00"]]) ; valid time, Picasso's death ;; transaction containing a `delete` operation, historical versions remain (crux/submit-tx node [[:crux.tx/delete :dbpedia.resource/Pablo-Picasso #inst "1973-04-08T09:20:27.966-00:00"]]) ;; transaction containing an `evict` operation, historical data is destroyed (crux/submit-tx node [[:crux.tx/evict :dbpedia.resource/Pablo-Picasso]]) ;; query the node as-of now (crux/q (crux/db node) '{:find [e] :where [[e :name "Pablo"]] :full-results? true}) ; using `:full-results?` is useful for manual queries ;; `put` the new version of the document again (crux/submit-tx node [[:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "Pablo" :last-name "Picasso" :height 1.63 :location "France"} #inst "1973-04-08T09:20:27.966-00:00"]]) ;; again, query the node as-of now (crux/q (crux/db node) '{:find [e] :where [[e :name "Pablo"]] :full-results? true}) ;; again, query the node as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00" (crux/q (crux/db node #inst "1973-04-07T09:20:27.966-00:00") '{:find [e] :where [[e :name "Pablo"]] :full-results? true})
76708
;; load a repl with the latest crux-core dependency, e.g. using clj: ;; $ clj -Sdeps '{:deps {juxt/crux-core {:mvn/version "RELEASE"}}}' (ns walkthrough.crux-standalone (:require [crux.api :as crux]) (:import (crux.api ICruxAPI))) ;; this in-memory configuration is the easiest way to try Crux, no Kafka needed (def node (crux/start-node {})) ;; transaction containing a `put` operation, optionally specifying a valid time (crux/submit-tx node [[:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso ; id :name "<NAME>" :last-name "<NAME>" :location "Spain"} #inst "1881-10-25T09:20:27.966-00:00"] [:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso ; id :name "<NAME>" :last-name "<NAME>" :location "Sain2"} #inst "1881-10-25T09:20:27.966-00:00"]]) ; valid time, Picasso's birth ;; transaction containing a `match` operation (crux/submit-tx node [[:crux.tx/match ; check old version :dbpedia.resource/Pablo-Picasso {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "<NAME>" :last-name "<NAME>" :location "Spain"} #inst "1973-04-08T09:20:27.966-00:00"] [:crux.tx/put ; put new version if it matches {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "<NAME>" :last-name "<NAME>" :height 1.63 :location "France"} #inst "1973-04-08T09:20:27.966-00:00"]]) ; valid time, Picasso's death ;; transaction containing a `delete` operation, historical versions remain (crux/submit-tx node [[:crux.tx/delete :dbpedia.resource/Pablo-Picasso #inst "1973-04-08T09:20:27.966-00:00"]]) ;; transaction containing an `evict` operation, historical data is destroyed (crux/submit-tx node [[:crux.tx/evict :dbpedia.resource/Pablo-Picasso]]) ;; query the node as-of now (crux/q (crux/db node) '{:find [e] :where [[e :name "<NAME>"]] :full-results? true}) ; using `:full-results?` is useful for manual queries ;; `put` the new version of the document again (crux/submit-tx node [[:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "<NAME>" :last-name "<NAME>" :height 1.63 :location "France"} #inst "1973-04-08T09:20:27.966-00:00"]]) ;; again, query the node as-of now (crux/q (crux/db node) '{:find [e] :where [[e :name "<NAME>"]] :full-results? true}) ;; again, query the node as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00" (crux/q (crux/db node #inst "1973-04-07T09:20:27.966-00:00") '{:find [e] :where [[e :name "<NAME>"]] :full-results? true})
true
;; load a repl with the latest crux-core dependency, e.g. using clj: ;; $ clj -Sdeps '{:deps {juxt/crux-core {:mvn/version "RELEASE"}}}' (ns walkthrough.crux-standalone (:require [crux.api :as crux]) (:import (crux.api ICruxAPI))) ;; this in-memory configuration is the easiest way to try Crux, no Kafka needed (def node (crux/start-node {})) ;; transaction containing a `put` operation, optionally specifying a valid time (crux/submit-tx node [[:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso ; id :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :location "Spain"} #inst "1881-10-25T09:20:27.966-00:00"] [:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso ; id :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :location "Sain2"} #inst "1881-10-25T09:20:27.966-00:00"]]) ; valid time, Picasso's birth ;; transaction containing a `match` operation (crux/submit-tx node [[:crux.tx/match ; check old version :dbpedia.resource/Pablo-Picasso {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :location "Spain"} #inst "1973-04-08T09:20:27.966-00:00"] [:crux.tx/put ; put new version if it matches {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :height 1.63 :location "France"} #inst "1973-04-08T09:20:27.966-00:00"]]) ; valid time, Picasso's death ;; transaction containing a `delete` operation, historical versions remain (crux/submit-tx node [[:crux.tx/delete :dbpedia.resource/Pablo-Picasso #inst "1973-04-08T09:20:27.966-00:00"]]) ;; transaction containing an `evict` operation, historical data is destroyed (crux/submit-tx node [[:crux.tx/evict :dbpedia.resource/Pablo-Picasso]]) ;; query the node as-of now (crux/q (crux/db node) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]] :full-results? true}) ; using `:full-results?` is useful for manual queries ;; `put` the new version of the document again (crux/submit-tx node [[:crux.tx/put {:crux.db/id :dbpedia.resource/Pablo-Picasso :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :height 1.63 :location "France"} #inst "1973-04-08T09:20:27.966-00:00"]]) ;; again, query the node as-of now (crux/q (crux/db node) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]] :full-results? true}) ;; again, query the node as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00" (crux/q (crux/db node #inst "1973-04-07T09:20:27.966-00:00") '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]] :full-results? true})
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998687505722046, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "\"Tests for clojure.core/gen-class\"\n :author \"Stuart Halloway, Daniel Solano Gómez\"}\n clojure.test-clojure.gen", "end": 540, "score": 0.9998773336410522, "start": 525, "tag": "NAME", "value": "Stuart Halloway" }, { "context": "re.core/gen-class\"\n :author \"Stuart Halloway, Daniel Solano Gómez\"}\n clojure.test-clojure.genclass\n (:use clojure", "end": 561, "score": 0.9998509287834167, "start": 542, "tag": "NAME", "value": "Daniel Solano Gómez" } ]
test/clojure/test_clojure/genclass.clj
lorettahe/clojure
1
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Tests for clojure.core/gen-class" :author "Stuart Halloway, Daniel Solano Gómez"} clojure.test-clojure.genclass (:use clojure.test clojure.test-helper) (:require clojure.test_clojure.genclass.examples) (:import [clojure.test_clojure.genclass.examples ExampleClass ExampleAnnotationClass ProtectedFinalTester ArrayDefInterface ArrayGenInterface] [java.lang.annotation ElementType Retention RetentionPolicy Target])) (deftest arg-support (let [example (ExampleClass.) o (Object.)] (is (= "foo with o, o" (.foo example o o))) (is (= "foo with o, i" (.foo example o (int 1)))) (is (thrown? java.lang.UnsupportedOperationException (.foo example o))))) (deftest name-munging (testing "mapping from Java fields to Clojure vars" (is (= #'clojure.test-clojure.genclass.examples/-foo-Object-int (get-field ExampleClass 'foo_Object_int__var))) (is (= #'clojure.test-clojure.genclass.examples/-toString (get-field ExampleClass 'toString__var))))) ;todo - fix this, it depends on the order of things out of a hash-map #_(deftest test-annotations (let [annot-class ExampleAnnotationClass foo-method (.getDeclaredMethod annot-class "foo" (into-array [String]))] (testing "Class annotations:" (is (= 2 (count (.getDeclaredAnnotations annot-class)))) (testing "@Deprecated" (let [deprecated (.getAnnotation annot-class Deprecated)] (is deprecated))) (testing "@Target([])" (let [resource (.getAnnotation annot-class Target)] (is (= 0 (count (.value resource))))))) (testing "Method annotations:" (testing "@Deprecated void foo(String):" (is (= 1 (count (.getDeclaredAnnotations foo-method)))) (is (.getAnnotation foo-method Deprecated)))) (testing "Parameter annotations:" (let [param-annots (.getParameterAnnotations foo-method)] (is (= 1 (alength param-annots))) (let [first-param-annots (aget param-annots 0)] (is (= 2 (alength first-param-annots))) (testing "void foo(@Retention(…) String)" (let [retention (aget first-param-annots 0)] (is (instance? Retention retention)) (= RetentionPolicy/SOURCE (.value retention)))) (testing "void foo(@Target(…) String)" (let [target (aget first-param-annots 1)] (is (instance? Target target)) (is (= [ElementType/TYPE ElementType/PARAMETER] (seq (.value target))))))))))) (deftest genclass-option-validation (is (fails-with-cause? IllegalArgumentException #"Not a valid method name: has-hyphen" (@#'clojure.core/validate-generate-class-options {:methods '[[fine [] void] [has-hyphen [] void]]})))) (deftest protected-final-access (let [obj (ProtectedFinalTester.)] (testing "Protected final method visibility" (is (thrown? IllegalArgumentException (.findSystemClass obj "java.lang.String")))) (testing "Allow exposition of protected final method." (is (= String (.superFindSystemClass obj "java.lang.String")))))) (deftest interface-array-type-hints (let [array-types {:ints (class (int-array 0)) :bytes (class (byte-array 0)) :shorts (class (short-array 0)) :chars (class (char-array 0)) :longs (class (long-array 0)) :floats (class (float-array 0)) :doubles (class (double-array 0)) :booleans (class (boolean-array 0)) :maps (class (into-array java.util.Map []))} array-types (assoc array-types :maps-2d (class (into-array (:maps array-types) []))) method-with-name (fn [name methods] (first (filter #(= name (.getName %)) methods))) parameter-type (fn [method] (first (.getParameterTypes method))) return-type (fn [method] (.getReturnType method))] (testing "definterface" (let [method-with-name #(method-with-name % (.getMethods ArrayDefInterface))] (testing "sugar primitive array hints" (are [name type] (= (type array-types) (parameter-type (method-with-name name))) "takesByteArray" :bytes "takesCharArray" :chars "takesShortArray" :shorts "takesIntArray" :ints "takesLongArray" :longs "takesFloatArray" :floats "takesDoubleArray" :doubles "takesBooleanArray" :booleans)) (testing "raw primitive array hints" (are [name type] (= (type array-types) (return-type (method-with-name name))) "returnsByteArray" :bytes "returnsCharArray" :chars "returnsShortArray" :shorts "returnsIntArray" :ints "returnsLongArray" :longs "returnsFloatArray" :floats "returnsDoubleArray" :doubles "returnsBooleanArray" :booleans)))) (testing "gen-interface" (let [method-with-name #(method-with-name % (.getMethods ArrayGenInterface))] (testing "sugar primitive array hints" (are [name type] (= (type array-types) (parameter-type (method-with-name name))) "takesByteArray" :bytes "takesCharArray" :chars "takesShortArray" :shorts "takesIntArray" :ints "takesLongArray" :longs "takesFloatArray" :floats "takesDoubleArray" :doubles "takesBooleanArray" :booleans)) (testing "raw primitive array hints" (are [name type] (= (type array-types) (return-type (method-with-name name))) "returnsByteArray" :bytes "returnsCharArray" :chars "returnsShortArray" :shorts "returnsIntArray" :ints "returnsLongArray" :longs "returnsFloatArray" :floats "returnsDoubleArray" :doubles "returnsBooleanArray" :booleans))))))
81302
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Tests for clojure.core/gen-class" :author "<NAME>, <NAME>"} clojure.test-clojure.genclass (:use clojure.test clojure.test-helper) (:require clojure.test_clojure.genclass.examples) (:import [clojure.test_clojure.genclass.examples ExampleClass ExampleAnnotationClass ProtectedFinalTester ArrayDefInterface ArrayGenInterface] [java.lang.annotation ElementType Retention RetentionPolicy Target])) (deftest arg-support (let [example (ExampleClass.) o (Object.)] (is (= "foo with o, o" (.foo example o o))) (is (= "foo with o, i" (.foo example o (int 1)))) (is (thrown? java.lang.UnsupportedOperationException (.foo example o))))) (deftest name-munging (testing "mapping from Java fields to Clojure vars" (is (= #'clojure.test-clojure.genclass.examples/-foo-Object-int (get-field ExampleClass 'foo_Object_int__var))) (is (= #'clojure.test-clojure.genclass.examples/-toString (get-field ExampleClass 'toString__var))))) ;todo - fix this, it depends on the order of things out of a hash-map #_(deftest test-annotations (let [annot-class ExampleAnnotationClass foo-method (.getDeclaredMethod annot-class "foo" (into-array [String]))] (testing "Class annotations:" (is (= 2 (count (.getDeclaredAnnotations annot-class)))) (testing "@Deprecated" (let [deprecated (.getAnnotation annot-class Deprecated)] (is deprecated))) (testing "@Target([])" (let [resource (.getAnnotation annot-class Target)] (is (= 0 (count (.value resource))))))) (testing "Method annotations:" (testing "@Deprecated void foo(String):" (is (= 1 (count (.getDeclaredAnnotations foo-method)))) (is (.getAnnotation foo-method Deprecated)))) (testing "Parameter annotations:" (let [param-annots (.getParameterAnnotations foo-method)] (is (= 1 (alength param-annots))) (let [first-param-annots (aget param-annots 0)] (is (= 2 (alength first-param-annots))) (testing "void foo(@Retention(…) String)" (let [retention (aget first-param-annots 0)] (is (instance? Retention retention)) (= RetentionPolicy/SOURCE (.value retention)))) (testing "void foo(@Target(…) String)" (let [target (aget first-param-annots 1)] (is (instance? Target target)) (is (= [ElementType/TYPE ElementType/PARAMETER] (seq (.value target))))))))))) (deftest genclass-option-validation (is (fails-with-cause? IllegalArgumentException #"Not a valid method name: has-hyphen" (@#'clojure.core/validate-generate-class-options {:methods '[[fine [] void] [has-hyphen [] void]]})))) (deftest protected-final-access (let [obj (ProtectedFinalTester.)] (testing "Protected final method visibility" (is (thrown? IllegalArgumentException (.findSystemClass obj "java.lang.String")))) (testing "Allow exposition of protected final method." (is (= String (.superFindSystemClass obj "java.lang.String")))))) (deftest interface-array-type-hints (let [array-types {:ints (class (int-array 0)) :bytes (class (byte-array 0)) :shorts (class (short-array 0)) :chars (class (char-array 0)) :longs (class (long-array 0)) :floats (class (float-array 0)) :doubles (class (double-array 0)) :booleans (class (boolean-array 0)) :maps (class (into-array java.util.Map []))} array-types (assoc array-types :maps-2d (class (into-array (:maps array-types) []))) method-with-name (fn [name methods] (first (filter #(= name (.getName %)) methods))) parameter-type (fn [method] (first (.getParameterTypes method))) return-type (fn [method] (.getReturnType method))] (testing "definterface" (let [method-with-name #(method-with-name % (.getMethods ArrayDefInterface))] (testing "sugar primitive array hints" (are [name type] (= (type array-types) (parameter-type (method-with-name name))) "takesByteArray" :bytes "takesCharArray" :chars "takesShortArray" :shorts "takesIntArray" :ints "takesLongArray" :longs "takesFloatArray" :floats "takesDoubleArray" :doubles "takesBooleanArray" :booleans)) (testing "raw primitive array hints" (are [name type] (= (type array-types) (return-type (method-with-name name))) "returnsByteArray" :bytes "returnsCharArray" :chars "returnsShortArray" :shorts "returnsIntArray" :ints "returnsLongArray" :longs "returnsFloatArray" :floats "returnsDoubleArray" :doubles "returnsBooleanArray" :booleans)))) (testing "gen-interface" (let [method-with-name #(method-with-name % (.getMethods ArrayGenInterface))] (testing "sugar primitive array hints" (are [name type] (= (type array-types) (parameter-type (method-with-name name))) "takesByteArray" :bytes "takesCharArray" :chars "takesShortArray" :shorts "takesIntArray" :ints "takesLongArray" :longs "takesFloatArray" :floats "takesDoubleArray" :doubles "takesBooleanArray" :booleans)) (testing "raw primitive array hints" (are [name type] (= (type array-types) (return-type (method-with-name name))) "returnsByteArray" :bytes "returnsCharArray" :chars "returnsShortArray" :shorts "returnsIntArray" :ints "returnsLongArray" :longs "returnsFloatArray" :floats "returnsDoubleArray" :doubles "returnsBooleanArray" :booleans))))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Tests for clojure.core/gen-class" :author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"} clojure.test-clojure.genclass (:use clojure.test clojure.test-helper) (:require clojure.test_clojure.genclass.examples) (:import [clojure.test_clojure.genclass.examples ExampleClass ExampleAnnotationClass ProtectedFinalTester ArrayDefInterface ArrayGenInterface] [java.lang.annotation ElementType Retention RetentionPolicy Target])) (deftest arg-support (let [example (ExampleClass.) o (Object.)] (is (= "foo with o, o" (.foo example o o))) (is (= "foo with o, i" (.foo example o (int 1)))) (is (thrown? java.lang.UnsupportedOperationException (.foo example o))))) (deftest name-munging (testing "mapping from Java fields to Clojure vars" (is (= #'clojure.test-clojure.genclass.examples/-foo-Object-int (get-field ExampleClass 'foo_Object_int__var))) (is (= #'clojure.test-clojure.genclass.examples/-toString (get-field ExampleClass 'toString__var))))) ;todo - fix this, it depends on the order of things out of a hash-map #_(deftest test-annotations (let [annot-class ExampleAnnotationClass foo-method (.getDeclaredMethod annot-class "foo" (into-array [String]))] (testing "Class annotations:" (is (= 2 (count (.getDeclaredAnnotations annot-class)))) (testing "@Deprecated" (let [deprecated (.getAnnotation annot-class Deprecated)] (is deprecated))) (testing "@Target([])" (let [resource (.getAnnotation annot-class Target)] (is (= 0 (count (.value resource))))))) (testing "Method annotations:" (testing "@Deprecated void foo(String):" (is (= 1 (count (.getDeclaredAnnotations foo-method)))) (is (.getAnnotation foo-method Deprecated)))) (testing "Parameter annotations:" (let [param-annots (.getParameterAnnotations foo-method)] (is (= 1 (alength param-annots))) (let [first-param-annots (aget param-annots 0)] (is (= 2 (alength first-param-annots))) (testing "void foo(@Retention(…) String)" (let [retention (aget first-param-annots 0)] (is (instance? Retention retention)) (= RetentionPolicy/SOURCE (.value retention)))) (testing "void foo(@Target(…) String)" (let [target (aget first-param-annots 1)] (is (instance? Target target)) (is (= [ElementType/TYPE ElementType/PARAMETER] (seq (.value target))))))))))) (deftest genclass-option-validation (is (fails-with-cause? IllegalArgumentException #"Not a valid method name: has-hyphen" (@#'clojure.core/validate-generate-class-options {:methods '[[fine [] void] [has-hyphen [] void]]})))) (deftest protected-final-access (let [obj (ProtectedFinalTester.)] (testing "Protected final method visibility" (is (thrown? IllegalArgumentException (.findSystemClass obj "java.lang.String")))) (testing "Allow exposition of protected final method." (is (= String (.superFindSystemClass obj "java.lang.String")))))) (deftest interface-array-type-hints (let [array-types {:ints (class (int-array 0)) :bytes (class (byte-array 0)) :shorts (class (short-array 0)) :chars (class (char-array 0)) :longs (class (long-array 0)) :floats (class (float-array 0)) :doubles (class (double-array 0)) :booleans (class (boolean-array 0)) :maps (class (into-array java.util.Map []))} array-types (assoc array-types :maps-2d (class (into-array (:maps array-types) []))) method-with-name (fn [name methods] (first (filter #(= name (.getName %)) methods))) parameter-type (fn [method] (first (.getParameterTypes method))) return-type (fn [method] (.getReturnType method))] (testing "definterface" (let [method-with-name #(method-with-name % (.getMethods ArrayDefInterface))] (testing "sugar primitive array hints" (are [name type] (= (type array-types) (parameter-type (method-with-name name))) "takesByteArray" :bytes "takesCharArray" :chars "takesShortArray" :shorts "takesIntArray" :ints "takesLongArray" :longs "takesFloatArray" :floats "takesDoubleArray" :doubles "takesBooleanArray" :booleans)) (testing "raw primitive array hints" (are [name type] (= (type array-types) (return-type (method-with-name name))) "returnsByteArray" :bytes "returnsCharArray" :chars "returnsShortArray" :shorts "returnsIntArray" :ints "returnsLongArray" :longs "returnsFloatArray" :floats "returnsDoubleArray" :doubles "returnsBooleanArray" :booleans)))) (testing "gen-interface" (let [method-with-name #(method-with-name % (.getMethods ArrayGenInterface))] (testing "sugar primitive array hints" (are [name type] (= (type array-types) (parameter-type (method-with-name name))) "takesByteArray" :bytes "takesCharArray" :chars "takesShortArray" :shorts "takesIntArray" :ints "takesLongArray" :longs "takesFloatArray" :floats "takesDoubleArray" :doubles "takesBooleanArray" :booleans)) (testing "raw primitive array hints" (are [name type] (= (type array-types) (return-type (method-with-name name))) "returnsByteArray" :bytes "returnsCharArray" :chars "returnsShortArray" :shorts "returnsIntArray" :ints "returnsLongArray" :longs "returnsFloatArray" :floats "returnsDoubleArray" :doubles "returnsBooleanArray" :booleans))))))
[ { "context": ";;;; 05.aug.15\n\n;;; p. 14\n\n(conj #{} \"John\")\n\n(def visitors (atom #{}))\n\n;;; (swap! referenc", "end": 42, "score": 0.9997096061706543, "start": 38, "tag": "NAME", "value": "John" }, { "context": "eference update-fn & args)\n\n(swap! visitors conj \"Steph\")\n\n@visitors\n\n;;; or\n\n(deref visitors)\n\n(defn hel", "end": 140, "score": 0.9989974498748779, "start": 135, "tag": "NAME", "value": "Steph" }, { "context": "update-fn & args)\n\n(swap! visitors conj \"Steph\")\n\n@visitors\n\n;;; or\n\n(deref visitors)\n\n(defn hello\n \"Writes ", "end": 153, "score": 0.9038297533988953, "start": 144, "tag": "USERNAME", "value": "@visitors" }, { "context": "intln (str \"Hello \" (if (some #{username} @visitors) \"again \" \"\") username))\n (swap! visitors conj u", "end": 316, "score": 0.7813471555709839, "start": 315, "tag": "USERNAME", "value": "s" } ]
book-programming-clj-2nd-ed/visitors.clj
reddress/clojuring
0
;;;; 05.aug.15 ;;; p. 14 (conj #{} "John") (def visitors (atom #{})) ;;; (swap! reference update-fn & args) (swap! visitors conj "Steph") @visitors ;;; or (deref visitors) (defn hello "Writes 'Hello name'. Saves names to visitors atom" [username] (println (str "Hello " (if (some #{username} @visitors) "again " "") username)) (swap! visitors conj username) nil)
55750
;;;; 05.aug.15 ;;; p. 14 (conj #{} "<NAME>") (def visitors (atom #{})) ;;; (swap! reference update-fn & args) (swap! visitors conj "<NAME>") @visitors ;;; or (deref visitors) (defn hello "Writes 'Hello name'. Saves names to visitors atom" [username] (println (str "Hello " (if (some #{username} @visitors) "again " "") username)) (swap! visitors conj username) nil)
true
;;;; 05.aug.15 ;;; p. 14 (conj #{} "PI:NAME:<NAME>END_PI") (def visitors (atom #{})) ;;; (swap! reference update-fn & args) (swap! visitors conj "PI:NAME:<NAME>END_PI") @visitors ;;; or (deref visitors) (defn hello "Writes 'Hello name'. Saves names to visitors atom" [username] (println (str "Hello " (if (some #{username} @visitors) "again " "") username)) (swap! visitors conj username) nil)
[ { "context": "r]))\n\n; Most codes taken from: https://github.com/redplanetlabs/specter/blob/master/README.md\n\n; ex: Increment ev", "end": 138, "score": 0.9996509552001953, "start": 125, "tag": "USERNAME", "value": "redplanetlabs" }, { "context": " · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Navigators)\n\n ", "end": 7385, "score": 0.9983057975769043, "start": 7372, "tag": "USERNAME", "value": "redplanetlabs" }, { "context": " · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Macros)\n\n; collected?\n(selec", "end": 13487, "score": 0.9848403930664062, "start": 13474, "tag": "USERNAME", "value": "redplanetlabs" }, { "context": "rm\n\n\n\n; path ex: storing paths https://github.com/redplanetlabs/specter/wiki/List-of-Macros#path\n(def p0 (path ev", "end": 13718, "score": 0.9505030512809753, "start": 13705, "tag": "USERNAME", "value": "redplanetlabs" }, { "context": " Powerful and Simple Data Structure Manipulation - Nathan Marz - VTCy_DkAJGk id=g11450\n\n ", "end": 13895, "score": 0.9997978806495667, "start": 13884, "tag": "NAME", "value": "Nathan Marz" } ]
clj/ex/study_specter/e01/src/specter01.clj
mertnuhoglu/study
1
(ns specter01 (:use [com.rpl.specter]) (:require [clojure.string :as str])) ; Most codes taken from: https://github.com/redplanetlabs/specter/blob/master/README.md ; ex: Increment every even number nested within map of vector of maps id=g11441 (def data {:a [{:aa 1 :bb 2} {:cc 3}] :b [{:dd 4}]}) ;; Manual Clojure (defn map-vals [m afn] (->> m (map (fn [[k v]] [k (afn v)])) (into (empty m)))) (map-vals data (fn [v] (mapv (fn [m] (map-vals m (fn [v] (if (even? v) (inc v) v)))) v))) ;; => {:a [{:aa 1, :bb 3} {:cc 3}], :b [{:dd 5}]} ;; Specter (transform [MAP-VALS ALL MAP-VALS even?] inc data) ;; => {:a [{:aa 1, :bb 3} {:cc 3}], :b [{:dd 5}]} (select [MAP-VALS ALL MAP-VALS even?] data) ;; => [2 4] (select [MAP-VALS ALL MAP-VALS] data) ;; => [1 2 3 4] (select [MAP-VALS ALL] data) ;; => [{:aa 1, :bb 2} {:cc 3} {:dd 4}] (select [MAP-VALS] data) ;; => [[{:aa 1, :bb 2} {:cc 3}] [{:dd 4}]] ; ex: Append a sequence of elements to a nested vector id=g11440 (def data {:a [1 2 3]}) ;; Manual Clojure (update data :a (fn [v] (into (if v v []) [4 5]))) ;; => {:a [1 2 3 4 5]} ;; Specter (setval [:a END] [4 5] data) ;; => {:a [1 2 3 4 5]} (select [:a END] data) ;; => [[]] (select [:a] data) ;; => [[1 2 3]] ; ex: Increment the last odd number in a sequence id=g11442 (def data [1 2 3 4]) ;; Manual Clojure (let [idx (reduce-kv (fn [res i v] (if (odd? v) i res)) nil data)] (if idx (update data idx inc) data)) ;; => [1 2 4 4] ;; Specter (transform [(filterer odd?) LAST] inc data) ;; => [1 2 4 4] (select [(filterer odd?) LAST] data) ;; => [3] (select [(filterer odd?)] data) ;; => [[1 3]] (transform [(filterer odd?)] identity data) ;; => [1 2 3 4] ; ex: Map a function over a sequence without changing the type or order of the sequence id=g11446 ;; Manual Clojure (map inc data) ;; doesn't work, becomes a lazy sequence ;; => (2 3 4 5) (into (empty data) (map inc data)) ;; doesn't work, reverses the order of lists ;; => [2 3 4 5] ;; Specter (transform ALL inc data) ;; works for all Clojure datatypes with near-optimal efficiency ;; => [2 3 4 5] ; ex: Increment all the values in maps of maps: id=g11447 (transform [MAP-VALS MAP-VALS] inc {:a {:aa 1} :b {:ba -1}}) ;; => {:a {:aa 2}, :b {:ba 0}} ; ex: Increment all the even values for :a keys in a sequence of maps: (transform [ALL :a even?] inc [{:a 1} {:a 2}]) ;; => [{:a 1} {:a 3}] ; ex: Retrieve every number divisible by 3 out of a sequence of sequences: (select [ALL ALL #(= 0 (mod % 3))] [[6 2] [3]]) ;; => [6 3] ; ex: Increment the last odd number in a sequence: (transform [(filterer odd?) LAST] inc [2 1 4]) ;; => [2 2 4] ; ex: Remove nils from a nested sequence: (setval [:a ALL nil?] NONE {:a [1 2 nil]}) ;; => {:a [1 2]} ; ex: Remove key/value pair from nested map: (setval [:a :b :c] NONE {:a {:b {:c 1}}}) ;; => {:a {:b {}}} ; ex: Remove key/value pair from nested map, removing maps that become empty along the way: (setval [:a (compact :b :c)] NONE {:a {:b {:c 1}}}) ;; => {} ; ex: Increment all the odd numbers between indices 1 (inclusive) and 3 (exclusive): (transform [(srange 1 3) ALL odd?] inc [0 1 2 3]) ;; => [0 2 2 3] ; ex: Replace the subsequence from indices 1 to 3: (setval (srange 1 3) [:a :b] [0 1 2 3]) ;; => [0 :a :b 3] ; ex: Concatenate the sequence [:a :b] to every nested sequence of a sequence: (setval [ALL END] [:a] [[1] '(1 2)]) ;; => [[1 :a] (1 2 :a)] ; ex: Get all the numbers out of a data structure, no matter how they're nested: (select (walker number?) {2 [1] :a 4}) ;; => [2 1 4] ; ex: Navigate with string keys: (select ["a" "b"] {"a" {"b" 10}}) ;; => [10] ; ex: Reverse the positions of all even numbers between indices 0 and 4: (transform [(srange 0 4) (filterer even?)] reverse [0 1 2 3 4]) ;; => [2 1 0 3 4] ; ex: Append [:c :d] to every subsequence that has at least two even numbers: (setval [ALL (selected? (filterer even?) (view count) (pred>= 2)) END] [:c] [[1 2 4] [6]]) ;; => [[1 2 4 :c] [6]] ; Video: Understanding Specter - Clojure's missing piece - rh5J4vacG98 id=g11449 ; ex01 (mapv inc [1 2 3]) ;; => [2 3 4] (transform ALL inc #{1 2 3}) ;; => #{2 3 4} ; ex02 (def data [{:a 1 :b 2} {:c 3}]) ; clojure way: (defn apply-fn-to-hashmap [f m] (into {} (for [[k v] m ] [k (f v)]))) (map #(apply-fn-to-hashmap inc %) data) ;; => ({:a 2, :b 3} {:c 4}) (defn inc-even [n] (if (even? n) (inc n) n)) (mapv #(apply-fn-to-hashmap inc-even %) data) ;; => [{:a 1, :b 3} {:c 3}] ; specter: (transform [ALL MAP-VALS even?] inc data) ;; => [{:a 1, :b 3} {:c 3}] ; get-in is a navigator (get-in {:a {:b 3}} [:a :b]) ;; => 3 (get-in [:a {:b 1}] [1 :b]) ;; => 1 ; use01: query deep data with `select` (def data {:res [{:group 1 :catlist [{:cat 1 :points [{:point 1 :start "13" :stop "13.25"} {:point 2 :start "14" :stop "14.25"}]}]}]}) (select [:res ALL ] data) ;; => [{:group 1, :catlist [{:cat 1, :points [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}]}]}] (select [:res ALL :catlist ALL ] data) ;; => [{:cat 1, :points [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}]}] (select [:res ALL :catlist ALL :points ALL ] data) ;; => [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}] ; use02: update with `transform` (def data {:res [{:group 1 :as [{:a 1} {:a 2}]}]}) (transform [:res ALL :as] #(reverse (sort-by :stop %)) data) ;; => {:res [{:group 1, :as ({:a 2} {:a 1})}]} ; use03: update with value `setval` ; opt01: single value (setval [:res ALL :group] 2 data) ;; => {:res [{:group 2, :as [{:a 1} {:a 2}]}]} (transform [:res ALL :group] (constantly 2) data) ;; => {:res [{:group 2, :as [{:a 1} {:a 2}]}]} ; opt02: a collection (setval [:res FIRST :as FIRST] {:a "X"} data) ;; => {:res [{:group 1, :as [{:a "X"} {:a 2}]}]} ; opt03: insert new value (setval [:res FIRST :as AFTER-ELEM] {:a "Z"} data) ;; => {:res [{:group 1, :as [{:a 1} {:a 2} {:a "Z"}]}]} (setval [:res FIRST :as (before-index 1)] {:a "Z"} data) ;; => {:res [{:group 1, :as [{:a 1} {:a "Z"} {:a 2}]}]} ; use04: walking entire data (select [(walker number?)] data) ;; => [1 1 2] (select [(walker string?)] data) ;; => [] (select [(walker keyword?)] data) ;; => [:res :group :as :a :a] ; use05: parsing (def data {:res [{:group 1 :as [{:a "13:30"} {:a "14:45"}]}]}) (defn parse [time] (str/split time #"\:")) (defn unparse [split-time] (str/join ":" split-time)) (parse "3.5") ;; => ["3" "5"] (unparse ["3" "5"]) ;; => "3.5" (select [:res ALL :as ALL :a] data) ;; => ["13:30" "14:45"] (select [:res ALL :as ALL :a (parser parse unparse)] data) ;; => [["13" "30"] ["14" "45"]] (setval [:res ALL :as ALL :a (parser parse unparse) LAST] "00" data) ;; => {:res [{:group 1, :as [{:a "13:00"} {:a "14:00"}]}]} ; Article: [List of Navigators · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Navigators) ; AFTER-ELEM (setval AFTER-ELEM 3 [1 2]) ;; => [1 2 3] ; ALL (select ALL [0 1 2]) ;; => [0 1 2] (select ALL (list 0 1 2)) ;; => [0 1 2] (select ALL {:a :b, :c :d}) ;; => [[:a :b] [:c :d]] (transform ALL identity {:a :b}) ;; => {:a :b} (setval [ALL nil?] NONE [0 1 nil 2]) ;; => [0 1 2] ; ALL-WITH-META: same as ALL (meta (select ALL ^{:purpose "count"} [0 1 2])) ;; => nil (transform ALL-WITH-META inc ^{:purpose "count"} [0 1 2]) ;; => [1 2 3] (meta (transform ALL-WITH-META inc ^{:purpose "count"} [0 1 2])) ;; => {:purpose "count"} ; ATOM (def a (atom 0)) ;; => #'clojure_by_example_kimh/a (select-one ATOM a) ;; => 0 (swap! a inc) ;; => 1 (select-one ATOM a) ;; => 1 (transform ATOM inc a) (deref a) ;; => 2 ; BEFORE-ELEM (setval BEFORE-ELEM 3 [1 2]) ;; => [3 1 2] ; BEGINNING (setval BEGINNING '(0 1) (range 3 6)) ;; => (0 1 3 4 5) ; DISPENSE (select [ALL VAL] (range 3)) ;; => [[0 0] [1 1] [2 2]] (transform [ALL VAL] + (range 3)) ;; => (0 2 4) (transform [ALL VAL DISPENSE] + (range 3)) ;; => (0 1 2) ; END (setval END '(5) (range 3)) ;; => (0 1 2 5) ; FIRST (select-one FIRST (range 3)) ;; => 0 ; INDEXED-VALS (select [INDEXED-VALS] [5 6 7]) ;; => [[0 5] [1 6] [2 7]] ; LAST (select-one LAST (range 3)) ;; => 2 ; MAP-KEYS (select [MAP-KEYS] {:a 3 :b 4}) ;; => [:a :b] ; MAP-VALS (select MAP-VALS {:a :b, :c :d}) ;; => [:b :d] (select [MAP-VALS MAP-VALS] {:a {:b :c}}) ;; => [:c] ; META (select-one META (with-meta {:a 0} {:meta :data})) ;; => {:meta :data} ; NAME (select [NAME] :key) ;; => ["key"] (select [MAP-KEYS NAME] {:a 3 :b 4}) ;; => ["a" "b"] (setval [MAP-KEYS NAME] "q" {'a/b 3}) ;; => #:a{q 3} ; NAMESPACE (select [ALL NAMESPACE] [::test ::fun]) ;; => ["specter01" "specter01"] (setval [ALL NAMESPACE] "a" [::test]) ;; => [:a/test] ; NIL->LIST (select-one NIL->LIST nil) ;; => () (select-one NIL->LIST :foo) ;; => :foo ; VALS (select [VAL ALL] (range 3)) ;; => [[(0 1 2) 0] [(0 1 2) 1] [(0 1 2) 2]] (transform [VAL ALL] (fn [coll x] (+ x (count coll))) (range 3)) ;; => (3 4 5) ; before-index (select-any (before-index 0) [1 2 3]) ;; => :com.rpl.specter.impl/NONE (setval (before-index 0) :a [1 2 3]) ;; => [:a 1 2 3] ; codewalker ; collect (select-one [(collect ALL) FIRST] (range 3)) ;; => [[0 1 2] 0] ; collect-one (select-one [(collect-one FIRST) LAST] (range 3)) ;; => [0 2] (select [(collect-one FIRST) LAST] (range 3)) ;; => [[0 2]] (select [(collect-one FIRST) ALL] (range 3)) ;; => [[0 0] [0 1] [0 2]] (transform [(collect-one :b) :a] + {:a 2, :b 3}) ;; => {:a 5, :b 3} ; comp-paths (select (comp-paths ALL LAST) {:a 1 :b 2}) ;; => [1 2] ; equivalent to: (select [MAP-VALS] {:a 1 :b 2}) ;; => [1 2] ; compact (setval [1 (compact 0)] NONE [1 [2] 3]) ;; => [1 3] (setval [:a :b (compact :c)] NONE {:a {:b {:c 1}}}) ;; => {:a {}} ; filterer (select-one (filterer even?) (range 3)) ;; => [0 2] ; if-path (select (if-path (must :d) :a) {:a 0, :d 1}) ;; => [0] (select (if-path (must :d) :a :b) {:a 0, :b 1}) ;; => [1] ; keypath (select-one (keypath :a) {:a 0}) ;; => 0 (select [ALL (keypath :a) (nil->val :boo)] [{:a 0} {:b 1}]) ;; => [0 :boo] ; map-key (select [(map-key :a)] {:a 2 :b 3}) ;; => [:a] (setval [(map-key :a)] :c {:a 2 :b 3}) ;; => {:b 3, :c 2} ; multi-path (select (multi-path :a :b) {:a 0, :b 1, :c 2}) ;; => [0 1] (select (multi-path (filterer odd?) (filterer even?)) (range 7)) ;; => [[1 3 5] [0 2 4 6]] ; must (select-one (must :a) {:a 0}) ;; => 0 (select-one (must :a) {:b 0}) ;; => nil ; nil->val (select-one (nil->val :a) nil) ;; => :a (select-one (nil->val :a) :b) ;; => :b ; nthpath (select [(nthpath 0)] [1 2 3]) ;; => [1] (setval [(nthpath 0)] NONE [1 2 3]) ;; => [2 3] (select [(nthpath 0 1)] [[5 7] 1]) ;; => [7] ; parser ; pred (select [ALL (pred even?)] (range 3)) ;; => [0 2] (select [ALL (pred> 2)] [1 2 3]) ;; => [3] ; putval (transform [:a :b (putval 3)] + {:a {:b 0}}) ;; => {:a {:b 3}} ; not-selected? ; regex-nav (select (regex-nav #"t") "test") ;; => ["t" "t"] (select [:a (regex-nav #"t")] {:a "tx"}) ;; => ["t"] ; selected? (select [ALL (selected? even?)] (range 3)) ;; => [0 2] (select [ALL (selected? [(must :a) even?])] [{:a 0} {:a 1} {:a 2} {:a 3}]) ;; => [{:a 0} {:a 2}] (select [ALL (selected? :money #(>= % 10))] [{:id 1 :money 15} {:id 2 :money 5}]) ;; => [{:id 1, :money 15}] ; set-elements (select [(set-elem 3)] #{3 4 5}) ;; => [3] ; srange (select-one (srange 2 4) (range 5)) ;; => [2 3] ; Article: [List of Macros · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Macros) ; collected? (select [ALL (collect-one FIRST) LAST (collected? [k] (= k :a))] {:a 0 :b 1}) ;; => [[:a 0]] ;; => [[:a 0]] ; multi-transform ; path ex: storing paths https://github.com/redplanetlabs/specter/wiki/List-of-Macros#path (def p0 (path even?)) (select [ALL p0] (range 3)) ;; => [0 2] ; Video: Specter Powerful and Simple Data Structure Manipulation - Nathan Marz - VTCy_DkAJGk id=g11450 ; ex: add a value to a nested set (def d0 {:a #{2 3} :b #{4 5}}) (def d1 { :b #{4 5}}) ; common (update d0 :a (fn [s] (if s (conj s 1) #{1}))) ;; => {:a #{1 3 2}, :b #{4 5}} (update d1 :a (fn [s] (if s (conj s 1) #{1}))) ;; => {:b #{4 5}, :a #{1}} ; opt01: specter (transform :a (fn [s] (if s (conj s 1) #{1})) d0) ;; => {:a #{1 3 2}, :b #{4 5}} (transform :a (fn [s] (if s (conj s 1) #{1})) d1) ;; => {:b #{4 5}, :a #{1}} ; opt02: nil handling (transform [:a NIL->SET] (fn [s] (if s (conj s 1) #{1})) d0) ;; => {:a #{1 3 2}, :b #{4 5}} (transform [:a NIL->SET] (fn [s] (conj s 1)) d1) ;; => {:b #{4 5}, :a #{1}} ; opt03: replace value ; navigate to empty subset and replace it with new value (transform [:a (subset #{})] (fn [_] #{1}) d1) ;; => {:b #{4 5}, :a #{1}} ; opt04: replace value (setval [:a (subset #{})] #{1} d1) ;; => {:b #{4 5}, :a #{1}}
74739
(ns specter01 (:use [com.rpl.specter]) (:require [clojure.string :as str])) ; Most codes taken from: https://github.com/redplanetlabs/specter/blob/master/README.md ; ex: Increment every even number nested within map of vector of maps id=g11441 (def data {:a [{:aa 1 :bb 2} {:cc 3}] :b [{:dd 4}]}) ;; Manual Clojure (defn map-vals [m afn] (->> m (map (fn [[k v]] [k (afn v)])) (into (empty m)))) (map-vals data (fn [v] (mapv (fn [m] (map-vals m (fn [v] (if (even? v) (inc v) v)))) v))) ;; => {:a [{:aa 1, :bb 3} {:cc 3}], :b [{:dd 5}]} ;; Specter (transform [MAP-VALS ALL MAP-VALS even?] inc data) ;; => {:a [{:aa 1, :bb 3} {:cc 3}], :b [{:dd 5}]} (select [MAP-VALS ALL MAP-VALS even?] data) ;; => [2 4] (select [MAP-VALS ALL MAP-VALS] data) ;; => [1 2 3 4] (select [MAP-VALS ALL] data) ;; => [{:aa 1, :bb 2} {:cc 3} {:dd 4}] (select [MAP-VALS] data) ;; => [[{:aa 1, :bb 2} {:cc 3}] [{:dd 4}]] ; ex: Append a sequence of elements to a nested vector id=g11440 (def data {:a [1 2 3]}) ;; Manual Clojure (update data :a (fn [v] (into (if v v []) [4 5]))) ;; => {:a [1 2 3 4 5]} ;; Specter (setval [:a END] [4 5] data) ;; => {:a [1 2 3 4 5]} (select [:a END] data) ;; => [[]] (select [:a] data) ;; => [[1 2 3]] ; ex: Increment the last odd number in a sequence id=g11442 (def data [1 2 3 4]) ;; Manual Clojure (let [idx (reduce-kv (fn [res i v] (if (odd? v) i res)) nil data)] (if idx (update data idx inc) data)) ;; => [1 2 4 4] ;; Specter (transform [(filterer odd?) LAST] inc data) ;; => [1 2 4 4] (select [(filterer odd?) LAST] data) ;; => [3] (select [(filterer odd?)] data) ;; => [[1 3]] (transform [(filterer odd?)] identity data) ;; => [1 2 3 4] ; ex: Map a function over a sequence without changing the type or order of the sequence id=g11446 ;; Manual Clojure (map inc data) ;; doesn't work, becomes a lazy sequence ;; => (2 3 4 5) (into (empty data) (map inc data)) ;; doesn't work, reverses the order of lists ;; => [2 3 4 5] ;; Specter (transform ALL inc data) ;; works for all Clojure datatypes with near-optimal efficiency ;; => [2 3 4 5] ; ex: Increment all the values in maps of maps: id=g11447 (transform [MAP-VALS MAP-VALS] inc {:a {:aa 1} :b {:ba -1}}) ;; => {:a {:aa 2}, :b {:ba 0}} ; ex: Increment all the even values for :a keys in a sequence of maps: (transform [ALL :a even?] inc [{:a 1} {:a 2}]) ;; => [{:a 1} {:a 3}] ; ex: Retrieve every number divisible by 3 out of a sequence of sequences: (select [ALL ALL #(= 0 (mod % 3))] [[6 2] [3]]) ;; => [6 3] ; ex: Increment the last odd number in a sequence: (transform [(filterer odd?) LAST] inc [2 1 4]) ;; => [2 2 4] ; ex: Remove nils from a nested sequence: (setval [:a ALL nil?] NONE {:a [1 2 nil]}) ;; => {:a [1 2]} ; ex: Remove key/value pair from nested map: (setval [:a :b :c] NONE {:a {:b {:c 1}}}) ;; => {:a {:b {}}} ; ex: Remove key/value pair from nested map, removing maps that become empty along the way: (setval [:a (compact :b :c)] NONE {:a {:b {:c 1}}}) ;; => {} ; ex: Increment all the odd numbers between indices 1 (inclusive) and 3 (exclusive): (transform [(srange 1 3) ALL odd?] inc [0 1 2 3]) ;; => [0 2 2 3] ; ex: Replace the subsequence from indices 1 to 3: (setval (srange 1 3) [:a :b] [0 1 2 3]) ;; => [0 :a :b 3] ; ex: Concatenate the sequence [:a :b] to every nested sequence of a sequence: (setval [ALL END] [:a] [[1] '(1 2)]) ;; => [[1 :a] (1 2 :a)] ; ex: Get all the numbers out of a data structure, no matter how they're nested: (select (walker number?) {2 [1] :a 4}) ;; => [2 1 4] ; ex: Navigate with string keys: (select ["a" "b"] {"a" {"b" 10}}) ;; => [10] ; ex: Reverse the positions of all even numbers between indices 0 and 4: (transform [(srange 0 4) (filterer even?)] reverse [0 1 2 3 4]) ;; => [2 1 0 3 4] ; ex: Append [:c :d] to every subsequence that has at least two even numbers: (setval [ALL (selected? (filterer even?) (view count) (pred>= 2)) END] [:c] [[1 2 4] [6]]) ;; => [[1 2 4 :c] [6]] ; Video: Understanding Specter - Clojure's missing piece - rh5J4vacG98 id=g11449 ; ex01 (mapv inc [1 2 3]) ;; => [2 3 4] (transform ALL inc #{1 2 3}) ;; => #{2 3 4} ; ex02 (def data [{:a 1 :b 2} {:c 3}]) ; clojure way: (defn apply-fn-to-hashmap [f m] (into {} (for [[k v] m ] [k (f v)]))) (map #(apply-fn-to-hashmap inc %) data) ;; => ({:a 2, :b 3} {:c 4}) (defn inc-even [n] (if (even? n) (inc n) n)) (mapv #(apply-fn-to-hashmap inc-even %) data) ;; => [{:a 1, :b 3} {:c 3}] ; specter: (transform [ALL MAP-VALS even?] inc data) ;; => [{:a 1, :b 3} {:c 3}] ; get-in is a navigator (get-in {:a {:b 3}} [:a :b]) ;; => 3 (get-in [:a {:b 1}] [1 :b]) ;; => 1 ; use01: query deep data with `select` (def data {:res [{:group 1 :catlist [{:cat 1 :points [{:point 1 :start "13" :stop "13.25"} {:point 2 :start "14" :stop "14.25"}]}]}]}) (select [:res ALL ] data) ;; => [{:group 1, :catlist [{:cat 1, :points [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}]}]}] (select [:res ALL :catlist ALL ] data) ;; => [{:cat 1, :points [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}]}] (select [:res ALL :catlist ALL :points ALL ] data) ;; => [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}] ; use02: update with `transform` (def data {:res [{:group 1 :as [{:a 1} {:a 2}]}]}) (transform [:res ALL :as] #(reverse (sort-by :stop %)) data) ;; => {:res [{:group 1, :as ({:a 2} {:a 1})}]} ; use03: update with value `setval` ; opt01: single value (setval [:res ALL :group] 2 data) ;; => {:res [{:group 2, :as [{:a 1} {:a 2}]}]} (transform [:res ALL :group] (constantly 2) data) ;; => {:res [{:group 2, :as [{:a 1} {:a 2}]}]} ; opt02: a collection (setval [:res FIRST :as FIRST] {:a "X"} data) ;; => {:res [{:group 1, :as [{:a "X"} {:a 2}]}]} ; opt03: insert new value (setval [:res FIRST :as AFTER-ELEM] {:a "Z"} data) ;; => {:res [{:group 1, :as [{:a 1} {:a 2} {:a "Z"}]}]} (setval [:res FIRST :as (before-index 1)] {:a "Z"} data) ;; => {:res [{:group 1, :as [{:a 1} {:a "Z"} {:a 2}]}]} ; use04: walking entire data (select [(walker number?)] data) ;; => [1 1 2] (select [(walker string?)] data) ;; => [] (select [(walker keyword?)] data) ;; => [:res :group :as :a :a] ; use05: parsing (def data {:res [{:group 1 :as [{:a "13:30"} {:a "14:45"}]}]}) (defn parse [time] (str/split time #"\:")) (defn unparse [split-time] (str/join ":" split-time)) (parse "3.5") ;; => ["3" "5"] (unparse ["3" "5"]) ;; => "3.5" (select [:res ALL :as ALL :a] data) ;; => ["13:30" "14:45"] (select [:res ALL :as ALL :a (parser parse unparse)] data) ;; => [["13" "30"] ["14" "45"]] (setval [:res ALL :as ALL :a (parser parse unparse) LAST] "00" data) ;; => {:res [{:group 1, :as [{:a "13:00"} {:a "14:00"}]}]} ; Article: [List of Navigators · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Navigators) ; AFTER-ELEM (setval AFTER-ELEM 3 [1 2]) ;; => [1 2 3] ; ALL (select ALL [0 1 2]) ;; => [0 1 2] (select ALL (list 0 1 2)) ;; => [0 1 2] (select ALL {:a :b, :c :d}) ;; => [[:a :b] [:c :d]] (transform ALL identity {:a :b}) ;; => {:a :b} (setval [ALL nil?] NONE [0 1 nil 2]) ;; => [0 1 2] ; ALL-WITH-META: same as ALL (meta (select ALL ^{:purpose "count"} [0 1 2])) ;; => nil (transform ALL-WITH-META inc ^{:purpose "count"} [0 1 2]) ;; => [1 2 3] (meta (transform ALL-WITH-META inc ^{:purpose "count"} [0 1 2])) ;; => {:purpose "count"} ; ATOM (def a (atom 0)) ;; => #'clojure_by_example_kimh/a (select-one ATOM a) ;; => 0 (swap! a inc) ;; => 1 (select-one ATOM a) ;; => 1 (transform ATOM inc a) (deref a) ;; => 2 ; BEFORE-ELEM (setval BEFORE-ELEM 3 [1 2]) ;; => [3 1 2] ; BEGINNING (setval BEGINNING '(0 1) (range 3 6)) ;; => (0 1 3 4 5) ; DISPENSE (select [ALL VAL] (range 3)) ;; => [[0 0] [1 1] [2 2]] (transform [ALL VAL] + (range 3)) ;; => (0 2 4) (transform [ALL VAL DISPENSE] + (range 3)) ;; => (0 1 2) ; END (setval END '(5) (range 3)) ;; => (0 1 2 5) ; FIRST (select-one FIRST (range 3)) ;; => 0 ; INDEXED-VALS (select [INDEXED-VALS] [5 6 7]) ;; => [[0 5] [1 6] [2 7]] ; LAST (select-one LAST (range 3)) ;; => 2 ; MAP-KEYS (select [MAP-KEYS] {:a 3 :b 4}) ;; => [:a :b] ; MAP-VALS (select MAP-VALS {:a :b, :c :d}) ;; => [:b :d] (select [MAP-VALS MAP-VALS] {:a {:b :c}}) ;; => [:c] ; META (select-one META (with-meta {:a 0} {:meta :data})) ;; => {:meta :data} ; NAME (select [NAME] :key) ;; => ["key"] (select [MAP-KEYS NAME] {:a 3 :b 4}) ;; => ["a" "b"] (setval [MAP-KEYS NAME] "q" {'a/b 3}) ;; => #:a{q 3} ; NAMESPACE (select [ALL NAMESPACE] [::test ::fun]) ;; => ["specter01" "specter01"] (setval [ALL NAMESPACE] "a" [::test]) ;; => [:a/test] ; NIL->LIST (select-one NIL->LIST nil) ;; => () (select-one NIL->LIST :foo) ;; => :foo ; VALS (select [VAL ALL] (range 3)) ;; => [[(0 1 2) 0] [(0 1 2) 1] [(0 1 2) 2]] (transform [VAL ALL] (fn [coll x] (+ x (count coll))) (range 3)) ;; => (3 4 5) ; before-index (select-any (before-index 0) [1 2 3]) ;; => :com.rpl.specter.impl/NONE (setval (before-index 0) :a [1 2 3]) ;; => [:a 1 2 3] ; codewalker ; collect (select-one [(collect ALL) FIRST] (range 3)) ;; => [[0 1 2] 0] ; collect-one (select-one [(collect-one FIRST) LAST] (range 3)) ;; => [0 2] (select [(collect-one FIRST) LAST] (range 3)) ;; => [[0 2]] (select [(collect-one FIRST) ALL] (range 3)) ;; => [[0 0] [0 1] [0 2]] (transform [(collect-one :b) :a] + {:a 2, :b 3}) ;; => {:a 5, :b 3} ; comp-paths (select (comp-paths ALL LAST) {:a 1 :b 2}) ;; => [1 2] ; equivalent to: (select [MAP-VALS] {:a 1 :b 2}) ;; => [1 2] ; compact (setval [1 (compact 0)] NONE [1 [2] 3]) ;; => [1 3] (setval [:a :b (compact :c)] NONE {:a {:b {:c 1}}}) ;; => {:a {}} ; filterer (select-one (filterer even?) (range 3)) ;; => [0 2] ; if-path (select (if-path (must :d) :a) {:a 0, :d 1}) ;; => [0] (select (if-path (must :d) :a :b) {:a 0, :b 1}) ;; => [1] ; keypath (select-one (keypath :a) {:a 0}) ;; => 0 (select [ALL (keypath :a) (nil->val :boo)] [{:a 0} {:b 1}]) ;; => [0 :boo] ; map-key (select [(map-key :a)] {:a 2 :b 3}) ;; => [:a] (setval [(map-key :a)] :c {:a 2 :b 3}) ;; => {:b 3, :c 2} ; multi-path (select (multi-path :a :b) {:a 0, :b 1, :c 2}) ;; => [0 1] (select (multi-path (filterer odd?) (filterer even?)) (range 7)) ;; => [[1 3 5] [0 2 4 6]] ; must (select-one (must :a) {:a 0}) ;; => 0 (select-one (must :a) {:b 0}) ;; => nil ; nil->val (select-one (nil->val :a) nil) ;; => :a (select-one (nil->val :a) :b) ;; => :b ; nthpath (select [(nthpath 0)] [1 2 3]) ;; => [1] (setval [(nthpath 0)] NONE [1 2 3]) ;; => [2 3] (select [(nthpath 0 1)] [[5 7] 1]) ;; => [7] ; parser ; pred (select [ALL (pred even?)] (range 3)) ;; => [0 2] (select [ALL (pred> 2)] [1 2 3]) ;; => [3] ; putval (transform [:a :b (putval 3)] + {:a {:b 0}}) ;; => {:a {:b 3}} ; not-selected? ; regex-nav (select (regex-nav #"t") "test") ;; => ["t" "t"] (select [:a (regex-nav #"t")] {:a "tx"}) ;; => ["t"] ; selected? (select [ALL (selected? even?)] (range 3)) ;; => [0 2] (select [ALL (selected? [(must :a) even?])] [{:a 0} {:a 1} {:a 2} {:a 3}]) ;; => [{:a 0} {:a 2}] (select [ALL (selected? :money #(>= % 10))] [{:id 1 :money 15} {:id 2 :money 5}]) ;; => [{:id 1, :money 15}] ; set-elements (select [(set-elem 3)] #{3 4 5}) ;; => [3] ; srange (select-one (srange 2 4) (range 5)) ;; => [2 3] ; Article: [List of Macros · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Macros) ; collected? (select [ALL (collect-one FIRST) LAST (collected? [k] (= k :a))] {:a 0 :b 1}) ;; => [[:a 0]] ;; => [[:a 0]] ; multi-transform ; path ex: storing paths https://github.com/redplanetlabs/specter/wiki/List-of-Macros#path (def p0 (path even?)) (select [ALL p0] (range 3)) ;; => [0 2] ; Video: Specter Powerful and Simple Data Structure Manipulation - <NAME> - VTCy_DkAJGk id=g11450 ; ex: add a value to a nested set (def d0 {:a #{2 3} :b #{4 5}}) (def d1 { :b #{4 5}}) ; common (update d0 :a (fn [s] (if s (conj s 1) #{1}))) ;; => {:a #{1 3 2}, :b #{4 5}} (update d1 :a (fn [s] (if s (conj s 1) #{1}))) ;; => {:b #{4 5}, :a #{1}} ; opt01: specter (transform :a (fn [s] (if s (conj s 1) #{1})) d0) ;; => {:a #{1 3 2}, :b #{4 5}} (transform :a (fn [s] (if s (conj s 1) #{1})) d1) ;; => {:b #{4 5}, :a #{1}} ; opt02: nil handling (transform [:a NIL->SET] (fn [s] (if s (conj s 1) #{1})) d0) ;; => {:a #{1 3 2}, :b #{4 5}} (transform [:a NIL->SET] (fn [s] (conj s 1)) d1) ;; => {:b #{4 5}, :a #{1}} ; opt03: replace value ; navigate to empty subset and replace it with new value (transform [:a (subset #{})] (fn [_] #{1}) d1) ;; => {:b #{4 5}, :a #{1}} ; opt04: replace value (setval [:a (subset #{})] #{1} d1) ;; => {:b #{4 5}, :a #{1}}
true
(ns specter01 (:use [com.rpl.specter]) (:require [clojure.string :as str])) ; Most codes taken from: https://github.com/redplanetlabs/specter/blob/master/README.md ; ex: Increment every even number nested within map of vector of maps id=g11441 (def data {:a [{:aa 1 :bb 2} {:cc 3}] :b [{:dd 4}]}) ;; Manual Clojure (defn map-vals [m afn] (->> m (map (fn [[k v]] [k (afn v)])) (into (empty m)))) (map-vals data (fn [v] (mapv (fn [m] (map-vals m (fn [v] (if (even? v) (inc v) v)))) v))) ;; => {:a [{:aa 1, :bb 3} {:cc 3}], :b [{:dd 5}]} ;; Specter (transform [MAP-VALS ALL MAP-VALS even?] inc data) ;; => {:a [{:aa 1, :bb 3} {:cc 3}], :b [{:dd 5}]} (select [MAP-VALS ALL MAP-VALS even?] data) ;; => [2 4] (select [MAP-VALS ALL MAP-VALS] data) ;; => [1 2 3 4] (select [MAP-VALS ALL] data) ;; => [{:aa 1, :bb 2} {:cc 3} {:dd 4}] (select [MAP-VALS] data) ;; => [[{:aa 1, :bb 2} {:cc 3}] [{:dd 4}]] ; ex: Append a sequence of elements to a nested vector id=g11440 (def data {:a [1 2 3]}) ;; Manual Clojure (update data :a (fn [v] (into (if v v []) [4 5]))) ;; => {:a [1 2 3 4 5]} ;; Specter (setval [:a END] [4 5] data) ;; => {:a [1 2 3 4 5]} (select [:a END] data) ;; => [[]] (select [:a] data) ;; => [[1 2 3]] ; ex: Increment the last odd number in a sequence id=g11442 (def data [1 2 3 4]) ;; Manual Clojure (let [idx (reduce-kv (fn [res i v] (if (odd? v) i res)) nil data)] (if idx (update data idx inc) data)) ;; => [1 2 4 4] ;; Specter (transform [(filterer odd?) LAST] inc data) ;; => [1 2 4 4] (select [(filterer odd?) LAST] data) ;; => [3] (select [(filterer odd?)] data) ;; => [[1 3]] (transform [(filterer odd?)] identity data) ;; => [1 2 3 4] ; ex: Map a function over a sequence without changing the type or order of the sequence id=g11446 ;; Manual Clojure (map inc data) ;; doesn't work, becomes a lazy sequence ;; => (2 3 4 5) (into (empty data) (map inc data)) ;; doesn't work, reverses the order of lists ;; => [2 3 4 5] ;; Specter (transform ALL inc data) ;; works for all Clojure datatypes with near-optimal efficiency ;; => [2 3 4 5] ; ex: Increment all the values in maps of maps: id=g11447 (transform [MAP-VALS MAP-VALS] inc {:a {:aa 1} :b {:ba -1}}) ;; => {:a {:aa 2}, :b {:ba 0}} ; ex: Increment all the even values for :a keys in a sequence of maps: (transform [ALL :a even?] inc [{:a 1} {:a 2}]) ;; => [{:a 1} {:a 3}] ; ex: Retrieve every number divisible by 3 out of a sequence of sequences: (select [ALL ALL #(= 0 (mod % 3))] [[6 2] [3]]) ;; => [6 3] ; ex: Increment the last odd number in a sequence: (transform [(filterer odd?) LAST] inc [2 1 4]) ;; => [2 2 4] ; ex: Remove nils from a nested sequence: (setval [:a ALL nil?] NONE {:a [1 2 nil]}) ;; => {:a [1 2]} ; ex: Remove key/value pair from nested map: (setval [:a :b :c] NONE {:a {:b {:c 1}}}) ;; => {:a {:b {}}} ; ex: Remove key/value pair from nested map, removing maps that become empty along the way: (setval [:a (compact :b :c)] NONE {:a {:b {:c 1}}}) ;; => {} ; ex: Increment all the odd numbers between indices 1 (inclusive) and 3 (exclusive): (transform [(srange 1 3) ALL odd?] inc [0 1 2 3]) ;; => [0 2 2 3] ; ex: Replace the subsequence from indices 1 to 3: (setval (srange 1 3) [:a :b] [0 1 2 3]) ;; => [0 :a :b 3] ; ex: Concatenate the sequence [:a :b] to every nested sequence of a sequence: (setval [ALL END] [:a] [[1] '(1 2)]) ;; => [[1 :a] (1 2 :a)] ; ex: Get all the numbers out of a data structure, no matter how they're nested: (select (walker number?) {2 [1] :a 4}) ;; => [2 1 4] ; ex: Navigate with string keys: (select ["a" "b"] {"a" {"b" 10}}) ;; => [10] ; ex: Reverse the positions of all even numbers between indices 0 and 4: (transform [(srange 0 4) (filterer even?)] reverse [0 1 2 3 4]) ;; => [2 1 0 3 4] ; ex: Append [:c :d] to every subsequence that has at least two even numbers: (setval [ALL (selected? (filterer even?) (view count) (pred>= 2)) END] [:c] [[1 2 4] [6]]) ;; => [[1 2 4 :c] [6]] ; Video: Understanding Specter - Clojure's missing piece - rh5J4vacG98 id=g11449 ; ex01 (mapv inc [1 2 3]) ;; => [2 3 4] (transform ALL inc #{1 2 3}) ;; => #{2 3 4} ; ex02 (def data [{:a 1 :b 2} {:c 3}]) ; clojure way: (defn apply-fn-to-hashmap [f m] (into {} (for [[k v] m ] [k (f v)]))) (map #(apply-fn-to-hashmap inc %) data) ;; => ({:a 2, :b 3} {:c 4}) (defn inc-even [n] (if (even? n) (inc n) n)) (mapv #(apply-fn-to-hashmap inc-even %) data) ;; => [{:a 1, :b 3} {:c 3}] ; specter: (transform [ALL MAP-VALS even?] inc data) ;; => [{:a 1, :b 3} {:c 3}] ; get-in is a navigator (get-in {:a {:b 3}} [:a :b]) ;; => 3 (get-in [:a {:b 1}] [1 :b]) ;; => 1 ; use01: query deep data with `select` (def data {:res [{:group 1 :catlist [{:cat 1 :points [{:point 1 :start "13" :stop "13.25"} {:point 2 :start "14" :stop "14.25"}]}]}]}) (select [:res ALL ] data) ;; => [{:group 1, :catlist [{:cat 1, :points [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}]}]}] (select [:res ALL :catlist ALL ] data) ;; => [{:cat 1, :points [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}]}] (select [:res ALL :catlist ALL :points ALL ] data) ;; => [{:point 1, :start "13", :stop "13.25"} {:point 2, :start "14", :stop "14.25"}] ; use02: update with `transform` (def data {:res [{:group 1 :as [{:a 1} {:a 2}]}]}) (transform [:res ALL :as] #(reverse (sort-by :stop %)) data) ;; => {:res [{:group 1, :as ({:a 2} {:a 1})}]} ; use03: update with value `setval` ; opt01: single value (setval [:res ALL :group] 2 data) ;; => {:res [{:group 2, :as [{:a 1} {:a 2}]}]} (transform [:res ALL :group] (constantly 2) data) ;; => {:res [{:group 2, :as [{:a 1} {:a 2}]}]} ; opt02: a collection (setval [:res FIRST :as FIRST] {:a "X"} data) ;; => {:res [{:group 1, :as [{:a "X"} {:a 2}]}]} ; opt03: insert new value (setval [:res FIRST :as AFTER-ELEM] {:a "Z"} data) ;; => {:res [{:group 1, :as [{:a 1} {:a 2} {:a "Z"}]}]} (setval [:res FIRST :as (before-index 1)] {:a "Z"} data) ;; => {:res [{:group 1, :as [{:a 1} {:a "Z"} {:a 2}]}]} ; use04: walking entire data (select [(walker number?)] data) ;; => [1 1 2] (select [(walker string?)] data) ;; => [] (select [(walker keyword?)] data) ;; => [:res :group :as :a :a] ; use05: parsing (def data {:res [{:group 1 :as [{:a "13:30"} {:a "14:45"}]}]}) (defn parse [time] (str/split time #"\:")) (defn unparse [split-time] (str/join ":" split-time)) (parse "3.5") ;; => ["3" "5"] (unparse ["3" "5"]) ;; => "3.5" (select [:res ALL :as ALL :a] data) ;; => ["13:30" "14:45"] (select [:res ALL :as ALL :a (parser parse unparse)] data) ;; => [["13" "30"] ["14" "45"]] (setval [:res ALL :as ALL :a (parser parse unparse) LAST] "00" data) ;; => {:res [{:group 1, :as [{:a "13:00"} {:a "14:00"}]}]} ; Article: [List of Navigators · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Navigators) ; AFTER-ELEM (setval AFTER-ELEM 3 [1 2]) ;; => [1 2 3] ; ALL (select ALL [0 1 2]) ;; => [0 1 2] (select ALL (list 0 1 2)) ;; => [0 1 2] (select ALL {:a :b, :c :d}) ;; => [[:a :b] [:c :d]] (transform ALL identity {:a :b}) ;; => {:a :b} (setval [ALL nil?] NONE [0 1 nil 2]) ;; => [0 1 2] ; ALL-WITH-META: same as ALL (meta (select ALL ^{:purpose "count"} [0 1 2])) ;; => nil (transform ALL-WITH-META inc ^{:purpose "count"} [0 1 2]) ;; => [1 2 3] (meta (transform ALL-WITH-META inc ^{:purpose "count"} [0 1 2])) ;; => {:purpose "count"} ; ATOM (def a (atom 0)) ;; => #'clojure_by_example_kimh/a (select-one ATOM a) ;; => 0 (swap! a inc) ;; => 1 (select-one ATOM a) ;; => 1 (transform ATOM inc a) (deref a) ;; => 2 ; BEFORE-ELEM (setval BEFORE-ELEM 3 [1 2]) ;; => [3 1 2] ; BEGINNING (setval BEGINNING '(0 1) (range 3 6)) ;; => (0 1 3 4 5) ; DISPENSE (select [ALL VAL] (range 3)) ;; => [[0 0] [1 1] [2 2]] (transform [ALL VAL] + (range 3)) ;; => (0 2 4) (transform [ALL VAL DISPENSE] + (range 3)) ;; => (0 1 2) ; END (setval END '(5) (range 3)) ;; => (0 1 2 5) ; FIRST (select-one FIRST (range 3)) ;; => 0 ; INDEXED-VALS (select [INDEXED-VALS] [5 6 7]) ;; => [[0 5] [1 6] [2 7]] ; LAST (select-one LAST (range 3)) ;; => 2 ; MAP-KEYS (select [MAP-KEYS] {:a 3 :b 4}) ;; => [:a :b] ; MAP-VALS (select MAP-VALS {:a :b, :c :d}) ;; => [:b :d] (select [MAP-VALS MAP-VALS] {:a {:b :c}}) ;; => [:c] ; META (select-one META (with-meta {:a 0} {:meta :data})) ;; => {:meta :data} ; NAME (select [NAME] :key) ;; => ["key"] (select [MAP-KEYS NAME] {:a 3 :b 4}) ;; => ["a" "b"] (setval [MAP-KEYS NAME] "q" {'a/b 3}) ;; => #:a{q 3} ; NAMESPACE (select [ALL NAMESPACE] [::test ::fun]) ;; => ["specter01" "specter01"] (setval [ALL NAMESPACE] "a" [::test]) ;; => [:a/test] ; NIL->LIST (select-one NIL->LIST nil) ;; => () (select-one NIL->LIST :foo) ;; => :foo ; VALS (select [VAL ALL] (range 3)) ;; => [[(0 1 2) 0] [(0 1 2) 1] [(0 1 2) 2]] (transform [VAL ALL] (fn [coll x] (+ x (count coll))) (range 3)) ;; => (3 4 5) ; before-index (select-any (before-index 0) [1 2 3]) ;; => :com.rpl.specter.impl/NONE (setval (before-index 0) :a [1 2 3]) ;; => [:a 1 2 3] ; codewalker ; collect (select-one [(collect ALL) FIRST] (range 3)) ;; => [[0 1 2] 0] ; collect-one (select-one [(collect-one FIRST) LAST] (range 3)) ;; => [0 2] (select [(collect-one FIRST) LAST] (range 3)) ;; => [[0 2]] (select [(collect-one FIRST) ALL] (range 3)) ;; => [[0 0] [0 1] [0 2]] (transform [(collect-one :b) :a] + {:a 2, :b 3}) ;; => {:a 5, :b 3} ; comp-paths (select (comp-paths ALL LAST) {:a 1 :b 2}) ;; => [1 2] ; equivalent to: (select [MAP-VALS] {:a 1 :b 2}) ;; => [1 2] ; compact (setval [1 (compact 0)] NONE [1 [2] 3]) ;; => [1 3] (setval [:a :b (compact :c)] NONE {:a {:b {:c 1}}}) ;; => {:a {}} ; filterer (select-one (filterer even?) (range 3)) ;; => [0 2] ; if-path (select (if-path (must :d) :a) {:a 0, :d 1}) ;; => [0] (select (if-path (must :d) :a :b) {:a 0, :b 1}) ;; => [1] ; keypath (select-one (keypath :a) {:a 0}) ;; => 0 (select [ALL (keypath :a) (nil->val :boo)] [{:a 0} {:b 1}]) ;; => [0 :boo] ; map-key (select [(map-key :a)] {:a 2 :b 3}) ;; => [:a] (setval [(map-key :a)] :c {:a 2 :b 3}) ;; => {:b 3, :c 2} ; multi-path (select (multi-path :a :b) {:a 0, :b 1, :c 2}) ;; => [0 1] (select (multi-path (filterer odd?) (filterer even?)) (range 7)) ;; => [[1 3 5] [0 2 4 6]] ; must (select-one (must :a) {:a 0}) ;; => 0 (select-one (must :a) {:b 0}) ;; => nil ; nil->val (select-one (nil->val :a) nil) ;; => :a (select-one (nil->val :a) :b) ;; => :b ; nthpath (select [(nthpath 0)] [1 2 3]) ;; => [1] (setval [(nthpath 0)] NONE [1 2 3]) ;; => [2 3] (select [(nthpath 0 1)] [[5 7] 1]) ;; => [7] ; parser ; pred (select [ALL (pred even?)] (range 3)) ;; => [0 2] (select [ALL (pred> 2)] [1 2 3]) ;; => [3] ; putval (transform [:a :b (putval 3)] + {:a {:b 0}}) ;; => {:a {:b 3}} ; not-selected? ; regex-nav (select (regex-nav #"t") "test") ;; => ["t" "t"] (select [:a (regex-nav #"t")] {:a "tx"}) ;; => ["t"] ; selected? (select [ALL (selected? even?)] (range 3)) ;; => [0 2] (select [ALL (selected? [(must :a) even?])] [{:a 0} {:a 1} {:a 2} {:a 3}]) ;; => [{:a 0} {:a 2}] (select [ALL (selected? :money #(>= % 10))] [{:id 1 :money 15} {:id 2 :money 5}]) ;; => [{:id 1, :money 15}] ; set-elements (select [(set-elem 3)] #{3 4 5}) ;; => [3] ; srange (select-one (srange 2 4) (range 5)) ;; => [2 3] ; Article: [List of Macros · redplanetlabs/specter Wiki](https://github.com/redplanetlabs/specter/wiki/List-of-Macros) ; collected? (select [ALL (collect-one FIRST) LAST (collected? [k] (= k :a))] {:a 0 :b 1}) ;; => [[:a 0]] ;; => [[:a 0]] ; multi-transform ; path ex: storing paths https://github.com/redplanetlabs/specter/wiki/List-of-Macros#path (def p0 (path even?)) (select [ALL p0] (range 3)) ;; => [0 2] ; Video: Specter Powerful and Simple Data Structure Manipulation - PI:NAME:<NAME>END_PI - VTCy_DkAJGk id=g11450 ; ex: add a value to a nested set (def d0 {:a #{2 3} :b #{4 5}}) (def d1 { :b #{4 5}}) ; common (update d0 :a (fn [s] (if s (conj s 1) #{1}))) ;; => {:a #{1 3 2}, :b #{4 5}} (update d1 :a (fn [s] (if s (conj s 1) #{1}))) ;; => {:b #{4 5}, :a #{1}} ; opt01: specter (transform :a (fn [s] (if s (conj s 1) #{1})) d0) ;; => {:a #{1 3 2}, :b #{4 5}} (transform :a (fn [s] (if s (conj s 1) #{1})) d1) ;; => {:b #{4 5}, :a #{1}} ; opt02: nil handling (transform [:a NIL->SET] (fn [s] (if s (conj s 1) #{1})) d0) ;; => {:a #{1 3 2}, :b #{4 5}} (transform [:a NIL->SET] (fn [s] (conj s 1)) d1) ;; => {:b #{4 5}, :a #{1}} ; opt03: replace value ; navigate to empty subset and replace it with new value (transform [:a (subset #{})] (fn [_] #{1}) d1) ;; => {:b #{4 5}, :a #{1}} ; opt04: replace value (setval [:a (subset #{})] #{1} d1) ;; => {:b #{4 5}, :a #{1}}
[ { "context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License, Vers", "end": 36, "score": 0.7134128212928772, "start": 29, "tag": "NAME", "value": "Walmart" }, { "context": "\"\n :best_friend {:name \"Luke Skywalker\"}}}}\n (execute-parsed-query q {:terse f", "end": 3396, "score": 0.9997934103012085, "start": 3382, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "with-missing-value\n (let [villains {\"01\" {:name \"Wilhuff Tarkin\" ::type :villain}\n \"02\" {:name \"", "end": 3915, "score": 0.9997665286064148, "start": 3901, "tag": "NAME", "value": "Wilhuff Tarkin" }, { "context": "\" ::type :villain}\n \"02\" {:name \"Darth Vader\" ::type :villain}}\n get-villain (fn [episo", "end": 3976, "score": 0.9988633394241333, "start": 3965, "tag": "NAME", "value": "Darth Vader" }, { "context": " \"Darth Bane\")]\n ", "end": 5259, "score": 0.9988124966621399, "start": 5249, "tag": "NAME", "value": "Darth Bane" }, { "context": "is null\")\n (is (= {:data {:villain {:name \"Wilhuff Tarkin\"}}}\n (execute-parsed-query q {:epis", "end": 6540, "score": 0.9998498558998108, "start": 6526, "tag": "NAME", "value": "Wilhuff Tarkin" }, { "context": " }\")]\n (is (= {:data {:villain {:name \"Darth Vader\"}}}\n (execute-parsed-query q nil ni", "end": 7083, "score": 0.9983406662940979, "start": 7072, "tag": "NAME", "value": "Darth Vader" }, { "context": "ovided\")\n\n (is (= {:data {:villain {:name \"Wilhuff Tarkin\"}}}\n (execute-parsed-query q {:epis", "end": 7265, "score": 0.9998577833175659, "start": 7251, "tag": "NAME", "value": "Wilhuff Tarkin" }, { "context": " }\")]\n (is (= {:data {:changeName {:name \"Rey\"}}}\n (execute-parsed-query q {:id \"", "end": 7817, "score": 0.9991151690483093, "start": 7814, "tag": "NAME", "value": "Rey" }, { "context": " (execute-parsed-query q {:id \"01\" :name \"Rey\"} nil)))\n (is (= {:data {:changeName {:nam", "end": 7881, "score": 0.9992578625679016, "start": 7878, "tag": "NAME", "value": "Rey" }, { "context": "null\")\n (is (= {:data {:changeName {:name \"Darth Bane\"}}}\n (execute-parsed-query q {:id \"", "end": 8101, "score": 0.9991792440414429, "start": 8091, "tag": "NAME", "value": "Darth Bane" }, { "context": "uery q {:id \"01\"} nil))\n \"should return Darth Bane when new_name is not present in arguments\")))\n\n ", "end": 8199, "score": 0.9619492888450623, "start": 8189, "tag": "NAME", "value": "Darth Bane" }, { "context": " }\")]\n (is (= {:data {:changeName {:name \"Rey\"}}}\n (execute-parsed-query q {:id \"", "end": 8694, "score": 0.9990425705909729, "start": 8691, "tag": "NAME", "value": "Rey" }, { "context": " (execute-parsed-query q {:id \"01\" :name \"Rey\"} nil)))\n (is (= {:data {:changeName {:nam", "end": 8758, "score": 0.9992014169692993, "start": 8755, "tag": "NAME", "value": "Rey" } ]
test/com/walmartlabs/lacinia/variables_test.clj
hagenek/lacinia
1,762
; Copyright (c) 2017-present Walmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.variables-test (:require [clojure.test :refer [deftest is are testing]] [com.walmartlabs.test-schema :refer [test-schema]] [com.walmartlabs.test-utils :refer [compile-schema execute]] [com.walmartlabs.lacinia :refer [execute-parsed-query]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia.parser :as parser])) (def compiled-schema (schema/compile test-schema)) (deftest variables-can-have-default-values (let [q (parser/parse-query compiled-schema "query ($id : String = \"2001\") { droid (id : $id) { name } }")] (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q nil nil))) (is (= {:data {:droid {:name "C-3PO"}}} (execute-parsed-query q {:id "2000"} nil))))) (deftest references-missing-variable (let [compiled-schema (schema/compile {:queries {:echo {:type :String :args {:input {:type '(non-null String)}} :resolve (fn [_ {:keys [input]} _] (when-not input (throw (NullPointerException.))) input)}}}) q (parser/parse-query compiled-schema "query ($i : String) { echo (input : $i) }")] ;; Double check the success case: (is (= {:data {:echo "foo"}} (execute-parsed-query q {:i "foo"} nil))) ;; Should not get as far as the resolver function: (is (= {:errors [{:message "No variable `i' was supplied for argument `Query/echo.input', which is required." :locations [{:line 2 :column 34}] :extensions {:argument :Query/echo.input :field-name :Query/echo :variable-name :i}}]} (execute-parsed-query q nil nil))))) (deftest fragments-can-reference-variables (let [q (parser/parse-query compiled-schema " query ($terse : Boolean = true, $id : String) { droid (id: $id) { ... droidInfo } } fragment droidInfo on droid { name best_friend @skip(if: $terse) { name } }")] (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q nil nil)) "should skip best_friend when variable defaults to true") (is (= {:data {:droid {:name "C-3PO" :best_friend {:name "Luke Skywalker"}}}} (execute-parsed-query q {:terse false :id "2000"} nil)) "should not skip best_friend when variable is set to false") (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q {:terse true} nil)) "should skip best_friend when variable is set to true"))) (defn with-tag [v] (if-let [type (::type v)] (schema/tag-with-type v type) v)) (deftest variables-with-missing-value (let [villains {"01" {:name "Wilhuff Tarkin" ::type :villain} "02" {:name "Darth Vader" ::type :villain}} get-villain (fn [episode] (let [id (condp = episode "NEW HOPE" "01" "EMPIRE" "02" "JEDI" "02" nil)] (get villains id))) schema {:interfaces {:character {:fields {:id {:type 'String} :name {:type 'String}}}} :objects {:villain {:implements [:character] :fields {:id {:type 'String} :name {:type 'String}}}} :mutations {:changeName {:type :character :args {:id {:type 'String} :new_name {:type 'String}} :resolve (fn [ctx args v] (let [{:keys [id new_name]} args] (let [new-name (if (contains? args :new_name) new_name "Darth Bane")] (-> (get villains id) (assoc :name new-name) (with-tag)))))}} :queries {:villain {:type :villain :args {:episode {:type 'String}} :resolve (fn [ctx args v] (get-villain (:episode args)))}}} compiled-schema (schema/compile schema)] (testing "query with a variable without default-value" (let [q (parser/parse-query compiled-schema "query ($episode : String) { villain (episode : $episode) { name } }")] (is (= {:data {:villain nil}} (execute-parsed-query q nil nil)) "should return no data when variable is missing") (is (= {:data {:villain nil}} (execute-parsed-query q {:episode nil} nil)) "should return no data when variable is null") (is (= {:data {:villain {:name "Wilhuff Tarkin"}}} (execute-parsed-query q {:episode "NEW HOPE"} nil)) "should return a villain"))) (testing "query with a variable with a default value" (let [q (parser/parse-query compiled-schema "query ($episode : String = \"EMPIRE\") { villain (episode : $episode) { name } }")] (is (= {:data {:villain {:name "Darth Vader"}}} (execute-parsed-query q nil nil)) "should return default value when variable is not provided") (is (= {:data {:villain {:name "Wilhuff Tarkin"}}} (execute-parsed-query q {:episode "NEW HOPE"} nil)) "should return a villain"))) (testing "mutation with a variable without a default value" (let [q (parser/parse-query compiled-schema "mutation ($id : String!, $name : String) { changeName(id: $id, new_name: $name) { name } }")] (is (= {:data {:changeName {:name "Rey"}}} (execute-parsed-query q {:id "01" :name "Rey"} nil))) (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "02" :name nil} nil)) "should change name to null") (is (= {:data {:changeName {:name "Darth Bane"}}} (execute-parsed-query q {:id "01"} nil)) "should return Darth Bane when new_name is not present in arguments"))) (testing "mutation with a variable with a NULL default value" (let [q (parser/parse-query compiled-schema "mutation ($id : String!, $name : String = null) { changeName(id: $id, new_name: $name) { name } }")] (is (= {:data {:changeName {:name "Rey"}}} (execute-parsed-query q {:id "01" :name "Rey"} nil))) (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "02" :name nil} nil)) "should change name to null when variable is null") (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "01"} nil)) "should use default-value that is null (as opposed to returning Darth Bane)")))))
117872
; Copyright (c) 2017-present <NAME>, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.variables-test (:require [clojure.test :refer [deftest is are testing]] [com.walmartlabs.test-schema :refer [test-schema]] [com.walmartlabs.test-utils :refer [compile-schema execute]] [com.walmartlabs.lacinia :refer [execute-parsed-query]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia.parser :as parser])) (def compiled-schema (schema/compile test-schema)) (deftest variables-can-have-default-values (let [q (parser/parse-query compiled-schema "query ($id : String = \"2001\") { droid (id : $id) { name } }")] (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q nil nil))) (is (= {:data {:droid {:name "C-3PO"}}} (execute-parsed-query q {:id "2000"} nil))))) (deftest references-missing-variable (let [compiled-schema (schema/compile {:queries {:echo {:type :String :args {:input {:type '(non-null String)}} :resolve (fn [_ {:keys [input]} _] (when-not input (throw (NullPointerException.))) input)}}}) q (parser/parse-query compiled-schema "query ($i : String) { echo (input : $i) }")] ;; Double check the success case: (is (= {:data {:echo "foo"}} (execute-parsed-query q {:i "foo"} nil))) ;; Should not get as far as the resolver function: (is (= {:errors [{:message "No variable `i' was supplied for argument `Query/echo.input', which is required." :locations [{:line 2 :column 34}] :extensions {:argument :Query/echo.input :field-name :Query/echo :variable-name :i}}]} (execute-parsed-query q nil nil))))) (deftest fragments-can-reference-variables (let [q (parser/parse-query compiled-schema " query ($terse : Boolean = true, $id : String) { droid (id: $id) { ... droidInfo } } fragment droidInfo on droid { name best_friend @skip(if: $terse) { name } }")] (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q nil nil)) "should skip best_friend when variable defaults to true") (is (= {:data {:droid {:name "C-3PO" :best_friend {:name "<NAME>"}}}} (execute-parsed-query q {:terse false :id "2000"} nil)) "should not skip best_friend when variable is set to false") (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q {:terse true} nil)) "should skip best_friend when variable is set to true"))) (defn with-tag [v] (if-let [type (::type v)] (schema/tag-with-type v type) v)) (deftest variables-with-missing-value (let [villains {"01" {:name "<NAME>" ::type :villain} "02" {:name "<NAME>" ::type :villain}} get-villain (fn [episode] (let [id (condp = episode "NEW HOPE" "01" "EMPIRE" "02" "JEDI" "02" nil)] (get villains id))) schema {:interfaces {:character {:fields {:id {:type 'String} :name {:type 'String}}}} :objects {:villain {:implements [:character] :fields {:id {:type 'String} :name {:type 'String}}}} :mutations {:changeName {:type :character :args {:id {:type 'String} :new_name {:type 'String}} :resolve (fn [ctx args v] (let [{:keys [id new_name]} args] (let [new-name (if (contains? args :new_name) new_name "<NAME>")] (-> (get villains id) (assoc :name new-name) (with-tag)))))}} :queries {:villain {:type :villain :args {:episode {:type 'String}} :resolve (fn [ctx args v] (get-villain (:episode args)))}}} compiled-schema (schema/compile schema)] (testing "query with a variable without default-value" (let [q (parser/parse-query compiled-schema "query ($episode : String) { villain (episode : $episode) { name } }")] (is (= {:data {:villain nil}} (execute-parsed-query q nil nil)) "should return no data when variable is missing") (is (= {:data {:villain nil}} (execute-parsed-query q {:episode nil} nil)) "should return no data when variable is null") (is (= {:data {:villain {:name "<NAME>"}}} (execute-parsed-query q {:episode "NEW HOPE"} nil)) "should return a villain"))) (testing "query with a variable with a default value" (let [q (parser/parse-query compiled-schema "query ($episode : String = \"EMPIRE\") { villain (episode : $episode) { name } }")] (is (= {:data {:villain {:name "<NAME>"}}} (execute-parsed-query q nil nil)) "should return default value when variable is not provided") (is (= {:data {:villain {:name "<NAME>"}}} (execute-parsed-query q {:episode "NEW HOPE"} nil)) "should return a villain"))) (testing "mutation with a variable without a default value" (let [q (parser/parse-query compiled-schema "mutation ($id : String!, $name : String) { changeName(id: $id, new_name: $name) { name } }")] (is (= {:data {:changeName {:name "<NAME>"}}} (execute-parsed-query q {:id "01" :name "<NAME>"} nil))) (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "02" :name nil} nil)) "should change name to null") (is (= {:data {:changeName {:name "<NAME>"}}} (execute-parsed-query q {:id "01"} nil)) "should return <NAME> when new_name is not present in arguments"))) (testing "mutation with a variable with a NULL default value" (let [q (parser/parse-query compiled-schema "mutation ($id : String!, $name : String = null) { changeName(id: $id, new_name: $name) { name } }")] (is (= {:data {:changeName {:name "<NAME>"}}} (execute-parsed-query q {:id "01" :name "<NAME>"} nil))) (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "02" :name nil} nil)) "should change name to null when variable is null") (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "01"} nil)) "should use default-value that is null (as opposed to returning Darth Bane)")))))
true
; Copyright (c) 2017-present PI:NAME:<NAME>END_PI, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.variables-test (:require [clojure.test :refer [deftest is are testing]] [com.walmartlabs.test-schema :refer [test-schema]] [com.walmartlabs.test-utils :refer [compile-schema execute]] [com.walmartlabs.lacinia :refer [execute-parsed-query]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia.parser :as parser])) (def compiled-schema (schema/compile test-schema)) (deftest variables-can-have-default-values (let [q (parser/parse-query compiled-schema "query ($id : String = \"2001\") { droid (id : $id) { name } }")] (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q nil nil))) (is (= {:data {:droid {:name "C-3PO"}}} (execute-parsed-query q {:id "2000"} nil))))) (deftest references-missing-variable (let [compiled-schema (schema/compile {:queries {:echo {:type :String :args {:input {:type '(non-null String)}} :resolve (fn [_ {:keys [input]} _] (when-not input (throw (NullPointerException.))) input)}}}) q (parser/parse-query compiled-schema "query ($i : String) { echo (input : $i) }")] ;; Double check the success case: (is (= {:data {:echo "foo"}} (execute-parsed-query q {:i "foo"} nil))) ;; Should not get as far as the resolver function: (is (= {:errors [{:message "No variable `i' was supplied for argument `Query/echo.input', which is required." :locations [{:line 2 :column 34}] :extensions {:argument :Query/echo.input :field-name :Query/echo :variable-name :i}}]} (execute-parsed-query q nil nil))))) (deftest fragments-can-reference-variables (let [q (parser/parse-query compiled-schema " query ($terse : Boolean = true, $id : String) { droid (id: $id) { ... droidInfo } } fragment droidInfo on droid { name best_friend @skip(if: $terse) { name } }")] (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q nil nil)) "should skip best_friend when variable defaults to true") (is (= {:data {:droid {:name "C-3PO" :best_friend {:name "PI:NAME:<NAME>END_PI"}}}} (execute-parsed-query q {:terse false :id "2000"} nil)) "should not skip best_friend when variable is set to false") (is (= {:data {:droid {:name "R2-D2"}}} (execute-parsed-query q {:terse true} nil)) "should skip best_friend when variable is set to true"))) (defn with-tag [v] (if-let [type (::type v)] (schema/tag-with-type v type) v)) (deftest variables-with-missing-value (let [villains {"01" {:name "PI:NAME:<NAME>END_PI" ::type :villain} "02" {:name "PI:NAME:<NAME>END_PI" ::type :villain}} get-villain (fn [episode] (let [id (condp = episode "NEW HOPE" "01" "EMPIRE" "02" "JEDI" "02" nil)] (get villains id))) schema {:interfaces {:character {:fields {:id {:type 'String} :name {:type 'String}}}} :objects {:villain {:implements [:character] :fields {:id {:type 'String} :name {:type 'String}}}} :mutations {:changeName {:type :character :args {:id {:type 'String} :new_name {:type 'String}} :resolve (fn [ctx args v] (let [{:keys [id new_name]} args] (let [new-name (if (contains? args :new_name) new_name "PI:NAME:<NAME>END_PI")] (-> (get villains id) (assoc :name new-name) (with-tag)))))}} :queries {:villain {:type :villain :args {:episode {:type 'String}} :resolve (fn [ctx args v] (get-villain (:episode args)))}}} compiled-schema (schema/compile schema)] (testing "query with a variable without default-value" (let [q (parser/parse-query compiled-schema "query ($episode : String) { villain (episode : $episode) { name } }")] (is (= {:data {:villain nil}} (execute-parsed-query q nil nil)) "should return no data when variable is missing") (is (= {:data {:villain nil}} (execute-parsed-query q {:episode nil} nil)) "should return no data when variable is null") (is (= {:data {:villain {:name "PI:NAME:<NAME>END_PI"}}} (execute-parsed-query q {:episode "NEW HOPE"} nil)) "should return a villain"))) (testing "query with a variable with a default value" (let [q (parser/parse-query compiled-schema "query ($episode : String = \"EMPIRE\") { villain (episode : $episode) { name } }")] (is (= {:data {:villain {:name "PI:NAME:<NAME>END_PI"}}} (execute-parsed-query q nil nil)) "should return default value when variable is not provided") (is (= {:data {:villain {:name "PI:NAME:<NAME>END_PI"}}} (execute-parsed-query q {:episode "NEW HOPE"} nil)) "should return a villain"))) (testing "mutation with a variable without a default value" (let [q (parser/parse-query compiled-schema "mutation ($id : String!, $name : String) { changeName(id: $id, new_name: $name) { name } }")] (is (= {:data {:changeName {:name "PI:NAME:<NAME>END_PI"}}} (execute-parsed-query q {:id "01" :name "PI:NAME:<NAME>END_PI"} nil))) (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "02" :name nil} nil)) "should change name to null") (is (= {:data {:changeName {:name "PI:NAME:<NAME>END_PI"}}} (execute-parsed-query q {:id "01"} nil)) "should return PI:NAME:<NAME>END_PI when new_name is not present in arguments"))) (testing "mutation with a variable with a NULL default value" (let [q (parser/parse-query compiled-schema "mutation ($id : String!, $name : String = null) { changeName(id: $id, new_name: $name) { name } }")] (is (= {:data {:changeName {:name "PI:NAME:<NAME>END_PI"}}} (execute-parsed-query q {:id "01" :name "PI:NAME:<NAME>END_PI"} nil))) (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "02" :name nil} nil)) "should change name to null when variable is null") (is (= {:data {:changeName {:name nil}}} (execute-parsed-query q {:id "01"} nil)) "should use default-value that is null (as opposed to returning Darth Bane)")))))
[ { "context": "e* tool that you can find at: <https://github.com/fredokun/markdownize>\n;; \n;; Also, there are a few exercis", "end": 1936, "score": 0.9866346716880798, "start": 1928, "tag": "USERNAME", "value": "fredokun" }, { "context": "plaining things to other people.\n;; \n;; My name is Frederic Peschanski, I am an associated professor in computer science", "end": 2306, "score": 0.9998809099197388, "start": 2287, "tag": "NAME", "value": "Frederic Peschanski" }, { "context": "h me professionally at the following address:\n;; <[email protected]>. I will be happy to answer\n;; but don't mind to", "end": 2879, "score": 0.9999147653579712, "start": 2852, "tag": "EMAIL", "value": "[email protected]" }, { "context": "y and Formal Proof: an Introduction**.\n;; >\n;; > *Rob Nederpelt and Herman Geuvers*\n;; >\n;; > Cambridge Universit", "end": 3153, "score": 0.9998787045478821, "start": 3140, "tag": "NAME", "value": "Rob Nederpelt" }, { "context": "f: an Introduction**.\n;; >\n;; > *Rob Nederpelt and Herman Geuvers*\n;; >\n;; > Cambridge University Press, 2012\n;; \n;", "end": 3172, "score": 0.9998776316642761, "start": 3158, "tag": "NAME", "value": "Herman Geuvers" }, { "context": "and using LaTTe.\n;; \n;; I would also like to thank Yeonathan Sharvit and Hiram Madelaine as well as\n;; the (few) contr", "end": 3557, "score": 0.9998874664306641, "start": 3540, "tag": "NAME", "value": "Yeonathan Sharvit" }, { "context": "; I would also like to thank Yeonathan Sharvit and Hiram Madelaine as well as\n;; the (few) contributors to LaTTE. An", "end": 3577, "score": 0.9998784065246582, "start": 3562, "tag": "NAME", "value": "Hiram Madelaine" }, { "context": "\n;; \n;; This document source is copyright (C) 2018 Frédéric Peschanski\n;; distributed under the MIT License (cf. `LICENS", "end": 8201, "score": 0.9998111724853516, "start": 8182, "tag": "NAME", "value": "Frédéric Peschanski" } ]
src/latte_tutorial/ch01_front_matter.clj
latte-central/latte-tutorial
2
;;{ ;; # Introduction ;;} (ns latte-tutorial.ch01-front-matter) ;;{ ;; This document is a tutorial introduction to the LaTTe proof assistant. ;; ;; My primary goal is to write: ;; ;; - a quick startup guide to LaTTe, ;; - a pedagogical overview of its main features, ;; - a first experiment with important proof rules. ;; ;; Some non-goals are: ;; ;; - a complete course about e.g. type theory or logic, or whatever, ;; - an exhaustive manual for the proof assistant, ;; - a maths lecture. ;; ;; Thus I'll go straight-to-the-point, often omitting (probably) important ;; aspects. ;; ;; The tutorial is heavily inspired by [a talk about LaTTe](https://www.youtube.com/watch?v=5YTCY7wm0Nw) ;; that I gave at EuroClojure'2016. ;; LaTTe changed quite a bit since then, but the video is still a ;; good example of what I call "live coding mathematics". ;; ;; The source for this tutorial is a *literate programming* document, which means it is ;; both a textual document with Clojure (and LaTTe) code examples, and also ;; a set of heavy commented Clojure source files that can be compiled, executed, ;; tested, etc. ;; ;; For each namespace `nsp` (in the Clojure terminology), you'll find : ;; ;; - one file `nsp.clj` containing the Clojure **code source view** with all the explanations ;; (e.g. this very sentence) as comments ;; - a corresponding file `nsp.clj.md` containing the **document view** as a markdown ;; text with all the source code. ;; ;; For example, the following line is an expression of the Clojure language that ;; can be evaluated directly when loading the `.clj` source file: ;;} ((fn [x] x) 42) ;; => 42 ;;{ ;; For many examples the expected evaluation results is shown as a comment: `;; => <value>`. ;; ;; **Remark**: The translation of the code source view to the document view is handled ;; by a very simple *Markownize* tool that you can find at: <https://github.com/fredokun/markdownize> ;; ;; Also, there are a few exercises and questions in the `master` branch of the tutorial. ;; The solutions are available in the `solutions` branch (which should be at least one commit beyond `master`). ;; ;;} ;;{ ;; ## Author ;; ;; I think it is good to introduce oneself when explaining things to other people. ;; ;; My name is Frederic Peschanski, I am an associated professor in computer science ;; at Sorbonne University in Paris, France. I do research mostly on theoretical ;; things, but my main hobby is programming thus I try sometimes to mix work and pleasure ;; by coding research prototypes (in various languages, Clojure among them of course). ;; ;; On my spare time I develop largely experimental free (as in freedom) software, ;; and for a few of them I do get some users which thus involves some maintenance. ;; ;; You can reach me professionally at the following address: ;; <[email protected]>. I will be happy to answer ;; but don't mind to much if it takes some time. ;;} ;;{ ;; ## Acknowledgments ;; ;; I developed LaTTe after reading (devouring, more so) the following book: ;; ;; > **Type Theory and Formal Proof: an Introduction**. ;; > ;; > *Rob Nederpelt and Herman Geuvers* ;; > ;; > Cambridge University Press, 2012 ;; ;; That's a heavily recommended lecture if you are interested in logic in general, ;; and the $\lambda$-calculus in particular. It is also the best source of information ;; to understand the underlying theory of LaTTe. However it is not a prerequisite ;; for learning and using LaTTe. ;; ;; I would also like to thank Yeonathan Sharvit and Hiram Madelaine as well as ;; the (few) contributors to LaTTE. And of course "big five" to the Clojure core ;; dev. team and all the community. ;; ;; ## About LaTTe ;; ;; **LaTTe** stands for "Laboratory for Type Theory Experiments" but it ;; is in fact a perfectly usable **proof assistant** for doing formal mathematics ;; and logic on a computer. It's far from being the most advanced proof assistance ;; technology but it still provides some interesting features. ;; ;; **Remark**: The double *TT* of LaTTe intentioanally looks like ;; Π the Greek capital letter Pi, which is one of the very few ;; constructors of the type theory used by LaTTe. ;; This will be explained, at least superficially, in the tutorial. ;; ;; The basic activity of a proof assistant user is to: ;; - state "fundamental truths" as **axioms**, ;; - write **definitions** of mathematical concepts (e.g. what it is to be a bijection) ;; - state properties about these concepts based on their definition, in the form of **theorem** (or lemma) statements ;; - and for each theorem (or lemma) statement, assist in writing a **formal proof** that it is, indeed, a theorem. ;; ;; So it's of no surprise that these are the main features of LaTTe. ;; But it is also a library for the Clojure programming language, which is unlike ;; many other proof assistants designed as standalone tools (one exception being the ;; members of the HOL family, as well as ACL2, both important sources of inspiration). ;; Thanks to the power of the Lisp language in general, ;; and its Clojure variant in particular, all the main features of the proof assistant ;; are usable directly in Clojure programs or at the REPL (Read-Eval-Print-Loop). ;; ;; Also this means that any Clojure development environment (e.g. Cider, Cursive) can ;; be used as a proof assistant GUI. And this is where most of the power of LaTTe lies. ;; Indeed, the Clojure IDEs support very advanced interactive features. Moreover, one can ;; extend the assistant directly in Clojure and without any intermediate such as a ;; plugins system or complex API. ;; In fact, you develop mathematics in Clojure ;; *exactly like* you develop programs in general, there's not difference at all! ;; ;; Moreover, the mathematical contents developed using LaTTe can be distributed ;; using the very powerful Clojure ecosystem based on the Maven packaging tool. ;; Also, there is a simple yet effective *proof certification* scheme that ;; corresponds to a form of compilation for the distributed content. ;; Proving things in type theory can become rather computationally intensive, ;; but a certified proof can be "taken for granted". ;; ;; Last but not least, the main innovative feature of LaTTe is its *declarative proof language*, ;; which makes the proofs follow the *natural deduction* style. The objective is to make LaTTe proofs ;; quite similar to standard mathematical proofs, at least strucutrally. One still has to ;; deal with the Clojure-enhanced Lisp notation, i.e. a perfectly non-ambiguous mathematical ;; notation, only slightly remote from "mainstream" mathematics. ;; ;;} ;;{ ;; ## Intended audience ;; ;; You might be interested in LaTTe because as a Clojure developer you are curious ;; about the lambda-calculus, dependent types, the Curry-Howard correspondance, ;; or simply formal logic and mathematics. ;; ;; You might also be interested in LaTTe to develop some formal mathematical contents, based on ;; an approach that is not exactly like other proof assistants. I very much welcome mathematical ;; contributions to the project! ;; ;; Finally, you might be interested in how one may embed a *domain-specific language*, the ;; Lisp way, in Clojure (thus with an extra-layer of data-orientation). Clojure the language ;; is still there when using LaTTe, but you're doing not only programming but also ;; mathematics and reasoning... The *same* difference, the Lisp way... ;; ;; Or maybe you're here and that's it! ;; ;; In any case you are very **Welcome**! ;; ;;} ;;{ ;; ## Prerequisites ;; ;; Since LaTTe is a Clojure library, it is required to know at least a bit of ;; Clojure and one of its development environment to follow this tutorial. ;; LaTTe works pretty well in Cider or Cursive, or simply with a basic editor ;; and the REPL. ;; Note that beyond basic functional programming principles, there's nothing much to ;; learn on the Clojure side. Still, if you don't know Clojure I can only recommend ;; to read the first few chapters of an introductory Clojure book. ;; ;;} ;;{ ;; ## License ;; ;; This document source is copyright (C) 2018 Frédéric Peschanski ;; distributed under the MIT License (cf. `LICENSE` file in the root directory). ;;} ;;{ ;; ## Tutorial plan ;; ;; The following steps should be followed in order: ;; ;; 1. first steps (install & friends) ;; 2. the rules of the game (a.k.a. lambda, forall and friends) ;; 3. a bit of logic: natural deduction ;; 4. a glimpse of (typed) set theory ;; 5. a sip of integer arithmetics ;; 6. proving in the large: from proof certification to Clojars deploy ;; ;;} (println "Let's begin!") ;; => nil
53534
;;{ ;; # Introduction ;;} (ns latte-tutorial.ch01-front-matter) ;;{ ;; This document is a tutorial introduction to the LaTTe proof assistant. ;; ;; My primary goal is to write: ;; ;; - a quick startup guide to LaTTe, ;; - a pedagogical overview of its main features, ;; - a first experiment with important proof rules. ;; ;; Some non-goals are: ;; ;; - a complete course about e.g. type theory or logic, or whatever, ;; - an exhaustive manual for the proof assistant, ;; - a maths lecture. ;; ;; Thus I'll go straight-to-the-point, often omitting (probably) important ;; aspects. ;; ;; The tutorial is heavily inspired by [a talk about LaTTe](https://www.youtube.com/watch?v=5YTCY7wm0Nw) ;; that I gave at EuroClojure'2016. ;; LaTTe changed quite a bit since then, but the video is still a ;; good example of what I call "live coding mathematics". ;; ;; The source for this tutorial is a *literate programming* document, which means it is ;; both a textual document with Clojure (and LaTTe) code examples, and also ;; a set of heavy commented Clojure source files that can be compiled, executed, ;; tested, etc. ;; ;; For each namespace `nsp` (in the Clojure terminology), you'll find : ;; ;; - one file `nsp.clj` containing the Clojure **code source view** with all the explanations ;; (e.g. this very sentence) as comments ;; - a corresponding file `nsp.clj.md` containing the **document view** as a markdown ;; text with all the source code. ;; ;; For example, the following line is an expression of the Clojure language that ;; can be evaluated directly when loading the `.clj` source file: ;;} ((fn [x] x) 42) ;; => 42 ;;{ ;; For many examples the expected evaluation results is shown as a comment: `;; => <value>`. ;; ;; **Remark**: The translation of the code source view to the document view is handled ;; by a very simple *Markownize* tool that you can find at: <https://github.com/fredokun/markdownize> ;; ;; Also, there are a few exercises and questions in the `master` branch of the tutorial. ;; The solutions are available in the `solutions` branch (which should be at least one commit beyond `master`). ;; ;;} ;;{ ;; ## Author ;; ;; I think it is good to introduce oneself when explaining things to other people. ;; ;; My name is <NAME>, I am an associated professor in computer science ;; at Sorbonne University in Paris, France. I do research mostly on theoretical ;; things, but my main hobby is programming thus I try sometimes to mix work and pleasure ;; by coding research prototypes (in various languages, Clojure among them of course). ;; ;; On my spare time I develop largely experimental free (as in freedom) software, ;; and for a few of them I do get some users which thus involves some maintenance. ;; ;; You can reach me professionally at the following address: ;; <<EMAIL>>. I will be happy to answer ;; but don't mind to much if it takes some time. ;;} ;;{ ;; ## Acknowledgments ;; ;; I developed LaTTe after reading (devouring, more so) the following book: ;; ;; > **Type Theory and Formal Proof: an Introduction**. ;; > ;; > *<NAME> and <NAME>* ;; > ;; > Cambridge University Press, 2012 ;; ;; That's a heavily recommended lecture if you are interested in logic in general, ;; and the $\lambda$-calculus in particular. It is also the best source of information ;; to understand the underlying theory of LaTTe. However it is not a prerequisite ;; for learning and using LaTTe. ;; ;; I would also like to thank <NAME> and <NAME> as well as ;; the (few) contributors to LaTTE. And of course "big five" to the Clojure core ;; dev. team and all the community. ;; ;; ## About LaTTe ;; ;; **LaTTe** stands for "Laboratory for Type Theory Experiments" but it ;; is in fact a perfectly usable **proof assistant** for doing formal mathematics ;; and logic on a computer. It's far from being the most advanced proof assistance ;; technology but it still provides some interesting features. ;; ;; **Remark**: The double *TT* of LaTTe intentioanally looks like ;; Π the Greek capital letter Pi, which is one of the very few ;; constructors of the type theory used by LaTTe. ;; This will be explained, at least superficially, in the tutorial. ;; ;; The basic activity of a proof assistant user is to: ;; - state "fundamental truths" as **axioms**, ;; - write **definitions** of mathematical concepts (e.g. what it is to be a bijection) ;; - state properties about these concepts based on their definition, in the form of **theorem** (or lemma) statements ;; - and for each theorem (or lemma) statement, assist in writing a **formal proof** that it is, indeed, a theorem. ;; ;; So it's of no surprise that these are the main features of LaTTe. ;; But it is also a library for the Clojure programming language, which is unlike ;; many other proof assistants designed as standalone tools (one exception being the ;; members of the HOL family, as well as ACL2, both important sources of inspiration). ;; Thanks to the power of the Lisp language in general, ;; and its Clojure variant in particular, all the main features of the proof assistant ;; are usable directly in Clojure programs or at the REPL (Read-Eval-Print-Loop). ;; ;; Also this means that any Clojure development environment (e.g. Cider, Cursive) can ;; be used as a proof assistant GUI. And this is where most of the power of LaTTe lies. ;; Indeed, the Clojure IDEs support very advanced interactive features. Moreover, one can ;; extend the assistant directly in Clojure and without any intermediate such as a ;; plugins system or complex API. ;; In fact, you develop mathematics in Clojure ;; *exactly like* you develop programs in general, there's not difference at all! ;; ;; Moreover, the mathematical contents developed using LaTTe can be distributed ;; using the very powerful Clojure ecosystem based on the Maven packaging tool. ;; Also, there is a simple yet effective *proof certification* scheme that ;; corresponds to a form of compilation for the distributed content. ;; Proving things in type theory can become rather computationally intensive, ;; but a certified proof can be "taken for granted". ;; ;; Last but not least, the main innovative feature of LaTTe is its *declarative proof language*, ;; which makes the proofs follow the *natural deduction* style. The objective is to make LaTTe proofs ;; quite similar to standard mathematical proofs, at least strucutrally. One still has to ;; deal with the Clojure-enhanced Lisp notation, i.e. a perfectly non-ambiguous mathematical ;; notation, only slightly remote from "mainstream" mathematics. ;; ;;} ;;{ ;; ## Intended audience ;; ;; You might be interested in LaTTe because as a Clojure developer you are curious ;; about the lambda-calculus, dependent types, the Curry-Howard correspondance, ;; or simply formal logic and mathematics. ;; ;; You might also be interested in LaTTe to develop some formal mathematical contents, based on ;; an approach that is not exactly like other proof assistants. I very much welcome mathematical ;; contributions to the project! ;; ;; Finally, you might be interested in how one may embed a *domain-specific language*, the ;; Lisp way, in Clojure (thus with an extra-layer of data-orientation). Clojure the language ;; is still there when using LaTTe, but you're doing not only programming but also ;; mathematics and reasoning... The *same* difference, the Lisp way... ;; ;; Or maybe you're here and that's it! ;; ;; In any case you are very **Welcome**! ;; ;;} ;;{ ;; ## Prerequisites ;; ;; Since LaTTe is a Clojure library, it is required to know at least a bit of ;; Clojure and one of its development environment to follow this tutorial. ;; LaTTe works pretty well in Cider or Cursive, or simply with a basic editor ;; and the REPL. ;; Note that beyond basic functional programming principles, there's nothing much to ;; learn on the Clojure side. Still, if you don't know Clojure I can only recommend ;; to read the first few chapters of an introductory Clojure book. ;; ;;} ;;{ ;; ## License ;; ;; This document source is copyright (C) 2018 <NAME> ;; distributed under the MIT License (cf. `LICENSE` file in the root directory). ;;} ;;{ ;; ## Tutorial plan ;; ;; The following steps should be followed in order: ;; ;; 1. first steps (install & friends) ;; 2. the rules of the game (a.k.a. lambda, forall and friends) ;; 3. a bit of logic: natural deduction ;; 4. a glimpse of (typed) set theory ;; 5. a sip of integer arithmetics ;; 6. proving in the large: from proof certification to Clojars deploy ;; ;;} (println "Let's begin!") ;; => nil
true
;;{ ;; # Introduction ;;} (ns latte-tutorial.ch01-front-matter) ;;{ ;; This document is a tutorial introduction to the LaTTe proof assistant. ;; ;; My primary goal is to write: ;; ;; - a quick startup guide to LaTTe, ;; - a pedagogical overview of its main features, ;; - a first experiment with important proof rules. ;; ;; Some non-goals are: ;; ;; - a complete course about e.g. type theory or logic, or whatever, ;; - an exhaustive manual for the proof assistant, ;; - a maths lecture. ;; ;; Thus I'll go straight-to-the-point, often omitting (probably) important ;; aspects. ;; ;; The tutorial is heavily inspired by [a talk about LaTTe](https://www.youtube.com/watch?v=5YTCY7wm0Nw) ;; that I gave at EuroClojure'2016. ;; LaTTe changed quite a bit since then, but the video is still a ;; good example of what I call "live coding mathematics". ;; ;; The source for this tutorial is a *literate programming* document, which means it is ;; both a textual document with Clojure (and LaTTe) code examples, and also ;; a set of heavy commented Clojure source files that can be compiled, executed, ;; tested, etc. ;; ;; For each namespace `nsp` (in the Clojure terminology), you'll find : ;; ;; - one file `nsp.clj` containing the Clojure **code source view** with all the explanations ;; (e.g. this very sentence) as comments ;; - a corresponding file `nsp.clj.md` containing the **document view** as a markdown ;; text with all the source code. ;; ;; For example, the following line is an expression of the Clojure language that ;; can be evaluated directly when loading the `.clj` source file: ;;} ((fn [x] x) 42) ;; => 42 ;;{ ;; For many examples the expected evaluation results is shown as a comment: `;; => <value>`. ;; ;; **Remark**: The translation of the code source view to the document view is handled ;; by a very simple *Markownize* tool that you can find at: <https://github.com/fredokun/markdownize> ;; ;; Also, there are a few exercises and questions in the `master` branch of the tutorial. ;; The solutions are available in the `solutions` branch (which should be at least one commit beyond `master`). ;; ;;} ;;{ ;; ## Author ;; ;; I think it is good to introduce oneself when explaining things to other people. ;; ;; My name is PI:NAME:<NAME>END_PI, I am an associated professor in computer science ;; at Sorbonne University in Paris, France. I do research mostly on theoretical ;; things, but my main hobby is programming thus I try sometimes to mix work and pleasure ;; by coding research prototypes (in various languages, Clojure among them of course). ;; ;; On my spare time I develop largely experimental free (as in freedom) software, ;; and for a few of them I do get some users which thus involves some maintenance. ;; ;; You can reach me professionally at the following address: ;; <PI:EMAIL:<EMAIL>END_PI>. I will be happy to answer ;; but don't mind to much if it takes some time. ;;} ;;{ ;; ## Acknowledgments ;; ;; I developed LaTTe after reading (devouring, more so) the following book: ;; ;; > **Type Theory and Formal Proof: an Introduction**. ;; > ;; > *PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI* ;; > ;; > Cambridge University Press, 2012 ;; ;; That's a heavily recommended lecture if you are interested in logic in general, ;; and the $\lambda$-calculus in particular. It is also the best source of information ;; to understand the underlying theory of LaTTe. However it is not a prerequisite ;; for learning and using LaTTe. ;; ;; I would also like to thank PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI as well as ;; the (few) contributors to LaTTE. And of course "big five" to the Clojure core ;; dev. team and all the community. ;; ;; ## About LaTTe ;; ;; **LaTTe** stands for "Laboratory for Type Theory Experiments" but it ;; is in fact a perfectly usable **proof assistant** for doing formal mathematics ;; and logic on a computer. It's far from being the most advanced proof assistance ;; technology but it still provides some interesting features. ;; ;; **Remark**: The double *TT* of LaTTe intentioanally looks like ;; Π the Greek capital letter Pi, which is one of the very few ;; constructors of the type theory used by LaTTe. ;; This will be explained, at least superficially, in the tutorial. ;; ;; The basic activity of a proof assistant user is to: ;; - state "fundamental truths" as **axioms**, ;; - write **definitions** of mathematical concepts (e.g. what it is to be a bijection) ;; - state properties about these concepts based on their definition, in the form of **theorem** (or lemma) statements ;; - and for each theorem (or lemma) statement, assist in writing a **formal proof** that it is, indeed, a theorem. ;; ;; So it's of no surprise that these are the main features of LaTTe. ;; But it is also a library for the Clojure programming language, which is unlike ;; many other proof assistants designed as standalone tools (one exception being the ;; members of the HOL family, as well as ACL2, both important sources of inspiration). ;; Thanks to the power of the Lisp language in general, ;; and its Clojure variant in particular, all the main features of the proof assistant ;; are usable directly in Clojure programs or at the REPL (Read-Eval-Print-Loop). ;; ;; Also this means that any Clojure development environment (e.g. Cider, Cursive) can ;; be used as a proof assistant GUI. And this is where most of the power of LaTTe lies. ;; Indeed, the Clojure IDEs support very advanced interactive features. Moreover, one can ;; extend the assistant directly in Clojure and without any intermediate such as a ;; plugins system or complex API. ;; In fact, you develop mathematics in Clojure ;; *exactly like* you develop programs in general, there's not difference at all! ;; ;; Moreover, the mathematical contents developed using LaTTe can be distributed ;; using the very powerful Clojure ecosystem based on the Maven packaging tool. ;; Also, there is a simple yet effective *proof certification* scheme that ;; corresponds to a form of compilation for the distributed content. ;; Proving things in type theory can become rather computationally intensive, ;; but a certified proof can be "taken for granted". ;; ;; Last but not least, the main innovative feature of LaTTe is its *declarative proof language*, ;; which makes the proofs follow the *natural deduction* style. The objective is to make LaTTe proofs ;; quite similar to standard mathematical proofs, at least strucutrally. One still has to ;; deal with the Clojure-enhanced Lisp notation, i.e. a perfectly non-ambiguous mathematical ;; notation, only slightly remote from "mainstream" mathematics. ;; ;;} ;;{ ;; ## Intended audience ;; ;; You might be interested in LaTTe because as a Clojure developer you are curious ;; about the lambda-calculus, dependent types, the Curry-Howard correspondance, ;; or simply formal logic and mathematics. ;; ;; You might also be interested in LaTTe to develop some formal mathematical contents, based on ;; an approach that is not exactly like other proof assistants. I very much welcome mathematical ;; contributions to the project! ;; ;; Finally, you might be interested in how one may embed a *domain-specific language*, the ;; Lisp way, in Clojure (thus with an extra-layer of data-orientation). Clojure the language ;; is still there when using LaTTe, but you're doing not only programming but also ;; mathematics and reasoning... The *same* difference, the Lisp way... ;; ;; Or maybe you're here and that's it! ;; ;; In any case you are very **Welcome**! ;; ;;} ;;{ ;; ## Prerequisites ;; ;; Since LaTTe is a Clojure library, it is required to know at least a bit of ;; Clojure and one of its development environment to follow this tutorial. ;; LaTTe works pretty well in Cider or Cursive, or simply with a basic editor ;; and the REPL. ;; Note that beyond basic functional programming principles, there's nothing much to ;; learn on the Clojure side. Still, if you don't know Clojure I can only recommend ;; to read the first few chapters of an introductory Clojure book. ;; ;;} ;;{ ;; ## License ;; ;; This document source is copyright (C) 2018 PI:NAME:<NAME>END_PI ;; distributed under the MIT License (cf. `LICENSE` file in the root directory). ;;} ;;{ ;; ## Tutorial plan ;; ;; The following steps should be followed in order: ;; ;; 1. first steps (install & friends) ;; 2. the rules of the game (a.k.a. lambda, forall and friends) ;; 3. a bit of logic: natural deduction ;; 4. a glimpse of (typed) set theory ;; 5. a sip of integer arithmetics ;; 6. proving in the large: from proof certification to Clojars deploy ;; ;;} (println "Let's begin!") ;; => nil
[ { "context": "eflate, sdch\",\n :X-Forwarded-For \"127.0.0.1, 127.0.0.2\",\n :CloudFront-Viewer-Country \"U", "end": 1394, "score": 0.9997550249099731, "start": 1385, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "h\",\n :X-Forwarded-For \"127.0.0.1, 127.0.0.2\",\n :CloudFront-Viewer-Country \"US\",\n :Ac", "end": 1405, "score": 0.9997628331184387, "start": 1396, "tag": "IP_ADDRESS", "value": "127.0.0.2" }, { "context": " nil,\n :sourceIp \"127.0.0.1\",\n :cognitoIdentityId nil,\n :", "end": 2271, "score": 0.9997212886810303, "start": 2262, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "stTimeEpoch 1428582896000,\n :accountId \"123456789012\",\n :apiId \"1234567890\"},\n :body ", "end": 3011, "score": 0.9995625019073486, "start": 2999, "tag": "KEY", "value": "123456789012" }, { "context": "late, sdch\"],\n :X-Forwarded-For [\"127.0.0.1, 127.0.0.2\"],\n :CloudFront-Viewer-Country [", "end": 3642, "score": 0.9996230602264404, "start": 3633, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "],\n :X-Forwarded-For [\"127.0.0.1, 127.0.0.2\"],\n :CloudFront-Viewer-Country [\"US\"],\n ", "end": 3653, "score": 0.9996216297149658, "start": 3644, "tag": "IP_ADDRESS", "value": "127.0.0.2" }, { "context": "eflate, sdch\",\n :X-Forwarded-For \"127.0.0.1, 127.0.0.2\",\n :CloudFront-Viewer-Country \"U", "end": 4930, "score": 0.9996821880340576, "start": 4921, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "h\",\n :X-Forwarded-For \"127.0.0.1, 127.0.0.2\",\n :CloudFront-Viewer-Country \"US\",\n :Ac", "end": 4941, "score": 0.9996893405914307, "start": 4932, "tag": "IP_ADDRESS", "value": "127.0.0.2" }, { "context": " nil,\n :sourceIp \"127.0.0.1\",\n :cognitoIdentityId nil,\n :", "end": 5808, "score": 0.9996987581253052, "start": 5799, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "stTimeEpoch 1428582896000,\n :accountId \"123456789012\",\n :apiId \"1234567890\"},\n :body ", "end": 6548, "score": 0.9995017647743225, "start": 6536, "tag": "KEY", "value": "123456789012" }, { "context": "nsecure-Requests [\"1\"],\n :X-Amz-Cf-Id\n [\"cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==\"],\n :CloudFront-Is-Tablet-Viewer [\"false\"],\n ", "end": 6778, "score": 0.9676113128662109, "start": 6721, "tag": "KEY", "value": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==\"" }, { "context": "late, sdch\"],\n :X-Forwarded-For [\"127.0.0.1, 127.0.0.2\"],\n :CloudFront-Viewer-Country [", "end": 7159, "score": 0.9997109174728394, "start": 7150, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "],\n :X-Forwarded-For [\"127.0.0.1, 127.0.0.2\"],\n :CloudFront-Viewer-Country [\"US\"],\n ", "end": 7170, "score": 0.9997079372406006, "start": 7161, "tag": "IP_ADDRESS", "value": "127.0.0.2" }, { "context": " :user {:id \"[email protected]\"\n :em", "end": 8347, "score": 0.9998922944068909, "start": 8325, "tag": "EMAIL", "value": "[email protected]" }, { "context": " :email \"[email protected]\",\n :r", "end": 8424, "score": 0.9999068379402161, "start": 8402, "tag": "EMAIL", "value": "[email protected]" }, { "context": " :user {:id \"[email protected]\"\n :em", "end": 9810, "score": 0.999910295009613, "start": 9788, "tag": "EMAIL", "value": "[email protected]" }, { "context": " :email \"[email protected]\",\n :r", "end": 9887, "score": 0.9999136924743652, "start": 9865, "tag": "EMAIL", "value": "[email protected]" } ]
test/lambda/api_test.clj
raiffeisenbankinternational/edd-core
4
(ns lambda.api-test (:require [lambda.core :refer [handle-request]] [clojure.string :as str] [lambda.util :refer [to-edn]] [lambda.filters :as fl] [lambda.util :as util] [clojure.test :refer :all] [lambda.core :as core] [lambda.jwt-test :as jwt-test] [lambda.test.fixture.client :refer [verify-traffic-json]] [lambda.test.fixture.core :refer [mock-core]]) (:import (clojure.lang ExceptionInfo))) (def cmd-id #uuid "c5c4d4df-0570-43c9-a0c5-2df32f3be124") (def dummy-cmd {:commands [{:id cmd-id :cmd-id :dummy-cmd}] :user {:selected-role :group-2}}) (defn base64request [body & {:keys [token path http-method] :or {token jwt-test/token}}] {:path (or path "/path/to/resource"), :queryStringParameters {:foo "bar"}, :pathParameters {:proxy "/path/to/resource"}, :headers {:Upgrade-Insecure-Requests "1", :X-Amz-Cf-Id "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", :CloudFront-Is-Tablet-Viewer "false", :CloudFront-Forwarded-Proto "https", :X-Forwarded-Proto "https", :X-Forwarded-Port "443", :x-authorization token :Accept "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", :Accept-Encoding "gzip, deflate, sdch", :X-Forwarded-For "127.0.0.1, 127.0.0.2", :CloudFront-Viewer-Country "US", :Accept-Language "en-US,en;q=0.8", :Cache-Control "max-age=0", :CloudFront-Is-Desktop-Viewer "true", :Via "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", :CloudFront-Is-SmartTV-Viewer "false", :CloudFront-Is-Mobile-Viewer "false", :Host "1234567890.execute-api.eu-central-1.amazonaws.com", :User-Agent "Custom User Agent String"}, :stageVariables {:baz "qux"}, :resource "/{proxy+}", :isBase64Encoded true, :multiValueQueryStringParameters {:foo ["bar"]}, :httpMethod (or http-method "POST"), :requestContext {:path "/prod/path/to/resource", :identity {:caller nil, :sourceIp "127.0.0.1", :cognitoIdentityId nil, :userAgent "Custom User Agent String", :cognitoAuthenticationProvider nil, :accessKey nil, :accountId nil, :user nil, :cognitoAuthenticationType nil, :cognitoIdentityPoolId nil, :userArn nil}, :stage "prod", :protocol "HTTP/1.1", :resourcePath "/{proxy+}", :resourceId "123456", :requestTime "09/Apr/2015:12:34:56 +0000", :requestId "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", :httpMethod "POST", :requestTimeEpoch 1428582896000, :accountId "123456789012", :apiId "1234567890"}, :body (util/base64encode (util/to-json body)), :multiValueHeaders {:Upgrade-Insecure-Requests ["1"], :X-Amz-Cf-Id ["cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA=="], :CloudFront-Is-Tablet-Viewer ["false"], :CloudFront-Forwarded-Proto ["https"], :X-Forwarded-Proto ["https"], :X-Forwarded-Port ["443"], :Accept ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], :Accept-Encoding ["gzip, deflate, sdch"], :X-Forwarded-For ["127.0.0.1, 127.0.0.2"], :CloudFront-Viewer-Country ["US"], :Accept-Language ["en-US,en;q=0.8"], :Cache-Control ["max-age=0"], :CloudFront-Is-Desktop-Viewer ["true"], :Via ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"], :CloudFront-Is-SmartTV-Viewer ["false"], :CloudFront-Is-Mobile-Viewer ["false"], :Host ["0123456789.execute-api.eu-central-1.amazonaws.com"], :User-Agent ["Custom User Agent String"]}}) (defn request [body & {:keys [token path http-method] :or {token jwt-test/token}}] {:path (or path "/path/to/resource"), :queryStringParameters {:foo "bar"}, :pathParameters {:proxy "/path/to/resource"}, :headers {:Upgrade-Insecure-Requests "1", :X-Amz-Cf-Id "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", :CloudFront-Is-Tablet-Viewer "false", :CloudFront-Forwarded-Proto "https", :X-Forwarded-Proto "https", :X-Forwarded-Port "443", :x-authorization token :Accept "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", :Accept-Encoding "gzip, deflate, sdch", :X-Forwarded-For "127.0.0.1, 127.0.0.2", :CloudFront-Viewer-Country "US", :Accept-Language "en-US,en;q=0.8", :Cache-Control "max-age=0", :CloudFront-Is-Desktop-Viewer "true", :Via "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", :CloudFront-Is-SmartTV-Viewer "false", :CloudFront-Is-Mobile-Viewer "false", :Host "1234567890.execute-api.eu-central-1.amazonaws.com", :User-Agent "Custom User Agent String"}, :stageVariables {:baz "qux"}, :resource "/{proxy+}", :isBase64Encoded false, :multiValueQueryStringParameters {:foo ["bar"]}, :httpMethod (or http-method "POST"), :requestContext {:path "/prod/path/to/resource", :identity {:caller nil, :sourceIp "127.0.0.1", :cognitoIdentityId nil, :userAgent "Custom User Agent String", :cognitoAuthenticationProvider nil, :accessKey nil, :accountId nil, :user nil, :cognitoAuthenticationType nil, :cognitoIdentityPoolId nil, :userArn nil}, :stage "prod", :protocol "HTTP/1.1", :resourcePath "/{proxy+}", :resourceId "123456", :requestTime "09/Apr/2015:12:34:56 +0000", :requestId "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", :httpMethod "POST", :requestTimeEpoch 1428582896000, :accountId "123456789012", :apiId "1234567890"}, :body (util/to-json body), :multiValueHeaders {:Upgrade-Insecure-Requests ["1"], :X-Amz-Cf-Id ["cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA=="], :CloudFront-Is-Tablet-Viewer ["false"], :CloudFront-Forwarded-Proto ["https"], :X-Forwarded-Proto ["https"], :X-Forwarded-Port ["443"], :Accept ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], :Accept-Encoding ["gzip, deflate, sdch"], :X-Forwarded-For ["127.0.0.1, 127.0.0.2"], :CloudFront-Viewer-Country ["US"], :Accept-Language ["en-US,en;q=0.8"], :Cache-Control ["max-age=0"], :CloudFront-Is-Desktop-Viewer ["true"], :Via ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"], :CloudFront-Is-SmartTV-Viewer ["false"], :CloudFront-Is-Mobile-Viewer ["false"], :Host ["0123456789.execute-api.eu-central-1.amazonaws.com"], :User-Agent ["Custom User Agent String"]}}) (defn api-request [& params] (util/to-json (apply request params))) (defn api-request-base64 [& params] (util/to-json (apply base64request params))) (deftest has-role-test (is (= nil (fl/has-role? {:roles []} nil)))) (deftest api-handler-test (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (do (verify-traffic-json [{:body {:body (util/to-json {:source dummy-cmd :user {:id "[email protected]" :email "[email protected]", :role :group-2 :roles [:anonymous :group-1 :group-2 :group-3]}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}])))) (deftest api-handler-test-base64 (mock-core :invocations [(api-request-base64 dummy-cmd)] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (do (verify-traffic-json [{:body {:body (util/to-json {:source dummy-cmd :user {:id "[email protected]" :email "[email protected]", :role :group-2 :roles [:anonymous :group-1 :group-2 :group-3]}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}])))) (deftest api-handler-invalid-token-test (mock-core :invocations [(api-request dummy-cmd :token "")] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error {:jwt :invalid}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-error-result (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:error "Some error"}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error "Some error"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-handler-exception (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] (throw (new RuntimeException "Some error"))) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error "Some error"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-bucket-filter-ignored (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:source body}) :filters [fl/from-bucket] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:source (request dummy-cmd)}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-health-check (mock-core :invocations [(api-request dummy-cmd :path "/health")] (core/start {} (fn [ctx body] {:healthy false}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:healthy true :build-id "b0"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-options-check (mock-core :invocations [(api-request dummy-cmd :http-method "OPTIONS")] (core/start {} (fn [ctx body] {:healthy false}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:healthy true :build-id "b0"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-custom-config (mock-core :env {"CustomConfig" (util/to-json {:a :b :c :d})} :invocations [(util/to-json {})] (core/start {} (fn [ctx body] (is (= {:a :b :c :d} (select-keys ctx [:a :c]))) {:source body :user (:user ctx)})) (do))) (deftest test-realm-filter (is (= :test (fl/get-realm {} {:roles [:some-role :realm-test]} :some-role))) (is (thrown? ExceptionInfo (fl/get-realm {} {:roles [:some-role]} :some-role))))
106366
(ns lambda.api-test (:require [lambda.core :refer [handle-request]] [clojure.string :as str] [lambda.util :refer [to-edn]] [lambda.filters :as fl] [lambda.util :as util] [clojure.test :refer :all] [lambda.core :as core] [lambda.jwt-test :as jwt-test] [lambda.test.fixture.client :refer [verify-traffic-json]] [lambda.test.fixture.core :refer [mock-core]]) (:import (clojure.lang ExceptionInfo))) (def cmd-id #uuid "c5c4d4df-0570-43c9-a0c5-2df32f3be124") (def dummy-cmd {:commands [{:id cmd-id :cmd-id :dummy-cmd}] :user {:selected-role :group-2}}) (defn base64request [body & {:keys [token path http-method] :or {token jwt-test/token}}] {:path (or path "/path/to/resource"), :queryStringParameters {:foo "bar"}, :pathParameters {:proxy "/path/to/resource"}, :headers {:Upgrade-Insecure-Requests "1", :X-Amz-Cf-Id "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", :CloudFront-Is-Tablet-Viewer "false", :CloudFront-Forwarded-Proto "https", :X-Forwarded-Proto "https", :X-Forwarded-Port "443", :x-authorization token :Accept "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", :Accept-Encoding "gzip, deflate, sdch", :X-Forwarded-For "127.0.0.1, 127.0.0.2", :CloudFront-Viewer-Country "US", :Accept-Language "en-US,en;q=0.8", :Cache-Control "max-age=0", :CloudFront-Is-Desktop-Viewer "true", :Via "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", :CloudFront-Is-SmartTV-Viewer "false", :CloudFront-Is-Mobile-Viewer "false", :Host "1234567890.execute-api.eu-central-1.amazonaws.com", :User-Agent "Custom User Agent String"}, :stageVariables {:baz "qux"}, :resource "/{proxy+}", :isBase64Encoded true, :multiValueQueryStringParameters {:foo ["bar"]}, :httpMethod (or http-method "POST"), :requestContext {:path "/prod/path/to/resource", :identity {:caller nil, :sourceIp "127.0.0.1", :cognitoIdentityId nil, :userAgent "Custom User Agent String", :cognitoAuthenticationProvider nil, :accessKey nil, :accountId nil, :user nil, :cognitoAuthenticationType nil, :cognitoIdentityPoolId nil, :userArn nil}, :stage "prod", :protocol "HTTP/1.1", :resourcePath "/{proxy+}", :resourceId "123456", :requestTime "09/Apr/2015:12:34:56 +0000", :requestId "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", :httpMethod "POST", :requestTimeEpoch 1428582896000, :accountId "<KEY>", :apiId "1234567890"}, :body (util/base64encode (util/to-json body)), :multiValueHeaders {:Upgrade-Insecure-Requests ["1"], :X-Amz-Cf-Id ["cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA=="], :CloudFront-Is-Tablet-Viewer ["false"], :CloudFront-Forwarded-Proto ["https"], :X-Forwarded-Proto ["https"], :X-Forwarded-Port ["443"], :Accept ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], :Accept-Encoding ["gzip, deflate, sdch"], :X-Forwarded-For ["127.0.0.1, 127.0.0.2"], :CloudFront-Viewer-Country ["US"], :Accept-Language ["en-US,en;q=0.8"], :Cache-Control ["max-age=0"], :CloudFront-Is-Desktop-Viewer ["true"], :Via ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"], :CloudFront-Is-SmartTV-Viewer ["false"], :CloudFront-Is-Mobile-Viewer ["false"], :Host ["0123456789.execute-api.eu-central-1.amazonaws.com"], :User-Agent ["Custom User Agent String"]}}) (defn request [body & {:keys [token path http-method] :or {token jwt-test/token}}] {:path (or path "/path/to/resource"), :queryStringParameters {:foo "bar"}, :pathParameters {:proxy "/path/to/resource"}, :headers {:Upgrade-Insecure-Requests "1", :X-Amz-Cf-Id "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", :CloudFront-Is-Tablet-Viewer "false", :CloudFront-Forwarded-Proto "https", :X-Forwarded-Proto "https", :X-Forwarded-Port "443", :x-authorization token :Accept "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", :Accept-Encoding "gzip, deflate, sdch", :X-Forwarded-For "127.0.0.1, 127.0.0.2", :CloudFront-Viewer-Country "US", :Accept-Language "en-US,en;q=0.8", :Cache-Control "max-age=0", :CloudFront-Is-Desktop-Viewer "true", :Via "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", :CloudFront-Is-SmartTV-Viewer "false", :CloudFront-Is-Mobile-Viewer "false", :Host "1234567890.execute-api.eu-central-1.amazonaws.com", :User-Agent "Custom User Agent String"}, :stageVariables {:baz "qux"}, :resource "/{proxy+}", :isBase64Encoded false, :multiValueQueryStringParameters {:foo ["bar"]}, :httpMethod (or http-method "POST"), :requestContext {:path "/prod/path/to/resource", :identity {:caller nil, :sourceIp "127.0.0.1", :cognitoIdentityId nil, :userAgent "Custom User Agent String", :cognitoAuthenticationProvider nil, :accessKey nil, :accountId nil, :user nil, :cognitoAuthenticationType nil, :cognitoIdentityPoolId nil, :userArn nil}, :stage "prod", :protocol "HTTP/1.1", :resourcePath "/{proxy+}", :resourceId "123456", :requestTime "09/Apr/2015:12:34:56 +0000", :requestId "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", :httpMethod "POST", :requestTimeEpoch 1428582896000, :accountId "<KEY>", :apiId "1234567890"}, :body (util/to-json body), :multiValueHeaders {:Upgrade-Insecure-Requests ["1"], :X-Amz-Cf-Id ["<KEY>], :CloudFront-Is-Tablet-Viewer ["false"], :CloudFront-Forwarded-Proto ["https"], :X-Forwarded-Proto ["https"], :X-Forwarded-Port ["443"], :Accept ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], :Accept-Encoding ["gzip, deflate, sdch"], :X-Forwarded-For ["127.0.0.1, 127.0.0.2"], :CloudFront-Viewer-Country ["US"], :Accept-Language ["en-US,en;q=0.8"], :Cache-Control ["max-age=0"], :CloudFront-Is-Desktop-Viewer ["true"], :Via ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"], :CloudFront-Is-SmartTV-Viewer ["false"], :CloudFront-Is-Mobile-Viewer ["false"], :Host ["0123456789.execute-api.eu-central-1.amazonaws.com"], :User-Agent ["Custom User Agent String"]}}) (defn api-request [& params] (util/to-json (apply request params))) (defn api-request-base64 [& params] (util/to-json (apply base64request params))) (deftest has-role-test (is (= nil (fl/has-role? {:roles []} nil)))) (deftest api-handler-test (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (do (verify-traffic-json [{:body {:body (util/to-json {:source dummy-cmd :user {:id "<EMAIL>" :email "<EMAIL>", :role :group-2 :roles [:anonymous :group-1 :group-2 :group-3]}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}])))) (deftest api-handler-test-base64 (mock-core :invocations [(api-request-base64 dummy-cmd)] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (do (verify-traffic-json [{:body {:body (util/to-json {:source dummy-cmd :user {:id "<EMAIL>" :email "<EMAIL>", :role :group-2 :roles [:anonymous :group-1 :group-2 :group-3]}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}])))) (deftest api-handler-invalid-token-test (mock-core :invocations [(api-request dummy-cmd :token "")] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error {:jwt :invalid}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-error-result (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:error "Some error"}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error "Some error"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-handler-exception (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] (throw (new RuntimeException "Some error"))) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error "Some error"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-bucket-filter-ignored (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:source body}) :filters [fl/from-bucket] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:source (request dummy-cmd)}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-health-check (mock-core :invocations [(api-request dummy-cmd :path "/health")] (core/start {} (fn [ctx body] {:healthy false}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:healthy true :build-id "b0"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-options-check (mock-core :invocations [(api-request dummy-cmd :http-method "OPTIONS")] (core/start {} (fn [ctx body] {:healthy false}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:healthy true :build-id "b0"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-custom-config (mock-core :env {"CustomConfig" (util/to-json {:a :b :c :d})} :invocations [(util/to-json {})] (core/start {} (fn [ctx body] (is (= {:a :b :c :d} (select-keys ctx [:a :c]))) {:source body :user (:user ctx)})) (do))) (deftest test-realm-filter (is (= :test (fl/get-realm {} {:roles [:some-role :realm-test]} :some-role))) (is (thrown? ExceptionInfo (fl/get-realm {} {:roles [:some-role]} :some-role))))
true
(ns lambda.api-test (:require [lambda.core :refer [handle-request]] [clojure.string :as str] [lambda.util :refer [to-edn]] [lambda.filters :as fl] [lambda.util :as util] [clojure.test :refer :all] [lambda.core :as core] [lambda.jwt-test :as jwt-test] [lambda.test.fixture.client :refer [verify-traffic-json]] [lambda.test.fixture.core :refer [mock-core]]) (:import (clojure.lang ExceptionInfo))) (def cmd-id #uuid "c5c4d4df-0570-43c9-a0c5-2df32f3be124") (def dummy-cmd {:commands [{:id cmd-id :cmd-id :dummy-cmd}] :user {:selected-role :group-2}}) (defn base64request [body & {:keys [token path http-method] :or {token jwt-test/token}}] {:path (or path "/path/to/resource"), :queryStringParameters {:foo "bar"}, :pathParameters {:proxy "/path/to/resource"}, :headers {:Upgrade-Insecure-Requests "1", :X-Amz-Cf-Id "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", :CloudFront-Is-Tablet-Viewer "false", :CloudFront-Forwarded-Proto "https", :X-Forwarded-Proto "https", :X-Forwarded-Port "443", :x-authorization token :Accept "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", :Accept-Encoding "gzip, deflate, sdch", :X-Forwarded-For "127.0.0.1, 127.0.0.2", :CloudFront-Viewer-Country "US", :Accept-Language "en-US,en;q=0.8", :Cache-Control "max-age=0", :CloudFront-Is-Desktop-Viewer "true", :Via "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", :CloudFront-Is-SmartTV-Viewer "false", :CloudFront-Is-Mobile-Viewer "false", :Host "1234567890.execute-api.eu-central-1.amazonaws.com", :User-Agent "Custom User Agent String"}, :stageVariables {:baz "qux"}, :resource "/{proxy+}", :isBase64Encoded true, :multiValueQueryStringParameters {:foo ["bar"]}, :httpMethod (or http-method "POST"), :requestContext {:path "/prod/path/to/resource", :identity {:caller nil, :sourceIp "127.0.0.1", :cognitoIdentityId nil, :userAgent "Custom User Agent String", :cognitoAuthenticationProvider nil, :accessKey nil, :accountId nil, :user nil, :cognitoAuthenticationType nil, :cognitoIdentityPoolId nil, :userArn nil}, :stage "prod", :protocol "HTTP/1.1", :resourcePath "/{proxy+}", :resourceId "123456", :requestTime "09/Apr/2015:12:34:56 +0000", :requestId "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", :httpMethod "POST", :requestTimeEpoch 1428582896000, :accountId "PI:KEY:<KEY>END_PI", :apiId "1234567890"}, :body (util/base64encode (util/to-json body)), :multiValueHeaders {:Upgrade-Insecure-Requests ["1"], :X-Amz-Cf-Id ["cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA=="], :CloudFront-Is-Tablet-Viewer ["false"], :CloudFront-Forwarded-Proto ["https"], :X-Forwarded-Proto ["https"], :X-Forwarded-Port ["443"], :Accept ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], :Accept-Encoding ["gzip, deflate, sdch"], :X-Forwarded-For ["127.0.0.1, 127.0.0.2"], :CloudFront-Viewer-Country ["US"], :Accept-Language ["en-US,en;q=0.8"], :Cache-Control ["max-age=0"], :CloudFront-Is-Desktop-Viewer ["true"], :Via ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"], :CloudFront-Is-SmartTV-Viewer ["false"], :CloudFront-Is-Mobile-Viewer ["false"], :Host ["0123456789.execute-api.eu-central-1.amazonaws.com"], :User-Agent ["Custom User Agent String"]}}) (defn request [body & {:keys [token path http-method] :or {token jwt-test/token}}] {:path (or path "/path/to/resource"), :queryStringParameters {:foo "bar"}, :pathParameters {:proxy "/path/to/resource"}, :headers {:Upgrade-Insecure-Requests "1", :X-Amz-Cf-Id "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", :CloudFront-Is-Tablet-Viewer "false", :CloudFront-Forwarded-Proto "https", :X-Forwarded-Proto "https", :X-Forwarded-Port "443", :x-authorization token :Accept "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", :Accept-Encoding "gzip, deflate, sdch", :X-Forwarded-For "127.0.0.1, 127.0.0.2", :CloudFront-Viewer-Country "US", :Accept-Language "en-US,en;q=0.8", :Cache-Control "max-age=0", :CloudFront-Is-Desktop-Viewer "true", :Via "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", :CloudFront-Is-SmartTV-Viewer "false", :CloudFront-Is-Mobile-Viewer "false", :Host "1234567890.execute-api.eu-central-1.amazonaws.com", :User-Agent "Custom User Agent String"}, :stageVariables {:baz "qux"}, :resource "/{proxy+}", :isBase64Encoded false, :multiValueQueryStringParameters {:foo ["bar"]}, :httpMethod (or http-method "POST"), :requestContext {:path "/prod/path/to/resource", :identity {:caller nil, :sourceIp "127.0.0.1", :cognitoIdentityId nil, :userAgent "Custom User Agent String", :cognitoAuthenticationProvider nil, :accessKey nil, :accountId nil, :user nil, :cognitoAuthenticationType nil, :cognitoIdentityPoolId nil, :userArn nil}, :stage "prod", :protocol "HTTP/1.1", :resourcePath "/{proxy+}", :resourceId "123456", :requestTime "09/Apr/2015:12:34:56 +0000", :requestId "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", :httpMethod "POST", :requestTimeEpoch 1428582896000, :accountId "PI:KEY:<KEY>END_PI", :apiId "1234567890"}, :body (util/to-json body), :multiValueHeaders {:Upgrade-Insecure-Requests ["1"], :X-Amz-Cf-Id ["PI:KEY:<KEY>END_PI], :CloudFront-Is-Tablet-Viewer ["false"], :CloudFront-Forwarded-Proto ["https"], :X-Forwarded-Proto ["https"], :X-Forwarded-Port ["443"], :Accept ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"], :Accept-Encoding ["gzip, deflate, sdch"], :X-Forwarded-For ["127.0.0.1, 127.0.0.2"], :CloudFront-Viewer-Country ["US"], :Accept-Language ["en-US,en;q=0.8"], :Cache-Control ["max-age=0"], :CloudFront-Is-Desktop-Viewer ["true"], :Via ["1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)"], :CloudFront-Is-SmartTV-Viewer ["false"], :CloudFront-Is-Mobile-Viewer ["false"], :Host ["0123456789.execute-api.eu-central-1.amazonaws.com"], :User-Agent ["Custom User Agent String"]}}) (defn api-request [& params] (util/to-json (apply request params))) (defn api-request-base64 [& params] (util/to-json (apply base64request params))) (deftest has-role-test (is (= nil (fl/has-role? {:roles []} nil)))) (deftest api-handler-test (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (do (verify-traffic-json [{:body {:body (util/to-json {:source dummy-cmd :user {:id "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI", :role :group-2 :roles [:anonymous :group-1 :group-2 :group-3]}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}])))) (deftest api-handler-test-base64 (mock-core :invocations [(api-request-base64 dummy-cmd)] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (do (verify-traffic-json [{:body {:body (util/to-json {:source dummy-cmd :user {:id "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI", :role :group-2 :roles [:anonymous :group-1 :group-2 :group-3]}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}])))) (deftest api-handler-invalid-token-test (mock-core :invocations [(api-request dummy-cmd :token "")] (core/start {} (fn [ctx body] {:source body :user (:user ctx)}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error {:jwt :invalid}}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-error-result (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:error "Some error"}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error "Some error"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-handler-exception (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] (throw (new RuntimeException "Some error"))) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:error "Some error"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-bucket-filter-ignored (mock-core :invocations [(api-request dummy-cmd)] (core/start {} (fn [ctx body] {:source body}) :filters [fl/from-bucket] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:source (request dummy-cmd)}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-health-check (mock-core :invocations [(api-request dummy-cmd :path "/health")] (core/start {} (fn [ctx body] {:healthy false}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:healthy true :build-id "b0"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-options-check (mock-core :invocations [(api-request dummy-cmd :http-method "OPTIONS")] (core/start {} (fn [ctx body] {:healthy false}) :filters [fl/from-api] :post-filter fl/to-api) (verify-traffic-json [{:body {:body (util/to-json {:healthy true :build-id "b0"}) :headers {:Access-Control-Allow-Headers "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" :Access-Control-Allow-Methods "OPTIONS,POST,PUT,GET" :Access-Control-Allow-Origin "*" :Access-Control-Expose-Headers "*" :Content-Type "application/json"} :isBase64Encoded false :statusCode 200} :method :post :url "http://mock/2018-06-01/runtime/invocation/0/response"} {:method :get :timeout 90000000 :url "http://mock/2018-06-01/runtime/invocation/next"}]))) (deftest test-custom-config (mock-core :env {"CustomConfig" (util/to-json {:a :b :c :d})} :invocations [(util/to-json {})] (core/start {} (fn [ctx body] (is (= {:a :b :c :d} (select-keys ctx [:a :c]))) {:source body :user (:user ctx)})) (do))) (deftest test-realm-filter (is (= :test (fl/get-realm {} {:roles [:some-role :realm-test]} :some-role))) (is (thrown? ExceptionInfo (fl/get-realm {} {:roles [:some-role]} :some-role))))
[ { "context": "\")\n\n; --- Day 4: The Ideal Stocking Stuffer ---\n\n; Santa needs help mining some AdventCoins (very similar ", "end": 123, "score": 0.7708238959312439, "start": 118, "tag": "NAME", "value": "Santa" }, { "context": "r in decimal. To mine AdventCoins, you\n; must find Santa the lowest positive number (no leading zeroes", "end": 521, "score": 0.5991746187210083, "start": 520, "tag": "NAME", "value": "S" }, { "context": "hash.\n\n; For example:\n\n; - If your secret key is abcdef, the answer is 609043, because the MD5 hash\n; ", "end": 667, "score": 0.9982553720474243, "start": 661, "tag": "KEY", "value": "abcdef" }, { "context": "; - If your secret key is abcdef, the answer is 609043, because the MD5 hash\n; of abcdef609043 start", "end": 689, "score": 0.9168625473976135, "start": 683, "tag": "KEY", "value": "609043" }, { "context": " such number to do so.\n; - If your secret key is pqrstuv, the lowest number it combines with to make\n; ", "end": 860, "score": 0.9989311695098877, "start": 853, "tag": "KEY", "value": "pqrstuv" } ]
src/aoc/day4.clj
magopian/adventofcode
0
; http://adventofcode.com/day/4 (ns aoc.day4) (def input "iwrupvqb") ; --- Day 4: The Ideal Stocking Stuffer --- ; Santa needs help mining some AdventCoins (very similar to bitcoins) to use as ; gifts for all the economically forward-thinking little girls and boys. ; To do this, he needs to find MD5 hashes which, in hexadecimal, start with at ; least five zeroes. The input to the MD5 hash is some secret key (your puzzle ; input, given below) followed by a number in decimal. To mine AdventCoins, you ; must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) ; that produces such a hash. ; For example: ; - If your secret key is abcdef, the answer is 609043, because the MD5 hash ; of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the ; lowest such number to do so. ; - If your secret key is pqrstuv, the lowest number it combines with to make ; an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash ; of pqrstuv1048970 looks like 000006136ef.... (defn digest [s] (.digest (doto (java.security.MessageDigest/getInstance "MD5") (.update (.getBytes s))))) (defn md5 [s] (apply str (map (partial format "%02x") (digest s)))) (defn coin? [num-zeroes secret-key number] (let [hashed (md5 (str secret-key number)) zeroes (repeat num-zeroes \0)] (= (take num-zeroes hashed) zeroes))) (def five-0-coin? (partial coin? 5)) (defn lowest-number [secret-key predicate] (first ; Take the first number that was not dropped. (drop-while #(not (predicate secret-key %)) ; Drop until we have a good result. (range)))) ; Infinite range of numbers. ; This is really slow, uncomment at your own risk. ; (assert (= 609043 (lowest-number "abcdef"))) ; (assert (= 1048970 (lowest-number "pqrstuv"))) ; This takes less than 10 seconds on a recent (2015) mbp. (defn part1 [] (println "First number which results in a hash with five zeroes:" (lowest-number input five-0-coin?))) ; --- Part Two --- ; Now find one that starts with six zeroes. (def six-0-coin? (partial coin? 6)) ; This takes less than 5 minutes on a recent (2015) mbp. (defn part2 [] (println "First number which results in a hash with six zeroes:" (lowest-number input six-0-coin?)))
75944
; http://adventofcode.com/day/4 (ns aoc.day4) (def input "iwrupvqb") ; --- Day 4: The Ideal Stocking Stuffer --- ; <NAME> needs help mining some AdventCoins (very similar to bitcoins) to use as ; gifts for all the economically forward-thinking little girls and boys. ; To do this, he needs to find MD5 hashes which, in hexadecimal, start with at ; least five zeroes. The input to the MD5 hash is some secret key (your puzzle ; input, given below) followed by a number in decimal. To mine AdventCoins, you ; must find <NAME>anta the lowest positive number (no leading zeroes: 1, 2, 3, ...) ; that produces such a hash. ; For example: ; - If your secret key is <KEY>, the answer is <KEY>, because the MD5 hash ; of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the ; lowest such number to do so. ; - If your secret key is <KEY>, the lowest number it combines with to make ; an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash ; of pqrstuv1048970 looks like 000006136ef.... (defn digest [s] (.digest (doto (java.security.MessageDigest/getInstance "MD5") (.update (.getBytes s))))) (defn md5 [s] (apply str (map (partial format "%02x") (digest s)))) (defn coin? [num-zeroes secret-key number] (let [hashed (md5 (str secret-key number)) zeroes (repeat num-zeroes \0)] (= (take num-zeroes hashed) zeroes))) (def five-0-coin? (partial coin? 5)) (defn lowest-number [secret-key predicate] (first ; Take the first number that was not dropped. (drop-while #(not (predicate secret-key %)) ; Drop until we have a good result. (range)))) ; Infinite range of numbers. ; This is really slow, uncomment at your own risk. ; (assert (= 609043 (lowest-number "abcdef"))) ; (assert (= 1048970 (lowest-number "pqrstuv"))) ; This takes less than 10 seconds on a recent (2015) mbp. (defn part1 [] (println "First number which results in a hash with five zeroes:" (lowest-number input five-0-coin?))) ; --- Part Two --- ; Now find one that starts with six zeroes. (def six-0-coin? (partial coin? 6)) ; This takes less than 5 minutes on a recent (2015) mbp. (defn part2 [] (println "First number which results in a hash with six zeroes:" (lowest-number input six-0-coin?)))
true
; http://adventofcode.com/day/4 (ns aoc.day4) (def input "iwrupvqb") ; --- Day 4: The Ideal Stocking Stuffer --- ; PI:NAME:<NAME>END_PI needs help mining some AdventCoins (very similar to bitcoins) to use as ; gifts for all the economically forward-thinking little girls and boys. ; To do this, he needs to find MD5 hashes which, in hexadecimal, start with at ; least five zeroes. The input to the MD5 hash is some secret key (your puzzle ; input, given below) followed by a number in decimal. To mine AdventCoins, you ; must find PI:NAME:<NAME>END_PIanta the lowest positive number (no leading zeroes: 1, 2, 3, ...) ; that produces such a hash. ; For example: ; - If your secret key is PI:KEY:<KEY>END_PI, the answer is PI:KEY:<KEY>END_PI, because the MD5 hash ; of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the ; lowest such number to do so. ; - If your secret key is PI:KEY:<KEY>END_PI, the lowest number it combines with to make ; an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash ; of pqrstuv1048970 looks like 000006136ef.... (defn digest [s] (.digest (doto (java.security.MessageDigest/getInstance "MD5") (.update (.getBytes s))))) (defn md5 [s] (apply str (map (partial format "%02x") (digest s)))) (defn coin? [num-zeroes secret-key number] (let [hashed (md5 (str secret-key number)) zeroes (repeat num-zeroes \0)] (= (take num-zeroes hashed) zeroes))) (def five-0-coin? (partial coin? 5)) (defn lowest-number [secret-key predicate] (first ; Take the first number that was not dropped. (drop-while #(not (predicate secret-key %)) ; Drop until we have a good result. (range)))) ; Infinite range of numbers. ; This is really slow, uncomment at your own risk. ; (assert (= 609043 (lowest-number "abcdef"))) ; (assert (= 1048970 (lowest-number "pqrstuv"))) ; This takes less than 10 seconds on a recent (2015) mbp. (defn part1 [] (println "First number which results in a hash with five zeroes:" (lowest-number input five-0-coin?))) ; --- Part Two --- ; Now find one that starts with six zeroes. (def six-0-coin? (partial coin? 6)) ; This takes less than 5 minutes on a recent (2015) mbp. (defn part2 [] (println "First number which results in a hash with six zeroes:" (lowest-number input six-0-coin?)))
[ { "context": "ollects results from workers via that socket\n;;\n;; Isaiah Peng <[email protected]>\n;;\n\n(defn -main []\n (let [ct", "end": 209, "score": 0.9998717904090881, "start": 198, "tag": "NAME", "value": "Isaiah Peng" }, { "context": "s from workers via that socket\n;;\n;; Isaiah Peng <[email protected]>\n;;\n\n(defn -main []\n (let [ctx (mq/context 1)\n ", "end": 228, "score": 0.9999242424964905, "start": 211, "tag": "EMAIL", "value": "[email protected]" } ]
docs/zeroMQ-guide2/examples/Clojure/tasksink.clj
krattai/noo-ebs
2
(ns tasksink (:refer-clojure :exclude [send]) (:require [zhelpers :as mq])) ;; ;; Task sink ;; Binds PULL socket to tcp://localhost:5558 ;; Collects results from workers via that socket ;; ;; Isaiah Peng <[email protected]> ;; (defn -main [] (let [ctx (mq/context 1) receiver (mq/socket ctx mq/pull)] (mq/bind receiver "tcp://*:5558") ; Wait for start of batch (mq/recv receiver 0) (let [tstart (System/currentTimeMillis)] (dotimes [i 100] (mq/recv receiver) (if (= i (-> (int (/ i 10)) (* 10 ))) (print ":") (print "."))) ;; Calculate and report duration of batch (println (str "Total elapsed time:" (- (System/currentTimeMillis) tstart) " msec")) (.close receiver) (.term ctx))))
56700
(ns tasksink (:refer-clojure :exclude [send]) (:require [zhelpers :as mq])) ;; ;; Task sink ;; Binds PULL socket to tcp://localhost:5558 ;; Collects results from workers via that socket ;; ;; <NAME> <<EMAIL>> ;; (defn -main [] (let [ctx (mq/context 1) receiver (mq/socket ctx mq/pull)] (mq/bind receiver "tcp://*:5558") ; Wait for start of batch (mq/recv receiver 0) (let [tstart (System/currentTimeMillis)] (dotimes [i 100] (mq/recv receiver) (if (= i (-> (int (/ i 10)) (* 10 ))) (print ":") (print "."))) ;; Calculate and report duration of batch (println (str "Total elapsed time:" (- (System/currentTimeMillis) tstart) " msec")) (.close receiver) (.term ctx))))
true
(ns tasksink (:refer-clojure :exclude [send]) (:require [zhelpers :as mq])) ;; ;; Task sink ;; Binds PULL socket to tcp://localhost:5558 ;; Collects results from workers via that socket ;; ;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; (defn -main [] (let [ctx (mq/context 1) receiver (mq/socket ctx mq/pull)] (mq/bind receiver "tcp://*:5558") ; Wait for start of batch (mq/recv receiver 0) (let [tstart (System/currentTimeMillis)] (dotimes [i 100] (mq/recv receiver) (if (= i (-> (int (/ i 10)) (* 10 ))) (print ":") (print "."))) ;; Calculate and report duration of batch (println (str "Total elapsed time:" (- (System/currentTimeMillis) tstart) " msec")) (.close receiver) (.term ctx))))
[ { "context": "ed\"})\n grape (default-conn/create! {:name \"grape\"})]\n (is (= (default-conn/update! {:appearance", "end": 2689, "score": 0.7036882638931274, "start": 2684, "tag": "NAME", "value": "grape" }, { "context": "ed\"})\n grape (default-conn/create! {:name \"grape\"})]\n (is (= (default-conn/delete! {:cost nil})", "end": 3763, "score": 0.6088213324546814, "start": 3758, "tag": "NAME", "value": "grape" } ]
test/simple_crud_jdbc/core_test.clj
adambaker/simple-crud-jdbc
1
(ns simple-crud-jdbc.core-test (:require [clojure.test :refer :all] [environ.core :refer [env]] [clojure.java.jdbc :as jdbc] [conman.core :refer [connect! disconnect! with-transaction]] [simple-crud-jdbc.core])) (def ^:dynamic *db* nil) (use-fixtures :once (fn [tests] (binding [*db* (connect! {:jdbc-url (env :db-url)})] (jdbc/db-do-commands *db* (jdbc/create-table-ddl :fruit [[:id "serial" :primary :key] [:name "varchar(32)"] [:appearance "varchar(32)"] [:cost :int]])) (tests) (jdbc/db-do-commands *db* (jdbc/drop-table-ddl :fruit)) (disconnect! *db*)))) (create-ns 'default-conn) (create-ns 'default-no-conn) (in-ns 'default-conn) (simple-crud-jdbc.core/crud-for :fruit {:connection simple-crud-jdbc.core-test/*db*}) (in-ns 'default-no-conn) (simple-crud-jdbc.core/crud-for :fruit) (in-ns 'simple-crud-jdbc.core-test) (use-fixtures :each (fn [tests] (with-transaction [*db*] (jdbc/db-set-rollback-only! *db*) (tests)))) (deftest default-conn-create-read! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear", :appearance "pear shaped", :cost 230}) grape (default-conn/create! {:name "grape", :appearance "purple", :cost 210}) grapefruit (default-conn/create! {:name "grapefruit", :appearance "grapefruit shaped" :cost 100})] (is (= (:count (first (jdbc/query *db* "select count(*) from fruit"))) 4)) (is (= (default-conn/read-one {:id (orange :id)}) orange)) (is (= (set (default-conn/read-all [:or [:like :name "grape%"] [:like :appearance "%shaped"]])) #{pear grape grapefruit})) ;call in different txn, returns nil (is (= (default-conn/read-one {:connection-uri (env :db-url)} {:id (orange :id)}) nil) "can still specify a connection to override default") )) (deftest default-conn-update! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear" :appearance "pear shaped"}) grape (default-conn/create! {:name "grape"})] (is (= (default-conn/update! {:appearance "more of a yellowish-orange"} {:id (orange :id)}) 1)) (is (= (default-conn/read-one {:name "orange"}) (assoc orange :appearance "more of a yellowish-orange"))) (is (= (default-conn/update! {:cost 100} {:cost nil}) 2)) (is (= (set (default-conn/read-all true)) #{(assoc orange :appearance "more of a yellowish-orange") (assoc pear :cost 100) (assoc grape :cost 100)})) (is (= (default-conn/update! {:appearance nil} [:<> :appearance nil]) 2)) (is (= (set (default-conn/read-all true)) #{(assoc orange :appearance nil) (assoc pear :cost 100 :appearance nil) (assoc grape :cost 100)})) )) (deftest default-conn-delete! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear" :appearance "pear shaped"}) grape (default-conn/create! {:name "grape"})] (is (= (default-conn/delete! {:cost nil}) 2)) (is (= (default-conn/read-all true) [orange])) (is (= (default-conn/delete! {:id (orange :id)}) 1)) (is (= (default-conn/read-all true) []))))
115633
(ns simple-crud-jdbc.core-test (:require [clojure.test :refer :all] [environ.core :refer [env]] [clojure.java.jdbc :as jdbc] [conman.core :refer [connect! disconnect! with-transaction]] [simple-crud-jdbc.core])) (def ^:dynamic *db* nil) (use-fixtures :once (fn [tests] (binding [*db* (connect! {:jdbc-url (env :db-url)})] (jdbc/db-do-commands *db* (jdbc/create-table-ddl :fruit [[:id "serial" :primary :key] [:name "varchar(32)"] [:appearance "varchar(32)"] [:cost :int]])) (tests) (jdbc/db-do-commands *db* (jdbc/drop-table-ddl :fruit)) (disconnect! *db*)))) (create-ns 'default-conn) (create-ns 'default-no-conn) (in-ns 'default-conn) (simple-crud-jdbc.core/crud-for :fruit {:connection simple-crud-jdbc.core-test/*db*}) (in-ns 'default-no-conn) (simple-crud-jdbc.core/crud-for :fruit) (in-ns 'simple-crud-jdbc.core-test) (use-fixtures :each (fn [tests] (with-transaction [*db*] (jdbc/db-set-rollback-only! *db*) (tests)))) (deftest default-conn-create-read! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear", :appearance "pear shaped", :cost 230}) grape (default-conn/create! {:name "grape", :appearance "purple", :cost 210}) grapefruit (default-conn/create! {:name "grapefruit", :appearance "grapefruit shaped" :cost 100})] (is (= (:count (first (jdbc/query *db* "select count(*) from fruit"))) 4)) (is (= (default-conn/read-one {:id (orange :id)}) orange)) (is (= (set (default-conn/read-all [:or [:like :name "grape%"] [:like :appearance "%shaped"]])) #{pear grape grapefruit})) ;call in different txn, returns nil (is (= (default-conn/read-one {:connection-uri (env :db-url)} {:id (orange :id)}) nil) "can still specify a connection to override default") )) (deftest default-conn-update! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear" :appearance "pear shaped"}) grape (default-conn/create! {:name "<NAME>"})] (is (= (default-conn/update! {:appearance "more of a yellowish-orange"} {:id (orange :id)}) 1)) (is (= (default-conn/read-one {:name "orange"}) (assoc orange :appearance "more of a yellowish-orange"))) (is (= (default-conn/update! {:cost 100} {:cost nil}) 2)) (is (= (set (default-conn/read-all true)) #{(assoc orange :appearance "more of a yellowish-orange") (assoc pear :cost 100) (assoc grape :cost 100)})) (is (= (default-conn/update! {:appearance nil} [:<> :appearance nil]) 2)) (is (= (set (default-conn/read-all true)) #{(assoc orange :appearance nil) (assoc pear :cost 100 :appearance nil) (assoc grape :cost 100)})) )) (deftest default-conn-delete! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear" :appearance "pear shaped"}) grape (default-conn/create! {:name "<NAME>"})] (is (= (default-conn/delete! {:cost nil}) 2)) (is (= (default-conn/read-all true) [orange])) (is (= (default-conn/delete! {:id (orange :id)}) 1)) (is (= (default-conn/read-all true) []))))
true
(ns simple-crud-jdbc.core-test (:require [clojure.test :refer :all] [environ.core :refer [env]] [clojure.java.jdbc :as jdbc] [conman.core :refer [connect! disconnect! with-transaction]] [simple-crud-jdbc.core])) (def ^:dynamic *db* nil) (use-fixtures :once (fn [tests] (binding [*db* (connect! {:jdbc-url (env :db-url)})] (jdbc/db-do-commands *db* (jdbc/create-table-ddl :fruit [[:id "serial" :primary :key] [:name "varchar(32)"] [:appearance "varchar(32)"] [:cost :int]])) (tests) (jdbc/db-do-commands *db* (jdbc/drop-table-ddl :fruit)) (disconnect! *db*)))) (create-ns 'default-conn) (create-ns 'default-no-conn) (in-ns 'default-conn) (simple-crud-jdbc.core/crud-for :fruit {:connection simple-crud-jdbc.core-test/*db*}) (in-ns 'default-no-conn) (simple-crud-jdbc.core/crud-for :fruit) (in-ns 'simple-crud-jdbc.core-test) (use-fixtures :each (fn [tests] (with-transaction [*db*] (jdbc/db-set-rollback-only! *db*) (tests)))) (deftest default-conn-create-read! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear", :appearance "pear shaped", :cost 230}) grape (default-conn/create! {:name "grape", :appearance "purple", :cost 210}) grapefruit (default-conn/create! {:name "grapefruit", :appearance "grapefruit shaped" :cost 100})] (is (= (:count (first (jdbc/query *db* "select count(*) from fruit"))) 4)) (is (= (default-conn/read-one {:id (orange :id)}) orange)) (is (= (set (default-conn/read-all [:or [:like :name "grape%"] [:like :appearance "%shaped"]])) #{pear grape grapefruit})) ;call in different txn, returns nil (is (= (default-conn/read-one {:connection-uri (env :db-url)} {:id (orange :id)}) nil) "can still specify a connection to override default") )) (deftest default-conn-update! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear" :appearance "pear shaped"}) grape (default-conn/create! {:name "PI:NAME:<NAME>END_PI"})] (is (= (default-conn/update! {:appearance "more of a yellowish-orange"} {:id (orange :id)}) 1)) (is (= (default-conn/read-one {:name "orange"}) (assoc orange :appearance "more of a yellowish-orange"))) (is (= (default-conn/update! {:cost 100} {:cost nil}) 2)) (is (= (set (default-conn/read-all true)) #{(assoc orange :appearance "more of a yellowish-orange") (assoc pear :cost 100) (assoc grape :cost 100)})) (is (= (default-conn/update! {:appearance nil} [:<> :appearance nil]) 2)) (is (= (set (default-conn/read-all true)) #{(assoc orange :appearance nil) (assoc pear :cost 100 :appearance nil) (assoc grape :cost 100)})) )) (deftest default-conn-delete! (let [orange (default-conn/create! {:name "orange", :appearance "orange", :cost 120}) pear (default-conn/create! {:name "pear" :appearance "pear shaped"}) grape (default-conn/create! {:name "PI:NAME:<NAME>END_PI"})] (is (= (default-conn/delete! {:cost nil}) 2)) (is (= (default-conn/read-all true) [orange])) (is (= (default-conn/delete! {:id (orange :id)}) 1)) (is (= (default-conn/read-all true) []))))
[ { "context": "www.fillmurray.com/300/200\"\n :alt \"Bill Murray is great!\"})\n(def img {:tag :img\n :attrs", "end": 9404, "score": 0.9985469579696655, "start": 9393, "tag": "NAME", "value": "Bill Murray" } ]
rss-saver-tests.clj
adam-james-v/rss-saver
4
(ns rss-saver.main-test (:require [clojure.string :as str] [clojure.data.xml :as xml] [clojure.java.io :as io] [clojure.zip :as zip] [clojure.java.shell :as sh :refer [sh]] [clojure.tools.cli :as cli] [clojure.test :as t :refer [deftest is]] [hiccup2.core :refer [html]])) ;; Zipper Tools ;; -------------- ;; https://ravi.pckl.me/short/functional-xml-editing-using-zippers-in-clojure/ (defn edit-nodes "Edit nodes from `zipper` that return `true` from the `matcher` predicate fn with the `editor` fn. Returns the root of the provided zipper, *not* a zipper. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil). The `editor` fn expects a `node` and returns a potentially modified `node`." [zipper matcher editor] (loop [loc zipper] (if (zip/end? loc) (zip/root loc) (if-let [matcher-result (matcher loc)] (let [new-loc (zip/edit loc editor)] (if (not (= (zip/node new-loc) (zip/node loc))) (recur (zip/next new-loc)) (recur (zip/next loc)))) (recur (zip/next loc)))))) (defn remove-nodes "Remove nodes from `zipper` that return `true` from the `matcher` predicate fn. Returns the root of the provided zipper, *not* a zipper. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil)." [zipper matcher] (loop [loc zipper] (if (zip/end? loc) (zip/root loc) (if-let [matcher-result (matcher loc)] (let [new-loc (zip/remove loc)] (recur (zip/next new-loc))) (recur (zip/next loc)))))) (defn get-nodes "Returns a list of nodes from `zipper` that return `true` from the `matcher` predicate fn. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil)." [zipper matcher] (loop [loc zipper acc []] (if (zip/end? loc) acc (if (matcher loc) (recur (zip/next loc) (conj acc (zip/node loc))) (recur (zip/next loc) acc))))) (defn match-tag "Returns a `matcher` fn that matches any node containing the specified `key` as its `:tag` value." [key] (fn [loc] (let [node (zip/node loc) {:keys [tag]} node] (= tag key)))) ;; Entry Nodes ;; ------------- (defn feed-str->entries "Returns a sequence of parsed article entry nodes from an XML feed string." [s] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (get-nodes (match-tag :entry)))) ;; Entry Transforms ;; ------------------ (defn normalize-entry "Normalizes the entry node by flattening content into a map." [entry] (let [content (filter map? (:content entry)) f (fn [{:keys [tag content] :as node}] (let [val (cond (= tag :link) (get-in node [:attrs :href]) :else (first content))] {tag val})) author-map (->> content (filter #(= (:tag %) :author)) first :content (filter map?) (map f) (apply merge))] (apply merge (conj (map f (remove #(= (:tag %) :author) content)) author-map)))) (defn unwrap-img-from-figure "Returns the simplified `:img` node from its parent node." [node] (let [img-node (-> node zip/xml-zip (get-nodes (match-tag :img)) first) new-attrs (-> img-node :attrs (dissoc :srcset :decoding :loading))] (assoc img-node :attrs new-attrs))) (defn clean-html "Cleans up the html string `s`. The string is well-formed html, but is coerced into XML conforming form by closing <br> and <img> tags. The emitted XML string has the <\\?xml...> tag stripped. This cleaning is done so that clojure.data.xml can continue to be used for parsing in later stages." [s] (let [s (-> s (str/replace "<br>" "<br></br>") (str/replace #"<img[\w\W]+?>" #(str %1 "</img>")))] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (edit-nodes (match-tag :figure) unwrap-img-from-figure) xml/emit-str (str/replace #"<\?xml[\w\W]+?>" "")))) ;; Node Transforms ;; ----------------- (defmulti node->hiccup (fn [node] (cond (map? node) (:tag node) (and (seqable? node) (not (string? node))) :list :else :string))) (defmethod node->hiccup :string [node] (when-not (= (str/trim node) "") node)) (defmethod node->hiccup :br [_] [:br]) (defmethod node->hiccup :div [node] (node->hiccup (:content node))) (defmethod node->hiccup :default [{:keys [tag attrs content]}] [tag attrs (node->hiccup content)]) (defmethod node->hiccup :img [{:keys [tag attrs]}] [tag (assoc attrs :style {:max-width 500})]) (defn de-dupe "Remove only consecutive duplicate entries from the `list`." [list] (->> list (partition-by identity) (map first))) (defn selective-flatten ([l] (selective-flatten [] l)) ([acc l] (if (seq l) (let [item (first l) xacc (if (or (string? item) (and (vector? item) (keyword? (first item)))) (conj acc item) (into [] (concat acc (selective-flatten item))))] (recur xacc (rest l))) (apply list acc)))) (defmethod node->hiccup :list [node] (->> node (map node->hiccup) (remove nil?) de-dupe selective-flatten)) (defn inline-elem? [item] (when (#{:em :strong :a} (first item)) true)) (defn inline? [item] (or (string? item) (inline-elem? item))) (defn group-inline "Groups the `list` of strings and Hiccup elements using the `inline?` predicate and wraps them in <p> tags. Once all groups are wrapped, the list is flattened again and any remaining <br> tags are removed." [list] (let [groups (partition-by inline? list) f (fn [l] (if (not= (first (first l)) :br) (into [:p] l) l))] (->> groups (map f) selective-flatten (remove #(= :br (first %)))))) ;; entry-> ;; --------- (defn html-str->hiccup "Parses and converts an html string `s` into a Hiccup data structure." [s] (-> s (xml/parse-str {:namespace-aware false}) node->hiccup group-inline de-dupe)) (defn entry->edn "Converts a parsed XML entry node into a Hiccup data structure." [entry] (let [entry (normalize-entry entry)] {:id (:id entry) :file-contents (assoc entry :post (->> entry :content clean-html html-str->hiccup))})) (defn readable-date "Format the date string `s` into a nicer form for display." [s] (as-> s s (str/split s #"[a-zA-Z]") (str/join " " s))) (defn entry->html "Converts a parsed XML entry node into an html document." [entry] (let [entry (normalize-entry entry) info-span (fn [label s] [:span {:style {:display "block" :margin-bottom "2px"}} [:strong label] s]) post (->> entry :content clean-html html-str->hiccup)] (assoc entry :file-contents (-> (str "<!DOCTYPE html>\n" (html {:mode :html} [:head [:meta {:charset "utf-8"}] [:title (:title entry)]] [:body [:div {:class "post-info"} (info-span "Author: " (:name entry)) (info-span "Email: " (:email entry)) (info-span "Published: " (readable-date (:published entry))) (info-span "Updated: " (readable-date (:updated entry)))] [:a {:href (:link entry)} [:h1 (:title entry)]] post])) (str/replace #"</br>" ""))))) ;; Tests ;; ------- ;; this is a pull from my feed.atom at a point where 7 posts existed (def entries (feed-str->entries (slurp "sample-feed.atom"))) (def raw-entry-content (:content (nth entries 4))) (def normalized-entry (normalize-entry (nth entries 4))) (def normalized-entry-keys #{:name :email :id :published :updated :link :title :content}) (deftest entry-tests (is (= 7 (count entries))) (is (seq? raw-entry-content)) (is (= (type (:content normalized-entry)) java.lang.String)) (is (= normalized-entry-keys (into #{} (keys normalized-entry))))) (defn get-figure-nodes [s] (let [s (-> s (str/replace "<br>" "<br></br>") (str/replace #"<img[\w\W]+?>" #(str %1 "</img>")))] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (get-nodes (match-tag :figure))))) (def fig-img (-> (:content normalized-entry) get-figure-nodes first)) (def unwrapped-img (unwrap-img-from-figure fig-img)) (deftest image-tests (is (= :figure (:tag fig-img))) (is (= :img (:tag unwrapped-img)))) (def some-string "Hi there!") (def empty-string " ") (def br {:tag :br :attrs {} :content '()}) (def img-attrs {:src "https://www.fillmurray.com/300/200" :alt "Bill Murray is great!"}) (def img {:tag :img :attrs img-attrs :content '()}) (def img-result [:img (merge img-attrs {:style {:max-width 500}})]) (def div {:tag :div :attrs {:a 1 :b 2} :content (list some-string br img)}) (def div-result (list "Hi there!" [:br] img-result)) (def default (assoc div :tag :anything)) (def default-result [:anything (:attrs div) div-result]) (def duplicates ["a" "a" "a" "b" "a" "c" "c" "d" "d" "c"]) (def nested (list (list (repeat 4 "a") (repeat 3 [:br]) "a" [:em "b"] "c"))) (deftest node->hiccup-tests (is (= (node->hiccup some-string) "Hi there!")) (is (nil? (node->hiccup empty-string))) (is (= (node->hiccup br) [:br])) (is (= (node->hiccup img) img-result)) (is (= (node->hiccup div) div-result)) (is (= (node->hiccup default) default-result)) (is (= (de-dupe duplicates) ["a" "b" "a" "c" "d" "c"])) (is (= (selective-flatten nested) (list "a" "a" "a" "a" [:br] [:br] [:br] "a" [:em "b"] "c"))) (is (= (group-inline (selective-flatten nested)) (list [:p "a" "a" "a" "a"] [:p "a" [:em "b"] "c"])))) (t/run-tests)
99923
(ns rss-saver.main-test (:require [clojure.string :as str] [clojure.data.xml :as xml] [clojure.java.io :as io] [clojure.zip :as zip] [clojure.java.shell :as sh :refer [sh]] [clojure.tools.cli :as cli] [clojure.test :as t :refer [deftest is]] [hiccup2.core :refer [html]])) ;; Zipper Tools ;; -------------- ;; https://ravi.pckl.me/short/functional-xml-editing-using-zippers-in-clojure/ (defn edit-nodes "Edit nodes from `zipper` that return `true` from the `matcher` predicate fn with the `editor` fn. Returns the root of the provided zipper, *not* a zipper. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil). The `editor` fn expects a `node` and returns a potentially modified `node`." [zipper matcher editor] (loop [loc zipper] (if (zip/end? loc) (zip/root loc) (if-let [matcher-result (matcher loc)] (let [new-loc (zip/edit loc editor)] (if (not (= (zip/node new-loc) (zip/node loc))) (recur (zip/next new-loc)) (recur (zip/next loc)))) (recur (zip/next loc)))))) (defn remove-nodes "Remove nodes from `zipper` that return `true` from the `matcher` predicate fn. Returns the root of the provided zipper, *not* a zipper. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil)." [zipper matcher] (loop [loc zipper] (if (zip/end? loc) (zip/root loc) (if-let [matcher-result (matcher loc)] (let [new-loc (zip/remove loc)] (recur (zip/next new-loc))) (recur (zip/next loc)))))) (defn get-nodes "Returns a list of nodes from `zipper` that return `true` from the `matcher` predicate fn. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil)." [zipper matcher] (loop [loc zipper acc []] (if (zip/end? loc) acc (if (matcher loc) (recur (zip/next loc) (conj acc (zip/node loc))) (recur (zip/next loc) acc))))) (defn match-tag "Returns a `matcher` fn that matches any node containing the specified `key` as its `:tag` value." [key] (fn [loc] (let [node (zip/node loc) {:keys [tag]} node] (= tag key)))) ;; Entry Nodes ;; ------------- (defn feed-str->entries "Returns a sequence of parsed article entry nodes from an XML feed string." [s] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (get-nodes (match-tag :entry)))) ;; Entry Transforms ;; ------------------ (defn normalize-entry "Normalizes the entry node by flattening content into a map." [entry] (let [content (filter map? (:content entry)) f (fn [{:keys [tag content] :as node}] (let [val (cond (= tag :link) (get-in node [:attrs :href]) :else (first content))] {tag val})) author-map (->> content (filter #(= (:tag %) :author)) first :content (filter map?) (map f) (apply merge))] (apply merge (conj (map f (remove #(= (:tag %) :author) content)) author-map)))) (defn unwrap-img-from-figure "Returns the simplified `:img` node from its parent node." [node] (let [img-node (-> node zip/xml-zip (get-nodes (match-tag :img)) first) new-attrs (-> img-node :attrs (dissoc :srcset :decoding :loading))] (assoc img-node :attrs new-attrs))) (defn clean-html "Cleans up the html string `s`. The string is well-formed html, but is coerced into XML conforming form by closing <br> and <img> tags. The emitted XML string has the <\\?xml...> tag stripped. This cleaning is done so that clojure.data.xml can continue to be used for parsing in later stages." [s] (let [s (-> s (str/replace "<br>" "<br></br>") (str/replace #"<img[\w\W]+?>" #(str %1 "</img>")))] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (edit-nodes (match-tag :figure) unwrap-img-from-figure) xml/emit-str (str/replace #"<\?xml[\w\W]+?>" "")))) ;; Node Transforms ;; ----------------- (defmulti node->hiccup (fn [node] (cond (map? node) (:tag node) (and (seqable? node) (not (string? node))) :list :else :string))) (defmethod node->hiccup :string [node] (when-not (= (str/trim node) "") node)) (defmethod node->hiccup :br [_] [:br]) (defmethod node->hiccup :div [node] (node->hiccup (:content node))) (defmethod node->hiccup :default [{:keys [tag attrs content]}] [tag attrs (node->hiccup content)]) (defmethod node->hiccup :img [{:keys [tag attrs]}] [tag (assoc attrs :style {:max-width 500})]) (defn de-dupe "Remove only consecutive duplicate entries from the `list`." [list] (->> list (partition-by identity) (map first))) (defn selective-flatten ([l] (selective-flatten [] l)) ([acc l] (if (seq l) (let [item (first l) xacc (if (or (string? item) (and (vector? item) (keyword? (first item)))) (conj acc item) (into [] (concat acc (selective-flatten item))))] (recur xacc (rest l))) (apply list acc)))) (defmethod node->hiccup :list [node] (->> node (map node->hiccup) (remove nil?) de-dupe selective-flatten)) (defn inline-elem? [item] (when (#{:em :strong :a} (first item)) true)) (defn inline? [item] (or (string? item) (inline-elem? item))) (defn group-inline "Groups the `list` of strings and Hiccup elements using the `inline?` predicate and wraps them in <p> tags. Once all groups are wrapped, the list is flattened again and any remaining <br> tags are removed." [list] (let [groups (partition-by inline? list) f (fn [l] (if (not= (first (first l)) :br) (into [:p] l) l))] (->> groups (map f) selective-flatten (remove #(= :br (first %)))))) ;; entry-> ;; --------- (defn html-str->hiccup "Parses and converts an html string `s` into a Hiccup data structure." [s] (-> s (xml/parse-str {:namespace-aware false}) node->hiccup group-inline de-dupe)) (defn entry->edn "Converts a parsed XML entry node into a Hiccup data structure." [entry] (let [entry (normalize-entry entry)] {:id (:id entry) :file-contents (assoc entry :post (->> entry :content clean-html html-str->hiccup))})) (defn readable-date "Format the date string `s` into a nicer form for display." [s] (as-> s s (str/split s #"[a-zA-Z]") (str/join " " s))) (defn entry->html "Converts a parsed XML entry node into an html document." [entry] (let [entry (normalize-entry entry) info-span (fn [label s] [:span {:style {:display "block" :margin-bottom "2px"}} [:strong label] s]) post (->> entry :content clean-html html-str->hiccup)] (assoc entry :file-contents (-> (str "<!DOCTYPE html>\n" (html {:mode :html} [:head [:meta {:charset "utf-8"}] [:title (:title entry)]] [:body [:div {:class "post-info"} (info-span "Author: " (:name entry)) (info-span "Email: " (:email entry)) (info-span "Published: " (readable-date (:published entry))) (info-span "Updated: " (readable-date (:updated entry)))] [:a {:href (:link entry)} [:h1 (:title entry)]] post])) (str/replace #"</br>" ""))))) ;; Tests ;; ------- ;; this is a pull from my feed.atom at a point where 7 posts existed (def entries (feed-str->entries (slurp "sample-feed.atom"))) (def raw-entry-content (:content (nth entries 4))) (def normalized-entry (normalize-entry (nth entries 4))) (def normalized-entry-keys #{:name :email :id :published :updated :link :title :content}) (deftest entry-tests (is (= 7 (count entries))) (is (seq? raw-entry-content)) (is (= (type (:content normalized-entry)) java.lang.String)) (is (= normalized-entry-keys (into #{} (keys normalized-entry))))) (defn get-figure-nodes [s] (let [s (-> s (str/replace "<br>" "<br></br>") (str/replace #"<img[\w\W]+?>" #(str %1 "</img>")))] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (get-nodes (match-tag :figure))))) (def fig-img (-> (:content normalized-entry) get-figure-nodes first)) (def unwrapped-img (unwrap-img-from-figure fig-img)) (deftest image-tests (is (= :figure (:tag fig-img))) (is (= :img (:tag unwrapped-img)))) (def some-string "Hi there!") (def empty-string " ") (def br {:tag :br :attrs {} :content '()}) (def img-attrs {:src "https://www.fillmurray.com/300/200" :alt "<NAME> is great!"}) (def img {:tag :img :attrs img-attrs :content '()}) (def img-result [:img (merge img-attrs {:style {:max-width 500}})]) (def div {:tag :div :attrs {:a 1 :b 2} :content (list some-string br img)}) (def div-result (list "Hi there!" [:br] img-result)) (def default (assoc div :tag :anything)) (def default-result [:anything (:attrs div) div-result]) (def duplicates ["a" "a" "a" "b" "a" "c" "c" "d" "d" "c"]) (def nested (list (list (repeat 4 "a") (repeat 3 [:br]) "a" [:em "b"] "c"))) (deftest node->hiccup-tests (is (= (node->hiccup some-string) "Hi there!")) (is (nil? (node->hiccup empty-string))) (is (= (node->hiccup br) [:br])) (is (= (node->hiccup img) img-result)) (is (= (node->hiccup div) div-result)) (is (= (node->hiccup default) default-result)) (is (= (de-dupe duplicates) ["a" "b" "a" "c" "d" "c"])) (is (= (selective-flatten nested) (list "a" "a" "a" "a" [:br] [:br] [:br] "a" [:em "b"] "c"))) (is (= (group-inline (selective-flatten nested)) (list [:p "a" "a" "a" "a"] [:p "a" [:em "b"] "c"])))) (t/run-tests)
true
(ns rss-saver.main-test (:require [clojure.string :as str] [clojure.data.xml :as xml] [clojure.java.io :as io] [clojure.zip :as zip] [clojure.java.shell :as sh :refer [sh]] [clojure.tools.cli :as cli] [clojure.test :as t :refer [deftest is]] [hiccup2.core :refer [html]])) ;; Zipper Tools ;; -------------- ;; https://ravi.pckl.me/short/functional-xml-editing-using-zippers-in-clojure/ (defn edit-nodes "Edit nodes from `zipper` that return `true` from the `matcher` predicate fn with the `editor` fn. Returns the root of the provided zipper, *not* a zipper. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil). The `editor` fn expects a `node` and returns a potentially modified `node`." [zipper matcher editor] (loop [loc zipper] (if (zip/end? loc) (zip/root loc) (if-let [matcher-result (matcher loc)] (let [new-loc (zip/edit loc editor)] (if (not (= (zip/node new-loc) (zip/node loc))) (recur (zip/next new-loc)) (recur (zip/next loc)))) (recur (zip/next loc)))))) (defn remove-nodes "Remove nodes from `zipper` that return `true` from the `matcher` predicate fn. Returns the root of the provided zipper, *not* a zipper. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil)." [zipper matcher] (loop [loc zipper] (if (zip/end? loc) (zip/root loc) (if-let [matcher-result (matcher loc)] (let [new-loc (zip/remove loc)] (recur (zip/next new-loc))) (recur (zip/next loc)))))) (defn get-nodes "Returns a list of nodes from `zipper` that return `true` from the `matcher` predicate fn. The `matcher` fn expects a zipper location, `loc`, and returns `true` (or some value) or `false` (or nil)." [zipper matcher] (loop [loc zipper acc []] (if (zip/end? loc) acc (if (matcher loc) (recur (zip/next loc) (conj acc (zip/node loc))) (recur (zip/next loc) acc))))) (defn match-tag "Returns a `matcher` fn that matches any node containing the specified `key` as its `:tag` value." [key] (fn [loc] (let [node (zip/node loc) {:keys [tag]} node] (= tag key)))) ;; Entry Nodes ;; ------------- (defn feed-str->entries "Returns a sequence of parsed article entry nodes from an XML feed string." [s] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (get-nodes (match-tag :entry)))) ;; Entry Transforms ;; ------------------ (defn normalize-entry "Normalizes the entry node by flattening content into a map." [entry] (let [content (filter map? (:content entry)) f (fn [{:keys [tag content] :as node}] (let [val (cond (= tag :link) (get-in node [:attrs :href]) :else (first content))] {tag val})) author-map (->> content (filter #(= (:tag %) :author)) first :content (filter map?) (map f) (apply merge))] (apply merge (conj (map f (remove #(= (:tag %) :author) content)) author-map)))) (defn unwrap-img-from-figure "Returns the simplified `:img` node from its parent node." [node] (let [img-node (-> node zip/xml-zip (get-nodes (match-tag :img)) first) new-attrs (-> img-node :attrs (dissoc :srcset :decoding :loading))] (assoc img-node :attrs new-attrs))) (defn clean-html "Cleans up the html string `s`. The string is well-formed html, but is coerced into XML conforming form by closing <br> and <img> tags. The emitted XML string has the <\\?xml...> tag stripped. This cleaning is done so that clojure.data.xml can continue to be used for parsing in later stages." [s] (let [s (-> s (str/replace "<br>" "<br></br>") (str/replace #"<img[\w\W]+?>" #(str %1 "</img>")))] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (edit-nodes (match-tag :figure) unwrap-img-from-figure) xml/emit-str (str/replace #"<\?xml[\w\W]+?>" "")))) ;; Node Transforms ;; ----------------- (defmulti node->hiccup (fn [node] (cond (map? node) (:tag node) (and (seqable? node) (not (string? node))) :list :else :string))) (defmethod node->hiccup :string [node] (when-not (= (str/trim node) "") node)) (defmethod node->hiccup :br [_] [:br]) (defmethod node->hiccup :div [node] (node->hiccup (:content node))) (defmethod node->hiccup :default [{:keys [tag attrs content]}] [tag attrs (node->hiccup content)]) (defmethod node->hiccup :img [{:keys [tag attrs]}] [tag (assoc attrs :style {:max-width 500})]) (defn de-dupe "Remove only consecutive duplicate entries from the `list`." [list] (->> list (partition-by identity) (map first))) (defn selective-flatten ([l] (selective-flatten [] l)) ([acc l] (if (seq l) (let [item (first l) xacc (if (or (string? item) (and (vector? item) (keyword? (first item)))) (conj acc item) (into [] (concat acc (selective-flatten item))))] (recur xacc (rest l))) (apply list acc)))) (defmethod node->hiccup :list [node] (->> node (map node->hiccup) (remove nil?) de-dupe selective-flatten)) (defn inline-elem? [item] (when (#{:em :strong :a} (first item)) true)) (defn inline? [item] (or (string? item) (inline-elem? item))) (defn group-inline "Groups the `list` of strings and Hiccup elements using the `inline?` predicate and wraps them in <p> tags. Once all groups are wrapped, the list is flattened again and any remaining <br> tags are removed." [list] (let [groups (partition-by inline? list) f (fn [l] (if (not= (first (first l)) :br) (into [:p] l) l))] (->> groups (map f) selective-flatten (remove #(= :br (first %)))))) ;; entry-> ;; --------- (defn html-str->hiccup "Parses and converts an html string `s` into a Hiccup data structure." [s] (-> s (xml/parse-str {:namespace-aware false}) node->hiccup group-inline de-dupe)) (defn entry->edn "Converts a parsed XML entry node into a Hiccup data structure." [entry] (let [entry (normalize-entry entry)] {:id (:id entry) :file-contents (assoc entry :post (->> entry :content clean-html html-str->hiccup))})) (defn readable-date "Format the date string `s` into a nicer form for display." [s] (as-> s s (str/split s #"[a-zA-Z]") (str/join " " s))) (defn entry->html "Converts a parsed XML entry node into an html document." [entry] (let [entry (normalize-entry entry) info-span (fn [label s] [:span {:style {:display "block" :margin-bottom "2px"}} [:strong label] s]) post (->> entry :content clean-html html-str->hiccup)] (assoc entry :file-contents (-> (str "<!DOCTYPE html>\n" (html {:mode :html} [:head [:meta {:charset "utf-8"}] [:title (:title entry)]] [:body [:div {:class "post-info"} (info-span "Author: " (:name entry)) (info-span "Email: " (:email entry)) (info-span "Published: " (readable-date (:published entry))) (info-span "Updated: " (readable-date (:updated entry)))] [:a {:href (:link entry)} [:h1 (:title entry)]] post])) (str/replace #"</br>" ""))))) ;; Tests ;; ------- ;; this is a pull from my feed.atom at a point where 7 posts existed (def entries (feed-str->entries (slurp "sample-feed.atom"))) (def raw-entry-content (:content (nth entries 4))) (def normalized-entry (normalize-entry (nth entries 4))) (def normalized-entry-keys #{:name :email :id :published :updated :link :title :content}) (deftest entry-tests (is (= 7 (count entries))) (is (seq? raw-entry-content)) (is (= (type (:content normalized-entry)) java.lang.String)) (is (= normalized-entry-keys (into #{} (keys normalized-entry))))) (defn get-figure-nodes [s] (let [s (-> s (str/replace "<br>" "<br></br>") (str/replace #"<img[\w\W]+?>" #(str %1 "</img>")))] (-> s (xml/parse-str {:namespace-aware false}) zip/xml-zip (get-nodes (match-tag :figure))))) (def fig-img (-> (:content normalized-entry) get-figure-nodes first)) (def unwrapped-img (unwrap-img-from-figure fig-img)) (deftest image-tests (is (= :figure (:tag fig-img))) (is (= :img (:tag unwrapped-img)))) (def some-string "Hi there!") (def empty-string " ") (def br {:tag :br :attrs {} :content '()}) (def img-attrs {:src "https://www.fillmurray.com/300/200" :alt "PI:NAME:<NAME>END_PI is great!"}) (def img {:tag :img :attrs img-attrs :content '()}) (def img-result [:img (merge img-attrs {:style {:max-width 500}})]) (def div {:tag :div :attrs {:a 1 :b 2} :content (list some-string br img)}) (def div-result (list "Hi there!" [:br] img-result)) (def default (assoc div :tag :anything)) (def default-result [:anything (:attrs div) div-result]) (def duplicates ["a" "a" "a" "b" "a" "c" "c" "d" "d" "c"]) (def nested (list (list (repeat 4 "a") (repeat 3 [:br]) "a" [:em "b"] "c"))) (deftest node->hiccup-tests (is (= (node->hiccup some-string) "Hi there!")) (is (nil? (node->hiccup empty-string))) (is (= (node->hiccup br) [:br])) (is (= (node->hiccup img) img-result)) (is (= (node->hiccup div) div-result)) (is (= (node->hiccup default) default-result)) (is (= (de-dupe duplicates) ["a" "b" "a" "c" "d" "c"])) (is (= (selective-flatten nested) (list "a" "a" "a" "a" [:br] [:br] [:br] "a" [:em "b"] "c"))) (is (= (group-inline (selective-flatten nested)) (list [:p "a" "a" "a" "a"] [:p "a" [:em "b"] "c"])))) (t/run-tests)
[ { "context": "rapper for Mithril.js\"\n :url \"https://github.com/owengalenjones/moria\"\n :signing {:gpg-key \"owengalenjones@gmail", "end": 114, "score": 0.9991634488105774, "start": 100, "tag": "USERNAME", "value": "owengalenjones" }, { "context": "b.com/owengalenjones/moria\"\n :signing {:gpg-key \"[email protected]\"}\n :dependencies [[org.clojure/clojure \"1.8.0\"]\n", "end": 168, "score": 0.9998505711555481, "start": 144, "tag": "EMAIL", "value": "[email protected]" } ]
project.clj
chr15m/moria
25
(defproject moria "1.0.1-0" :description "CLJS Wrapper for Mithril.js" :url "https://github.com/owengalenjones/moria" :signing {:gpg-key "[email protected]"} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.8.51"] [cljsjs/mithril "1.0.1-0"]] :jvm-opts ^:replace ["-Xmx1g" "-server"] :plugins [[lein-npm "0.6.1"]] :source-paths ["src" "target/classes"] :clean-targets ["out" "release"] :target-path "target")
115309
(defproject moria "1.0.1-0" :description "CLJS Wrapper for Mithril.js" :url "https://github.com/owengalenjones/moria" :signing {:gpg-key "<EMAIL>"} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.8.51"] [cljsjs/mithril "1.0.1-0"]] :jvm-opts ^:replace ["-Xmx1g" "-server"] :plugins [[lein-npm "0.6.1"]] :source-paths ["src" "target/classes"] :clean-targets ["out" "release"] :target-path "target")
true
(defproject moria "1.0.1-0" :description "CLJS Wrapper for Mithril.js" :url "https://github.com/owengalenjones/moria" :signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.8.51"] [cljsjs/mithril "1.0.1-0"]] :jvm-opts ^:replace ["-Xmx1g" "-server"] :plugins [[lein-npm "0.6.1"]] :source-paths ["src" "target/classes"] :clean-targets ["out" "release"] :target-path "target")
[ { "context": " (:use cloki))\n\n(def test-wiki \"http://localhost/~steve/mediawiki/api.php\")\n(def test-user \"Admin\")\n(def ", "end": 93, "score": 0.9990675449371338, "start": 88, "tag": "USERNAME", "value": "steve" }, { "context": "alhost/~steve/mediawiki/api.php\")\n(def test-user \"Admin\")\n(def test-password \"password\")\n\n(deftest test-l", "end": 135, "score": 0.9989482164382935, "start": 130, "tag": "USERNAME", "value": "Admin" }, { "context": "php\")\n(def test-user \"Admin\")\n(def test-password \"password\")\n\n(deftest test-login\n (let [session (login tes", "end": 166, "score": 0.9995678067207336, "start": 158, "tag": "PASSWORD", "value": "password" } ]
test/cloki_test.clj
stevemolitor/cloki
3
(ns cloki-test (:use clojure.test) (:use cloki)) (def test-wiki "http://localhost/~steve/mediawiki/api.php") (def test-user "Admin") (def test-password "password") (deftest test-login (let [session (login test-wiki test-user test-password)] (is (not (nil? (:cookies @(:state session))))) (is (= test-wiki (:url session))))) (deftest test-logout (let [session (login test-wiki test-user test-password) state (:state session)] (is (not (empty? (:cookies @state)))) (logout session) (is (empty? (:cookies @state))) (is (nil? (:edit-token @state))))) (deftest test-with-login (with-login [session (login test-wiki test-user test-password)] (is (not (nil? (:cookies @(:state session))))) (is (= test-wiki (:url session))))) (deftest test-pages (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "TestPage")] (put page {:text "page content"}) (= "page content" (content page)) (delete page)))) (deftest test-examples (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "My Page")] (put page {:text "page content"}) )) (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "My Page")] (println (content page)))))
72229
(ns cloki-test (:use clojure.test) (:use cloki)) (def test-wiki "http://localhost/~steve/mediawiki/api.php") (def test-user "Admin") (def test-password "<PASSWORD>") (deftest test-login (let [session (login test-wiki test-user test-password)] (is (not (nil? (:cookies @(:state session))))) (is (= test-wiki (:url session))))) (deftest test-logout (let [session (login test-wiki test-user test-password) state (:state session)] (is (not (empty? (:cookies @state)))) (logout session) (is (empty? (:cookies @state))) (is (nil? (:edit-token @state))))) (deftest test-with-login (with-login [session (login test-wiki test-user test-password)] (is (not (nil? (:cookies @(:state session))))) (is (= test-wiki (:url session))))) (deftest test-pages (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "TestPage")] (put page {:text "page content"}) (= "page content" (content page)) (delete page)))) (deftest test-examples (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "My Page")] (put page {:text "page content"}) )) (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "My Page")] (println (content page)))))
true
(ns cloki-test (:use clojure.test) (:use cloki)) (def test-wiki "http://localhost/~steve/mediawiki/api.php") (def test-user "Admin") (def test-password "PI:PASSWORD:<PASSWORD>END_PI") (deftest test-login (let [session (login test-wiki test-user test-password)] (is (not (nil? (:cookies @(:state session))))) (is (= test-wiki (:url session))))) (deftest test-logout (let [session (login test-wiki test-user test-password) state (:state session)] (is (not (empty? (:cookies @state)))) (logout session) (is (empty? (:cookies @state))) (is (nil? (:edit-token @state))))) (deftest test-with-login (with-login [session (login test-wiki test-user test-password)] (is (not (nil? (:cookies @(:state session))))) (is (= test-wiki (:url session))))) (deftest test-pages (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "TestPage")] (put page {:text "page content"}) (= "page content" (content page)) (delete page)))) (deftest test-examples (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "My Page")] (put page {:text "page content"}) )) (with-login [session (login test-wiki test-user test-password)] (let [page (get-page session "My Page")] (println (content page)))))
[ { "context": "d-username\n (let [short-id \"st\"\n long-id \"[email protected]://aai-logon.vho-switch", "end": 625, "score": 0.6634045839309692, "start": 624, "tag": "EMAIL", "value": "4" }, { "context": "rname\n (let [short-id \"st\"\n long-id \"[email protected]://aai-logon.vho-switchaai.ch/idp/shibboleth!", "end": 647, "score": 0.9238830804824829, "start": 629, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\n :email \"[email protected]\"\n :roles ", "end": 1012, "score": 0.9998677372932434, "start": 1004, "tag": "EMAIL", "value": "[email protected]" }, { "context": " :email \"[email protected]\"\n :roles ", "end": 1592, "score": 0.9998621940612793, "start": 1584, "tag": "EMAIL", "value": "[email protected]" }, { "context": " :email \"[email protected]\"\n :roles ", "end": 2156, "score": 0.9998964071273804, "start": 2148, "tag": "EMAIL", "value": "[email protected]" }, { "context": " (is (= false (:deleted user)))\n (is (= \"[email protected]\" (:emailAddress user)))\n (is (= false (:isSu", "end": 2651, "score": 0.9997982978820801, "start": 2643, "tag": "EMAIL", "value": "[email protected]" }, { "context": "t\"\n :email \"[email protected]\"\n :roles \"a", "end": 3153, "score": 0.9998817443847656, "start": 3145, "tag": "EMAIL", "value": "[email protected]" }, { "context": "od \"github\"\n :email \"[email protected]\"\n :external-login \"stef\"}]\n\n ", "end": 3566, "score": 0.9998957514762878, "start": 3558, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ef\"}]\n\n (th/add-user-for-test! {:username \"stef\"\n :password \"secre", "end": 3660, "score": 0.9886361956596375, "start": 3656, "tag": "USERNAME", "value": "stef" }, { "context": "\"stef\"\n :password \"secret\"\n :emailAddress \"st@s.", "end": 3711, "score": 0.9995419383049011, "start": 3705, "tag": "PASSWORD", "value": "secret" }, { "context": "ecret\"\n :emailAddress \"[email protected]\"})\n\n (is (= \"stef\" (db/create-user! user-info)", "end": 3764, "score": 0.9998739361763, "start": 3756, "tag": "EMAIL", "value": "[email protected]" }, { "context": ":username name\n :password \"12345\"\n :emailAddress \"[email protected]\"}]\n (t", "end": 4095, "score": 0.999363124370575, "start": 4090, "tag": "PASSWORD", "value": "12345" }, { "context": "-deleted\n (th/add-user-for-test! {:username \"jack\"\n :password \"123456\"", "end": 4409, "score": 0.9974495768547058, "start": 4405, "tag": "USERNAME", "value": "jack" }, { "context": " \"jack\"\n :password \"123456\"\n :emailAddress \"jack@si", "end": 4458, "score": 0.9993690848350525, "start": 4452, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :state \"DELETED", "end": 4515, "score": 0.9998999238014221, "start": 4501, "tag": "EMAIL", "value": "[email protected]" }, { "context": "TED\"})\n\n (is (= #{} (db/find-usernames-by-email \"[email protected]\")))\n (is (= #{} (db/find-usernames-by-email \"jac", "end": 4627, "score": 0.9998638033866882, "start": 4612, "tag": "EMAIL", "value": "[email protected]" }, { "context": "com\")))\n (is (= #{} (db/find-usernames-by-email \"[email protected]\"))))\n\n\n(deftest test-users-by-email\n (th/add-use", "end": 4688, "score": 0.9999013543128967, "start": 4674, "tag": "EMAIL", "value": "[email protected]" }, { "context": "by-email\n (th/add-user-for-test! {:username \"jack\"\n :password \"123456\"", "end": 4770, "score": 0.9990003705024719, "start": 4766, "tag": "USERNAME", "value": "jack" }, { "context": " \"jack\"\n :password \"123456\"\n :emailAddress \"jack@si", "end": 4819, "score": 0.9993392825126648, "start": 4813, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n (th/add-user-for-test! {:username \"joe\"\n", "end": 4876, "score": 0.9999038577079773, "start": 4862, "tag": "EMAIL", "value": "[email protected]" }, { "context": "q.com\"})\n (th/add-user-for-test! {:username \"joe\"\n :password \"123456\"", "end": 4924, "score": 0.9983054995536804, "start": 4921, "tag": "USERNAME", "value": "joe" }, { "context": " \"joe\"\n :password \"123456\"\n :emailAddress \"joe@six", "end": 4973, "score": 0.9993857741355896, "start": 4967, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n (th/add-user-for-test! {:username \"joe-a", "end": 5029, "score": 0.9999117255210876, "start": 5016, "tag": "EMAIL", "value": "[email protected]" }, { "context": "q.com\"})\n (th/add-user-for-test! {:username \"joe-alias\"\n :password \"123456\"", "end": 5083, "score": 0.9981356859207153, "start": 5074, "tag": "USERNAME", "value": "joe-alias" }, { "context": "e-alias\"\n :password \"123456\"\n :emailAddress \"joe@six", "end": 5132, "score": 0.9993528723716736, "start": 5126, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n\n (is (= #{} (db/find-usernames-by-email \"unk", "end": 5188, "score": 0.9998911023139954, "start": 5175, "tag": "EMAIL", "value": "[email protected]" }, { "context": "com\"})\n\n (is (= #{} (db/find-usernames-by-email \"[email protected]\")))\n (is (= #{\"jack\"} (db/find-usernames-by-emai", "end": 5250, "score": 0.9998821020126343, "start": 5235, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ernames-by-email \"[email protected]\")))\n (is (= #{\"jack\"} (db/find-usernames-by-email \"[email protected]\")))", "end": 5271, "score": 0.9919402003288269, "start": 5267, "tag": "USERNAME", "value": "jack" }, { "context": ")\n (is (= #{\"jack\"} (db/find-usernames-by-email \"[email protected]\")))\n (is (= #{\"joe\" \"joe-alias\"} (db/find-userna", "end": 5317, "score": 0.999915599822998, "start": 5303, "tag": "EMAIL", "value": "[email protected]" }, { "context": "sernames-by-email \"[email protected]\")))\n (is (= #{\"joe\" \"joe-alias\"} (db/find-usernames-by-email \"joe@si", "end": 5337, "score": 0.9813249111175537, "start": 5334, "tag": "USERNAME", "value": "joe" }, { "context": "es-by-email \"[email protected]\")))\n (is (= #{\"joe\" \"joe-alias\"} (db/find-usernames-by-email \"[email protected]\"))))", "end": 5349, "score": 0.9054751992225647, "start": 5340, "tag": "USERNAME", "value": "joe-alias" }, { "context": "#{\"joe\" \"joe-alias\"} (db/find-usernames-by-email \"[email protected]\"))))\n\n\n(deftest test-users-by-authn-skips-deleted", "end": 5394, "score": 0.999914288520813, "start": 5381, "tag": "EMAIL", "value": "[email protected]" }, { "context": "d-legacy\n (th/add-user-for-test! {:username \"joe-slipstream\"\n :password \"123456\"", "end": 5507, "score": 0.9992696642875671, "start": 5493, "tag": "USERNAME", "value": "joe-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"joe@six", "end": 5556, "score": 0.99935382604599, "start": 5550, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :githublogin \"joe\"\n ", "end": 5612, "score": 0.9999257922172546, "start": 5599, "tag": "EMAIL", "value": "[email protected]" }, { "context": "xsq.com\"\n :githublogin \"joe\"\n :state \"DELETED", "end": 5658, "score": 0.9996783137321472, "start": 5655, "tag": "USERNAME", "value": "joe" }, { "context": "il? (uiu/find-username-by-identifier :github nil \"joe\"))))\n\n\n(deftest test-users-by-authn-skips-deleted", "end": 5773, "score": 0.9996019601821899, "start": 5770, "tag": "USERNAME", "value": "joe" }, { "context": "-deleted\n (th/add-user-for-test! {:username \"joe-slipstream\"\n :password \"123456\"", "end": 5879, "score": 0.9997015595436096, "start": 5865, "tag": "USERNAME", "value": "joe-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"joe@six", "end": 5928, "score": 0.9993459582328796, "start": 5922, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :state \"DELETED", "end": 5984, "score": 0.9999281167984009, "start": 5971, "tag": "EMAIL", "value": "[email protected]" }, { "context": " \"DELETED\"})\n (uiu/add-user-identifier! \"joe-slipstream\" :github \"joe\" nil)\n (is (nil? (uiu/f", "end": 6070, "score": 0.6968107223510742, "start": 6069, "tag": "USERNAME", "value": "e" }, { "context": " \"DELETED\"})\n (uiu/add-user-identifier! \"joe-slipstream\" :github \"joe\" nil)\n (is (nil? (uiu/find-u", "end": 6075, "score": 0.6490537524223328, "start": 6071, "tag": "USERNAME", "value": "slip" }, { "context": "iu/add-user-identifier! \"joe-slipstream\" :github \"joe\" nil)\n (is (nil? (uiu/find-username-by-identifie", "end": 6095, "score": 0.9995372295379639, "start": 6092, "tag": "USERNAME", "value": "joe" }, { "context": "il? (uiu/find-username-by-identifier :github nil \"joe\"))))\n\n\n(deftest test-users-by-authn-legacy\n (th/", "end": 6163, "score": 0.9994977116584778, "start": 6160, "tag": "USERNAME", "value": "joe" }, { "context": "n-legacy\n (th/add-user-for-test! {:username \"joe-slipstream\"\n :password \"123456\"", "end": 6262, "score": 0.9996692538261414, "start": 6248, "tag": "USERNAME", "value": "joe-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"joe@six", "end": 6311, "score": 0.9993709921836853, "start": 6305, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :githublogin \"joe\"})\n", "end": 6367, "score": 0.9999270439147949, "start": 6354, "tag": "EMAIL", "value": "[email protected]" }, { "context": "xsq.com\"\n :githublogin \"joe\"})\n\n (th/add-user-for-test! {:username \"jack", "end": 6413, "score": 0.9996987581253052, "start": 6410, "tag": "USERNAME", "value": "joe" }, { "context": "\"joe\"})\n\n (th/add-user-for-test! {:username \"jack-slipstream\"\n :password \"123456\"", "end": 6474, "score": 0.9996886253356934, "start": 6459, "tag": "USERNAME", "value": "jack-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"jack@si", "end": 6523, "score": 0.9993526339530945, "start": 6517, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :githublogin \"jack\"})", "end": 6580, "score": 0.999925434589386, "start": 6566, "tag": "EMAIL", "value": "[email protected]" }, { "context": "xsq.com\"\n :githublogin \"jack\"})\n\n (th/add-user-for-test! {:username \"alic", "end": 6627, "score": 0.9996315836906433, "start": 6623, "tag": "USERNAME", "value": "jack" }, { "context": "jack\"})\n\n (th/add-user-for-test! {:username \"alice-slipstream\"\n :password \"123456\"", "end": 6689, "score": 0.9996895790100098, "start": 6673, "tag": "USERNAME", "value": "alice-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"alice@s", "end": 6738, "score": 0.99935382604599, "start": 6732, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n\n (is (nil? (uiu/find-username-by-identifier ", "end": 6796, "score": 0.9999127388000488, "start": 6781, "tag": "EMAIL", "value": "[email protected]" }, { "context": "il? (uiu/find-username-by-identifier :github nil \"unknownid\")))\n (is (= \"joe-slipstream\" (uiu/find-username-", "end": 6868, "score": 0.9990060329437256, "start": 6859, "tag": "USERNAME", "value": "unknownid" }, { "context": "y-identifier :github nil \"unknownid\")))\n (is (= \"joe-slipstream\" (uiu/find-username-by-identifier :github nil \"jo", "end": 6897, "score": 0.9958842396736145, "start": 6883, "tag": "USERNAME", "value": "joe-slipstream" }, { "context": "am\" (uiu/find-username-by-identifier :github nil \"joe\"))))\n\n\n(deftest test-users-by-authn\n (th/add-use", "end": 6948, "score": 0.999359130859375, "start": 6945, "tag": "USERNAME", "value": "joe" }, { "context": "by-authn\n (th/add-user-for-test! {:username \"joe-slipstream\"\n :password \"123456\"", "end": 7040, "score": 0.9997131824493408, "start": 7026, "tag": "USERNAME", "value": "joe-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"joe@six", "end": 7089, "score": 0.9993469715118408, "start": 7083, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n (uiu/add-user-identifier! \"joe-slipstream\" :", "end": 7145, "score": 0.9999269843101501, "start": 7132, "tag": "EMAIL", "value": "[email protected]" }, { "context": "iu/add-user-identifier! \"joe-slipstream\" :github \"joe\" nil)\n\n (th/add-user-for-test! {:username \"j", "end": 7206, "score": 0.9964135885238647, "start": 7203, "tag": "USERNAME", "value": "joe" }, { "context": "e\" nil)\n\n (th/add-user-for-test! {:username \"jack-slipstream\"\n :password \"123456\"", "end": 7270, "score": 0.9997178316116333, "start": 7255, "tag": "USERNAME", "value": "jack-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"jack@si", "end": 7319, "score": 0.9993491768836975, "start": 7313, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n (uiu/add-user-identifier! \"jack-slipstream\" ", "end": 7376, "score": 0.9999256730079651, "start": 7362, "tag": "EMAIL", "value": "[email protected]" }, { "context": "tance\")\n\n (th/add-user-for-test! {:username \"william-slipstream\"\n :password \"123456\"", "end": 7514, "score": 0.9997256398200989, "start": 7496, "tag": "USERNAME", "value": "william-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"william", "end": 7563, "score": 0.9993403553962708, "start": 7557, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n (uiu/add-user-identifier! \"william-slipstrea", "end": 7623, "score": 0.9999249577522278, "start": 7606, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ance\")\n\n\n (th/add-user-for-test! {:username \"alice-slipstream\"\n :password \"123456\"", "end": 7772, "score": 0.9996921420097351, "start": 7756, "tag": "USERNAME", "value": "alice-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"alice@s", "end": 7821, "score": 0.999352753162384, "start": 7815, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"})\n\n (is (nil? (uiu/find-username-by-identifier ", "end": 7879, "score": 0.9999146461486816, "start": 7864, "tag": "EMAIL", "value": "[email protected]" }, { "context": "u/find-username-by-identifier :github nil \"unknownid\")))\n (is (= \"joe-slipstream\" (uiu/find-username-", "end": 7951, "score": 0.7478581070899963, "start": 7949, "tag": "USERNAME", "value": "id" }, { "context": "y-identifier :github nil \"unknownid\")))\n (is (= \"joe-slipstream\" (uiu/find-username-by-identifier :github nil \"jo", "end": 7980, "score": 0.9915929436683655, "start": 7966, "tag": "USERNAME", "value": "joe-slipstream" }, { "context": "am\" (uiu/find-username-by-identifier :github nil \"joe\")))\n (is (= \"jack-slipstream\" (uiu/find-username", "end": 8031, "score": 0.9929149150848389, "start": 8028, "tag": "USERNAME", "value": "joe" }, { "context": "name-by-identifier :github nil \"joe\")))\n (is (= \"jack-slipstream\" (uiu/find-username-by-identifier :oidc \"my-insta", "end": 8061, "score": 0.9657702445983887, "start": 8046, "tag": "USERNAME", "value": "jack-slipstream" }, { "context": "/find-username-by-identifier :oidc \"my-instance\" \"jack\")))\n (is (= \"william-slipstream\" (uiu/find-usern", "end": 8121, "score": 0.9601104855537415, "start": 8117, "tag": "USERNAME", "value": "jack" }, { "context": "entifier :oidc \"my-instance\" \"jack\")))\n (is (= \"william-slipstream\" (uiu/find-username-by-identifier :some-method \"s", "end": 8154, "score": 0.812267005443573, "start": 8137, "tag": "USERNAME", "value": "illiam-slipstream" }, { "context": "a-legacy\n (th/add-user-for-test! {:username \"joe1-slipstream\"\n :password \"123456\"", "end": 8348, "score": 0.9997366070747375, "start": 8333, "tag": "USERNAME", "value": "joe1-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"jane@ex", "end": 8397, "score": 0.9993391036987305, "start": 8391, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :firstName \"Jane\"\n ", "end": 8456, "score": 0.9999154210090637, "start": 8440, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ple.org\"\n :firstName \"Jane\"\n :lastName \"Tester\"", "end": 8503, "score": 0.9174018502235413, "start": 8499, "tag": "NAME", "value": "Jane" }, { "context": "\"Tester\"\n :githublogin \"joe\"})\n (th/add-user-for-test! {:username \"joe2-", "end": 8598, "score": 0.9987121820449829, "start": 8595, "tag": "USERNAME", "value": "joe" }, { "context": " \"joe\"})\n (th/add-user-for-test! {:username \"joe2-slipstream\"\n :password \"123456\"", "end": 8658, "score": 0.9997266530990601, "start": 8643, "tag": "USERNAME", "value": "joe2-slipstream" }, { "context": "pstream\"\n :password \"123456\"\n :emailAddress \"jane@ex", "end": 8707, "score": 0.9993807673454285, "start": 8701, "tag": "PASSWORD", "value": "123456" }, { "context": "\"123456\"\n :emailAddress \"[email protected]\"\n :firstName \"Jane\"\n ", "end": 8766, "score": 0.9999149441719055, "start": 8750, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ple.org\"\n :firstName \"Jane\"\n :lastName \"Tester\"", "end": 8813, "score": 0.797352135181427, "start": 8809, "tag": "NAME", "value": "Jane" }, { "context": "\"Tester\"\n :githublogin \"joe\"})\n (is (thrown-with-msg? Exception #\"one result", "end": 8908, "score": 0.9979698061943054, "start": 8905, "tag": "USERNAME", "value": "joe" }, { "context": " (uiu/find-username-by-identifier :github nil \"joe\"))))\n\n(deftest check-user-exists?\n (let [test-us", "end": 9041, "score": 0.9981380105018616, "start": 9038, "tag": "USERNAME", "value": "joe" }, { "context": "deftest check-user-exists?\n (let [test-username \"some-long-random-user-name-that-does-not-exist\"\n test-username-deleted (str test-username", "end": 9145, "score": 0.962405800819397, "start": 9099, "tag": "USERNAME", "value": "some-long-random-user-name-that-does-not-exist" }, { "context": " test-username-deleted (str test-username \"-deleted\")]\n (is (false? (db/user-exists? test-username", "end": 9205, "score": 0.9089425206184387, "start": 9198, "tag": "USERNAME", "value": "deleted" }, { "context": "leted)))\n (th/add-user-for-test! {:username test-username\n :password \"passwo", "end": 9372, "score": 0.9834849238395691, "start": 9359, "tag": "USERNAME", "value": "test-username" }, { "context": "ername\n :password \"password\"\n :emailAddress \"jane@", "end": 9424, "score": 0.9993765950202942, "start": 9416, "tag": "PASSWORD", "value": "password" }, { "context": "sword\"\n :emailAddress \"[email protected]\"\n :firstName \"Jane\"", "end": 9485, "score": 0.9999065399169922, "start": 9469, "tag": "EMAIL", "value": "[email protected]" }, { "context": "e.org\"\n :firstName \"Jane\"\n :lastName \"Teste", "end": 9534, "score": 0.9840959906578064, "start": 9530, "tag": "NAME", "value": "Jane" }, { "context": "CTIVE\"})\n (th/add-user-for-test! {:username test-username-deleted\n :password \"passwo", "end": 9703, "score": 0.9275907278060913, "start": 9682, "tag": "USERNAME", "value": "test-username-deleted" }, { "context": "eleted\n :password \"password\"\n :emailAddress \"jane@", "end": 9755, "score": 0.9993752837181091, "start": 9747, "tag": "PASSWORD", "value": "password" }, { "context": "sword\"\n :emailAddress \"[email protected]\"\n :firstName \"Jane\"", "end": 9816, "score": 0.9999060034751892, "start": 9800, "tag": "EMAIL", "value": "[email protected]" }, { "context": "e.org\"\n :firstName \"Jane\"\n :lastName \"Teste", "end": 9865, "score": 0.9926857948303223, "start": 9861, "tag": "NAME", "value": "Jane" }, { "context": "test-find-password-for-username\n (let [username \"testuser\"\n password \"password\"\n pass-hash (i", "end": 10285, "score": 0.9981461763381958, "start": 10277, "tag": "USERNAME", "value": "testuser" }, { "context": "ame\n (let [username \"testuser\"\n password \"password\"\n pass-hash (ia/hash-password password)\n ", "end": 10313, "score": 0.9996019005775452, "start": 10305, "tag": "PASSWORD", "value": "password" }, { "context": " user {:username username\n :password password}]\n (th/add-user-for-test! user)\n (is (= pas", "end": 10426, "score": 0.605887234210968, "start": 10418, "tag": "PASSWORD", "value": "password" }, { "context": "st test-find-roles-for-username\n (let [username \"testuser\"\n user {:username username\n ", "end": 10594, "score": 0.9980129599571228, "start": 10586, "tag": "USERNAME", "value": "testuser" }, { "context": ":username username\n :password \"password\"\n :isSuperUser false}]\n (th/add-u", "end": 10668, "score": 0.9995938539505005, "start": 10660, "tag": "PASSWORD", "value": "password" } ]
cimi/test/com/sixsq/slipstream/auth/utils/db_test.clj
slipstream/SlipStreamServer
6
(ns com.sixsq.slipstream.auth.utils.db-test (:refer-clojure :exclude [update]) (:require [clojure.test :refer :all] [com.sixsq.slipstream.auth.internal :as ia] [com.sixsq.slipstream.auth.test-helper :as th] [com.sixsq.slipstream.auth.utils.db :as db] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu])) (use-fixtures :each ltu/with-test-server-fixture) (deftest test-user-creation-standard-username (let [short-id "st" long-id "[email protected]://aai-logon.vho-switchaai.ch/idp/shibboleth!https://fed-id.nuv.la/samlbridge/module.php/saml/sp/metadata.php/sixsq-saml-bridge!uays4u2/dk2qefyxzsv9uiicv+y="] (doseq [id #{short-id long-id}] (is (= id (db/create-user! {:authn-method "github" :authn-login id :email "[email protected]" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"})))))) (deftest test-user-creation-standard-username-oidc (let [identifier "st"] (is (= identifier (db/create-user! {:authn-method "oidc" :instance "instance" :authn-login identifier :email "[email protected]" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"}))))) (deftest test-user-creation-uuid (let [uuid (u/random-uuid)] (is (= uuid (db/create-user! {:authn-method "github" :authn-login uuid :external-login "st" :email "[email protected]" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"}))) (let [usernames (db/existing-user-names) user (db/get-user (first usernames))] (is (= 1 (count usernames))) (is (= "alpha-role, beta-role" (:roles user))) (is (= false (:deleted user))) (is (= "[email protected]" (:emailAddress user))) (is (= false (:isSuperUser user))) (is (= uuid (:username user))) (is (= "ACTIVE" (:state user))) (is (= "first" (:firstName user))) (is (= "last" (:lastName user))) (is (:password user)) (is (:created user)) (is (= "USER ANON" (db/find-roles-for-username "st"))))) (is (= "st" (db/create-user! {:authn-method "github" :authn-login "st" :email "[email protected]" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"})))) (deftest test-no-creation-on-existing-user (let [user-info {:authn-login "stef" :authn-method "github" :email "[email protected]" :external-login "stef"}] (th/add-user-for-test! {:username "stef" :password "secret" :emailAddress "[email protected]"}) (is (= "stef" (db/create-user! user-info))) (is (nil? (db/create-user! (assoc user-info :fail-on-existing? true)))))) (defn create-users [n] (doseq [i (range n)] (let [name (str "foo_" i) user {:id (str "user/" name) :username name :password "12345" :emailAddress "[email protected]"}] (th/add-user-for-test! user)))) (deftest test-existing-user-names (is (empty? (db/existing-user-names))) (create-users 3) (is (= 3 (count (db/existing-user-names))))) (deftest test-users-by-email-skips-deleted (th/add-user-for-test! {:username "jack" :password "123456" :emailAddress "[email protected]" :state "DELETED"}) (is (= #{} (db/find-usernames-by-email "[email protected]"))) (is (= #{} (db/find-usernames-by-email "[email protected]")))) (deftest test-users-by-email (th/add-user-for-test! {:username "jack" :password "123456" :emailAddress "[email protected]"}) (th/add-user-for-test! {:username "joe" :password "123456" :emailAddress "[email protected]"}) (th/add-user-for-test! {:username "joe-alias" :password "123456" :emailAddress "[email protected]"}) (is (= #{} (db/find-usernames-by-email "[email protected]"))) (is (= #{"jack"} (db/find-usernames-by-email "[email protected]"))) (is (= #{"joe" "joe-alias"} (db/find-usernames-by-email "[email protected]")))) (deftest test-users-by-authn-skips-deleted-legacy (th/add-user-for-test! {:username "joe-slipstream" :password "123456" :emailAddress "[email protected]" :githublogin "joe" :state "DELETED"}) (is (nil? (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn-skips-deleted (th/add-user-for-test! {:username "joe-slipstream" :password "123456" :emailAddress "[email protected]" :state "DELETED"}) (uiu/add-user-identifier! "joe-slipstream" :github "joe" nil) (is (nil? (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn-legacy (th/add-user-for-test! {:username "joe-slipstream" :password "123456" :emailAddress "[email protected]" :githublogin "joe"}) (th/add-user-for-test! {:username "jack-slipstream" :password "123456" :emailAddress "[email protected]" :githublogin "jack"}) (th/add-user-for-test! {:username "alice-slipstream" :password "123456" :emailAddress "[email protected]"}) (is (nil? (uiu/find-username-by-identifier :github nil "unknownid"))) (is (= "joe-slipstream" (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn (th/add-user-for-test! {:username "joe-slipstream" :password "123456" :emailAddress "[email protected]"}) (uiu/add-user-identifier! "joe-slipstream" :github "joe" nil) (th/add-user-for-test! {:username "jack-slipstream" :password "123456" :emailAddress "[email protected]"}) (uiu/add-user-identifier! "jack-slipstream" :oidc "jack" "my-instance") (th/add-user-for-test! {:username "william-slipstream" :password "123456" :emailAddress "[email protected]"}) (uiu/add-user-identifier! "william-slipstream" :some-method "bill" "some-instance") (th/add-user-for-test! {:username "alice-slipstream" :password "123456" :emailAddress "[email protected]"}) (is (nil? (uiu/find-username-by-identifier :github nil "unknownid"))) (is (= "joe-slipstream" (uiu/find-username-by-identifier :github nil "joe"))) (is (= "jack-slipstream" (uiu/find-username-by-identifier :oidc "my-instance" "jack"))) (is (= "william-slipstream" (uiu/find-username-by-identifier :some-method "some-instance" "bill")))) (deftest test-users-by-authn-detect-inconsistent-data-legacy (th/add-user-for-test! {:username "joe1-slipstream" :password "123456" :emailAddress "[email protected]" :firstName "Jane" :lastName "Tester" :githublogin "joe"}) (th/add-user-for-test! {:username "joe2-slipstream" :password "123456" :emailAddress "[email protected]" :firstName "Jane" :lastName "Tester" :githublogin "joe"}) (is (thrown-with-msg? Exception #"one result for joe" (uiu/find-username-by-identifier :github nil "joe")))) (deftest check-user-exists? (let [test-username "some-long-random-user-name-that-does-not-exist" test-username-deleted (str test-username "-deleted")] (is (false? (db/user-exists? test-username))) (is (false? (db/user-exists? test-username-deleted))) (th/add-user-for-test! {:username test-username :password "password" :emailAddress "[email protected]" :firstName "Jane" :lastName "Tester" :state "ACTIVE"}) (th/add-user-for-test! {:username test-username-deleted :password "password" :emailAddress "[email protected]" :firstName "Jane" :lastName "Tester" :state "DELETED"}) (is (true? (db/user-exists? test-username))) ;; users in any state exist, but should not be listed as active (is (true? (db/user-exists? test-username-deleted))) (is (nil? (db/get-active-user-by-name test-username-deleted))))) (deftest test-find-password-for-username (let [username "testuser" password "password" pass-hash (ia/hash-password password) user {:username username :password password}] (th/add-user-for-test! user) (is (= pass-hash (db/find-password-for-username username))))) (deftest test-find-roles-for-username (let [username "testuser" user {:username username :password "password" :isSuperUser false}] (th/add-user-for-test! user) (is (= "USER ANON" (db/find-roles-for-username username)))))
94266
(ns com.sixsq.slipstream.auth.utils.db-test (:refer-clojure :exclude [update]) (:require [clojure.test :refer :all] [com.sixsq.slipstream.auth.internal :as ia] [com.sixsq.slipstream.auth.test-helper :as th] [com.sixsq.slipstream.auth.utils.db :as db] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu])) (use-fixtures :each ltu/with-test-server-fixture) (deftest test-user-creation-standard-username (let [short-id "st" long-id "<EMAIL>8587<EMAIL>https://aai-logon.vho-switchaai.ch/idp/shibboleth!https://fed-id.nuv.la/samlbridge/module.php/saml/sp/metadata.php/sixsq-saml-bridge!uays4u2/dk2qefyxzsv9uiicv+y="] (doseq [id #{short-id long-id}] (is (= id (db/create-user! {:authn-method "github" :authn-login id :email "<EMAIL>" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"})))))) (deftest test-user-creation-standard-username-oidc (let [identifier "st"] (is (= identifier (db/create-user! {:authn-method "oidc" :instance "instance" :authn-login identifier :email "<EMAIL>" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"}))))) (deftest test-user-creation-uuid (let [uuid (u/random-uuid)] (is (= uuid (db/create-user! {:authn-method "github" :authn-login uuid :external-login "st" :email "<EMAIL>" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"}))) (let [usernames (db/existing-user-names) user (db/get-user (first usernames))] (is (= 1 (count usernames))) (is (= "alpha-role, beta-role" (:roles user))) (is (= false (:deleted user))) (is (= "<EMAIL>" (:emailAddress user))) (is (= false (:isSuperUser user))) (is (= uuid (:username user))) (is (= "ACTIVE" (:state user))) (is (= "first" (:firstName user))) (is (= "last" (:lastName user))) (is (:password user)) (is (:created user)) (is (= "USER ANON" (db/find-roles-for-username "st"))))) (is (= "st" (db/create-user! {:authn-method "github" :authn-login "st" :email "<EMAIL>" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"})))) (deftest test-no-creation-on-existing-user (let [user-info {:authn-login "stef" :authn-method "github" :email "<EMAIL>" :external-login "stef"}] (th/add-user-for-test! {:username "stef" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (is (= "stef" (db/create-user! user-info))) (is (nil? (db/create-user! (assoc user-info :fail-on-existing? true)))))) (defn create-users [n] (doseq [i (range n)] (let [name (str "foo_" i) user {:id (str "user/" name) :username name :password "<PASSWORD>" :emailAddress "[email protected]"}] (th/add-user-for-test! user)))) (deftest test-existing-user-names (is (empty? (db/existing-user-names))) (create-users 3) (is (= 3 (count (db/existing-user-names))))) (deftest test-users-by-email-skips-deleted (th/add-user-for-test! {:username "jack" :password "<PASSWORD>" :emailAddress "<EMAIL>" :state "DELETED"}) (is (= #{} (db/find-usernames-by-email "<EMAIL>"))) (is (= #{} (db/find-usernames-by-email "<EMAIL>")))) (deftest test-users-by-email (th/add-user-for-test! {:username "jack" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (th/add-user-for-test! {:username "joe" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (th/add-user-for-test! {:username "joe-alias" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (is (= #{} (db/find-usernames-by-email "<EMAIL>"))) (is (= #{"jack"} (db/find-usernames-by-email "<EMAIL>"))) (is (= #{"joe" "joe-alias"} (db/find-usernames-by-email "<EMAIL>")))) (deftest test-users-by-authn-skips-deleted-legacy (th/add-user-for-test! {:username "joe-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>" :githublogin "joe" :state "DELETED"}) (is (nil? (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn-skips-deleted (th/add-user-for-test! {:username "joe-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>" :state "DELETED"}) (uiu/add-user-identifier! "joe-slipstream" :github "joe" nil) (is (nil? (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn-legacy (th/add-user-for-test! {:username "joe-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>" :githublogin "joe"}) (th/add-user-for-test! {:username "jack-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>" :githublogin "jack"}) (th/add-user-for-test! {:username "alice-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (is (nil? (uiu/find-username-by-identifier :github nil "unknownid"))) (is (= "joe-slipstream" (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn (th/add-user-for-test! {:username "joe-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (uiu/add-user-identifier! "joe-slipstream" :github "joe" nil) (th/add-user-for-test! {:username "jack-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (uiu/add-user-identifier! "jack-slipstream" :oidc "jack" "my-instance") (th/add-user-for-test! {:username "william-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (uiu/add-user-identifier! "william-slipstream" :some-method "bill" "some-instance") (th/add-user-for-test! {:username "alice-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>"}) (is (nil? (uiu/find-username-by-identifier :github nil "unknownid"))) (is (= "joe-slipstream" (uiu/find-username-by-identifier :github nil "joe"))) (is (= "jack-slipstream" (uiu/find-username-by-identifier :oidc "my-instance" "jack"))) (is (= "william-slipstream" (uiu/find-username-by-identifier :some-method "some-instance" "bill")))) (deftest test-users-by-authn-detect-inconsistent-data-legacy (th/add-user-for-test! {:username "joe1-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>" :firstName "<NAME>" :lastName "Tester" :githublogin "joe"}) (th/add-user-for-test! {:username "joe2-slipstream" :password "<PASSWORD>" :emailAddress "<EMAIL>" :firstName "<NAME>" :lastName "Tester" :githublogin "joe"}) (is (thrown-with-msg? Exception #"one result for joe" (uiu/find-username-by-identifier :github nil "joe")))) (deftest check-user-exists? (let [test-username "some-long-random-user-name-that-does-not-exist" test-username-deleted (str test-username "-deleted")] (is (false? (db/user-exists? test-username))) (is (false? (db/user-exists? test-username-deleted))) (th/add-user-for-test! {:username test-username :password "<PASSWORD>" :emailAddress "<EMAIL>" :firstName "<NAME>" :lastName "Tester" :state "ACTIVE"}) (th/add-user-for-test! {:username test-username-deleted :password "<PASSWORD>" :emailAddress "<EMAIL>" :firstName "<NAME>" :lastName "Tester" :state "DELETED"}) (is (true? (db/user-exists? test-username))) ;; users in any state exist, but should not be listed as active (is (true? (db/user-exists? test-username-deleted))) (is (nil? (db/get-active-user-by-name test-username-deleted))))) (deftest test-find-password-for-username (let [username "testuser" password "<PASSWORD>" pass-hash (ia/hash-password password) user {:username username :password <PASSWORD>}] (th/add-user-for-test! user) (is (= pass-hash (db/find-password-for-username username))))) (deftest test-find-roles-for-username (let [username "testuser" user {:username username :password "<PASSWORD>" :isSuperUser false}] (th/add-user-for-test! user) (is (= "USER ANON" (db/find-roles-for-username username)))))
true
(ns com.sixsq.slipstream.auth.utils.db-test (:refer-clojure :exclude [update]) (:require [clojure.test :refer :all] [com.sixsq.slipstream.auth.internal :as ia] [com.sixsq.slipstream.auth.test-helper :as th] [com.sixsq.slipstream.auth.utils.db :as db] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu])) (use-fixtures :each ltu/with-test-server-fixture) (deftest test-user-creation-standard-username (let [short-id "st" long-id "PI:EMAIL:<EMAIL>END_PI8587PI:EMAIL:<EMAIL>END_PIhttps://aai-logon.vho-switchaai.ch/idp/shibboleth!https://fed-id.nuv.la/samlbridge/module.php/saml/sp/metadata.php/sixsq-saml-bridge!uays4u2/dk2qefyxzsv9uiicv+y="] (doseq [id #{short-id long-id}] (is (= id (db/create-user! {:authn-method "github" :authn-login id :email "PI:EMAIL:<EMAIL>END_PI" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"})))))) (deftest test-user-creation-standard-username-oidc (let [identifier "st"] (is (= identifier (db/create-user! {:authn-method "oidc" :instance "instance" :authn-login identifier :email "PI:EMAIL:<EMAIL>END_PI" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"}))))) (deftest test-user-creation-uuid (let [uuid (u/random-uuid)] (is (= uuid (db/create-user! {:authn-method "github" :authn-login uuid :external-login "st" :email "PI:EMAIL:<EMAIL>END_PI" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"}))) (let [usernames (db/existing-user-names) user (db/get-user (first usernames))] (is (= 1 (count usernames))) (is (= "alpha-role, beta-role" (:roles user))) (is (= false (:deleted user))) (is (= "PI:EMAIL:<EMAIL>END_PI" (:emailAddress user))) (is (= false (:isSuperUser user))) (is (= uuid (:username user))) (is (= "ACTIVE" (:state user))) (is (= "first" (:firstName user))) (is (= "last" (:lastName user))) (is (:password user)) (is (:created user)) (is (= "USER ANON" (db/find-roles-for-username "st"))))) (is (= "st" (db/create-user! {:authn-method "github" :authn-login "st" :email "PI:EMAIL:<EMAIL>END_PI" :roles "alpha-role, beta-role" :firstname "first" :lastname "last" :organization "myorg"})))) (deftest test-no-creation-on-existing-user (let [user-info {:authn-login "stef" :authn-method "github" :email "PI:EMAIL:<EMAIL>END_PI" :external-login "stef"}] (th/add-user-for-test! {:username "stef" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (is (= "stef" (db/create-user! user-info))) (is (nil? (db/create-user! (assoc user-info :fail-on-existing? true)))))) (defn create-users [n] (doseq [i (range n)] (let [name (str "foo_" i) user {:id (str "user/" name) :username name :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "[email protected]"}] (th/add-user-for-test! user)))) (deftest test-existing-user-names (is (empty? (db/existing-user-names))) (create-users 3) (is (= 3 (count (db/existing-user-names))))) (deftest test-users-by-email-skips-deleted (th/add-user-for-test! {:username "jack" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :state "DELETED"}) (is (= #{} (db/find-usernames-by-email "PI:EMAIL:<EMAIL>END_PI"))) (is (= #{} (db/find-usernames-by-email "PI:EMAIL:<EMAIL>END_PI")))) (deftest test-users-by-email (th/add-user-for-test! {:username "jack" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (th/add-user-for-test! {:username "joe" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (th/add-user-for-test! {:username "joe-alias" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (is (= #{} (db/find-usernames-by-email "PI:EMAIL:<EMAIL>END_PI"))) (is (= #{"jack"} (db/find-usernames-by-email "PI:EMAIL:<EMAIL>END_PI"))) (is (= #{"joe" "joe-alias"} (db/find-usernames-by-email "PI:EMAIL:<EMAIL>END_PI")))) (deftest test-users-by-authn-skips-deleted-legacy (th/add-user-for-test! {:username "joe-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :githublogin "joe" :state "DELETED"}) (is (nil? (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn-skips-deleted (th/add-user-for-test! {:username "joe-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :state "DELETED"}) (uiu/add-user-identifier! "joe-slipstream" :github "joe" nil) (is (nil? (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn-legacy (th/add-user-for-test! {:username "joe-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :githublogin "joe"}) (th/add-user-for-test! {:username "jack-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :githublogin "jack"}) (th/add-user-for-test! {:username "alice-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (is (nil? (uiu/find-username-by-identifier :github nil "unknownid"))) (is (= "joe-slipstream" (uiu/find-username-by-identifier :github nil "joe")))) (deftest test-users-by-authn (th/add-user-for-test! {:username "joe-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (uiu/add-user-identifier! "joe-slipstream" :github "joe" nil) (th/add-user-for-test! {:username "jack-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (uiu/add-user-identifier! "jack-slipstream" :oidc "jack" "my-instance") (th/add-user-for-test! {:username "william-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (uiu/add-user-identifier! "william-slipstream" :some-method "bill" "some-instance") (th/add-user-for-test! {:username "alice-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI"}) (is (nil? (uiu/find-username-by-identifier :github nil "unknownid"))) (is (= "joe-slipstream" (uiu/find-username-by-identifier :github nil "joe"))) (is (= "jack-slipstream" (uiu/find-username-by-identifier :oidc "my-instance" "jack"))) (is (= "william-slipstream" (uiu/find-username-by-identifier :some-method "some-instance" "bill")))) (deftest test-users-by-authn-detect-inconsistent-data-legacy (th/add-user-for-test! {:username "joe1-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :firstName "PI:NAME:<NAME>END_PI" :lastName "Tester" :githublogin "joe"}) (th/add-user-for-test! {:username "joe2-slipstream" :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :firstName "PI:NAME:<NAME>END_PI" :lastName "Tester" :githublogin "joe"}) (is (thrown-with-msg? Exception #"one result for joe" (uiu/find-username-by-identifier :github nil "joe")))) (deftest check-user-exists? (let [test-username "some-long-random-user-name-that-does-not-exist" test-username-deleted (str test-username "-deleted")] (is (false? (db/user-exists? test-username))) (is (false? (db/user-exists? test-username-deleted))) (th/add-user-for-test! {:username test-username :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :firstName "PI:NAME:<NAME>END_PI" :lastName "Tester" :state "ACTIVE"}) (th/add-user-for-test! {:username test-username-deleted :password "PI:PASSWORD:<PASSWORD>END_PI" :emailAddress "PI:EMAIL:<EMAIL>END_PI" :firstName "PI:NAME:<NAME>END_PI" :lastName "Tester" :state "DELETED"}) (is (true? (db/user-exists? test-username))) ;; users in any state exist, but should not be listed as active (is (true? (db/user-exists? test-username-deleted))) (is (nil? (db/get-active-user-by-name test-username-deleted))))) (deftest test-find-password-for-username (let [username "testuser" password "PI:PASSWORD:<PASSWORD>END_PI" pass-hash (ia/hash-password password) user {:username username :password PI:PASSWORD:<PASSWORD>END_PI}] (th/add-user-for-test! user) (is (= pass-hash (db/find-password-for-username username))))) (deftest test-find-roles-for-username (let [username "testuser" user {:username username :password "PI:PASSWORD:<PASSWORD>END_PI" :isSuperUser false}] (th/add-user-for-test! user) (is (= "USER ANON" (db/find-roles-for-username username)))))
[ { "context": "ort-value :last-name}}\n item {:first-name \"Aku\" :last-name \"Ankka\"}]\n (testing \"no filters\"\n ", "end": 1443, "score": 0.9995077848434448, "start": 1440, "tag": "NAME", "value": "Aku" }, { "context": "ame}}\n item {:first-name \"Aku\" :last-name \"Ankka\"}]\n (testing \"no filters\"\n (is (= true (m", "end": 1462, "score": 0.9996428489685059, "start": 1457, "tag": "NAME", "value": "Ankka" }, { "context": "t-value :last-name}}\n items [{:first-name \"Aku\" :last-name \"Ankka\"}\n {:first-name ", "end": 2270, "score": 0.9996011257171631, "start": 2267, "tag": "NAME", "value": "Aku" }, { "context": "e}}\n items [{:first-name \"Aku\" :last-name \"Ankka\"}\n {:first-name \"Roope\" :last-name ", "end": 2289, "score": 0.9992243647575378, "start": 2284, "tag": "NAME", "value": "Ankka" }, { "context": " :last-name \"Ankka\"}\n {:first-name \"Roope\" :last-name \"Ankka\"}\n {:first-name ", "end": 2326, "score": 0.9996820092201233, "start": 2321, "tag": "NAME", "value": "Roope" }, { "context": "}\n {:first-name \"Roope\" :last-name \"Ankka\"}\n {:first-name \"Hannu\" :last-name ", "end": 2345, "score": 0.9976420402526855, "start": 2340, "tag": "NAME", "value": "Ankka" }, { "context": " :last-name \"Ankka\"}\n {:first-name \"Hannu\" :last-name \"Hanhi\"}]]\n (testing \"empty list\"\n", "end": 2382, "score": 0.9997138977050781, "start": 2377, "tag": "NAME", "value": "Hannu" }, { "context": "}\n {:first-name \"Hannu\" :last-name \"Hanhi\"}]]\n (testing \"empty list\"\n (is (= [] (ap", "end": 2401, "score": 0.9979366064071655, "start": 2396, "tag": "NAME", "value": "Hanhi" }, { "context": "esting \"with filters\"\n (is (= [{:first-name \"Aku\" :last-name \"Ankka\"}\n {:first-name \"", "end": 2665, "score": 0.9996457099914551, "start": 2662, "tag": "NAME", "value": "Aku" }, { "context": "ers\"\n (is (= [{:first-name \"Aku\" :last-name \"Ankka\"}\n {:first-name \"Roope\" :last-name \"", "end": 2684, "score": 0.9980218410491943, "start": 2679, "tag": "NAME", "value": "Ankka" }, { "context": "\" :last-name \"Ankka\"}\n {:first-name \"Roope\" :last-name \"Ankka\"}]\n (apply-filteri", "end": 2720, "score": 0.9997714161872864, "start": 2715, "tag": "NAME", "value": "Roope" }, { "context": "\"}\n {:first-name \"Roope\" :last-name \"Ankka\"}]\n (apply-filtering column-definitio", "end": 2739, "score": 0.9990063309669495, "start": 2734, "tag": "NAME", "value": "Ankka" } ]
test/cljs/rems/test/table.cljs
secureb2share/secureb2share-rems
0
(ns rems.test.table (:require [cljs.test :refer-macros [deftest is testing]] [rems.table :refer [matches-filter matches-filters apply-filtering]])) (deftest matches-filter-test (let [column-definitions {:string-col {:sort-value :string} :numeric-col {:sort-value :numeric}}] (testing "string column" (testing "mismatch" (is (= false (matches-filter column-definitions :string-col "foo" {:string "bar"})))) (testing "exact match" (is (= true (matches-filter column-definitions :string-col "foo" {:string "foo"})))) (testing "substring match" (is (= true (matches-filter column-definitions :string-col "ba" {:string "foobar"})))) (testing "case insensitive match" (is (= true (matches-filter column-definitions :string-col "Abc" {:string "abC"}))))) (testing "numeric column" (testing "mismatch" (is (= false (matches-filter column-definitions :numeric-col "42" {:numeric 123})))) (testing "exact match" (is (= true (matches-filter column-definitions :numeric-col "123" {:numeric 123})))) (testing "substring match" (is (= true (matches-filter column-definitions :numeric-col "2" {:numeric 123}))))))) (deftest matches-filters-test (let [column-definitions {:fname-col {:sort-value :first-name} :lname-col {:sort-value :last-name}} item {:first-name "Aku" :last-name "Ankka"}] (testing "no filters" (is (= true (matches-filters column-definitions {} item)))) (testing "one filter, matches" (is (= true (matches-filters column-definitions {:fname-col "Aku"} item)))) (testing "one filter, no match" (is (= false (matches-filters column-definitions {:fname-col "x"} item)))) (testing "many filters, all match" (is (= true (matches-filters column-definitions {:fname-col "Aku" :lname-col "Ankka"} item)))) (testing "many filters, only some match" (is (= false (matches-filters column-definitions {:fname-col "Aku" :lname-col "x"} item)))))) (deftest apply-filtering-test (let [column-definitions {:fname-col {:sort-value :first-name} :lname-col {:sort-value :last-name}} items [{:first-name "Aku" :last-name "Ankka"} {:first-name "Roope" :last-name "Ankka"} {:first-name "Hannu" :last-name "Hanhi"}]] (testing "empty list" (is (= [] (apply-filtering column-definitions {} [])))) (testing "without filters" (is (= items (apply-filtering column-definitions {} items)))) (testing "with filters" (is (= [{:first-name "Aku" :last-name "Ankka"} {:first-name "Roope" :last-name "Ankka"}] (apply-filtering column-definitions {:lname-col "Ankka"} items))))))
77797
(ns rems.test.table (:require [cljs.test :refer-macros [deftest is testing]] [rems.table :refer [matches-filter matches-filters apply-filtering]])) (deftest matches-filter-test (let [column-definitions {:string-col {:sort-value :string} :numeric-col {:sort-value :numeric}}] (testing "string column" (testing "mismatch" (is (= false (matches-filter column-definitions :string-col "foo" {:string "bar"})))) (testing "exact match" (is (= true (matches-filter column-definitions :string-col "foo" {:string "foo"})))) (testing "substring match" (is (= true (matches-filter column-definitions :string-col "ba" {:string "foobar"})))) (testing "case insensitive match" (is (= true (matches-filter column-definitions :string-col "Abc" {:string "abC"}))))) (testing "numeric column" (testing "mismatch" (is (= false (matches-filter column-definitions :numeric-col "42" {:numeric 123})))) (testing "exact match" (is (= true (matches-filter column-definitions :numeric-col "123" {:numeric 123})))) (testing "substring match" (is (= true (matches-filter column-definitions :numeric-col "2" {:numeric 123}))))))) (deftest matches-filters-test (let [column-definitions {:fname-col {:sort-value :first-name} :lname-col {:sort-value :last-name}} item {:first-name "<NAME>" :last-name "<NAME>"}] (testing "no filters" (is (= true (matches-filters column-definitions {} item)))) (testing "one filter, matches" (is (= true (matches-filters column-definitions {:fname-col "Aku"} item)))) (testing "one filter, no match" (is (= false (matches-filters column-definitions {:fname-col "x"} item)))) (testing "many filters, all match" (is (= true (matches-filters column-definitions {:fname-col "Aku" :lname-col "Ankka"} item)))) (testing "many filters, only some match" (is (= false (matches-filters column-definitions {:fname-col "Aku" :lname-col "x"} item)))))) (deftest apply-filtering-test (let [column-definitions {:fname-col {:sort-value :first-name} :lname-col {:sort-value :last-name}} items [{:first-name "<NAME>" :last-name "<NAME>"} {:first-name "<NAME>" :last-name "<NAME>"} {:first-name "<NAME>" :last-name "<NAME>"}]] (testing "empty list" (is (= [] (apply-filtering column-definitions {} [])))) (testing "without filters" (is (= items (apply-filtering column-definitions {} items)))) (testing "with filters" (is (= [{:first-name "<NAME>" :last-name "<NAME>"} {:first-name "<NAME>" :last-name "<NAME>"}] (apply-filtering column-definitions {:lname-col "Ankka"} items))))))
true
(ns rems.test.table (:require [cljs.test :refer-macros [deftest is testing]] [rems.table :refer [matches-filter matches-filters apply-filtering]])) (deftest matches-filter-test (let [column-definitions {:string-col {:sort-value :string} :numeric-col {:sort-value :numeric}}] (testing "string column" (testing "mismatch" (is (= false (matches-filter column-definitions :string-col "foo" {:string "bar"})))) (testing "exact match" (is (= true (matches-filter column-definitions :string-col "foo" {:string "foo"})))) (testing "substring match" (is (= true (matches-filter column-definitions :string-col "ba" {:string "foobar"})))) (testing "case insensitive match" (is (= true (matches-filter column-definitions :string-col "Abc" {:string "abC"}))))) (testing "numeric column" (testing "mismatch" (is (= false (matches-filter column-definitions :numeric-col "42" {:numeric 123})))) (testing "exact match" (is (= true (matches-filter column-definitions :numeric-col "123" {:numeric 123})))) (testing "substring match" (is (= true (matches-filter column-definitions :numeric-col "2" {:numeric 123}))))))) (deftest matches-filters-test (let [column-definitions {:fname-col {:sort-value :first-name} :lname-col {:sort-value :last-name}} item {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}] (testing "no filters" (is (= true (matches-filters column-definitions {} item)))) (testing "one filter, matches" (is (= true (matches-filters column-definitions {:fname-col "Aku"} item)))) (testing "one filter, no match" (is (= false (matches-filters column-definitions {:fname-col "x"} item)))) (testing "many filters, all match" (is (= true (matches-filters column-definitions {:fname-col "Aku" :lname-col "Ankka"} item)))) (testing "many filters, only some match" (is (= false (matches-filters column-definitions {:fname-col "Aku" :lname-col "x"} item)))))) (deftest apply-filtering-test (let [column-definitions {:fname-col {:sort-value :first-name} :lname-col {:sort-value :last-name}} items [{:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]] (testing "empty list" (is (= [] (apply-filtering column-definitions {} [])))) (testing "without filters" (is (= items (apply-filtering column-definitions {} items)))) (testing "with filters" (is (= [{:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}] (apply-filtering column-definitions {:lname-col "Ankka"} items))))))
[ { "context": "mplementations of reduce-map-filter.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"20", "end": 253, "score": 0.8178306221961975, "start": 250, "tag": "EMAIL", "value": "pal" }, { "context": "ementations of reduce-map-filter.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017", "end": 255, "score": 0.5029480457305908, "start": 253, "tag": "NAME", "value": "is" }, { "context": "entations of reduce-map-filter.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-18\"}\n (:r", "end": 269, "score": 0.6307295560836792, "start": 255, "tag": "EMAIL", "value": "ades dot lakes" }, { "context": "ce-map-filter.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-18\"}\n (:require [palisades", "end": 286, "score": 0.7254642248153687, "start": 273, "tag": "EMAIL", "value": "gmail dot com" } ]
src/main/clojure/palisades/lakes/collex/transduce.clj
palisades-lakes/collection-experiments
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.transduce {:doc "Alternate implementations of reduce-map-filter." :author "palisades dot lakes at gmail dot com" :version "2017-12-18"} (:require [palisades.lakes.collex.arrays :as arrays]) (:import [java.util ArrayList Iterator] [clojure.lang IFn IPersistentList IPersistentVector])) ;;---------------------------------------------------------------- ;; TODO: handle general init values ;; TODO: primitive type hints? (defn composed ^IFn [^IFn r ^IFn m ^IFn f] (comp (partial reduce r) (partial map m) (partial filter f))) (defn reduce-map-filter ^IFn [^IFn r ^IFn m ^IFn f] (fn rmf [s] (reduce r (map m (filter f s))))) ;; !!!compose backwards for transducers!!! (defn transducer ^IFn [^IFn r ^IFn m ^IFn f] (let [fm (comp (filter f) (map m))] (fn transducer-rmf [s] (transduce fm r s)))) (defn manual ^IFn [^IFn r ^IFn m ^IFn f] (let [rr (fn [a x] (if (f x) (r a (m x)) a))] (fn manual-rmf ([init s] (reduce rr init s)) ([s] (let [x (first s)] (if (f x) (manual-rmf (m x) (rest s)) (recur (rest s)))))))) ;;---------------------------------------------------------------- ;; a special case for benchmarking, could turn into a macro? (defn inline [s] (cond (instance? ArrayList s) (let [s ^ArrayList s n (int (.size s))] (loop [i (int 0) sum (double 0.0)] (if (>= i n) sum (let [si (double (.get s i))] (if (<= 0 si) (recur (+ i 1) (+ sum (* si si))) (recur (+ i 1) sum)))))) (or (instance? IPersistentVector s) (instance? IPersistentList s)) (loop [s s sum (double 0.0)] (if (empty? s) sum (recur (rest s) (+ sum (double (first s)))))) (instance? Iterable s) (let [^Iterator it (.iterator ^Iterable s)] (loop [sum (long 0)] (if-not (.hasNext it) sum (let [si (long (.next it))] (if (<= 0 si) (recur (+ sum (* si si))) (recur sum)))))) (arrays/int-array? s) (let [^ints a s n (int (alength a))] (loop [i (int 0) sum (long 0)] (if (<= n i) sum (let [ai (aget a i)] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))) (arrays/array? s Integer) (let [^objects a s n (int (alength a))] (loop [i (int 0) sum (long 0)] (if (<= n i) sum (let [ai (.intValue ^Integer (aget a i))] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))) (arrays/float-array? s) (let [^floats a s n (int (alength a))] (loop [i (int 0) sum (double 0.0)] (if (<= n i) sum (let [ai (double (aget a i))] (if (<= 0.0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i) sum)))))) (arrays/array? s Float) (let [^objects a s n (int (alength a))] (loop [i (int 0) sum (double 0.0)] (if (<= n i) sum (let [ai (.doubleValue ^Float (aget a i))] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))))) ;;----------------------------------------------------------------
91254
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.transduce {:doc "Alternate implementations of reduce-map-filter." :author "<EMAIL> <NAME> <EMAIL> at <EMAIL>" :version "2017-12-18"} (:require [palisades.lakes.collex.arrays :as arrays]) (:import [java.util ArrayList Iterator] [clojure.lang IFn IPersistentList IPersistentVector])) ;;---------------------------------------------------------------- ;; TODO: handle general init values ;; TODO: primitive type hints? (defn composed ^IFn [^IFn r ^IFn m ^IFn f] (comp (partial reduce r) (partial map m) (partial filter f))) (defn reduce-map-filter ^IFn [^IFn r ^IFn m ^IFn f] (fn rmf [s] (reduce r (map m (filter f s))))) ;; !!!compose backwards for transducers!!! (defn transducer ^IFn [^IFn r ^IFn m ^IFn f] (let [fm (comp (filter f) (map m))] (fn transducer-rmf [s] (transduce fm r s)))) (defn manual ^IFn [^IFn r ^IFn m ^IFn f] (let [rr (fn [a x] (if (f x) (r a (m x)) a))] (fn manual-rmf ([init s] (reduce rr init s)) ([s] (let [x (first s)] (if (f x) (manual-rmf (m x) (rest s)) (recur (rest s)))))))) ;;---------------------------------------------------------------- ;; a special case for benchmarking, could turn into a macro? (defn inline [s] (cond (instance? ArrayList s) (let [s ^ArrayList s n (int (.size s))] (loop [i (int 0) sum (double 0.0)] (if (>= i n) sum (let [si (double (.get s i))] (if (<= 0 si) (recur (+ i 1) (+ sum (* si si))) (recur (+ i 1) sum)))))) (or (instance? IPersistentVector s) (instance? IPersistentList s)) (loop [s s sum (double 0.0)] (if (empty? s) sum (recur (rest s) (+ sum (double (first s)))))) (instance? Iterable s) (let [^Iterator it (.iterator ^Iterable s)] (loop [sum (long 0)] (if-not (.hasNext it) sum (let [si (long (.next it))] (if (<= 0 si) (recur (+ sum (* si si))) (recur sum)))))) (arrays/int-array? s) (let [^ints a s n (int (alength a))] (loop [i (int 0) sum (long 0)] (if (<= n i) sum (let [ai (aget a i)] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))) (arrays/array? s Integer) (let [^objects a s n (int (alength a))] (loop [i (int 0) sum (long 0)] (if (<= n i) sum (let [ai (.intValue ^Integer (aget a i))] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))) (arrays/float-array? s) (let [^floats a s n (int (alength a))] (loop [i (int 0) sum (double 0.0)] (if (<= n i) sum (let [ai (double (aget a i))] (if (<= 0.0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i) sum)))))) (arrays/array? s Float) (let [^objects a s n (int (alength a))] (loop [i (int 0) sum (double 0.0)] (if (<= n i) sum (let [ai (.doubleValue ^Float (aget a i))] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.collex.transduce {:doc "Alternate implementations of reduce-map-filter." :author "PI:EMAIL:<EMAIL>END_PI PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI" :version "2017-12-18"} (:require [palisades.lakes.collex.arrays :as arrays]) (:import [java.util ArrayList Iterator] [clojure.lang IFn IPersistentList IPersistentVector])) ;;---------------------------------------------------------------- ;; TODO: handle general init values ;; TODO: primitive type hints? (defn composed ^IFn [^IFn r ^IFn m ^IFn f] (comp (partial reduce r) (partial map m) (partial filter f))) (defn reduce-map-filter ^IFn [^IFn r ^IFn m ^IFn f] (fn rmf [s] (reduce r (map m (filter f s))))) ;; !!!compose backwards for transducers!!! (defn transducer ^IFn [^IFn r ^IFn m ^IFn f] (let [fm (comp (filter f) (map m))] (fn transducer-rmf [s] (transduce fm r s)))) (defn manual ^IFn [^IFn r ^IFn m ^IFn f] (let [rr (fn [a x] (if (f x) (r a (m x)) a))] (fn manual-rmf ([init s] (reduce rr init s)) ([s] (let [x (first s)] (if (f x) (manual-rmf (m x) (rest s)) (recur (rest s)))))))) ;;---------------------------------------------------------------- ;; a special case for benchmarking, could turn into a macro? (defn inline [s] (cond (instance? ArrayList s) (let [s ^ArrayList s n (int (.size s))] (loop [i (int 0) sum (double 0.0)] (if (>= i n) sum (let [si (double (.get s i))] (if (<= 0 si) (recur (+ i 1) (+ sum (* si si))) (recur (+ i 1) sum)))))) (or (instance? IPersistentVector s) (instance? IPersistentList s)) (loop [s s sum (double 0.0)] (if (empty? s) sum (recur (rest s) (+ sum (double (first s)))))) (instance? Iterable s) (let [^Iterator it (.iterator ^Iterable s)] (loop [sum (long 0)] (if-not (.hasNext it) sum (let [si (long (.next it))] (if (<= 0 si) (recur (+ sum (* si si))) (recur sum)))))) (arrays/int-array? s) (let [^ints a s n (int (alength a))] (loop [i (int 0) sum (long 0)] (if (<= n i) sum (let [ai (aget a i)] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))) (arrays/array? s Integer) (let [^objects a s n (int (alength a))] (loop [i (int 0) sum (long 0)] (if (<= n i) sum (let [ai (.intValue ^Integer (aget a i))] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))) (arrays/float-array? s) (let [^floats a s n (int (alength a))] (loop [i (int 0) sum (double 0.0)] (if (<= n i) sum (let [ai (double (aget a i))] (if (<= 0.0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i) sum)))))) (arrays/array? s Float) (let [^objects a s n (int (alength a))] (loop [i (int 0) sum (double 0.0)] (if (<= n i) sum (let [ai (.doubleValue ^Float (aget a i))] (if (<= 0 ai) (recur (inc i) (+ sum (* ai ai))) (recur (inc i)sum)))))))) ;;----------------------------------------------------------------
[ { "context": "[1 2 3]\n(get [1 2 3] 0)\n(get [1 {:first-name \"Leandro\" :last-name \"TK\"} 2] 1)\n(vector \"a\" \"new\" \"vector", "end": 53, "score": 0.9996168613433838, "start": 46, "tag": "NAME", "value": "Leandro" }, { "context": " 3] 0)\n(get [1 {:first-name \"Leandro\" :last-name \"TK\"} 2] 1)\n(vector \"a\" \"new\" \"vector\" \"of\" \"strings\"", "end": 69, "score": 0.9997583627700806, "start": 67, "tag": "NAME", "value": "TK" } ]
clojure/vectors.clj
galanggg/learning-functional-programming
1
[1 2 3] (get [1 2 3] 0) (get [1 {:first-name "Leandro" :last-name "TK"} 2] 1) (vector "a" "new" "vector" "of" "strings") (conj [1 2 3] 4)
52919
[1 2 3] (get [1 2 3] 0) (get [1 {:first-name "<NAME>" :last-name "<NAME>"} 2] 1) (vector "a" "new" "vector" "of" "strings") (conj [1 2 3] 4)
true
[1 2 3] (get [1 2 3] 0) (get [1 {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} 2] 1) (vector "a" "new" "vector" "of" "strings") (conj [1 2 3] 4)
[ { "context": "ps://\" s3-host))\n\n(def my-cloud-creds {:key \"key\"\n :secret \"secret\"\n ", "end": 389, "score": 0.7133228778839111, "start": 386, "tag": "KEY", "value": "key" }, { "context": " {:key \"key\"\n :secret \"secret\"\n :endpoint s3-endpoint})\n\n(d", "end": 429, "score": 0.869552731513977, "start": 423, "tag": "KEY", "value": "secret" } ]
code/test/sixsq/nuvla/server/resources/data_object_test.clj
nuvla/server
6
(ns sixsq.nuvla.server.resources.data-object-test (:require [clojure.string :as str] [clojure.test :refer [deftest is]] [sixsq.nuvla.server.resources.data-object :as eo] [sixsq.nuvla.server.resources.data.utils :as s3]) (:import (clojure.lang ExceptionInfo))) (def s3-host "s3.cloud.com") (def s3-endpoint (str "https://" s3-host)) (def my-cloud-creds {:key "key" :secret "secret" :endpoint s3-endpoint}) (def bucketname "bucket") (def runUUID "1-2-3-4-5") (def filename "component.1.tgz") (def objectname "object/name") (deftest test-upload-fn (with-redefs [s3/credential->s3-client-cfg (constantly my-cloud-creds)] (let [expected-msg (eo/error-msg-bad-state "upload" #{eo/state-new eo/state-uploading} eo/state-ready)] (is (thrown-with-msg? ExceptionInfo (re-pattern expected-msg) (eo/upload-fn {:state eo/state-ready} {})))) ;; generic data object (is (str/starts-with? (eo/upload-fn {:state eo/state-new :content-type "application/tar+gzip" :bucket bucketname :object objectname :credential "credential/my-cred"} {}) (format "https://%s/%s/%s?" s3-host bucketname objectname))) ;; data object report (is (str/starts-with? (eo/upload-fn {:state eo/state-new :content-type "application/tar+gzip" :bucket bucketname :credential "credential/my-cred" :runUUID runUUID :filename filename} {}) (format "https://%s/%s/%s/%s?" s3-host bucketname runUUID filename))))) (deftest test-download-fn (with-redefs [s3/credential->s3-client-cfg (constantly my-cloud-creds)] (let [expected-msg (eo/error-msg-bad-state "download" #{eo/state-ready} eo/state-new)] (is (thrown-with-msg? ExceptionInfo (re-pattern expected-msg) (eo/download-subtype {:state eo/state-new} {})))) (is (str/starts-with? (eo/download-subtype {:state eo/state-ready :bucket bucketname :object objectname :credential "credential/my-cred"} {}) (format "https://%s/%s/%s?" s3-host bucketname objectname)))))
44967
(ns sixsq.nuvla.server.resources.data-object-test (:require [clojure.string :as str] [clojure.test :refer [deftest is]] [sixsq.nuvla.server.resources.data-object :as eo] [sixsq.nuvla.server.resources.data.utils :as s3]) (:import (clojure.lang ExceptionInfo))) (def s3-host "s3.cloud.com") (def s3-endpoint (str "https://" s3-host)) (def my-cloud-creds {:key "<KEY>" :secret "<KEY>" :endpoint s3-endpoint}) (def bucketname "bucket") (def runUUID "1-2-3-4-5") (def filename "component.1.tgz") (def objectname "object/name") (deftest test-upload-fn (with-redefs [s3/credential->s3-client-cfg (constantly my-cloud-creds)] (let [expected-msg (eo/error-msg-bad-state "upload" #{eo/state-new eo/state-uploading} eo/state-ready)] (is (thrown-with-msg? ExceptionInfo (re-pattern expected-msg) (eo/upload-fn {:state eo/state-ready} {})))) ;; generic data object (is (str/starts-with? (eo/upload-fn {:state eo/state-new :content-type "application/tar+gzip" :bucket bucketname :object objectname :credential "credential/my-cred"} {}) (format "https://%s/%s/%s?" s3-host bucketname objectname))) ;; data object report (is (str/starts-with? (eo/upload-fn {:state eo/state-new :content-type "application/tar+gzip" :bucket bucketname :credential "credential/my-cred" :runUUID runUUID :filename filename} {}) (format "https://%s/%s/%s/%s?" s3-host bucketname runUUID filename))))) (deftest test-download-fn (with-redefs [s3/credential->s3-client-cfg (constantly my-cloud-creds)] (let [expected-msg (eo/error-msg-bad-state "download" #{eo/state-ready} eo/state-new)] (is (thrown-with-msg? ExceptionInfo (re-pattern expected-msg) (eo/download-subtype {:state eo/state-new} {})))) (is (str/starts-with? (eo/download-subtype {:state eo/state-ready :bucket bucketname :object objectname :credential "credential/my-cred"} {}) (format "https://%s/%s/%s?" s3-host bucketname objectname)))))
true
(ns sixsq.nuvla.server.resources.data-object-test (:require [clojure.string :as str] [clojure.test :refer [deftest is]] [sixsq.nuvla.server.resources.data-object :as eo] [sixsq.nuvla.server.resources.data.utils :as s3]) (:import (clojure.lang ExceptionInfo))) (def s3-host "s3.cloud.com") (def s3-endpoint (str "https://" s3-host)) (def my-cloud-creds {:key "PI:KEY:<KEY>END_PI" :secret "PI:KEY:<KEY>END_PI" :endpoint s3-endpoint}) (def bucketname "bucket") (def runUUID "1-2-3-4-5") (def filename "component.1.tgz") (def objectname "object/name") (deftest test-upload-fn (with-redefs [s3/credential->s3-client-cfg (constantly my-cloud-creds)] (let [expected-msg (eo/error-msg-bad-state "upload" #{eo/state-new eo/state-uploading} eo/state-ready)] (is (thrown-with-msg? ExceptionInfo (re-pattern expected-msg) (eo/upload-fn {:state eo/state-ready} {})))) ;; generic data object (is (str/starts-with? (eo/upload-fn {:state eo/state-new :content-type "application/tar+gzip" :bucket bucketname :object objectname :credential "credential/my-cred"} {}) (format "https://%s/%s/%s?" s3-host bucketname objectname))) ;; data object report (is (str/starts-with? (eo/upload-fn {:state eo/state-new :content-type "application/tar+gzip" :bucket bucketname :credential "credential/my-cred" :runUUID runUUID :filename filename} {}) (format "https://%s/%s/%s/%s?" s3-host bucketname runUUID filename))))) (deftest test-download-fn (with-redefs [s3/credential->s3-client-cfg (constantly my-cloud-creds)] (let [expected-msg (eo/error-msg-bad-state "download" #{eo/state-ready} eo/state-new)] (is (thrown-with-msg? ExceptionInfo (re-pattern expected-msg) (eo/download-subtype {:state eo/state-new} {})))) (is (str/starts-with? (eo/download-subtype {:state eo/state-ready :bucket bucketname :object objectname :credential "credential/my-cred"} {}) (format "https://%s/%s/%s?" s3-host bucketname objectname)))))
[ { "context": "er [app-handler]]))\n\n(def auth-config {:username \"admin\" :password \"hunter2\"})\n\n(defn -main\n [& args]\n ", "end": 172, "score": 0.9958750605583191, "start": 167, "tag": "USERNAME", "value": "admin" }, { "context": ")\n\n(def auth-config {:username \"admin\" :password \"hunter2\"})\n\n(defn -main\n [& args]\n (println \"starting s", "end": 192, "score": 0.9985249638557434, "start": 185, "tag": "PASSWORD", "value": "hunter2" } ]
src/http_server/core.clj
andrewMacmurray/clojure-http
2
(ns http-server.core (:gen-class) (:require [http-server.server :as server] [http-server.cob-app :refer [app-handler]])) (def auth-config {:username "admin" :password "hunter2"}) (defn -main [& args] (println "starting server") (server/serve 5000 (app-handler "public" auth-config)))
74126
(ns http-server.core (:gen-class) (:require [http-server.server :as server] [http-server.cob-app :refer [app-handler]])) (def auth-config {:username "admin" :password "<PASSWORD>"}) (defn -main [& args] (println "starting server") (server/serve 5000 (app-handler "public" auth-config)))
true
(ns http-server.core (:gen-class) (:require [http-server.server :as server] [http-server.cob-app :refer [app-handler]])) (def auth-config {:username "admin" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (defn -main [& args] (println "starting server") (server/serve 5000 (app-handler "public" auth-config)))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998700618743896, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": " lazy trees and\n emit these as text.\"\n :author \"Chris Houser\"}\n clojure.data.xml\n (:require [clojure.string ", "end": 584, "score": 0.9998894929885864, "start": 572, "tag": "NAME", "value": "Chris Houser" } ]
clojure/data/xml.clj
prapisarda/Scripts
0
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Functions to parse XML into lazy sequences and lazy trees and emit these as text." :author "Chris Houser"} clojure.data.xml (:require [clojure.string :as str]) (:import (javax.xml.stream XMLInputFactory XMLStreamReader XMLStreamConstants) (java.nio.charset Charset) (java.io Reader))) ; Represents a parse event. ; type is one of :start-element, :end-element, or :characters (defrecord Event [type name attrs str]) (defn event [type name & [attrs str]] (Event. type name attrs str)) (defn qualified-name [event-name] (if (instance? clojure.lang.Named event-name) [(namespace event-name) (name event-name)] (let [name-parts (str/split event-name #"/" 2)] (if (= 2 (count name-parts)) name-parts [nil (first name-parts)])))) (defn write-attributes [attrs ^javax.xml.stream.XMLStreamWriter writer] (doseq [[k v] attrs] (let [[attr-ns attr-name] (qualified-name k)] (if attr-ns (.writeAttribute writer attr-ns attr-name (str v)) (.writeAttribute writer attr-name (str v)))))) ; Represents a node of an XML tree (defrecord Element [tag attrs content]) (defrecord CData [content]) (defrecord Comment [content]) (defn emit-start-tag [event ^javax.xml.stream.XMLStreamWriter writer] (let [[nspace qname] (qualified-name (:name event))] (.writeStartElement writer "" qname (or nspace "")) (write-attributes (:attrs event) writer))) (defn str-empty? [s] (or (nil? s) (= s ""))) (defn emit-cdata [^String cdata-str ^javax.xml.stream.XMLStreamWriter writer] (when-not (str-empty? cdata-str) (let [idx (.indexOf cdata-str "]]>")] (if (= idx -1) (.writeCData writer cdata-str ) (do (.writeCData writer (subs cdata-str 0 (+ idx 2))) (recur (subs cdata-str (+ idx 2)) writer)))))) (defn emit-event [event ^javax.xml.stream.XMLStreamWriter writer] (case (:type event) :start-element (emit-start-tag event writer) :end-element (.writeEndElement writer) :chars (.writeCharacters writer (:str event)) :cdata (emit-cdata (:str event) writer) :comment (.writeComment writer (:str event)))) (defprotocol EventGeneration "Protocol for generating new events based on element type" (gen-event [item] "Function to generate an event for e.") (next-events [item next-items] "Returns the next set of events that should occur after e. next-events are the events that should be generated after this one is complete.")) (extend-protocol EventGeneration Element (gen-event [element] (Event. :start-element (:tag element) (:attrs element) nil)) (next-events [element next-items] (cons (:content element) (cons (Event. :end-element (:tag element) nil nil) next-items))) Event (gen-event [event] event) (next-events [_ next-items] next-items) clojure.lang.Sequential (gen-event [coll] (gen-event (first coll))) (next-events [coll next-items] (if-let [r (seq (rest coll))] (cons (next-events (first coll) r) next-items) (next-events (first coll) next-items))) String (gen-event [s] (Event. :chars nil nil s)) (next-events [_ next-items] next-items) Boolean (gen-event [b] (Event. :chars nil nil (str b))) (next-events [_ next-items] next-items) Number (gen-event [b] (Event. :chars nil nil (str b))) (next-events [_ next-items] next-items) CData (gen-event [cdata] (Event. :cdata nil nil (:content cdata))) (next-events [_ next-items] next-items) Comment (gen-event [comment] (Event. :comment nil nil (:content comment))) (next-events [_ next-items] next-items) nil (gen-event [_] (Event. :chars nil nil "")) (next-events [_ next-items] next-items)) (defn flatten-elements [elements] (when (seq elements) (lazy-seq (let [e (first elements)] (cons (gen-event e) (flatten-elements (next-events e (rest elements)))))))) (defn element [tag & [attrs & content]] (Element. tag (or attrs {}) (remove nil? content))) (defn cdata [content] (CData. content)) (defn xml-comment [content] (Comment. content)) ;=== Parse-related functions === (defn seq-tree "Takes a seq of events that logically represents a tree by each event being one of: enter-sub-tree event, exit-sub-tree event, or node event. Returns a lazy sequence whose first element is a sequence of sub-trees and whose remaining elements are events that are not siblings or descendants of the initial event. The given exit? function must return true for any exit-sub-tree event. parent must be a function of two arguments: the first is an event, the second a sequence of nodes or subtrees that are children of the event. parent must return nil or false if the event is not an enter-sub-tree event. Any other return value will become a sub-tree of the output tree and should normally contain in some way the children passed as the second arg. The node function is called with a single event arg on every event that is neither parent nor exit, and its return value will become a node of the output tree. (seq-tree #(when (= %1 :<) (vector %2)) #{:>} str [1 2 :< 3 :< 4 :> :> 5 :> 6]) ;=> ((\"1\" \"2\" [(\"3\" [(\"4\")])] \"5\") 6)" [parent exit? node coll] (lazy-seq (when-let [[event] (seq coll)] (let [more (rest coll)] (if (exit? event) (cons nil more) (let [tree (seq-tree parent exit? node more)] (if-let [p (parent event (lazy-seq (first tree)))] (let [subtree (seq-tree parent exit? node (lazy-seq (rest tree)))] (cons (cons p (lazy-seq (first subtree))) (lazy-seq (rest subtree)))) (cons (cons (node event) (lazy-seq (first tree))) (lazy-seq (rest tree)))))))))) (defn event-tree "Returns a lazy tree of Element objects for the given seq of Event objects. See source-seq and parse." [events] (ffirst (seq-tree (fn [^Event event contents] (when (= :start-element (.type event)) (Element. (.name event) (.attrs event) contents))) (fn [^Event event] (= :end-element (.type event))) (fn [^Event event] (.str event)) events))) (defprotocol AsElements (as-elements [expr] "Return a seq of elements represented by an expression.")) (defn sexp-element [tag attrs child] (cond (= :-cdata tag) (CData. (first child)) (= :-comment tag) (Comment. (first child)) :else (Element. tag attrs (mapcat as-elements child)))) (extend-protocol AsElements clojure.lang.IPersistentVector (as-elements [v] (let [[tag & [attrs & after-attrs :as content]] v [attrs content] (if (map? attrs) [(into {} (for [[k v] attrs] [k (str v)])) after-attrs] [{} content])] [(sexp-element tag attrs content)])) clojure.lang.ISeq (as-elements [s] (mapcat as-elements s)) clojure.lang.Keyword (as-elements [k] [(Element. k {} ())]) java.lang.String (as-elements [s] [s]) nil (as-elements [_] nil) java.lang.Object (as-elements [o] [(str o)])) (defn sexps-as-fragment "Convert a compact prxml/hiccup-style data structure into the more formal tag/attrs/content format. A seq of elements will be returned, which may not be suitable for immediate use as there is no root element. See also sexp-as-element. The format is [:tag-name attr-map? content*]. Each vector opens a new tag; seqs do not open new tags, and are just used for inserting groups of elements into the parent tag. A bare keyword not in a vector creates an empty element. To provide XML conversion for your own data types, extend the AsElements protocol to them." ([] nil) ([sexp] (as-elements sexp)) ([sexp & sexps] (mapcat as-elements (cons sexp sexps)))) (defn sexp-as-element "Convert a single sexp into an Element" [sexp] (let [[root & more] (sexps-as-fragment sexp)] (when more (throw (IllegalArgumentException. "Cannot have multiple root elements; try creating a fragment instead"))) root)) (defn- attr-prefix [^XMLStreamReader sreader index] (let [p (.getAttributePrefix sreader index)] (when-not (str/blank? p) p))) (defn- attr-hash [^XMLStreamReader sreader] (into {} (for [i (range (.getAttributeCount sreader))] [(keyword (attr-prefix sreader i) (.getAttributeLocalName sreader i)) (.getAttributeValue sreader i)]))) ; Note, sreader is mutable and mutated here in pull-seq, but it's ; protected by a lazy-seq so it's thread-safe. (defn- pull-seq "Creates a seq of events. The XMLStreamConstants/SPACE clause below doesn't seem to be triggered by the JDK StAX parser, but is by others. Leaving in to be more complete." [^XMLStreamReader sreader] (lazy-seq (loop [] (condp == (.next sreader) XMLStreamConstants/START_ELEMENT (cons (event :start-element (keyword (.getLocalName sreader)) (attr-hash sreader) nil) (pull-seq sreader)) XMLStreamConstants/END_ELEMENT (cons (event :end-element (keyword (.getLocalName sreader)) nil nil) (pull-seq sreader)) XMLStreamConstants/CHARACTERS (if-let [text (and (not (.isWhiteSpace sreader)) (.getText sreader))] (cons (event :characters nil nil text) (pull-seq sreader)) (recur)) XMLStreamConstants/END_DOCUMENT nil (recur);; Consume and ignore comments, spaces, processing instructions etc )))) (def ^{:private true} xml-input-factory-props {:allocator javax.xml.stream.XMLInputFactory/ALLOCATOR :coalescing javax.xml.stream.XMLInputFactory/IS_COALESCING :namespace-aware javax.xml.stream.XMLInputFactory/IS_NAMESPACE_AWARE :replacing-entity-references javax.xml.stream.XMLInputFactory/IS_REPLACING_ENTITY_REFERENCES :supporting-external-entities javax.xml.stream.XMLInputFactory/IS_SUPPORTING_EXTERNAL_ENTITIES :validating javax.xml.stream.XMLInputFactory/IS_VALIDATING :reporter javax.xml.stream.XMLInputFactory/REPORTER :resolver javax.xml.stream.XMLInputFactory/RESOLVER :support-dtd javax.xml.stream.XMLInputFactory/SUPPORT_DTD}) (defn- new-xml-input-factory [props] (let [fac (javax.xml.stream.XMLInputFactory/newInstance)] (doseq [[k v] props :let [prop (xml-input-factory-props k)]] (.setProperty fac prop v)) fac)) (defn source-seq "Parses the XML InputSource source using a pull-parser. Returns a lazy sequence of Event records. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [s & {:as props}] (let [fac (new-xml-input-factory (merge {:coalescing true} props)) ;; Reflection on following line cannot be eliminated via a ;; type hint, because s is advertised by fn parse to be an ;; InputStream or Reader, and there are different ;; createXMLStreamReader signatures for each of those types. sreader (.createXMLStreamReader fac s)] (pull-seq sreader))) (defn parse "Parses the source, which can be an InputStream or Reader, and returns a lazy tree of Element records. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [source & props] (event-tree (apply source-seq source props))) (defn parse-str "Parses the passed in string to Clojure data structures. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [s & props] (let [sr (java.io.StringReader. s)] (apply parse sr props))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; XML Emitting ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn check-stream-encoding [^java.io.OutputStreamWriter stream xml-encoding] (when (not= (Charset/forName xml-encoding) (Charset/forName (.getEncoding stream))) (throw (Exception. (str "Output encoding of stream (" xml-encoding ") doesn't match declaration (" (.getEncoding stream) ")"))))) (defn emit "Prints the given Element tree as XML text to stream. Options: :encoding <str> Character encoding to use" [e ^java.io.Writer stream & {:as opts}] (let [^javax.xml.stream.XMLStreamWriter writer (-> (javax.xml.stream.XMLOutputFactory/newInstance) (.createXMLStreamWriter stream))] (when (instance? java.io.OutputStreamWriter stream) (check-stream-encoding stream (or (:encoding opts) "UTF-8"))) (.writeStartDocument writer (or (:encoding opts) "UTF-8") "1.0") (doseq [event (flatten-elements [e])] (emit-event event writer)) (.writeEndDocument writer) stream)) (defn emit-str "Emits the Element to String and returns it" [e] (let [^java.io.StringWriter sw (java.io.StringWriter.)] (emit e sw) (.toString sw))) (defn ^javax.xml.transform.Transformer indenting-transformer [] (doto (-> (javax.xml.transform.TransformerFactory/newInstance) .newTransformer) (.setOutputProperty (javax.xml.transform.OutputKeys/INDENT) "yes") (.setOutputProperty (javax.xml.transform.OutputKeys/METHOD) "xml") (.setOutputProperty "{http://xml.apache.org/xslt}indent-amount" "2"))) (defn indent "Emits the XML and indents the result. WARNING: this is slow it will emit the XML and read it in again to indent it. Intended for debugging/testing only." [e ^java.io.Writer stream & {:as opts}] (let [sw (java.io.StringWriter.) _ (apply emit e sw (apply concat opts)) source (-> sw .toString java.io.StringReader. javax.xml.transform.stream.StreamSource.) result (javax.xml.transform.stream.StreamResult. stream)] (.transform (indenting-transformer) source result))) (defn indent-str "Emits the XML and indents the result. Writes the results to a String and returns it" [e] (let [^java.io.StringWriter sw (java.io.StringWriter.)] (indent e sw) (.toString sw)))
30631
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Functions to parse XML into lazy sequences and lazy trees and emit these as text." :author "<NAME>"} clojure.data.xml (:require [clojure.string :as str]) (:import (javax.xml.stream XMLInputFactory XMLStreamReader XMLStreamConstants) (java.nio.charset Charset) (java.io Reader))) ; Represents a parse event. ; type is one of :start-element, :end-element, or :characters (defrecord Event [type name attrs str]) (defn event [type name & [attrs str]] (Event. type name attrs str)) (defn qualified-name [event-name] (if (instance? clojure.lang.Named event-name) [(namespace event-name) (name event-name)] (let [name-parts (str/split event-name #"/" 2)] (if (= 2 (count name-parts)) name-parts [nil (first name-parts)])))) (defn write-attributes [attrs ^javax.xml.stream.XMLStreamWriter writer] (doseq [[k v] attrs] (let [[attr-ns attr-name] (qualified-name k)] (if attr-ns (.writeAttribute writer attr-ns attr-name (str v)) (.writeAttribute writer attr-name (str v)))))) ; Represents a node of an XML tree (defrecord Element [tag attrs content]) (defrecord CData [content]) (defrecord Comment [content]) (defn emit-start-tag [event ^javax.xml.stream.XMLStreamWriter writer] (let [[nspace qname] (qualified-name (:name event))] (.writeStartElement writer "" qname (or nspace "")) (write-attributes (:attrs event) writer))) (defn str-empty? [s] (or (nil? s) (= s ""))) (defn emit-cdata [^String cdata-str ^javax.xml.stream.XMLStreamWriter writer] (when-not (str-empty? cdata-str) (let [idx (.indexOf cdata-str "]]>")] (if (= idx -1) (.writeCData writer cdata-str ) (do (.writeCData writer (subs cdata-str 0 (+ idx 2))) (recur (subs cdata-str (+ idx 2)) writer)))))) (defn emit-event [event ^javax.xml.stream.XMLStreamWriter writer] (case (:type event) :start-element (emit-start-tag event writer) :end-element (.writeEndElement writer) :chars (.writeCharacters writer (:str event)) :cdata (emit-cdata (:str event) writer) :comment (.writeComment writer (:str event)))) (defprotocol EventGeneration "Protocol for generating new events based on element type" (gen-event [item] "Function to generate an event for e.") (next-events [item next-items] "Returns the next set of events that should occur after e. next-events are the events that should be generated after this one is complete.")) (extend-protocol EventGeneration Element (gen-event [element] (Event. :start-element (:tag element) (:attrs element) nil)) (next-events [element next-items] (cons (:content element) (cons (Event. :end-element (:tag element) nil nil) next-items))) Event (gen-event [event] event) (next-events [_ next-items] next-items) clojure.lang.Sequential (gen-event [coll] (gen-event (first coll))) (next-events [coll next-items] (if-let [r (seq (rest coll))] (cons (next-events (first coll) r) next-items) (next-events (first coll) next-items))) String (gen-event [s] (Event. :chars nil nil s)) (next-events [_ next-items] next-items) Boolean (gen-event [b] (Event. :chars nil nil (str b))) (next-events [_ next-items] next-items) Number (gen-event [b] (Event. :chars nil nil (str b))) (next-events [_ next-items] next-items) CData (gen-event [cdata] (Event. :cdata nil nil (:content cdata))) (next-events [_ next-items] next-items) Comment (gen-event [comment] (Event. :comment nil nil (:content comment))) (next-events [_ next-items] next-items) nil (gen-event [_] (Event. :chars nil nil "")) (next-events [_ next-items] next-items)) (defn flatten-elements [elements] (when (seq elements) (lazy-seq (let [e (first elements)] (cons (gen-event e) (flatten-elements (next-events e (rest elements)))))))) (defn element [tag & [attrs & content]] (Element. tag (or attrs {}) (remove nil? content))) (defn cdata [content] (CData. content)) (defn xml-comment [content] (Comment. content)) ;=== Parse-related functions === (defn seq-tree "Takes a seq of events that logically represents a tree by each event being one of: enter-sub-tree event, exit-sub-tree event, or node event. Returns a lazy sequence whose first element is a sequence of sub-trees and whose remaining elements are events that are not siblings or descendants of the initial event. The given exit? function must return true for any exit-sub-tree event. parent must be a function of two arguments: the first is an event, the second a sequence of nodes or subtrees that are children of the event. parent must return nil or false if the event is not an enter-sub-tree event. Any other return value will become a sub-tree of the output tree and should normally contain in some way the children passed as the second arg. The node function is called with a single event arg on every event that is neither parent nor exit, and its return value will become a node of the output tree. (seq-tree #(when (= %1 :<) (vector %2)) #{:>} str [1 2 :< 3 :< 4 :> :> 5 :> 6]) ;=> ((\"1\" \"2\" [(\"3\" [(\"4\")])] \"5\") 6)" [parent exit? node coll] (lazy-seq (when-let [[event] (seq coll)] (let [more (rest coll)] (if (exit? event) (cons nil more) (let [tree (seq-tree parent exit? node more)] (if-let [p (parent event (lazy-seq (first tree)))] (let [subtree (seq-tree parent exit? node (lazy-seq (rest tree)))] (cons (cons p (lazy-seq (first subtree))) (lazy-seq (rest subtree)))) (cons (cons (node event) (lazy-seq (first tree))) (lazy-seq (rest tree)))))))))) (defn event-tree "Returns a lazy tree of Element objects for the given seq of Event objects. See source-seq and parse." [events] (ffirst (seq-tree (fn [^Event event contents] (when (= :start-element (.type event)) (Element. (.name event) (.attrs event) contents))) (fn [^Event event] (= :end-element (.type event))) (fn [^Event event] (.str event)) events))) (defprotocol AsElements (as-elements [expr] "Return a seq of elements represented by an expression.")) (defn sexp-element [tag attrs child] (cond (= :-cdata tag) (CData. (first child)) (= :-comment tag) (Comment. (first child)) :else (Element. tag attrs (mapcat as-elements child)))) (extend-protocol AsElements clojure.lang.IPersistentVector (as-elements [v] (let [[tag & [attrs & after-attrs :as content]] v [attrs content] (if (map? attrs) [(into {} (for [[k v] attrs] [k (str v)])) after-attrs] [{} content])] [(sexp-element tag attrs content)])) clojure.lang.ISeq (as-elements [s] (mapcat as-elements s)) clojure.lang.Keyword (as-elements [k] [(Element. k {} ())]) java.lang.String (as-elements [s] [s]) nil (as-elements [_] nil) java.lang.Object (as-elements [o] [(str o)])) (defn sexps-as-fragment "Convert a compact prxml/hiccup-style data structure into the more formal tag/attrs/content format. A seq of elements will be returned, which may not be suitable for immediate use as there is no root element. See also sexp-as-element. The format is [:tag-name attr-map? content*]. Each vector opens a new tag; seqs do not open new tags, and are just used for inserting groups of elements into the parent tag. A bare keyword not in a vector creates an empty element. To provide XML conversion for your own data types, extend the AsElements protocol to them." ([] nil) ([sexp] (as-elements sexp)) ([sexp & sexps] (mapcat as-elements (cons sexp sexps)))) (defn sexp-as-element "Convert a single sexp into an Element" [sexp] (let [[root & more] (sexps-as-fragment sexp)] (when more (throw (IllegalArgumentException. "Cannot have multiple root elements; try creating a fragment instead"))) root)) (defn- attr-prefix [^XMLStreamReader sreader index] (let [p (.getAttributePrefix sreader index)] (when-not (str/blank? p) p))) (defn- attr-hash [^XMLStreamReader sreader] (into {} (for [i (range (.getAttributeCount sreader))] [(keyword (attr-prefix sreader i) (.getAttributeLocalName sreader i)) (.getAttributeValue sreader i)]))) ; Note, sreader is mutable and mutated here in pull-seq, but it's ; protected by a lazy-seq so it's thread-safe. (defn- pull-seq "Creates a seq of events. The XMLStreamConstants/SPACE clause below doesn't seem to be triggered by the JDK StAX parser, but is by others. Leaving in to be more complete." [^XMLStreamReader sreader] (lazy-seq (loop [] (condp == (.next sreader) XMLStreamConstants/START_ELEMENT (cons (event :start-element (keyword (.getLocalName sreader)) (attr-hash sreader) nil) (pull-seq sreader)) XMLStreamConstants/END_ELEMENT (cons (event :end-element (keyword (.getLocalName sreader)) nil nil) (pull-seq sreader)) XMLStreamConstants/CHARACTERS (if-let [text (and (not (.isWhiteSpace sreader)) (.getText sreader))] (cons (event :characters nil nil text) (pull-seq sreader)) (recur)) XMLStreamConstants/END_DOCUMENT nil (recur);; Consume and ignore comments, spaces, processing instructions etc )))) (def ^{:private true} xml-input-factory-props {:allocator javax.xml.stream.XMLInputFactory/ALLOCATOR :coalescing javax.xml.stream.XMLInputFactory/IS_COALESCING :namespace-aware javax.xml.stream.XMLInputFactory/IS_NAMESPACE_AWARE :replacing-entity-references javax.xml.stream.XMLInputFactory/IS_REPLACING_ENTITY_REFERENCES :supporting-external-entities javax.xml.stream.XMLInputFactory/IS_SUPPORTING_EXTERNAL_ENTITIES :validating javax.xml.stream.XMLInputFactory/IS_VALIDATING :reporter javax.xml.stream.XMLInputFactory/REPORTER :resolver javax.xml.stream.XMLInputFactory/RESOLVER :support-dtd javax.xml.stream.XMLInputFactory/SUPPORT_DTD}) (defn- new-xml-input-factory [props] (let [fac (javax.xml.stream.XMLInputFactory/newInstance)] (doseq [[k v] props :let [prop (xml-input-factory-props k)]] (.setProperty fac prop v)) fac)) (defn source-seq "Parses the XML InputSource source using a pull-parser. Returns a lazy sequence of Event records. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [s & {:as props}] (let [fac (new-xml-input-factory (merge {:coalescing true} props)) ;; Reflection on following line cannot be eliminated via a ;; type hint, because s is advertised by fn parse to be an ;; InputStream or Reader, and there are different ;; createXMLStreamReader signatures for each of those types. sreader (.createXMLStreamReader fac s)] (pull-seq sreader))) (defn parse "Parses the source, which can be an InputStream or Reader, and returns a lazy tree of Element records. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [source & props] (event-tree (apply source-seq source props))) (defn parse-str "Parses the passed in string to Clojure data structures. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [s & props] (let [sr (java.io.StringReader. s)] (apply parse sr props))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; XML Emitting ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn check-stream-encoding [^java.io.OutputStreamWriter stream xml-encoding] (when (not= (Charset/forName xml-encoding) (Charset/forName (.getEncoding stream))) (throw (Exception. (str "Output encoding of stream (" xml-encoding ") doesn't match declaration (" (.getEncoding stream) ")"))))) (defn emit "Prints the given Element tree as XML text to stream. Options: :encoding <str> Character encoding to use" [e ^java.io.Writer stream & {:as opts}] (let [^javax.xml.stream.XMLStreamWriter writer (-> (javax.xml.stream.XMLOutputFactory/newInstance) (.createXMLStreamWriter stream))] (when (instance? java.io.OutputStreamWriter stream) (check-stream-encoding stream (or (:encoding opts) "UTF-8"))) (.writeStartDocument writer (or (:encoding opts) "UTF-8") "1.0") (doseq [event (flatten-elements [e])] (emit-event event writer)) (.writeEndDocument writer) stream)) (defn emit-str "Emits the Element to String and returns it" [e] (let [^java.io.StringWriter sw (java.io.StringWriter.)] (emit e sw) (.toString sw))) (defn ^javax.xml.transform.Transformer indenting-transformer [] (doto (-> (javax.xml.transform.TransformerFactory/newInstance) .newTransformer) (.setOutputProperty (javax.xml.transform.OutputKeys/INDENT) "yes") (.setOutputProperty (javax.xml.transform.OutputKeys/METHOD) "xml") (.setOutputProperty "{http://xml.apache.org/xslt}indent-amount" "2"))) (defn indent "Emits the XML and indents the result. WARNING: this is slow it will emit the XML and read it in again to indent it. Intended for debugging/testing only." [e ^java.io.Writer stream & {:as opts}] (let [sw (java.io.StringWriter.) _ (apply emit e sw (apply concat opts)) source (-> sw .toString java.io.StringReader. javax.xml.transform.stream.StreamSource.) result (javax.xml.transform.stream.StreamResult. stream)] (.transform (indenting-transformer) source result))) (defn indent-str "Emits the XML and indents the result. Writes the results to a String and returns it" [e] (let [^java.io.StringWriter sw (java.io.StringWriter.)] (indent e sw) (.toString sw)))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Functions to parse XML into lazy sequences and lazy trees and emit these as text." :author "PI:NAME:<NAME>END_PI"} clojure.data.xml (:require [clojure.string :as str]) (:import (javax.xml.stream XMLInputFactory XMLStreamReader XMLStreamConstants) (java.nio.charset Charset) (java.io Reader))) ; Represents a parse event. ; type is one of :start-element, :end-element, or :characters (defrecord Event [type name attrs str]) (defn event [type name & [attrs str]] (Event. type name attrs str)) (defn qualified-name [event-name] (if (instance? clojure.lang.Named event-name) [(namespace event-name) (name event-name)] (let [name-parts (str/split event-name #"/" 2)] (if (= 2 (count name-parts)) name-parts [nil (first name-parts)])))) (defn write-attributes [attrs ^javax.xml.stream.XMLStreamWriter writer] (doseq [[k v] attrs] (let [[attr-ns attr-name] (qualified-name k)] (if attr-ns (.writeAttribute writer attr-ns attr-name (str v)) (.writeAttribute writer attr-name (str v)))))) ; Represents a node of an XML tree (defrecord Element [tag attrs content]) (defrecord CData [content]) (defrecord Comment [content]) (defn emit-start-tag [event ^javax.xml.stream.XMLStreamWriter writer] (let [[nspace qname] (qualified-name (:name event))] (.writeStartElement writer "" qname (or nspace "")) (write-attributes (:attrs event) writer))) (defn str-empty? [s] (or (nil? s) (= s ""))) (defn emit-cdata [^String cdata-str ^javax.xml.stream.XMLStreamWriter writer] (when-not (str-empty? cdata-str) (let [idx (.indexOf cdata-str "]]>")] (if (= idx -1) (.writeCData writer cdata-str ) (do (.writeCData writer (subs cdata-str 0 (+ idx 2))) (recur (subs cdata-str (+ idx 2)) writer)))))) (defn emit-event [event ^javax.xml.stream.XMLStreamWriter writer] (case (:type event) :start-element (emit-start-tag event writer) :end-element (.writeEndElement writer) :chars (.writeCharacters writer (:str event)) :cdata (emit-cdata (:str event) writer) :comment (.writeComment writer (:str event)))) (defprotocol EventGeneration "Protocol for generating new events based on element type" (gen-event [item] "Function to generate an event for e.") (next-events [item next-items] "Returns the next set of events that should occur after e. next-events are the events that should be generated after this one is complete.")) (extend-protocol EventGeneration Element (gen-event [element] (Event. :start-element (:tag element) (:attrs element) nil)) (next-events [element next-items] (cons (:content element) (cons (Event. :end-element (:tag element) nil nil) next-items))) Event (gen-event [event] event) (next-events [_ next-items] next-items) clojure.lang.Sequential (gen-event [coll] (gen-event (first coll))) (next-events [coll next-items] (if-let [r (seq (rest coll))] (cons (next-events (first coll) r) next-items) (next-events (first coll) next-items))) String (gen-event [s] (Event. :chars nil nil s)) (next-events [_ next-items] next-items) Boolean (gen-event [b] (Event. :chars nil nil (str b))) (next-events [_ next-items] next-items) Number (gen-event [b] (Event. :chars nil nil (str b))) (next-events [_ next-items] next-items) CData (gen-event [cdata] (Event. :cdata nil nil (:content cdata))) (next-events [_ next-items] next-items) Comment (gen-event [comment] (Event. :comment nil nil (:content comment))) (next-events [_ next-items] next-items) nil (gen-event [_] (Event. :chars nil nil "")) (next-events [_ next-items] next-items)) (defn flatten-elements [elements] (when (seq elements) (lazy-seq (let [e (first elements)] (cons (gen-event e) (flatten-elements (next-events e (rest elements)))))))) (defn element [tag & [attrs & content]] (Element. tag (or attrs {}) (remove nil? content))) (defn cdata [content] (CData. content)) (defn xml-comment [content] (Comment. content)) ;=== Parse-related functions === (defn seq-tree "Takes a seq of events that logically represents a tree by each event being one of: enter-sub-tree event, exit-sub-tree event, or node event. Returns a lazy sequence whose first element is a sequence of sub-trees and whose remaining elements are events that are not siblings or descendants of the initial event. The given exit? function must return true for any exit-sub-tree event. parent must be a function of two arguments: the first is an event, the second a sequence of nodes or subtrees that are children of the event. parent must return nil or false if the event is not an enter-sub-tree event. Any other return value will become a sub-tree of the output tree and should normally contain in some way the children passed as the second arg. The node function is called with a single event arg on every event that is neither parent nor exit, and its return value will become a node of the output tree. (seq-tree #(when (= %1 :<) (vector %2)) #{:>} str [1 2 :< 3 :< 4 :> :> 5 :> 6]) ;=> ((\"1\" \"2\" [(\"3\" [(\"4\")])] \"5\") 6)" [parent exit? node coll] (lazy-seq (when-let [[event] (seq coll)] (let [more (rest coll)] (if (exit? event) (cons nil more) (let [tree (seq-tree parent exit? node more)] (if-let [p (parent event (lazy-seq (first tree)))] (let [subtree (seq-tree parent exit? node (lazy-seq (rest tree)))] (cons (cons p (lazy-seq (first subtree))) (lazy-seq (rest subtree)))) (cons (cons (node event) (lazy-seq (first tree))) (lazy-seq (rest tree)))))))))) (defn event-tree "Returns a lazy tree of Element objects for the given seq of Event objects. See source-seq and parse." [events] (ffirst (seq-tree (fn [^Event event contents] (when (= :start-element (.type event)) (Element. (.name event) (.attrs event) contents))) (fn [^Event event] (= :end-element (.type event))) (fn [^Event event] (.str event)) events))) (defprotocol AsElements (as-elements [expr] "Return a seq of elements represented by an expression.")) (defn sexp-element [tag attrs child] (cond (= :-cdata tag) (CData. (first child)) (= :-comment tag) (Comment. (first child)) :else (Element. tag attrs (mapcat as-elements child)))) (extend-protocol AsElements clojure.lang.IPersistentVector (as-elements [v] (let [[tag & [attrs & after-attrs :as content]] v [attrs content] (if (map? attrs) [(into {} (for [[k v] attrs] [k (str v)])) after-attrs] [{} content])] [(sexp-element tag attrs content)])) clojure.lang.ISeq (as-elements [s] (mapcat as-elements s)) clojure.lang.Keyword (as-elements [k] [(Element. k {} ())]) java.lang.String (as-elements [s] [s]) nil (as-elements [_] nil) java.lang.Object (as-elements [o] [(str o)])) (defn sexps-as-fragment "Convert a compact prxml/hiccup-style data structure into the more formal tag/attrs/content format. A seq of elements will be returned, which may not be suitable for immediate use as there is no root element. See also sexp-as-element. The format is [:tag-name attr-map? content*]. Each vector opens a new tag; seqs do not open new tags, and are just used for inserting groups of elements into the parent tag. A bare keyword not in a vector creates an empty element. To provide XML conversion for your own data types, extend the AsElements protocol to them." ([] nil) ([sexp] (as-elements sexp)) ([sexp & sexps] (mapcat as-elements (cons sexp sexps)))) (defn sexp-as-element "Convert a single sexp into an Element" [sexp] (let [[root & more] (sexps-as-fragment sexp)] (when more (throw (IllegalArgumentException. "Cannot have multiple root elements; try creating a fragment instead"))) root)) (defn- attr-prefix [^XMLStreamReader sreader index] (let [p (.getAttributePrefix sreader index)] (when-not (str/blank? p) p))) (defn- attr-hash [^XMLStreamReader sreader] (into {} (for [i (range (.getAttributeCount sreader))] [(keyword (attr-prefix sreader i) (.getAttributeLocalName sreader i)) (.getAttributeValue sreader i)]))) ; Note, sreader is mutable and mutated here in pull-seq, but it's ; protected by a lazy-seq so it's thread-safe. (defn- pull-seq "Creates a seq of events. The XMLStreamConstants/SPACE clause below doesn't seem to be triggered by the JDK StAX parser, but is by others. Leaving in to be more complete." [^XMLStreamReader sreader] (lazy-seq (loop [] (condp == (.next sreader) XMLStreamConstants/START_ELEMENT (cons (event :start-element (keyword (.getLocalName sreader)) (attr-hash sreader) nil) (pull-seq sreader)) XMLStreamConstants/END_ELEMENT (cons (event :end-element (keyword (.getLocalName sreader)) nil nil) (pull-seq sreader)) XMLStreamConstants/CHARACTERS (if-let [text (and (not (.isWhiteSpace sreader)) (.getText sreader))] (cons (event :characters nil nil text) (pull-seq sreader)) (recur)) XMLStreamConstants/END_DOCUMENT nil (recur);; Consume and ignore comments, spaces, processing instructions etc )))) (def ^{:private true} xml-input-factory-props {:allocator javax.xml.stream.XMLInputFactory/ALLOCATOR :coalescing javax.xml.stream.XMLInputFactory/IS_COALESCING :namespace-aware javax.xml.stream.XMLInputFactory/IS_NAMESPACE_AWARE :replacing-entity-references javax.xml.stream.XMLInputFactory/IS_REPLACING_ENTITY_REFERENCES :supporting-external-entities javax.xml.stream.XMLInputFactory/IS_SUPPORTING_EXTERNAL_ENTITIES :validating javax.xml.stream.XMLInputFactory/IS_VALIDATING :reporter javax.xml.stream.XMLInputFactory/REPORTER :resolver javax.xml.stream.XMLInputFactory/RESOLVER :support-dtd javax.xml.stream.XMLInputFactory/SUPPORT_DTD}) (defn- new-xml-input-factory [props] (let [fac (javax.xml.stream.XMLInputFactory/newInstance)] (doseq [[k v] props :let [prop (xml-input-factory-props k)]] (.setProperty fac prop v)) fac)) (defn source-seq "Parses the XML InputSource source using a pull-parser. Returns a lazy sequence of Event records. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [s & {:as props}] (let [fac (new-xml-input-factory (merge {:coalescing true} props)) ;; Reflection on following line cannot be eliminated via a ;; type hint, because s is advertised by fn parse to be an ;; InputStream or Reader, and there are different ;; createXMLStreamReader signatures for each of those types. sreader (.createXMLStreamReader fac s)] (pull-seq sreader))) (defn parse "Parses the source, which can be an InputStream or Reader, and returns a lazy tree of Element records. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [source & props] (event-tree (apply source-seq source props))) (defn parse-str "Parses the passed in string to Clojure data structures. Accepts key pairs with XMLInputFactory options, see http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLInputFactory.html and xml-input-factory-props for more information. Defaults coalescing true." [s & props] (let [sr (java.io.StringReader. s)] (apply parse sr props))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; XML Emitting ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn check-stream-encoding [^java.io.OutputStreamWriter stream xml-encoding] (when (not= (Charset/forName xml-encoding) (Charset/forName (.getEncoding stream))) (throw (Exception. (str "Output encoding of stream (" xml-encoding ") doesn't match declaration (" (.getEncoding stream) ")"))))) (defn emit "Prints the given Element tree as XML text to stream. Options: :encoding <str> Character encoding to use" [e ^java.io.Writer stream & {:as opts}] (let [^javax.xml.stream.XMLStreamWriter writer (-> (javax.xml.stream.XMLOutputFactory/newInstance) (.createXMLStreamWriter stream))] (when (instance? java.io.OutputStreamWriter stream) (check-stream-encoding stream (or (:encoding opts) "UTF-8"))) (.writeStartDocument writer (or (:encoding opts) "UTF-8") "1.0") (doseq [event (flatten-elements [e])] (emit-event event writer)) (.writeEndDocument writer) stream)) (defn emit-str "Emits the Element to String and returns it" [e] (let [^java.io.StringWriter sw (java.io.StringWriter.)] (emit e sw) (.toString sw))) (defn ^javax.xml.transform.Transformer indenting-transformer [] (doto (-> (javax.xml.transform.TransformerFactory/newInstance) .newTransformer) (.setOutputProperty (javax.xml.transform.OutputKeys/INDENT) "yes") (.setOutputProperty (javax.xml.transform.OutputKeys/METHOD) "xml") (.setOutputProperty "{http://xml.apache.org/xslt}indent-amount" "2"))) (defn indent "Emits the XML and indents the result. WARNING: this is slow it will emit the XML and read it in again to indent it. Intended for debugging/testing only." [e ^java.io.Writer stream & {:as opts}] (let [sw (java.io.StringWriter.) _ (apply emit e sw (apply concat opts)) source (-> sw .toString java.io.StringReader. javax.xml.transform.stream.StreamSource.) result (javax.xml.transform.stream.StreamResult. stream)] (.transform (indenting-transformer) source result))) (defn indent-str "Emits the XML and indents the result. Writes the results to a String and returns it" [e] (let [^java.io.StringWriter sw (java.io.StringWriter.)] (indent e sw) (.toString sw)))
[ { "context": "nch\n \n {:doc \"Benchmarks for sums.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-06\"\n :version \"2019-10-17\"}", "end": 276, "score": 0.9513103365898132, "start": 240, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/elements/scripts/numbers/sum/bench.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.sum.bench {:doc "Benchmarks for sums." :author "palisades dot lakes at gmail dot com" :since "2017-04-06" :version "2019-10-17"} (:require [clojure.string :as s] [clojure.java.io :as io] [clojure.edn :as edn] [clojure.pprint :as pp] [palisades.lakes.elements.api :as mc] [palisades.lakes.elements.scripts.defs :as defs]) (:import [java.util ArrayList] [com.carrotsearch.sizeof RamUsageEstimator] [palisades.lakes.elements.java.accumulate.sum BigFractionCondition])) ;;---------------------------------------------------------------- (set! *warn-on-reflection* false) (set! *unchecked-math* false) (require '[clatrix.core :as clatrix]) (require '[criterium.core :as criterium]) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- ;; coercions ;;---------------------------------------------------------------- (defn clatrix-vector ^clatrix.core.Vector [x] (clatrix/vector x)) ;;---------------------------------------------------------------- (defn data-sizes [] (mapv #(* (long %) 1024) (take 6 (iterate #(* 8 (long %)) 8)))) ;;---------------------------------------------------------------- (def ^{:private true :tag org.apache.commons.rng.UniformRandomProvider} -urp- (mc/well44497b (mc/read-seed (io/resource "seeds/Well44497b-2017-04-05.edn")))) ;;---------------------------------------------------------------- (defn data [generator n] (println (mc/fn-name generator) n) (let [^doubles raw (generator n -urp-) bdc (BigFractionCondition/make) _ (time (.addAll bdc raw)) truth (.sum bdc) condition (.doubleValue bdc) gname (mc/fn-name generator)] (println gname n truth condition) {:truth truth :condition condition :generator gname :n n :raw raw})) ;;---------------------------------------------------------------- (defn bench [f coerce data-map] (let [data (time (coerce (:raw data-map))) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data)) ename (.getCanonicalName (mc/element-type data)) fname (mc/fn-name f) cname (mc/fn-name coerce)] (println fname cname dname) (try (let [result (criterium/benchmark (f data) {}) value (double (first (:results result))) truth (double (:truth data-map)) result (defs/simplify (assoc (merge result (dissoc data-map :raw)) :value value :error (- truth value) :relative-error (Math/abs (/ (- truth value) truth)) :algorithm fname :representation cname :data dname :kB (/ sizeof 1024.0) :elementtype ename))] (pp/pprint result) (println) (flush) result) (catch UnsupportedOperationException e (println "No method for" fname dname))))) ;;----------------------------------------------------------------
43601
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.sum.bench {:doc "Benchmarks for sums." :author "<EMAIL>" :since "2017-04-06" :version "2019-10-17"} (:require [clojure.string :as s] [clojure.java.io :as io] [clojure.edn :as edn] [clojure.pprint :as pp] [palisades.lakes.elements.api :as mc] [palisades.lakes.elements.scripts.defs :as defs]) (:import [java.util ArrayList] [com.carrotsearch.sizeof RamUsageEstimator] [palisades.lakes.elements.java.accumulate.sum BigFractionCondition])) ;;---------------------------------------------------------------- (set! *warn-on-reflection* false) (set! *unchecked-math* false) (require '[clatrix.core :as clatrix]) (require '[criterium.core :as criterium]) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- ;; coercions ;;---------------------------------------------------------------- (defn clatrix-vector ^clatrix.core.Vector [x] (clatrix/vector x)) ;;---------------------------------------------------------------- (defn data-sizes [] (mapv #(* (long %) 1024) (take 6 (iterate #(* 8 (long %)) 8)))) ;;---------------------------------------------------------------- (def ^{:private true :tag org.apache.commons.rng.UniformRandomProvider} -urp- (mc/well44497b (mc/read-seed (io/resource "seeds/Well44497b-2017-04-05.edn")))) ;;---------------------------------------------------------------- (defn data [generator n] (println (mc/fn-name generator) n) (let [^doubles raw (generator n -urp-) bdc (BigFractionCondition/make) _ (time (.addAll bdc raw)) truth (.sum bdc) condition (.doubleValue bdc) gname (mc/fn-name generator)] (println gname n truth condition) {:truth truth :condition condition :generator gname :n n :raw raw})) ;;---------------------------------------------------------------- (defn bench [f coerce data-map] (let [data (time (coerce (:raw data-map))) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data)) ename (.getCanonicalName (mc/element-type data)) fname (mc/fn-name f) cname (mc/fn-name coerce)] (println fname cname dname) (try (let [result (criterium/benchmark (f data) {}) value (double (first (:results result))) truth (double (:truth data-map)) result (defs/simplify (assoc (merge result (dissoc data-map :raw)) :value value :error (- truth value) :relative-error (Math/abs (/ (- truth value) truth)) :algorithm fname :representation cname :data dname :kB (/ sizeof 1024.0) :elementtype ename))] (pp/pprint result) (println) (flush) result) (catch UnsupportedOperationException e (println "No method for" fname dname))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.sum.bench {:doc "Benchmarks for sums." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-04-06" :version "2019-10-17"} (:require [clojure.string :as s] [clojure.java.io :as io] [clojure.edn :as edn] [clojure.pprint :as pp] [palisades.lakes.elements.api :as mc] [palisades.lakes.elements.scripts.defs :as defs]) (:import [java.util ArrayList] [com.carrotsearch.sizeof RamUsageEstimator] [palisades.lakes.elements.java.accumulate.sum BigFractionCondition])) ;;---------------------------------------------------------------- (set! *warn-on-reflection* false) (set! *unchecked-math* false) (require '[clatrix.core :as clatrix]) (require '[criterium.core :as criterium]) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- ;; coercions ;;---------------------------------------------------------------- (defn clatrix-vector ^clatrix.core.Vector [x] (clatrix/vector x)) ;;---------------------------------------------------------------- (defn data-sizes [] (mapv #(* (long %) 1024) (take 6 (iterate #(* 8 (long %)) 8)))) ;;---------------------------------------------------------------- (def ^{:private true :tag org.apache.commons.rng.UniformRandomProvider} -urp- (mc/well44497b (mc/read-seed (io/resource "seeds/Well44497b-2017-04-05.edn")))) ;;---------------------------------------------------------------- (defn data [generator n] (println (mc/fn-name generator) n) (let [^doubles raw (generator n -urp-) bdc (BigFractionCondition/make) _ (time (.addAll bdc raw)) truth (.sum bdc) condition (.doubleValue bdc) gname (mc/fn-name generator)] (println gname n truth condition) {:truth truth :condition condition :generator gname :n n :raw raw})) ;;---------------------------------------------------------------- (defn bench [f coerce data-map] (let [data (time (coerce (:raw data-map))) sizeof (RamUsageEstimator/sizeOf data) dname (.getCanonicalName (class data)) ename (.getCanonicalName (mc/element-type data)) fname (mc/fn-name f) cname (mc/fn-name coerce)] (println fname cname dname) (try (let [result (criterium/benchmark (f data) {}) value (double (first (:results result))) truth (double (:truth data-map)) result (defs/simplify (assoc (merge result (dissoc data-map :raw)) :value value :error (- truth value) :relative-error (Math/abs (/ (- truth value) truth)) :algorithm fname :representation cname :data dname :kB (/ sizeof 1024.0) :elementtype ename))] (pp/pprint result) (println) (flush) result) (catch UnsupportedOperationException e (println "No method for" fname dname))))) ;;----------------------------------------------------------------
[ { "context": ";; Copyright (C) 2018, 2019 by Vlad Kozin\n\n(ns proc\n (:require\n [medley.core :refer :all", "end": 41, "score": 0.9998089671134949, "start": 31, "tag": "NAME", "value": "Vlad Kozin" } ]
src/proc.clj
vkz/bot
1
;; Copyright (C) 2018, 2019 by Vlad Kozin (ns proc (:require [medley.core :refer :all] [clojure.spec.alpha :as spec] [clojure.spec.gen.alpha :as gen] ;; aleph HTTPS client is broken for some HTTPS pages e.g. for GDAX ;; REST API [aleph.http :as http] ;; so we use clj-http instead [clj-http.client :as http-client] [manifold.deferred :as d] [manifold.stream :as s] [byte-streams :as bs] [cheshire.core :as json] [clojure.string :as string] [clojure.pprint :refer [pprint]] [clojure.core.async :as a] [clojure.core.async.impl.protocols :refer [Channel]] [taoensso.timbre :as log])) ;;* Proc ;; TODO could be worth having a pub for each process where you can substribe to ;; peek at the result of each iteration. With no subscribers it will just sit ;; there. (defrecord Proc [in cmd ret timeout api]) #_ (defprotocol IProc (send [p]) (command [p]) (kill [p]) (subscribe ([p]) ([p timeframe])) ;; ---------------------------- (take [p n]) (take-while [])) ;; Process ;; - reads msgs from in, which can be a channel or a thunk that returns a channel, ;; - reads tick from timout, which can be a channel or a thunk that returns a ;; channel, ;; - reads commands from cmd channel, ;; - puts the value of final expression in its body into ret channel, ;; - api a map of :command => (fn [& args] ...) ;; ;; Upon launch process starts a loop [in cmd timeout] where ;; - it (alts!! (in) cmd (timeout)) and conds on the channel ;; -- if in-ch it executes (body-fn msg) with msg from in-ch and recurs, ;; -- if cmd it invokes relevant cmd and recurs unless :kill, then it exits, ;; -- if timeout it exits. ;; - when done with the loop it logs reason for exit, ;; - returns (defn create-proc [& {:keys [name in cmd timeout api body done] :as opts :or {timeout (* 30 1000)}}] (let [proc (atom nil) api ;; every command receives proc as its first argument (merge {:kill (fn kill [proc & args] "[kill]")} api) in-fn (cond (fn? in) in (satisfies? Channel in) (constantly in) :else (throw (ex-info "Expected channel or thunk." {:in in}))) timeout-fn (cond (number? timeout) (fn [] (a/timeout timeout)) (fn? timeout) timeout (satisfies? Channel timeout) (constantly timeout)) cmd (or cmd (a/chan)) ret-ch ;; TODO (Thread. thunk "Thread name") this way I at least have access to ;; my thread and can spot it among others by name. (a/thread (try (let [reason (loop [in (in-fn) cmd cmd timeout (timeout-fn)] (let [[v ch] (a/alts!! [in cmd timeout])] (condp = ch in (do (body v) (recur (in-fn) cmd (timeout-fn))) cmd (let [[c args] v command (api c) kill? (= c :kill)] (cond kill? (apply command @proc args) command (do (apply command @proc args) (recur (in-fn) cmd (timeout-fn))) :unknown-command (do (log/error (str "Proc " @proc " received unrecognized command " c)) (recur (in-fn) cmd (timeout-fn))))) timeout "[timeout]")))] (log/info (format "Shutting down process %s because %s." @proc reason)) (done reason)) (catch java.lang.Throwable ex (log/error "Exception in proc " @proc (ex-info (ex-message ex) {} (ex-cause ex))) (throw ex))))] (reset! proc (map->Proc {:in in :cmd cmd :ret ret-ch :timeout timeout :api api})) (fn get-proc [] (deref proc)))) (defmacro let-proc ([bindings body] `(let-proc ~bindings ~body (done [reason#] (log/info "Process stopped because " reason#)))) ([bindings body done] (let [bindings (->> bindings (apply hash-map) (map-keys keyword)) [do? [msg] & body] body [done? [reason] done] done opts (-> bindings (assoc :body `(fn [~msg] ~@body)) (assoc :done `(fn [~reason] ~done)))] ;; check do? ;; check done? ;; check bindings are what we expect `(create-proc ~@(mapcat identity opts))))) (comment (def p (create-proc :api {:log (fn [] (log/info "log"))} :done (fn [reason] (println "done because " reason)) :timeout (* 30 1000) :body (fn [msg] (println "received " msg)) :in (a/chan))) (def p (let-proc [in (a/chan) timeout (* 30 1000) api {:log (fn [] (log/info "log"))}] (do [msg] (println "received " msg)) (done [reason] (println "done because " reason)))) (a/put! (:cmd (p)) [:kill]) (a/go (println (a/<! (:ret (p)))))) (comment ;; Proc examples (def-proc eth-btc-proc [msg] (let-proc [in (a/chan) ;or e.g. (fn [] (a/timeout 2000)) cmd (a/chan) api {} timeout (* 60 1000)] (update order-book msg))) (def-proc eth-btc-poll-proc [msg] (let-proc [in (a/chan) cmd (a/chan) api {} timeout (* 60 1000)] (update order-book msg))) (def-proc hb-proc [hb] (let-proc [in (a/chan) cmd (a/chan) api {} timeout (* 60 1000)] (log/info "Heartbeat"))) ;; "global" timer to subscribe to (let [timer-ch (a/chan) pub (pub timer-ch identity)] {:proc (def-proc timer-proc [t] (let-proc [in (fn [] (a/timeout 2000))] (log/info "tick") (>! timer-ch :tick))) :pub-timer pub}) ;; one-off timer proc (defn fresh-timer-proc [period] (let [timer-ch (a/chan)] (def-proc timer-proc [t] (let-proc [in (fn [] (a/timeout 2000))] (log/info "tick") (>! timer-ch :tick))))) ;; effectively a (while true ...) proc (let [const-ch (a/chan)] ;; TODO I suspect this requires priority in alts else (in) will always win but ;; we want cmd to have the chance to break process. (let-proc [in (fn [] (a/put! 1))] (do [msg] something) (done [reason] done))) ;; no way to shutdown (defn create-polling-proc [period queue] (future (while true (Thread/sleep period) (when-let [msg (pop queue)] (send msg)))))) (defrecord Connection [in out pub transform-in transform-out proc]) (def ^:private CONNECTION (atom nil)) ;;* WS (defn connect-ws [& {in :in out :out transform-in :transform-in transform-out :transform-out :or {in (a/chan) out (a/chan) transform-in identity transform-out identity} :as conn}] (if (some-> @CONNECTION (:proc) ;; TODO generic closed? (s/closed?) (not)) ;; connection already exists (fn [] (deref CONNECTION)) ;; fresh connection (let [connection-stream ;; NOTE the 2 connect-via below work only because this here returns a ;; DUPLEX stream. Regular stream would act an async channel, so the two ;; connections below would deadlock. (s/splice sink source) creates a ;; duplex stream. @(http/websocket-client ;; TODO abstract connection endpoint "wss://ws-feed.gdax.com" {:max-frame-payload 1e6 :max-frame-size 1e6}) in-stream ;; sink of msgs from exchange for users to consume (s/->sink in) out-stream ;; source of user msgs to send to exchange (s/->source out) _ ;; exchange <= transform-out <= out <= user (s/connect-via out-stream (fn [msg] ;; TODO validate msg properly (if (or (get msg :type) (get msg "type")) (s/put! connection-stream (json/encode (transform-out msg))) (let [err (d/success-deferred "Malformed msg")] (log/error (ex-info "Malformed msg" {:msg msg})) err))) connection-stream) _ ;; exchange => transform-in => in => user (s/connect-via connection-stream (fn [msg] (let [msg (transform-in (json/decode msg))] (if (or (get msg :type) (get msg "type")) (s/put! in-stream msg) (let [err (d/success-deferred "Maslformed msg")] (log/error (ex-info "Malformed msg" {:msg msg})) err)))) in-stream) pub (a/pub in (fn [msg] (select-keys msg [:type :ticker])))] (reset! CONNECTION (map->Connection {:in in :out out :pub pub :transform-in transform-in :transform-out transform-out ;; for REST it should be a thread? :proc connection-stream})) (fn [] (deref CONNECTION))))) #_ (defn orderbook-derefer [ticker] (fn orderbook [] (-> @BOOKS ticker ;; (agent OrderBook) deref))) #_ (defn subscribe [{in :ch ticker :ticker :as book}] (when-not (subscribed? book) (let [conn (connect) pub (:pub (conn)) snapshot {:type :snapshot :ticker ticker} updates {:type :update :ticker ticker} agent (swap! BOOKS assoc ticker (agent book)) proc (let-proc [in in] (do [msg] (send agent update-book msg)))] (a/sub pub snapshots in) (a/sub pub updates in) (a/put! (:out (conn)) {:type :subscribe :product (product ticker) :topic :update}) (send agent assoc :proc proc))) (orderbook-derefer ticker)) (comment (def conn (connect-ws :transform-in (fn [msg] (println "Received: ") (pprint msg) msg) :transform-out (fn [msg] (println "Sending: ") (pprint msg) msg))) ;; subscribe hb (a/put! (:out (conn)) {"type" "subscribe" "product_ids" ["ETH-BTC"] "channels" ["heartbeat"]}) ;; unsubscribe hb (a/put! (:out (conn)) {"type" "unsubscribe" "product_ids" ["ETH-BTC"] "channels" ["heartbeat"]}) (a/put! (:out (conn)) {:a 1}) (s/close! (:proc (conn)))) ;;* REST (defn get-book [ticker] (let [url (str "https://api.gdax.com" (format "/products/%s/book?level=2" ticker))] (-> url ;; TODO should it be async? http-client/get :body json/decode))) (defmulti send-msg :type) (defmethod send-msg :book [{ticker :ticker}] (get-book ticker)) (def QUEUE (atom (queue))) ;; TODO can I just extend some protocol to have conj, peek, pop work for an (atom ;; queue)? (defn conjq! [v] (swap! QUEUE conj v)) (defn popq! [] (when (peek @QUEUE) (first (deref-swap! QUEUE pop)))) (defn create-polling-proc [stream period] ;; TODO make it local to this proc, expose only conj, pop, count or some such. (reset! QUEUE (queue)) (let-proc [in (fn [] (a/timeout period))] (do [_] (let [len (count @QUEUE)] (when (> len 1) (log/info "Queue count: " len))) (when-let [msg (popq!)] (s/put! stream (send-msg msg)))))) (defn connect-rest [& {in :in out :out transform-in :transform-in transform-out :transform-out :or {in (a/chan) out (a/chan) transform-in identity transform-out identity} :as conn}] (let [exchange-stream (s/stream) poller (create-polling-proc exchange-stream 5000) in-stream ;; sink of msgs from exchange for users to consume (s/->sink in) out-stream ;; source of user msgs to send to exchange (s/->source out) _ ;; exchange <= transform-out <= out <= user (s/consume (fn [msg] (conjq! (transform-out msg))) out-stream) _ ;; exchange => transform-in => in => user (s/connect-via exchange-stream (fn [msg] (s/put! in-stream (transform-in msg))) in-stream) pub (a/pub in (fn [msg] (select-keys msg [:type :ticker])))] (reset! CONNECTION (map->Connection {:in in :out out :pub pub :transform-in transform-in :transform-out transform-out :proc poller})) (fn [] (deref CONNECTION)))) (defn subscribe-rest [ticker period] (let-proc [in (fn [] (a/timeout period))] (do [_] (conjq! {:type :book :ticker ticker})))) (comment (def conn (connect-rest :transform-in (fn [msg] (println "Received: ") (pprint msg) msg) :transform-out (fn [msg] (println "Sending: ") (pprint msg) msg))) (a/put! (:out (conn)) {:type :book :ticker "BTC-USD"}) (a/put! (:cmd ((:proc (conn)))) [:kill]) (a/go (pprint (a/<! (:cmd ((:proc (conn))))))) (deref QUEUE) (def btc-usd-rest (subscribe-rest "BTC-USD" 3000)) (a/put! (:cmd (btc-usd-rest)) [:kill]) ;; end ) #_ (defmethod disconnect :gdax [exch] (swap! at-connections disj exch) (s/close! (:process exch)) (a/close! (:in exch)) (a/close! (:out exch)) (doseq [sub (:subscribers exch)] (close sub)) (-> exch (assoc :in nil) (assoc :out nil) (assoc :process nil))) (comment (defn print-threads [& {:keys [headers pre-fn] :or {pre-fn identity}}] (let [thread-set (keys (Thread/getAllStackTraces)) thread-data (mapv bean thread-set) headers (or headers (-> thread-data first keys))] (clojure.pprint/print-table headers (pre-fn thread-data)))) (defn print-threads-str [& args] (with-out-str (apply print-threads args))) ;;print all properties for all threads (print-threads) ;;print name,state,alive,daemon properties for all threads (print-threads :headers [:name :state :alive :daemon]) ;;print name,state,alive,daemon properties for non-daemon threads (print-threads :headers [:name :state :alive :daemon] :pre-fn (partial filter #(false? (:daemon %)))) ;;log name,state,alive,daemon properties for non-daemon threads (log/debug (print-threads-str :headers [:name :state :alive :daemon] :pre-fn (partial filter #(false? (:daemon %)))))) ;;* Design (comment (defn connect "Establish connection with the exchange. WS API - connection is persistent, - we subscribe to the heartbeat messages, - received messages are transformed to a unified schema, - we create a pub from in-ch with a topic-fn for unified schema, - in-ch, pub, heartbeat subscriber added to the state. REST API - we send a test msg and verify exch server response, - start a \"polling\" process with period T, - polling proccess has in-ch where it puts msgs received from exchange, - polling process has queue from which it sends msg every T sec, - polling process has pub from in-ch - we subscribe to heartbeat msgs (proc that adds HB msg to polling queue every 10sec) - received messages are transformed to a unified schema, - we create a pub from channel with a topic-fn for unified schema, - in-ch, queue, pub, heartbeat subscriber added to the state. Return - true on success, - nil on failure. Connect is idempotent: it should check if connection is already open." []) (defn close " (unsub-all (:pub Connection)) Close (:in Connection) Close (:out Connection) Stop (:proc Connection) Reset CONN" [Connection]) (defn create-orderbook " If OrderBook record for this ticker exists in state, use that. Else add fresh OrderBook for ticker with channel ch to state. Create process that updates OrderBook atom every time it gets a msg on ch. Set proc field in OrderBook. Return (orderbook-derefer ticker). " ([ticker]) ;; custom channel e.g. backed by NoisySlidingBuffer ([ticker ch])) (defn create-heartbeat " If HEARTBEAT use that. Else add fresh HeartBeat with channel ch to HEARTBEAT. Create process that updates timestamp in HeartBeat atom every item it gets a mesg on ch. Set proc field in HeartBeat. Return (heartbeat-derefer).") (defn close " Close (:ch OrderBook). Remove OrderBook from BOOKS. " [OrderBook]) (defn close " Close (:ch HeartBeat). Reset HEARTBEAT." [HeartBeat]) (defn subscribe "Subscribe OrderBook for updates from Exchange: WS API - send request for orderbook updates to exch, - (sub pub :topic (:ch OrderBook)), - add subscriber to state. REST API - Create proc that adds orderbook update request to polling q every T sec, - (sub pub :topic (:ch OrderBook)) - add subscriber to state." ([OrderBook]) ([OrderBook T])) (defn send "" [msg]) (defn unsubscribe " WS - send request to stop orderbook updates to exch, - (unsub pub :topic (:ch OrderBook)) - remove subscriber from state. REST - stop proc that enqueues orderbook update requests, - (unsub pub :topic (:ch OrderBook)), - remove subscriber from state." [OrderBook]) (defn subscribe " WS API - send :hb subscribtion message to exch, - (sub pub :hb (:ch HeartBeat)), - add subscriber to state. REST API - Create proc that adds HB msg to the polling queue every N sec, - (sub pub :hb (:ch HeartBeat)), - add subscriber to state." [HeartBeat]) (defn unsubscribe " WS API - send :hb unsubscribe msg to exch, - (unsub-all pub :hb), - remove subscriber from state. REST API - stop proc that queues HB msgs, - (unsub pub :hb (:ch HeartBeat)) - remove subscriber from state." [HeartBeat]))
99863
;; Copyright (C) 2018, 2019 by <NAME> (ns proc (:require [medley.core :refer :all] [clojure.spec.alpha :as spec] [clojure.spec.gen.alpha :as gen] ;; aleph HTTPS client is broken for some HTTPS pages e.g. for GDAX ;; REST API [aleph.http :as http] ;; so we use clj-http instead [clj-http.client :as http-client] [manifold.deferred :as d] [manifold.stream :as s] [byte-streams :as bs] [cheshire.core :as json] [clojure.string :as string] [clojure.pprint :refer [pprint]] [clojure.core.async :as a] [clojure.core.async.impl.protocols :refer [Channel]] [taoensso.timbre :as log])) ;;* Proc ;; TODO could be worth having a pub for each process where you can substribe to ;; peek at the result of each iteration. With no subscribers it will just sit ;; there. (defrecord Proc [in cmd ret timeout api]) #_ (defprotocol IProc (send [p]) (command [p]) (kill [p]) (subscribe ([p]) ([p timeframe])) ;; ---------------------------- (take [p n]) (take-while [])) ;; Process ;; - reads msgs from in, which can be a channel or a thunk that returns a channel, ;; - reads tick from timout, which can be a channel or a thunk that returns a ;; channel, ;; - reads commands from cmd channel, ;; - puts the value of final expression in its body into ret channel, ;; - api a map of :command => (fn [& args] ...) ;; ;; Upon launch process starts a loop [in cmd timeout] where ;; - it (alts!! (in) cmd (timeout)) and conds on the channel ;; -- if in-ch it executes (body-fn msg) with msg from in-ch and recurs, ;; -- if cmd it invokes relevant cmd and recurs unless :kill, then it exits, ;; -- if timeout it exits. ;; - when done with the loop it logs reason for exit, ;; - returns (defn create-proc [& {:keys [name in cmd timeout api body done] :as opts :or {timeout (* 30 1000)}}] (let [proc (atom nil) api ;; every command receives proc as its first argument (merge {:kill (fn kill [proc & args] "[kill]")} api) in-fn (cond (fn? in) in (satisfies? Channel in) (constantly in) :else (throw (ex-info "Expected channel or thunk." {:in in}))) timeout-fn (cond (number? timeout) (fn [] (a/timeout timeout)) (fn? timeout) timeout (satisfies? Channel timeout) (constantly timeout)) cmd (or cmd (a/chan)) ret-ch ;; TODO (Thread. thunk "Thread name") this way I at least have access to ;; my thread and can spot it among others by name. (a/thread (try (let [reason (loop [in (in-fn) cmd cmd timeout (timeout-fn)] (let [[v ch] (a/alts!! [in cmd timeout])] (condp = ch in (do (body v) (recur (in-fn) cmd (timeout-fn))) cmd (let [[c args] v command (api c) kill? (= c :kill)] (cond kill? (apply command @proc args) command (do (apply command @proc args) (recur (in-fn) cmd (timeout-fn))) :unknown-command (do (log/error (str "Proc " @proc " received unrecognized command " c)) (recur (in-fn) cmd (timeout-fn))))) timeout "[timeout]")))] (log/info (format "Shutting down process %s because %s." @proc reason)) (done reason)) (catch java.lang.Throwable ex (log/error "Exception in proc " @proc (ex-info (ex-message ex) {} (ex-cause ex))) (throw ex))))] (reset! proc (map->Proc {:in in :cmd cmd :ret ret-ch :timeout timeout :api api})) (fn get-proc [] (deref proc)))) (defmacro let-proc ([bindings body] `(let-proc ~bindings ~body (done [reason#] (log/info "Process stopped because " reason#)))) ([bindings body done] (let [bindings (->> bindings (apply hash-map) (map-keys keyword)) [do? [msg] & body] body [done? [reason] done] done opts (-> bindings (assoc :body `(fn [~msg] ~@body)) (assoc :done `(fn [~reason] ~done)))] ;; check do? ;; check done? ;; check bindings are what we expect `(create-proc ~@(mapcat identity opts))))) (comment (def p (create-proc :api {:log (fn [] (log/info "log"))} :done (fn [reason] (println "done because " reason)) :timeout (* 30 1000) :body (fn [msg] (println "received " msg)) :in (a/chan))) (def p (let-proc [in (a/chan) timeout (* 30 1000) api {:log (fn [] (log/info "log"))}] (do [msg] (println "received " msg)) (done [reason] (println "done because " reason)))) (a/put! (:cmd (p)) [:kill]) (a/go (println (a/<! (:ret (p)))))) (comment ;; Proc examples (def-proc eth-btc-proc [msg] (let-proc [in (a/chan) ;or e.g. (fn [] (a/timeout 2000)) cmd (a/chan) api {} timeout (* 60 1000)] (update order-book msg))) (def-proc eth-btc-poll-proc [msg] (let-proc [in (a/chan) cmd (a/chan) api {} timeout (* 60 1000)] (update order-book msg))) (def-proc hb-proc [hb] (let-proc [in (a/chan) cmd (a/chan) api {} timeout (* 60 1000)] (log/info "Heartbeat"))) ;; "global" timer to subscribe to (let [timer-ch (a/chan) pub (pub timer-ch identity)] {:proc (def-proc timer-proc [t] (let-proc [in (fn [] (a/timeout 2000))] (log/info "tick") (>! timer-ch :tick))) :pub-timer pub}) ;; one-off timer proc (defn fresh-timer-proc [period] (let [timer-ch (a/chan)] (def-proc timer-proc [t] (let-proc [in (fn [] (a/timeout 2000))] (log/info "tick") (>! timer-ch :tick))))) ;; effectively a (while true ...) proc (let [const-ch (a/chan)] ;; TODO I suspect this requires priority in alts else (in) will always win but ;; we want cmd to have the chance to break process. (let-proc [in (fn [] (a/put! 1))] (do [msg] something) (done [reason] done))) ;; no way to shutdown (defn create-polling-proc [period queue] (future (while true (Thread/sleep period) (when-let [msg (pop queue)] (send msg)))))) (defrecord Connection [in out pub transform-in transform-out proc]) (def ^:private CONNECTION (atom nil)) ;;* WS (defn connect-ws [& {in :in out :out transform-in :transform-in transform-out :transform-out :or {in (a/chan) out (a/chan) transform-in identity transform-out identity} :as conn}] (if (some-> @CONNECTION (:proc) ;; TODO generic closed? (s/closed?) (not)) ;; connection already exists (fn [] (deref CONNECTION)) ;; fresh connection (let [connection-stream ;; NOTE the 2 connect-via below work only because this here returns a ;; DUPLEX stream. Regular stream would act an async channel, so the two ;; connections below would deadlock. (s/splice sink source) creates a ;; duplex stream. @(http/websocket-client ;; TODO abstract connection endpoint "wss://ws-feed.gdax.com" {:max-frame-payload 1e6 :max-frame-size 1e6}) in-stream ;; sink of msgs from exchange for users to consume (s/->sink in) out-stream ;; source of user msgs to send to exchange (s/->source out) _ ;; exchange <= transform-out <= out <= user (s/connect-via out-stream (fn [msg] ;; TODO validate msg properly (if (or (get msg :type) (get msg "type")) (s/put! connection-stream (json/encode (transform-out msg))) (let [err (d/success-deferred "Malformed msg")] (log/error (ex-info "Malformed msg" {:msg msg})) err))) connection-stream) _ ;; exchange => transform-in => in => user (s/connect-via connection-stream (fn [msg] (let [msg (transform-in (json/decode msg))] (if (or (get msg :type) (get msg "type")) (s/put! in-stream msg) (let [err (d/success-deferred "Maslformed msg")] (log/error (ex-info "Malformed msg" {:msg msg})) err)))) in-stream) pub (a/pub in (fn [msg] (select-keys msg [:type :ticker])))] (reset! CONNECTION (map->Connection {:in in :out out :pub pub :transform-in transform-in :transform-out transform-out ;; for REST it should be a thread? :proc connection-stream})) (fn [] (deref CONNECTION))))) #_ (defn orderbook-derefer [ticker] (fn orderbook [] (-> @BOOKS ticker ;; (agent OrderBook) deref))) #_ (defn subscribe [{in :ch ticker :ticker :as book}] (when-not (subscribed? book) (let [conn (connect) pub (:pub (conn)) snapshot {:type :snapshot :ticker ticker} updates {:type :update :ticker ticker} agent (swap! BOOKS assoc ticker (agent book)) proc (let-proc [in in] (do [msg] (send agent update-book msg)))] (a/sub pub snapshots in) (a/sub pub updates in) (a/put! (:out (conn)) {:type :subscribe :product (product ticker) :topic :update}) (send agent assoc :proc proc))) (orderbook-derefer ticker)) (comment (def conn (connect-ws :transform-in (fn [msg] (println "Received: ") (pprint msg) msg) :transform-out (fn [msg] (println "Sending: ") (pprint msg) msg))) ;; subscribe hb (a/put! (:out (conn)) {"type" "subscribe" "product_ids" ["ETH-BTC"] "channels" ["heartbeat"]}) ;; unsubscribe hb (a/put! (:out (conn)) {"type" "unsubscribe" "product_ids" ["ETH-BTC"] "channels" ["heartbeat"]}) (a/put! (:out (conn)) {:a 1}) (s/close! (:proc (conn)))) ;;* REST (defn get-book [ticker] (let [url (str "https://api.gdax.com" (format "/products/%s/book?level=2" ticker))] (-> url ;; TODO should it be async? http-client/get :body json/decode))) (defmulti send-msg :type) (defmethod send-msg :book [{ticker :ticker}] (get-book ticker)) (def QUEUE (atom (queue))) ;; TODO can I just extend some protocol to have conj, peek, pop work for an (atom ;; queue)? (defn conjq! [v] (swap! QUEUE conj v)) (defn popq! [] (when (peek @QUEUE) (first (deref-swap! QUEUE pop)))) (defn create-polling-proc [stream period] ;; TODO make it local to this proc, expose only conj, pop, count or some such. (reset! QUEUE (queue)) (let-proc [in (fn [] (a/timeout period))] (do [_] (let [len (count @QUEUE)] (when (> len 1) (log/info "Queue count: " len))) (when-let [msg (popq!)] (s/put! stream (send-msg msg)))))) (defn connect-rest [& {in :in out :out transform-in :transform-in transform-out :transform-out :or {in (a/chan) out (a/chan) transform-in identity transform-out identity} :as conn}] (let [exchange-stream (s/stream) poller (create-polling-proc exchange-stream 5000) in-stream ;; sink of msgs from exchange for users to consume (s/->sink in) out-stream ;; source of user msgs to send to exchange (s/->source out) _ ;; exchange <= transform-out <= out <= user (s/consume (fn [msg] (conjq! (transform-out msg))) out-stream) _ ;; exchange => transform-in => in => user (s/connect-via exchange-stream (fn [msg] (s/put! in-stream (transform-in msg))) in-stream) pub (a/pub in (fn [msg] (select-keys msg [:type :ticker])))] (reset! CONNECTION (map->Connection {:in in :out out :pub pub :transform-in transform-in :transform-out transform-out :proc poller})) (fn [] (deref CONNECTION)))) (defn subscribe-rest [ticker period] (let-proc [in (fn [] (a/timeout period))] (do [_] (conjq! {:type :book :ticker ticker})))) (comment (def conn (connect-rest :transform-in (fn [msg] (println "Received: ") (pprint msg) msg) :transform-out (fn [msg] (println "Sending: ") (pprint msg) msg))) (a/put! (:out (conn)) {:type :book :ticker "BTC-USD"}) (a/put! (:cmd ((:proc (conn)))) [:kill]) (a/go (pprint (a/<! (:cmd ((:proc (conn))))))) (deref QUEUE) (def btc-usd-rest (subscribe-rest "BTC-USD" 3000)) (a/put! (:cmd (btc-usd-rest)) [:kill]) ;; end ) #_ (defmethod disconnect :gdax [exch] (swap! at-connections disj exch) (s/close! (:process exch)) (a/close! (:in exch)) (a/close! (:out exch)) (doseq [sub (:subscribers exch)] (close sub)) (-> exch (assoc :in nil) (assoc :out nil) (assoc :process nil))) (comment (defn print-threads [& {:keys [headers pre-fn] :or {pre-fn identity}}] (let [thread-set (keys (Thread/getAllStackTraces)) thread-data (mapv bean thread-set) headers (or headers (-> thread-data first keys))] (clojure.pprint/print-table headers (pre-fn thread-data)))) (defn print-threads-str [& args] (with-out-str (apply print-threads args))) ;;print all properties for all threads (print-threads) ;;print name,state,alive,daemon properties for all threads (print-threads :headers [:name :state :alive :daemon]) ;;print name,state,alive,daemon properties for non-daemon threads (print-threads :headers [:name :state :alive :daemon] :pre-fn (partial filter #(false? (:daemon %)))) ;;log name,state,alive,daemon properties for non-daemon threads (log/debug (print-threads-str :headers [:name :state :alive :daemon] :pre-fn (partial filter #(false? (:daemon %)))))) ;;* Design (comment (defn connect "Establish connection with the exchange. WS API - connection is persistent, - we subscribe to the heartbeat messages, - received messages are transformed to a unified schema, - we create a pub from in-ch with a topic-fn for unified schema, - in-ch, pub, heartbeat subscriber added to the state. REST API - we send a test msg and verify exch server response, - start a \"polling\" process with period T, - polling proccess has in-ch where it puts msgs received from exchange, - polling process has queue from which it sends msg every T sec, - polling process has pub from in-ch - we subscribe to heartbeat msgs (proc that adds HB msg to polling queue every 10sec) - received messages are transformed to a unified schema, - we create a pub from channel with a topic-fn for unified schema, - in-ch, queue, pub, heartbeat subscriber added to the state. Return - true on success, - nil on failure. Connect is idempotent: it should check if connection is already open." []) (defn close " (unsub-all (:pub Connection)) Close (:in Connection) Close (:out Connection) Stop (:proc Connection) Reset CONN" [Connection]) (defn create-orderbook " If OrderBook record for this ticker exists in state, use that. Else add fresh OrderBook for ticker with channel ch to state. Create process that updates OrderBook atom every time it gets a msg on ch. Set proc field in OrderBook. Return (orderbook-derefer ticker). " ([ticker]) ;; custom channel e.g. backed by NoisySlidingBuffer ([ticker ch])) (defn create-heartbeat " If HEARTBEAT use that. Else add fresh HeartBeat with channel ch to HEARTBEAT. Create process that updates timestamp in HeartBeat atom every item it gets a mesg on ch. Set proc field in HeartBeat. Return (heartbeat-derefer).") (defn close " Close (:ch OrderBook). Remove OrderBook from BOOKS. " [OrderBook]) (defn close " Close (:ch HeartBeat). Reset HEARTBEAT." [HeartBeat]) (defn subscribe "Subscribe OrderBook for updates from Exchange: WS API - send request for orderbook updates to exch, - (sub pub :topic (:ch OrderBook)), - add subscriber to state. REST API - Create proc that adds orderbook update request to polling q every T sec, - (sub pub :topic (:ch OrderBook)) - add subscriber to state." ([OrderBook]) ([OrderBook T])) (defn send "" [msg]) (defn unsubscribe " WS - send request to stop orderbook updates to exch, - (unsub pub :topic (:ch OrderBook)) - remove subscriber from state. REST - stop proc that enqueues orderbook update requests, - (unsub pub :topic (:ch OrderBook)), - remove subscriber from state." [OrderBook]) (defn subscribe " WS API - send :hb subscribtion message to exch, - (sub pub :hb (:ch HeartBeat)), - add subscriber to state. REST API - Create proc that adds HB msg to the polling queue every N sec, - (sub pub :hb (:ch HeartBeat)), - add subscriber to state." [HeartBeat]) (defn unsubscribe " WS API - send :hb unsubscribe msg to exch, - (unsub-all pub :hb), - remove subscriber from state. REST API - stop proc that queues HB msgs, - (unsub pub :hb (:ch HeartBeat)) - remove subscriber from state." [HeartBeat]))
true
;; Copyright (C) 2018, 2019 by PI:NAME:<NAME>END_PI (ns proc (:require [medley.core :refer :all] [clojure.spec.alpha :as spec] [clojure.spec.gen.alpha :as gen] ;; aleph HTTPS client is broken for some HTTPS pages e.g. for GDAX ;; REST API [aleph.http :as http] ;; so we use clj-http instead [clj-http.client :as http-client] [manifold.deferred :as d] [manifold.stream :as s] [byte-streams :as bs] [cheshire.core :as json] [clojure.string :as string] [clojure.pprint :refer [pprint]] [clojure.core.async :as a] [clojure.core.async.impl.protocols :refer [Channel]] [taoensso.timbre :as log])) ;;* Proc ;; TODO could be worth having a pub for each process where you can substribe to ;; peek at the result of each iteration. With no subscribers it will just sit ;; there. (defrecord Proc [in cmd ret timeout api]) #_ (defprotocol IProc (send [p]) (command [p]) (kill [p]) (subscribe ([p]) ([p timeframe])) ;; ---------------------------- (take [p n]) (take-while [])) ;; Process ;; - reads msgs from in, which can be a channel or a thunk that returns a channel, ;; - reads tick from timout, which can be a channel or a thunk that returns a ;; channel, ;; - reads commands from cmd channel, ;; - puts the value of final expression in its body into ret channel, ;; - api a map of :command => (fn [& args] ...) ;; ;; Upon launch process starts a loop [in cmd timeout] where ;; - it (alts!! (in) cmd (timeout)) and conds on the channel ;; -- if in-ch it executes (body-fn msg) with msg from in-ch and recurs, ;; -- if cmd it invokes relevant cmd and recurs unless :kill, then it exits, ;; -- if timeout it exits. ;; - when done with the loop it logs reason for exit, ;; - returns (defn create-proc [& {:keys [name in cmd timeout api body done] :as opts :or {timeout (* 30 1000)}}] (let [proc (atom nil) api ;; every command receives proc as its first argument (merge {:kill (fn kill [proc & args] "[kill]")} api) in-fn (cond (fn? in) in (satisfies? Channel in) (constantly in) :else (throw (ex-info "Expected channel or thunk." {:in in}))) timeout-fn (cond (number? timeout) (fn [] (a/timeout timeout)) (fn? timeout) timeout (satisfies? Channel timeout) (constantly timeout)) cmd (or cmd (a/chan)) ret-ch ;; TODO (Thread. thunk "Thread name") this way I at least have access to ;; my thread and can spot it among others by name. (a/thread (try (let [reason (loop [in (in-fn) cmd cmd timeout (timeout-fn)] (let [[v ch] (a/alts!! [in cmd timeout])] (condp = ch in (do (body v) (recur (in-fn) cmd (timeout-fn))) cmd (let [[c args] v command (api c) kill? (= c :kill)] (cond kill? (apply command @proc args) command (do (apply command @proc args) (recur (in-fn) cmd (timeout-fn))) :unknown-command (do (log/error (str "Proc " @proc " received unrecognized command " c)) (recur (in-fn) cmd (timeout-fn))))) timeout "[timeout]")))] (log/info (format "Shutting down process %s because %s." @proc reason)) (done reason)) (catch java.lang.Throwable ex (log/error "Exception in proc " @proc (ex-info (ex-message ex) {} (ex-cause ex))) (throw ex))))] (reset! proc (map->Proc {:in in :cmd cmd :ret ret-ch :timeout timeout :api api})) (fn get-proc [] (deref proc)))) (defmacro let-proc ([bindings body] `(let-proc ~bindings ~body (done [reason#] (log/info "Process stopped because " reason#)))) ([bindings body done] (let [bindings (->> bindings (apply hash-map) (map-keys keyword)) [do? [msg] & body] body [done? [reason] done] done opts (-> bindings (assoc :body `(fn [~msg] ~@body)) (assoc :done `(fn [~reason] ~done)))] ;; check do? ;; check done? ;; check bindings are what we expect `(create-proc ~@(mapcat identity opts))))) (comment (def p (create-proc :api {:log (fn [] (log/info "log"))} :done (fn [reason] (println "done because " reason)) :timeout (* 30 1000) :body (fn [msg] (println "received " msg)) :in (a/chan))) (def p (let-proc [in (a/chan) timeout (* 30 1000) api {:log (fn [] (log/info "log"))}] (do [msg] (println "received " msg)) (done [reason] (println "done because " reason)))) (a/put! (:cmd (p)) [:kill]) (a/go (println (a/<! (:ret (p)))))) (comment ;; Proc examples (def-proc eth-btc-proc [msg] (let-proc [in (a/chan) ;or e.g. (fn [] (a/timeout 2000)) cmd (a/chan) api {} timeout (* 60 1000)] (update order-book msg))) (def-proc eth-btc-poll-proc [msg] (let-proc [in (a/chan) cmd (a/chan) api {} timeout (* 60 1000)] (update order-book msg))) (def-proc hb-proc [hb] (let-proc [in (a/chan) cmd (a/chan) api {} timeout (* 60 1000)] (log/info "Heartbeat"))) ;; "global" timer to subscribe to (let [timer-ch (a/chan) pub (pub timer-ch identity)] {:proc (def-proc timer-proc [t] (let-proc [in (fn [] (a/timeout 2000))] (log/info "tick") (>! timer-ch :tick))) :pub-timer pub}) ;; one-off timer proc (defn fresh-timer-proc [period] (let [timer-ch (a/chan)] (def-proc timer-proc [t] (let-proc [in (fn [] (a/timeout 2000))] (log/info "tick") (>! timer-ch :tick))))) ;; effectively a (while true ...) proc (let [const-ch (a/chan)] ;; TODO I suspect this requires priority in alts else (in) will always win but ;; we want cmd to have the chance to break process. (let-proc [in (fn [] (a/put! 1))] (do [msg] something) (done [reason] done))) ;; no way to shutdown (defn create-polling-proc [period queue] (future (while true (Thread/sleep period) (when-let [msg (pop queue)] (send msg)))))) (defrecord Connection [in out pub transform-in transform-out proc]) (def ^:private CONNECTION (atom nil)) ;;* WS (defn connect-ws [& {in :in out :out transform-in :transform-in transform-out :transform-out :or {in (a/chan) out (a/chan) transform-in identity transform-out identity} :as conn}] (if (some-> @CONNECTION (:proc) ;; TODO generic closed? (s/closed?) (not)) ;; connection already exists (fn [] (deref CONNECTION)) ;; fresh connection (let [connection-stream ;; NOTE the 2 connect-via below work only because this here returns a ;; DUPLEX stream. Regular stream would act an async channel, so the two ;; connections below would deadlock. (s/splice sink source) creates a ;; duplex stream. @(http/websocket-client ;; TODO abstract connection endpoint "wss://ws-feed.gdax.com" {:max-frame-payload 1e6 :max-frame-size 1e6}) in-stream ;; sink of msgs from exchange for users to consume (s/->sink in) out-stream ;; source of user msgs to send to exchange (s/->source out) _ ;; exchange <= transform-out <= out <= user (s/connect-via out-stream (fn [msg] ;; TODO validate msg properly (if (or (get msg :type) (get msg "type")) (s/put! connection-stream (json/encode (transform-out msg))) (let [err (d/success-deferred "Malformed msg")] (log/error (ex-info "Malformed msg" {:msg msg})) err))) connection-stream) _ ;; exchange => transform-in => in => user (s/connect-via connection-stream (fn [msg] (let [msg (transform-in (json/decode msg))] (if (or (get msg :type) (get msg "type")) (s/put! in-stream msg) (let [err (d/success-deferred "Maslformed msg")] (log/error (ex-info "Malformed msg" {:msg msg})) err)))) in-stream) pub (a/pub in (fn [msg] (select-keys msg [:type :ticker])))] (reset! CONNECTION (map->Connection {:in in :out out :pub pub :transform-in transform-in :transform-out transform-out ;; for REST it should be a thread? :proc connection-stream})) (fn [] (deref CONNECTION))))) #_ (defn orderbook-derefer [ticker] (fn orderbook [] (-> @BOOKS ticker ;; (agent OrderBook) deref))) #_ (defn subscribe [{in :ch ticker :ticker :as book}] (when-not (subscribed? book) (let [conn (connect) pub (:pub (conn)) snapshot {:type :snapshot :ticker ticker} updates {:type :update :ticker ticker} agent (swap! BOOKS assoc ticker (agent book)) proc (let-proc [in in] (do [msg] (send agent update-book msg)))] (a/sub pub snapshots in) (a/sub pub updates in) (a/put! (:out (conn)) {:type :subscribe :product (product ticker) :topic :update}) (send agent assoc :proc proc))) (orderbook-derefer ticker)) (comment (def conn (connect-ws :transform-in (fn [msg] (println "Received: ") (pprint msg) msg) :transform-out (fn [msg] (println "Sending: ") (pprint msg) msg))) ;; subscribe hb (a/put! (:out (conn)) {"type" "subscribe" "product_ids" ["ETH-BTC"] "channels" ["heartbeat"]}) ;; unsubscribe hb (a/put! (:out (conn)) {"type" "unsubscribe" "product_ids" ["ETH-BTC"] "channels" ["heartbeat"]}) (a/put! (:out (conn)) {:a 1}) (s/close! (:proc (conn)))) ;;* REST (defn get-book [ticker] (let [url (str "https://api.gdax.com" (format "/products/%s/book?level=2" ticker))] (-> url ;; TODO should it be async? http-client/get :body json/decode))) (defmulti send-msg :type) (defmethod send-msg :book [{ticker :ticker}] (get-book ticker)) (def QUEUE (atom (queue))) ;; TODO can I just extend some protocol to have conj, peek, pop work for an (atom ;; queue)? (defn conjq! [v] (swap! QUEUE conj v)) (defn popq! [] (when (peek @QUEUE) (first (deref-swap! QUEUE pop)))) (defn create-polling-proc [stream period] ;; TODO make it local to this proc, expose only conj, pop, count or some such. (reset! QUEUE (queue)) (let-proc [in (fn [] (a/timeout period))] (do [_] (let [len (count @QUEUE)] (when (> len 1) (log/info "Queue count: " len))) (when-let [msg (popq!)] (s/put! stream (send-msg msg)))))) (defn connect-rest [& {in :in out :out transform-in :transform-in transform-out :transform-out :or {in (a/chan) out (a/chan) transform-in identity transform-out identity} :as conn}] (let [exchange-stream (s/stream) poller (create-polling-proc exchange-stream 5000) in-stream ;; sink of msgs from exchange for users to consume (s/->sink in) out-stream ;; source of user msgs to send to exchange (s/->source out) _ ;; exchange <= transform-out <= out <= user (s/consume (fn [msg] (conjq! (transform-out msg))) out-stream) _ ;; exchange => transform-in => in => user (s/connect-via exchange-stream (fn [msg] (s/put! in-stream (transform-in msg))) in-stream) pub (a/pub in (fn [msg] (select-keys msg [:type :ticker])))] (reset! CONNECTION (map->Connection {:in in :out out :pub pub :transform-in transform-in :transform-out transform-out :proc poller})) (fn [] (deref CONNECTION)))) (defn subscribe-rest [ticker period] (let-proc [in (fn [] (a/timeout period))] (do [_] (conjq! {:type :book :ticker ticker})))) (comment (def conn (connect-rest :transform-in (fn [msg] (println "Received: ") (pprint msg) msg) :transform-out (fn [msg] (println "Sending: ") (pprint msg) msg))) (a/put! (:out (conn)) {:type :book :ticker "BTC-USD"}) (a/put! (:cmd ((:proc (conn)))) [:kill]) (a/go (pprint (a/<! (:cmd ((:proc (conn))))))) (deref QUEUE) (def btc-usd-rest (subscribe-rest "BTC-USD" 3000)) (a/put! (:cmd (btc-usd-rest)) [:kill]) ;; end ) #_ (defmethod disconnect :gdax [exch] (swap! at-connections disj exch) (s/close! (:process exch)) (a/close! (:in exch)) (a/close! (:out exch)) (doseq [sub (:subscribers exch)] (close sub)) (-> exch (assoc :in nil) (assoc :out nil) (assoc :process nil))) (comment (defn print-threads [& {:keys [headers pre-fn] :or {pre-fn identity}}] (let [thread-set (keys (Thread/getAllStackTraces)) thread-data (mapv bean thread-set) headers (or headers (-> thread-data first keys))] (clojure.pprint/print-table headers (pre-fn thread-data)))) (defn print-threads-str [& args] (with-out-str (apply print-threads args))) ;;print all properties for all threads (print-threads) ;;print name,state,alive,daemon properties for all threads (print-threads :headers [:name :state :alive :daemon]) ;;print name,state,alive,daemon properties for non-daemon threads (print-threads :headers [:name :state :alive :daemon] :pre-fn (partial filter #(false? (:daemon %)))) ;;log name,state,alive,daemon properties for non-daemon threads (log/debug (print-threads-str :headers [:name :state :alive :daemon] :pre-fn (partial filter #(false? (:daemon %)))))) ;;* Design (comment (defn connect "Establish connection with the exchange. WS API - connection is persistent, - we subscribe to the heartbeat messages, - received messages are transformed to a unified schema, - we create a pub from in-ch with a topic-fn for unified schema, - in-ch, pub, heartbeat subscriber added to the state. REST API - we send a test msg and verify exch server response, - start a \"polling\" process with period T, - polling proccess has in-ch where it puts msgs received from exchange, - polling process has queue from which it sends msg every T sec, - polling process has pub from in-ch - we subscribe to heartbeat msgs (proc that adds HB msg to polling queue every 10sec) - received messages are transformed to a unified schema, - we create a pub from channel with a topic-fn for unified schema, - in-ch, queue, pub, heartbeat subscriber added to the state. Return - true on success, - nil on failure. Connect is idempotent: it should check if connection is already open." []) (defn close " (unsub-all (:pub Connection)) Close (:in Connection) Close (:out Connection) Stop (:proc Connection) Reset CONN" [Connection]) (defn create-orderbook " If OrderBook record for this ticker exists in state, use that. Else add fresh OrderBook for ticker with channel ch to state. Create process that updates OrderBook atom every time it gets a msg on ch. Set proc field in OrderBook. Return (orderbook-derefer ticker). " ([ticker]) ;; custom channel e.g. backed by NoisySlidingBuffer ([ticker ch])) (defn create-heartbeat " If HEARTBEAT use that. Else add fresh HeartBeat with channel ch to HEARTBEAT. Create process that updates timestamp in HeartBeat atom every item it gets a mesg on ch. Set proc field in HeartBeat. Return (heartbeat-derefer).") (defn close " Close (:ch OrderBook). Remove OrderBook from BOOKS. " [OrderBook]) (defn close " Close (:ch HeartBeat). Reset HEARTBEAT." [HeartBeat]) (defn subscribe "Subscribe OrderBook for updates from Exchange: WS API - send request for orderbook updates to exch, - (sub pub :topic (:ch OrderBook)), - add subscriber to state. REST API - Create proc that adds orderbook update request to polling q every T sec, - (sub pub :topic (:ch OrderBook)) - add subscriber to state." ([OrderBook]) ([OrderBook T])) (defn send "" [msg]) (defn unsubscribe " WS - send request to stop orderbook updates to exch, - (unsub pub :topic (:ch OrderBook)) - remove subscriber from state. REST - stop proc that enqueues orderbook update requests, - (unsub pub :topic (:ch OrderBook)), - remove subscriber from state." [OrderBook]) (defn subscribe " WS API - send :hb subscribtion message to exch, - (sub pub :hb (:ch HeartBeat)), - add subscriber to state. REST API - Create proc that adds HB msg to the polling queue every N sec, - (sub pub :hb (:ch HeartBeat)), - add subscriber to state." [HeartBeat]) (defn unsubscribe " WS API - send :hb unsubscribe msg to exch, - (unsub-all pub :hb), - remove subscriber from state. REST API - stop proc that queues HB msgs, - (unsub pub :hb (:ch HeartBeat)) - remove subscriber from state." [HeartBeat]))
[ { "context": "nt] ...) \n \n (dofut [[user-id] (create-user \\\"Brandon\\\" \\\"Bickford\\\")\n [business-id] (crea", "end": 2877, "score": 0.9997693300247192, "start": 2870, "tag": "NAME", "value": "Brandon" }, { "context": "\n (dofut [[user-id] (create-user \\\"Brandon\\\" \\\"Bickford\\\")\n [business-id] (create-business \\", "end": 2890, "score": 0.9997744560241699, "start": 2882, "tag": "NAME", "value": "Bickford" }, { "context": "\")\n [business-id] (create-business \\\"Gary Danko\\\")\n [review-id] (when (and user-id b", "end": 2951, "score": 0.9994004368782043, "start": 2941, "tag": "NAME", "value": "Gary Danko" } ]
src/peloton/fut.clj
bickfordb/Peloton
1
(ns peloton.fut "Fancy asynchronous future library This is named \"fut\" instead of \"future\" to avoid conflicting with the built-in future blocking/synchronous future support " (:require clojure.walk) (:use peloton.cell) (:use peloton.util) ) ; a cell which only fires once. (deftype Fut [^:volatile-mutable promised ^boolean ^:volatile-mutable done ^:volatile-mutable listeners] ICell (bind! [this listener] (if done (listener promised) (set! listeners (conj listeners listener))) nil) (unbind! [this listener] (set! listeners (remove #(= %1) listeners)) nil) clojure.lang.IFn (invoke [this val] (when (not done) (set! promised val) (set! done (boolean true)) ; send the message (doseq [listener listeners] (listener val)) ; clear existing listeners (set! listeners ()) nil))) (defn fut "Create a future" [] (Fut. nil false ())) (defn fut? "Check to see if x is a future" [x] (instance? peloton.fut.Fut x)) (defn to-fut "Convert a function which takes a \"finish\" callback to a future" ([f] (fn [& xs] (let [^Fut a-fut (fut) g (fn [y & ys] (if ys (a-fut (conj y ys)) (a-fut y)))] (apply f (concat xs [g])) a-fut))) ([f arg-idx] (fn [ & xs] (let [^Fut a-fut (fut) g (fn [y & ys] (if ys (a-fut (conj y ys)) (a-fut y)))] (apply f (concat (take arg-idx xs) [g] (drop arg-idx xs))) a-fut)))) (defn do-fut-inner-body [outer-fut body] (list outer-fut (cons `do body))) (defn do-fut-inner-bind [bind-to bind-from-fut on-fut] (let [bind-from-fut0 (gensym "bind-from-fut-") bind-fn (gensym "bind-fn")] (list 'let [bind-from-fut0 bind-from-fut bind-fn (list 'fn [bind-to] on-fut)] (list 'if (list `fut? bind-from-fut0) (list 'peloton.cell/bind! bind-from-fut0 bind-fn) (list bind-fn bind-from-fut0))))) (defn do-fut-inner [bindings outer-fut body] (cond (empty? bindings) (do-fut-inner-body outer-fut body) :else (let [[bind-to bind-from-fut & tail] bindings rec (do-fut-inner tail outer-fut body)] (do-fut-inner-bind bind-to bind-from-fut rec)))) (defmacro dofut "Execute a body when a sequence of futures are ready. Each binding will be executed when the future from the previous binding is delivered. The body will be executed when all of the futures in the bindings are delivered. Example: (defn create-user ^Fut [first last] ...) (defn create-business ^Fut [] ...) (defn create-review ^Fut [user-id business-id rating comment] ...) (dofut [[user-id] (create-user \"Brandon\" \"Bickford\") [business-id] (create-business \"Gary Danko\") [review-id] (when (and user-id business-id) (create-review user-id business-id 5 \"Liked it\" ))] (println \"user:\" user-id) (println \"business:\" business-id) (println \"review:\" review-id)) " [bindings & body] (let [ret-fut-sym (gensym "retfut") dofut-body (do-fut-inner bindings ret-fut-sym body)] (list 'let [ret-fut-sym (list `fut)] dofut-body ret-fut-sym))) (defn future-ref? [form] (and (symbol? form) (.startsWith (name form) "?"))) (declare replace-future-ref) (defn replace-future-ref-list [a-form] (loop [before () t a-form] (cond (empty? t) a-form ; we couldn't find any replacements :else (let [[h & t0] t] (cond (future-ref? h) (let [bind-to (gensym "fut") bind-from (symbol (.substring (name h) 1)) replaced (list 'dofut [bind-to bind-from] (replace-future-ref-list (concat before (list bind-to) t0)))] replaced) :else (recur (concat before (list h)) t0)))))) (defn replace-future-ref [a-form] (cond (list? a-form) (replace-future-ref-list a-form) :else a-form)) (defn replace-future-sym [a-sym] (let [bind-to (gensym "fut") bind-from (symbol (.substring (name a-sym) 1))] (list 'dofut [bind-to bind-from] bind-to))) (defmacro >? [form] (cond (future-ref? form) (replace-future-sym form) :else (clojure.walk/postwalk replace-future-ref form)))
35127
(ns peloton.fut "Fancy asynchronous future library This is named \"fut\" instead of \"future\" to avoid conflicting with the built-in future blocking/synchronous future support " (:require clojure.walk) (:use peloton.cell) (:use peloton.util) ) ; a cell which only fires once. (deftype Fut [^:volatile-mutable promised ^boolean ^:volatile-mutable done ^:volatile-mutable listeners] ICell (bind! [this listener] (if done (listener promised) (set! listeners (conj listeners listener))) nil) (unbind! [this listener] (set! listeners (remove #(= %1) listeners)) nil) clojure.lang.IFn (invoke [this val] (when (not done) (set! promised val) (set! done (boolean true)) ; send the message (doseq [listener listeners] (listener val)) ; clear existing listeners (set! listeners ()) nil))) (defn fut "Create a future" [] (Fut. nil false ())) (defn fut? "Check to see if x is a future" [x] (instance? peloton.fut.Fut x)) (defn to-fut "Convert a function which takes a \"finish\" callback to a future" ([f] (fn [& xs] (let [^Fut a-fut (fut) g (fn [y & ys] (if ys (a-fut (conj y ys)) (a-fut y)))] (apply f (concat xs [g])) a-fut))) ([f arg-idx] (fn [ & xs] (let [^Fut a-fut (fut) g (fn [y & ys] (if ys (a-fut (conj y ys)) (a-fut y)))] (apply f (concat (take arg-idx xs) [g] (drop arg-idx xs))) a-fut)))) (defn do-fut-inner-body [outer-fut body] (list outer-fut (cons `do body))) (defn do-fut-inner-bind [bind-to bind-from-fut on-fut] (let [bind-from-fut0 (gensym "bind-from-fut-") bind-fn (gensym "bind-fn")] (list 'let [bind-from-fut0 bind-from-fut bind-fn (list 'fn [bind-to] on-fut)] (list 'if (list `fut? bind-from-fut0) (list 'peloton.cell/bind! bind-from-fut0 bind-fn) (list bind-fn bind-from-fut0))))) (defn do-fut-inner [bindings outer-fut body] (cond (empty? bindings) (do-fut-inner-body outer-fut body) :else (let [[bind-to bind-from-fut & tail] bindings rec (do-fut-inner tail outer-fut body)] (do-fut-inner-bind bind-to bind-from-fut rec)))) (defmacro dofut "Execute a body when a sequence of futures are ready. Each binding will be executed when the future from the previous binding is delivered. The body will be executed when all of the futures in the bindings are delivered. Example: (defn create-user ^Fut [first last] ...) (defn create-business ^Fut [] ...) (defn create-review ^Fut [user-id business-id rating comment] ...) (dofut [[user-id] (create-user \"<NAME>\" \"<NAME>\") [business-id] (create-business \"<NAME>\") [review-id] (when (and user-id business-id) (create-review user-id business-id 5 \"Liked it\" ))] (println \"user:\" user-id) (println \"business:\" business-id) (println \"review:\" review-id)) " [bindings & body] (let [ret-fut-sym (gensym "retfut") dofut-body (do-fut-inner bindings ret-fut-sym body)] (list 'let [ret-fut-sym (list `fut)] dofut-body ret-fut-sym))) (defn future-ref? [form] (and (symbol? form) (.startsWith (name form) "?"))) (declare replace-future-ref) (defn replace-future-ref-list [a-form] (loop [before () t a-form] (cond (empty? t) a-form ; we couldn't find any replacements :else (let [[h & t0] t] (cond (future-ref? h) (let [bind-to (gensym "fut") bind-from (symbol (.substring (name h) 1)) replaced (list 'dofut [bind-to bind-from] (replace-future-ref-list (concat before (list bind-to) t0)))] replaced) :else (recur (concat before (list h)) t0)))))) (defn replace-future-ref [a-form] (cond (list? a-form) (replace-future-ref-list a-form) :else a-form)) (defn replace-future-sym [a-sym] (let [bind-to (gensym "fut") bind-from (symbol (.substring (name a-sym) 1))] (list 'dofut [bind-to bind-from] bind-to))) (defmacro >? [form] (cond (future-ref? form) (replace-future-sym form) :else (clojure.walk/postwalk replace-future-ref form)))
true
(ns peloton.fut "Fancy asynchronous future library This is named \"fut\" instead of \"future\" to avoid conflicting with the built-in future blocking/synchronous future support " (:require clojure.walk) (:use peloton.cell) (:use peloton.util) ) ; a cell which only fires once. (deftype Fut [^:volatile-mutable promised ^boolean ^:volatile-mutable done ^:volatile-mutable listeners] ICell (bind! [this listener] (if done (listener promised) (set! listeners (conj listeners listener))) nil) (unbind! [this listener] (set! listeners (remove #(= %1) listeners)) nil) clojure.lang.IFn (invoke [this val] (when (not done) (set! promised val) (set! done (boolean true)) ; send the message (doseq [listener listeners] (listener val)) ; clear existing listeners (set! listeners ()) nil))) (defn fut "Create a future" [] (Fut. nil false ())) (defn fut? "Check to see if x is a future" [x] (instance? peloton.fut.Fut x)) (defn to-fut "Convert a function which takes a \"finish\" callback to a future" ([f] (fn [& xs] (let [^Fut a-fut (fut) g (fn [y & ys] (if ys (a-fut (conj y ys)) (a-fut y)))] (apply f (concat xs [g])) a-fut))) ([f arg-idx] (fn [ & xs] (let [^Fut a-fut (fut) g (fn [y & ys] (if ys (a-fut (conj y ys)) (a-fut y)))] (apply f (concat (take arg-idx xs) [g] (drop arg-idx xs))) a-fut)))) (defn do-fut-inner-body [outer-fut body] (list outer-fut (cons `do body))) (defn do-fut-inner-bind [bind-to bind-from-fut on-fut] (let [bind-from-fut0 (gensym "bind-from-fut-") bind-fn (gensym "bind-fn")] (list 'let [bind-from-fut0 bind-from-fut bind-fn (list 'fn [bind-to] on-fut)] (list 'if (list `fut? bind-from-fut0) (list 'peloton.cell/bind! bind-from-fut0 bind-fn) (list bind-fn bind-from-fut0))))) (defn do-fut-inner [bindings outer-fut body] (cond (empty? bindings) (do-fut-inner-body outer-fut body) :else (let [[bind-to bind-from-fut & tail] bindings rec (do-fut-inner tail outer-fut body)] (do-fut-inner-bind bind-to bind-from-fut rec)))) (defmacro dofut "Execute a body when a sequence of futures are ready. Each binding will be executed when the future from the previous binding is delivered. The body will be executed when all of the futures in the bindings are delivered. Example: (defn create-user ^Fut [first last] ...) (defn create-business ^Fut [] ...) (defn create-review ^Fut [user-id business-id rating comment] ...) (dofut [[user-id] (create-user \"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\") [business-id] (create-business \"PI:NAME:<NAME>END_PI\") [review-id] (when (and user-id business-id) (create-review user-id business-id 5 \"Liked it\" ))] (println \"user:\" user-id) (println \"business:\" business-id) (println \"review:\" review-id)) " [bindings & body] (let [ret-fut-sym (gensym "retfut") dofut-body (do-fut-inner bindings ret-fut-sym body)] (list 'let [ret-fut-sym (list `fut)] dofut-body ret-fut-sym))) (defn future-ref? [form] (and (symbol? form) (.startsWith (name form) "?"))) (declare replace-future-ref) (defn replace-future-ref-list [a-form] (loop [before () t a-form] (cond (empty? t) a-form ; we couldn't find any replacements :else (let [[h & t0] t] (cond (future-ref? h) (let [bind-to (gensym "fut") bind-from (symbol (.substring (name h) 1)) replaced (list 'dofut [bind-to bind-from] (replace-future-ref-list (concat before (list bind-to) t0)))] replaced) :else (recur (concat before (list h)) t0)))))) (defn replace-future-ref [a-form] (cond (list? a-form) (replace-future-ref-list a-form) :else a-form)) (defn replace-future-sym [a-sym] (let [bind-to (gensym "fut") bind-from (symbol (.substring (name a-sym) 1))] (list 'dofut [bind-to bind-from] bind-to))) (defmacro >? [form] (cond (future-ref? form) (replace-future-sym form) :else (clojure.walk/postwalk replace-future-ref form)))
[ { "context": "2003-12-13T18:30:02Z</updated>\n <author>\n <name>John Doe</name>\n <email>[email protected]</email>\n </a", "end": 1264, "score": 0.9996744394302368, "start": 1256, "tag": "NAME", "value": "John Doe" }, { "context": "ted>\n <author>\n <name>John Doe</name>\n <email>[email protected]</email>\n </author>\n <id>urn:uuid:60a76c80-d399-11", "end": 1301, "score": 0.9995058178901672, "start": 1282, "tag": "EMAIL", "value": "[email protected]" } ]
webjure/src/webjure/xml/feeds.clj
tatut/Webjure
15
;; Working with XML-based feed formats (ns webjure.xml.feeds (:refer-clojure) (:use webjure.xml)) (defn parse-atom1-link [link-node] (parse link-node {} (attr "href" (collect-as :url #(.getValue %))) (attr "rel" (collect-as :rel #(.getValue %))))) (defn parse-atom1-entry [entry-node] (parse entry-node {:links {}} (<> "title" (collect-as :title text)) (<>* "link" (modify-key :links #(let [lnk (parse-atom1-link %2)] (assoc %1 (lnk :rel) lnk)))) (<>? "author" (<>? "email" (collect-as :email text)) (<>? "name" (collect-as :author text))))) (defn load-atom1-feed [file-or-istream] (parse (. (load-dom file-or-istream) (getDocumentElement)) {:entries []} (<> "title" (collect-as :title text)) (<>? "subtitle" (collect-as :subtitle text)) (<>* "entry" (modify-key :entries #(conj %1 (parse-atom1-entry %2)))))) ;; example modified from Wikipedia: (def +atom-test-xml+ "<?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xmlns=\"http://www.w3.org/2005/Atom\"> <title>Example Feed</title> <subtitle>A subtitle.</subtitle> <link href=\"http://example.org/feed/\" rel=\"self\"/> <link href=\"http://example.org/\"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>John Doe</name> <email>[email protected]</email> </author> <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href=\"http://example.org/2003/12/13/atom03\"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> <entry> <title>Webjure gains preliminary support form feeds</title> <link href=\"http://example.org/2008/11/18/story\"/> <id>urn:uuid:this-is-my-story-and-im-sticking-to-it-2008118tt</id> <summary>We can parse these.</summary> </entry> </feed>")
111245
;; Working with XML-based feed formats (ns webjure.xml.feeds (:refer-clojure) (:use webjure.xml)) (defn parse-atom1-link [link-node] (parse link-node {} (attr "href" (collect-as :url #(.getValue %))) (attr "rel" (collect-as :rel #(.getValue %))))) (defn parse-atom1-entry [entry-node] (parse entry-node {:links {}} (<> "title" (collect-as :title text)) (<>* "link" (modify-key :links #(let [lnk (parse-atom1-link %2)] (assoc %1 (lnk :rel) lnk)))) (<>? "author" (<>? "email" (collect-as :email text)) (<>? "name" (collect-as :author text))))) (defn load-atom1-feed [file-or-istream] (parse (. (load-dom file-or-istream) (getDocumentElement)) {:entries []} (<> "title" (collect-as :title text)) (<>? "subtitle" (collect-as :subtitle text)) (<>* "entry" (modify-key :entries #(conj %1 (parse-atom1-entry %2)))))) ;; example modified from Wikipedia: (def +atom-test-xml+ "<?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xmlns=\"http://www.w3.org/2005/Atom\"> <title>Example Feed</title> <subtitle>A subtitle.</subtitle> <link href=\"http://example.org/feed/\" rel=\"self\"/> <link href=\"http://example.org/\"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name><NAME></name> <email><EMAIL></email> </author> <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href=\"http://example.org/2003/12/13/atom03\"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> <entry> <title>Webjure gains preliminary support form feeds</title> <link href=\"http://example.org/2008/11/18/story\"/> <id>urn:uuid:this-is-my-story-and-im-sticking-to-it-2008118tt</id> <summary>We can parse these.</summary> </entry> </feed>")
true
;; Working with XML-based feed formats (ns webjure.xml.feeds (:refer-clojure) (:use webjure.xml)) (defn parse-atom1-link [link-node] (parse link-node {} (attr "href" (collect-as :url #(.getValue %))) (attr "rel" (collect-as :rel #(.getValue %))))) (defn parse-atom1-entry [entry-node] (parse entry-node {:links {}} (<> "title" (collect-as :title text)) (<>* "link" (modify-key :links #(let [lnk (parse-atom1-link %2)] (assoc %1 (lnk :rel) lnk)))) (<>? "author" (<>? "email" (collect-as :email text)) (<>? "name" (collect-as :author text))))) (defn load-atom1-feed [file-or-istream] (parse (. (load-dom file-or-istream) (getDocumentElement)) {:entries []} (<> "title" (collect-as :title text)) (<>? "subtitle" (collect-as :subtitle text)) (<>* "entry" (modify-key :entries #(conj %1 (parse-atom1-entry %2)))))) ;; example modified from Wikipedia: (def +atom-test-xml+ "<?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xmlns=\"http://www.w3.org/2005/Atom\"> <title>Example Feed</title> <subtitle>A subtitle.</subtitle> <link href=\"http://example.org/feed/\" rel=\"self\"/> <link href=\"http://example.org/\"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>PI:NAME:<NAME>END_PI</name> <email>PI:EMAIL:<EMAIL>END_PI</email> </author> <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href=\"http://example.org/2003/12/13/atom03\"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> <entry> <title>Webjure gains preliminary support form feeds</title> <link href=\"http://example.org/2008/11/18/story\"/> <id>urn:uuid:this-is-my-story-and-im-sticking-to-it-2008118tt</id> <summary>We can parse these.</summary> </entry> </feed>")
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998305439949036, "start": 96, "tag": "NAME", "value": "Ragnar Svensson" }, { "context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ", "end": 129, "score": 0.9998278021812439, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/internal/cache_test.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.cache-test (:require [clojure.test :refer :all] [support.test-support :refer :all] [internal.cache :refer :all] [internal.graph.types :as gt] [internal.system :as is])) (defn- mock-system [cache-size ch] (is/make-system {:cache-size cache-size})) (defn- as-map [c] (select-keys c (keys c))) (deftest items-in-and-out (testing "things put into cache appear in snapshot" (with-clean-system {:cache-size 1000} (let [snapshot (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]))] (are [k v] (= v (get snapshot k)) :a 1 :b 2 :c 3)))) (testing "one item can be decached" (with-clean-system (is (= {:a 1 :c 3} (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]) (cache-invalidate [:b]) (as-map)))))) (testing "multiple items can be decached" (with-clean-system (is (empty? (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]) (cache-invalidate [:b :c]) (cache-invalidate [:a]) (as-map))))))) (deftest limits (with-clean-system {:cache-size 3} (let [snapshot (-> cache (cache-encache [[[:a :a] 1] [[:b :b] 2] [[:c :c] 3]]) (cache-hit [[:a :a] [:c :c]]) (cache-encache [[[:d :d] 4]]))] (are [k v] (= v (get snapshot k)) [:a :a] 1 [:c :c] 3 [:d :d] 4))))
50023
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.cache-test (:require [clojure.test :refer :all] [support.test-support :refer :all] [internal.cache :refer :all] [internal.graph.types :as gt] [internal.system :as is])) (defn- mock-system [cache-size ch] (is/make-system {:cache-size cache-size})) (defn- as-map [c] (select-keys c (keys c))) (deftest items-in-and-out (testing "things put into cache appear in snapshot" (with-clean-system {:cache-size 1000} (let [snapshot (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]))] (are [k v] (= v (get snapshot k)) :a 1 :b 2 :c 3)))) (testing "one item can be decached" (with-clean-system (is (= {:a 1 :c 3} (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]) (cache-invalidate [:b]) (as-map)))))) (testing "multiple items can be decached" (with-clean-system (is (empty? (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]) (cache-invalidate [:b :c]) (cache-invalidate [:a]) (as-map))))))) (deftest limits (with-clean-system {:cache-size 3} (let [snapshot (-> cache (cache-encache [[[:a :a] 1] [[:b :b] 2] [[:c :c] 3]]) (cache-hit [[:a :a] [:c :c]]) (cache-encache [[[:d :d] 4]]))] (are [k v] (= v (get snapshot k)) [:a :a] 1 [:c :c] 3 [:d :d] 4))))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.cache-test (:require [clojure.test :refer :all] [support.test-support :refer :all] [internal.cache :refer :all] [internal.graph.types :as gt] [internal.system :as is])) (defn- mock-system [cache-size ch] (is/make-system {:cache-size cache-size})) (defn- as-map [c] (select-keys c (keys c))) (deftest items-in-and-out (testing "things put into cache appear in snapshot" (with-clean-system {:cache-size 1000} (let [snapshot (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]))] (are [k v] (= v (get snapshot k)) :a 1 :b 2 :c 3)))) (testing "one item can be decached" (with-clean-system (is (= {:a 1 :c 3} (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]) (cache-invalidate [:b]) (as-map)))))) (testing "multiple items can be decached" (with-clean-system (is (empty? (-> cache (cache-encache [[:a 1] [:b 2] [:c 3]]) (cache-invalidate [:b :c]) (cache-invalidate [:a]) (as-map))))))) (deftest limits (with-clean-system {:cache-size 3} (let [snapshot (-> cache (cache-encache [[[:a :a] 1] [[:b :b] 2] [[:c :c] 3]]) (cache-hit [[:a :a] [:c :c]]) (cache-encache [[[:d :d] 4]]))] (are [k v] (= v (get snapshot k)) [:a :a] 1 [:c :c] 3 [:d :d] 4))))
[ { "context": "; Overtone Translation of Vi Hart's Sound Braid by Roger Allen\n;; http://www.youtube.com/watch?v=VB6a4nI0BPA\n(ns", "end": 63, "score": 0.9998766183853149, "start": 52, "tag": "NAME", "value": "Roger Allen" } ]
examples/vihart_braid.clj
baskeboler/shadertone
304
;; Overtone Translation of Vi Hart's Sound Braid by Roger Allen ;; http://www.youtube.com/watch?v=VB6a4nI0BPA (ns vihart-braid (:require [overtone.live :as o] [overtone.synth.stringed :as strings] [shadertone.tone :as t] [leipzig.canon :as lc] [leipzig.live :as ll] [leipzig.melody :as lm] [leipzig.scale :as ls])) ;; instrument routines... (defn pick [amp {pitch :pitch, start :time, length :duration, pan :pan}] (let [synth-id (o/at start (strings/ektara pitch :amp amp :gate 1 :pan pan))] (o/at (+ start length) (o/ctl synth-id :gate 0)))) (defmethod ll/play-note :melody [note] (pick 0.6 note)) (def sol-do (o/sample (o/freesound-path 44929))) (def sol-re (o/sample (o/freesound-path 44934))) (def sol-mi (o/sample (o/freesound-path 44933))) (def sol-fa (o/sample (o/freesound-path 44931))) (def sol-so (o/sample (o/freesound-path 44935))) (def sol-la (o/sample (o/freesound-path 44932))) (def sol-ti (o/sample (o/freesound-path 44936))) (def sol-do-2 (o/sample (o/freesound-path 44930))) (defn sing-note [note] ;;(println note) (case (:pitch note) -4 (sol-do :vol 0.75 :pan (:pan note)) -3 (sol-re :vol 0.85 :pan (:pan note)) -2 (sol-mi :vol 0.85 :pan (:pan note)) -1 (sol-fa :vol 0.85 :pan (:pan note)) 0 (sol-so :vol 0.65 :pan (:pan note)) 1 (sol-la :vol 0.65 :pan (:pan note)) 2 (sol-ti :vol 0.75 :pan (:pan note)) 3 (sol-do-2 :vol 0.85 :pan (:pan note)) 4 (sol-ti :vol 0.85 :pan (:pan note) :rate (/ (Math/pow 2 (/ 14 12)) (Math/pow 2 (/ 11 12)))))) (def voice-1-atom (atom 0)) (def voice-2-atom (atom 0)) (def voice-3-atom (atom 0)) (defmethod ll/play-note :voice-1 [note] (swap! voice-1-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) (defmethod ll/play-note :voice-2 [note] (swap! voice-2-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) (defmethod ll/play-note :voice-3 [note] (swap! voice-3-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) ;; utility for Vi's panning technique (defn add-pan "given a min and max pitch and notes, pan from -0.99 to 0.99 depending on the pitch" [min-pitch max-pitch ns] (let [pans (map #(* 0.9 (- (* 2 (/ (- (:pitch %) min-pitch) (- max-pitch min-pitch))) 1)) ns)] (->> ns (lm/having :pan pans)))) ;; gather her strands of notes into a braid (defn make-braid [N] (let [strand (lm/phrase [ 1 1 2, 3 1, 2 2] [nil 0 1, 2 3, 4 3]) strand-0 (add-pan -4 4 strand) strand-1 (add-pan -4 4 (lc/mirror strand-0)) strand-a (lm/times N (->> strand-0 (lm/then strand-1))) strand-b (lm/times N (->> strand-1 (lm/then strand-0)))] (->> (->> strand-a (lm/where :part (lm/is :voice-1))) (lm/with (->> strand-b (lm/where :part (lm/is :voice-2)) (lm/after 4))) (lm/with (->> strand-a (lm/where :part (lm/is :voice-3)) (lm/after 8)))))) (defn play-song [speed key song] (->> song (lm/where :part (lm/is :melody)) (lm/where :time speed) (lm/where :duration speed) (lm/where :pitch key) ll/play)) (defn sing-song [speed song] (->> song (lm/where :time speed) (lm/where :duration speed) ll/play)) (t/start "examples/vihart_braid.glsl" :width 1280 :height 720 :textures [:previous-frame] :user-data {"v1" voice-1-atom, "v2" voice-2-atom, "v3" voice-3-atom}) ;; Vi Hart's version (play-song (lm/bpm 120) (comp ls/low ls/C ls/major) (make-braid 5)) (sing-song (lm/bpm 120) (make-braid 3)) (comment ;; but with Overtone & Leipzig you can change things about... (play-song (lm/bpm 172) (comp ls/low ls/D ls/flat ls/mixolydian) (make-braid 3)) (play-song (lm/bpm 92) (comp ls/low ls/C ls/minor) (make-braid 3)) )
122508
;; Overtone Translation of Vi Hart's Sound Braid by <NAME> ;; http://www.youtube.com/watch?v=VB6a4nI0BPA (ns vihart-braid (:require [overtone.live :as o] [overtone.synth.stringed :as strings] [shadertone.tone :as t] [leipzig.canon :as lc] [leipzig.live :as ll] [leipzig.melody :as lm] [leipzig.scale :as ls])) ;; instrument routines... (defn pick [amp {pitch :pitch, start :time, length :duration, pan :pan}] (let [synth-id (o/at start (strings/ektara pitch :amp amp :gate 1 :pan pan))] (o/at (+ start length) (o/ctl synth-id :gate 0)))) (defmethod ll/play-note :melody [note] (pick 0.6 note)) (def sol-do (o/sample (o/freesound-path 44929))) (def sol-re (o/sample (o/freesound-path 44934))) (def sol-mi (o/sample (o/freesound-path 44933))) (def sol-fa (o/sample (o/freesound-path 44931))) (def sol-so (o/sample (o/freesound-path 44935))) (def sol-la (o/sample (o/freesound-path 44932))) (def sol-ti (o/sample (o/freesound-path 44936))) (def sol-do-2 (o/sample (o/freesound-path 44930))) (defn sing-note [note] ;;(println note) (case (:pitch note) -4 (sol-do :vol 0.75 :pan (:pan note)) -3 (sol-re :vol 0.85 :pan (:pan note)) -2 (sol-mi :vol 0.85 :pan (:pan note)) -1 (sol-fa :vol 0.85 :pan (:pan note)) 0 (sol-so :vol 0.65 :pan (:pan note)) 1 (sol-la :vol 0.65 :pan (:pan note)) 2 (sol-ti :vol 0.75 :pan (:pan note)) 3 (sol-do-2 :vol 0.85 :pan (:pan note)) 4 (sol-ti :vol 0.85 :pan (:pan note) :rate (/ (Math/pow 2 (/ 14 12)) (Math/pow 2 (/ 11 12)))))) (def voice-1-atom (atom 0)) (def voice-2-atom (atom 0)) (def voice-3-atom (atom 0)) (defmethod ll/play-note :voice-1 [note] (swap! voice-1-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) (defmethod ll/play-note :voice-2 [note] (swap! voice-2-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) (defmethod ll/play-note :voice-3 [note] (swap! voice-3-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) ;; utility for Vi's panning technique (defn add-pan "given a min and max pitch and notes, pan from -0.99 to 0.99 depending on the pitch" [min-pitch max-pitch ns] (let [pans (map #(* 0.9 (- (* 2 (/ (- (:pitch %) min-pitch) (- max-pitch min-pitch))) 1)) ns)] (->> ns (lm/having :pan pans)))) ;; gather her strands of notes into a braid (defn make-braid [N] (let [strand (lm/phrase [ 1 1 2, 3 1, 2 2] [nil 0 1, 2 3, 4 3]) strand-0 (add-pan -4 4 strand) strand-1 (add-pan -4 4 (lc/mirror strand-0)) strand-a (lm/times N (->> strand-0 (lm/then strand-1))) strand-b (lm/times N (->> strand-1 (lm/then strand-0)))] (->> (->> strand-a (lm/where :part (lm/is :voice-1))) (lm/with (->> strand-b (lm/where :part (lm/is :voice-2)) (lm/after 4))) (lm/with (->> strand-a (lm/where :part (lm/is :voice-3)) (lm/after 8)))))) (defn play-song [speed key song] (->> song (lm/where :part (lm/is :melody)) (lm/where :time speed) (lm/where :duration speed) (lm/where :pitch key) ll/play)) (defn sing-song [speed song] (->> song (lm/where :time speed) (lm/where :duration speed) ll/play)) (t/start "examples/vihart_braid.glsl" :width 1280 :height 720 :textures [:previous-frame] :user-data {"v1" voice-1-atom, "v2" voice-2-atom, "v3" voice-3-atom}) ;; Vi Hart's version (play-song (lm/bpm 120) (comp ls/low ls/C ls/major) (make-braid 5)) (sing-song (lm/bpm 120) (make-braid 3)) (comment ;; but with Overtone & Leipzig you can change things about... (play-song (lm/bpm 172) (comp ls/low ls/D ls/flat ls/mixolydian) (make-braid 3)) (play-song (lm/bpm 92) (comp ls/low ls/C ls/minor) (make-braid 3)) )
true
;; Overtone Translation of Vi Hart's Sound Braid by PI:NAME:<NAME>END_PI ;; http://www.youtube.com/watch?v=VB6a4nI0BPA (ns vihart-braid (:require [overtone.live :as o] [overtone.synth.stringed :as strings] [shadertone.tone :as t] [leipzig.canon :as lc] [leipzig.live :as ll] [leipzig.melody :as lm] [leipzig.scale :as ls])) ;; instrument routines... (defn pick [amp {pitch :pitch, start :time, length :duration, pan :pan}] (let [synth-id (o/at start (strings/ektara pitch :amp amp :gate 1 :pan pan))] (o/at (+ start length) (o/ctl synth-id :gate 0)))) (defmethod ll/play-note :melody [note] (pick 0.6 note)) (def sol-do (o/sample (o/freesound-path 44929))) (def sol-re (o/sample (o/freesound-path 44934))) (def sol-mi (o/sample (o/freesound-path 44933))) (def sol-fa (o/sample (o/freesound-path 44931))) (def sol-so (o/sample (o/freesound-path 44935))) (def sol-la (o/sample (o/freesound-path 44932))) (def sol-ti (o/sample (o/freesound-path 44936))) (def sol-do-2 (o/sample (o/freesound-path 44930))) (defn sing-note [note] ;;(println note) (case (:pitch note) -4 (sol-do :vol 0.75 :pan (:pan note)) -3 (sol-re :vol 0.85 :pan (:pan note)) -2 (sol-mi :vol 0.85 :pan (:pan note)) -1 (sol-fa :vol 0.85 :pan (:pan note)) 0 (sol-so :vol 0.65 :pan (:pan note)) 1 (sol-la :vol 0.65 :pan (:pan note)) 2 (sol-ti :vol 0.75 :pan (:pan note)) 3 (sol-do-2 :vol 0.85 :pan (:pan note)) 4 (sol-ti :vol 0.85 :pan (:pan note) :rate (/ (Math/pow 2 (/ 14 12)) (Math/pow 2 (/ 11 12)))))) (def voice-1-atom (atom 0)) (def voice-2-atom (atom 0)) (def voice-3-atom (atom 0)) (defmethod ll/play-note :voice-1 [note] (swap! voice-1-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) (defmethod ll/play-note :voice-2 [note] (swap! voice-2-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) (defmethod ll/play-note :voice-3 [note] (swap! voice-3-atom (fn [x] (* 1.0 (:pitch note)))) (sing-note note)) ;; utility for Vi's panning technique (defn add-pan "given a min and max pitch and notes, pan from -0.99 to 0.99 depending on the pitch" [min-pitch max-pitch ns] (let [pans (map #(* 0.9 (- (* 2 (/ (- (:pitch %) min-pitch) (- max-pitch min-pitch))) 1)) ns)] (->> ns (lm/having :pan pans)))) ;; gather her strands of notes into a braid (defn make-braid [N] (let [strand (lm/phrase [ 1 1 2, 3 1, 2 2] [nil 0 1, 2 3, 4 3]) strand-0 (add-pan -4 4 strand) strand-1 (add-pan -4 4 (lc/mirror strand-0)) strand-a (lm/times N (->> strand-0 (lm/then strand-1))) strand-b (lm/times N (->> strand-1 (lm/then strand-0)))] (->> (->> strand-a (lm/where :part (lm/is :voice-1))) (lm/with (->> strand-b (lm/where :part (lm/is :voice-2)) (lm/after 4))) (lm/with (->> strand-a (lm/where :part (lm/is :voice-3)) (lm/after 8)))))) (defn play-song [speed key song] (->> song (lm/where :part (lm/is :melody)) (lm/where :time speed) (lm/where :duration speed) (lm/where :pitch key) ll/play)) (defn sing-song [speed song] (->> song (lm/where :time speed) (lm/where :duration speed) ll/play)) (t/start "examples/vihart_braid.glsl" :width 1280 :height 720 :textures [:previous-frame] :user-data {"v1" voice-1-atom, "v2" voice-2-atom, "v3" voice-3-atom}) ;; Vi Hart's version (play-song (lm/bpm 120) (comp ls/low ls/C ls/major) (make-braid 5)) (sing-song (lm/bpm 120) (make-braid 3)) (comment ;; but with Overtone & Leipzig you can change things about... (play-song (lm/bpm 172) (comp ls/low ls/D ls/flat ls/mixolydian) (make-braid 3)) (play-song (lm/bpm 92) (comp ls/low ls/C ls/minor) (make-braid 3)) )
[ { "context": "))))\n\n(let [particular (->PacienteParticular 15, \"Marco\", \"18052001\")\n plano (->PacienteComPlano 15,", "end": 1003, "score": 0.9996390342712402, "start": 998, "tag": "NAME", "value": "Marco" }, { "context": " \"18052001\")\n plano (->PacienteComPlano 15, \"Marco\", \"18052001\", [:raixo-x, :ultrasom])]\n (pprint (", "end": 1060, "score": 0.9995007514953613, "start": 1055, "tag": "NAME", "value": "Marco" } ]
curso4/src/hospital/aula2.clj
Caporiccii/Clojure-Class
0
(ns hospital.aula2 (:use clojure.pprint)) (defrecord PacienteParticular [id, nome, nascimento]) (defrecord PacienteComPlano [id, nome, nascimento, plano]) ;vantagem esta tudo em um bloco só ;Desvantagem concentração de tipos ;(defn deve-assinar-pre-autorizacao? [paciente procedimento valor] ; (if (= PacienteParticular (type paciente)) ; (>= valor 50) ; (if (= PacientePlanoDeSaude (type paciente)) ; (let [plano (get paciente :plano)] ; (not (some #(= % procedimento) plano))) ; true))) (defprotocol Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor])) ;como se fosse uma interface (extend-type PacienteParticular Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor] (>= valor 50))) (extend-type PacienteComPlano Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor] (let [plano (:plano paciente)] (not (some #(= % procedimento) plano))))) (let [particular (->PacienteParticular 15, "Marco", "18052001") plano (->PacienteComPlano 15, "Marco", "18052001", [:raixo-x, :ultrasom])] (pprint (deve-assinar-pre-autorizacao? particular, :raixo-x, 500)) (pprint (deve-assinar-pre-autorizacao? particular, :raixo-x, 40)) (pprint (deve-assinar-pre-autorizacao? plano, :raixo-x, 5000)) (pprint (deve-assinar-pre-autorizacao? plano, :coleta-de-sangue, 500)) ) ;uma alternativa seria implementar diretamente ;(defrecord PacienteComPlano ; [id, nome, nascimento, plano] ; Cobravel ; (deve-assinar-pre-autorizacao? [paciente procedimento valor] ; (let [plano (:plano paciente)] ; (not (some #(= % procedimento) plano))))) (defprotocol Dateable (to-ms [this])) (extend-type java.lang.Number Dateable (to-ms [this] this)) (pprint (to-ms 56)) (extend-type java.util.Date Dateable (to-ms [this] (.getTime this))) (pprint (to-ms (java.util.Date.))) (extend-type java.util.Calendar Dateable (to-ms [this] (to-ms (.getTime this)))) (pprint (to-ms (java.util.GregorianCalendar.))) ;Usamos Record e Protocols principalmente na integração com código Java ;Exato. Se já possuimos código Java que vamos utilizar de base para uma funcionalidade ;é comum ter que implementar interfaces através de Protocols e Records
55994
(ns hospital.aula2 (:use clojure.pprint)) (defrecord PacienteParticular [id, nome, nascimento]) (defrecord PacienteComPlano [id, nome, nascimento, plano]) ;vantagem esta tudo em um bloco só ;Desvantagem concentração de tipos ;(defn deve-assinar-pre-autorizacao? [paciente procedimento valor] ; (if (= PacienteParticular (type paciente)) ; (>= valor 50) ; (if (= PacientePlanoDeSaude (type paciente)) ; (let [plano (get paciente :plano)] ; (not (some #(= % procedimento) plano))) ; true))) (defprotocol Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor])) ;como se fosse uma interface (extend-type PacienteParticular Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor] (>= valor 50))) (extend-type PacienteComPlano Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor] (let [plano (:plano paciente)] (not (some #(= % procedimento) plano))))) (let [particular (->PacienteParticular 15, "<NAME>", "18052001") plano (->PacienteComPlano 15, "<NAME>", "18052001", [:raixo-x, :ultrasom])] (pprint (deve-assinar-pre-autorizacao? particular, :raixo-x, 500)) (pprint (deve-assinar-pre-autorizacao? particular, :raixo-x, 40)) (pprint (deve-assinar-pre-autorizacao? plano, :raixo-x, 5000)) (pprint (deve-assinar-pre-autorizacao? plano, :coleta-de-sangue, 500)) ) ;uma alternativa seria implementar diretamente ;(defrecord PacienteComPlano ; [id, nome, nascimento, plano] ; Cobravel ; (deve-assinar-pre-autorizacao? [paciente procedimento valor] ; (let [plano (:plano paciente)] ; (not (some #(= % procedimento) plano))))) (defprotocol Dateable (to-ms [this])) (extend-type java.lang.Number Dateable (to-ms [this] this)) (pprint (to-ms 56)) (extend-type java.util.Date Dateable (to-ms [this] (.getTime this))) (pprint (to-ms (java.util.Date.))) (extend-type java.util.Calendar Dateable (to-ms [this] (to-ms (.getTime this)))) (pprint (to-ms (java.util.GregorianCalendar.))) ;Usamos Record e Protocols principalmente na integração com código Java ;Exato. Se já possuimos código Java que vamos utilizar de base para uma funcionalidade ;é comum ter que implementar interfaces através de Protocols e Records
true
(ns hospital.aula2 (:use clojure.pprint)) (defrecord PacienteParticular [id, nome, nascimento]) (defrecord PacienteComPlano [id, nome, nascimento, plano]) ;vantagem esta tudo em um bloco só ;Desvantagem concentração de tipos ;(defn deve-assinar-pre-autorizacao? [paciente procedimento valor] ; (if (= PacienteParticular (type paciente)) ; (>= valor 50) ; (if (= PacientePlanoDeSaude (type paciente)) ; (let [plano (get paciente :plano)] ; (not (some #(= % procedimento) plano))) ; true))) (defprotocol Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor])) ;como se fosse uma interface (extend-type PacienteParticular Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor] (>= valor 50))) (extend-type PacienteComPlano Cobravel (deve-assinar-pre-autorizacao? [paciente procedimento valor] (let [plano (:plano paciente)] (not (some #(= % procedimento) plano))))) (let [particular (->PacienteParticular 15, "PI:NAME:<NAME>END_PI", "18052001") plano (->PacienteComPlano 15, "PI:NAME:<NAME>END_PI", "18052001", [:raixo-x, :ultrasom])] (pprint (deve-assinar-pre-autorizacao? particular, :raixo-x, 500)) (pprint (deve-assinar-pre-autorizacao? particular, :raixo-x, 40)) (pprint (deve-assinar-pre-autorizacao? plano, :raixo-x, 5000)) (pprint (deve-assinar-pre-autorizacao? plano, :coleta-de-sangue, 500)) ) ;uma alternativa seria implementar diretamente ;(defrecord PacienteComPlano ; [id, nome, nascimento, plano] ; Cobravel ; (deve-assinar-pre-autorizacao? [paciente procedimento valor] ; (let [plano (:plano paciente)] ; (not (some #(= % procedimento) plano))))) (defprotocol Dateable (to-ms [this])) (extend-type java.lang.Number Dateable (to-ms [this] this)) (pprint (to-ms 56)) (extend-type java.util.Date Dateable (to-ms [this] (.getTime this))) (pprint (to-ms (java.util.Date.))) (extend-type java.util.Calendar Dateable (to-ms [this] (to-ms (.getTime this)))) (pprint (to-ms (java.util.GregorianCalendar.))) ;Usamos Record e Protocols principalmente na integração com código Java ;Exato. Se já possuimos código Java que vamos utilizar de base para uma funcionalidade ;é comum ter que implementar interfaces através de Protocols e Records
[ { "context": ";\n; Copyright © 2013 Sebastian Hoß <[email protected]>\n; This work is free. You can redi", "end": 34, "score": 0.9998724460601807, "start": 21, "tag": "NAME", "value": "Sebastian Hoß" }, { "context": ";\n; Copyright © 2013 Sebastian Hoß <[email protected]>\n; This work is free. You can redistribute it and", "end": 49, "score": 0.9999275803565979, "start": 36, "tag": "EMAIL", "value": "[email protected]" } ]
src/main/clojure/finj/compound_interest.clj
sebhoss/finj
30
; ; Copyright © 2013 Sebastian Hoß <[email protected]> ; This work is free. You can redistribute it and/or modify it under the ; terms of the Do What The Fuck You Want To Public License, Version 2, ; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. ; (ns finj.compound-interest "Compound interest arises when interest is added to the principal, so that, from that moment on, the interest that has been added also earns interest. This addition of interest to the principal is called compounding. Definitions: * p - Rate per cent * rate - Rate of interest (= p/100) * period - Multiple of a interest period or point in time * days-per-year - Number of days per year * amount - Generated amount of interest * present-value - Present value of a investment or seed capital * final-value - Final value of a investment or capital at a certain point in time * days - Number of interest days References: * http://en.wikipedia.org/wiki/Compound_interest" (:require [com.github.sebhoss.math :refer :all] [com.github.sebhoss.def :refer :all])) (defnk final-value "Calculates the final value for a given investment with a given rate over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods Examples: * (final-value :present-value 100 :rate 0.05 :period 5) => 127.62815625000003 * (final-value :present-value 500 :rate 0.1 :period 8) => 1071.7944050000008 * (final-value :present-value 800 :rate 0.15 :period 12) => 4280.200084378965" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (* present-value (pow (inc rate) period))) (defnk amount "Calculates the generated amount of interest for a given investment with a given rate over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods Examples: * (amount :present-value 100 :rate 0.05 :period 5) => 27.628156250000032 * (amount :present-value 500 :rate 0.1 :period 8) => 571.7944050000008 * (amount :present-value 800 :rate 0.15 :period 12) => 3480.2000843789647" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (- (final-value :present-value present-value :rate rate :period period) present-value)) (defnk present-value "Calculates the present value for a given final value with a given rate over a given period of time. Parameters: * final-value - Final value of a investment * rate - Rate of interest of final value * period - Number of periods of final value Examples: * (present-value :final-value 250 :rate 0.05 :period 5) => 195.8815416171147 * (present-value :final-value 400 :rate 0.1 :period 8) => 186.60295208389323 * (present-value :final-value 750 :rate 0.15 :period 12) => 140.18036263999954" [:final-value :rate :period] {:pre [(number? final-value) (number? rate) (number? period)]} (/ final-value (pow (inc rate) period))) (defnk yield "Calculates the yield for a given seed capital to reach a given final value within a given period of time. Parameters: * final-value - Final value to reach * present-value - Seed capital * period - Number of periods Examples: * (yield :final-value 300 :present-value 150 :period 5) => 14.869835499703509 * (yield :final-value 500 :present-value 180 :period 8) => 13.621936646749933 * (yield :final-value 800 :present-value 230 :period 12) => 10.946476081096757" [:final-value :present-value :period] {:pre [(number? final-value) (number? present-value) (number? period)]} (* 100 (dec (root period (/ final-value present-value))))) (defnk period "Calculates the number of periods for a given seed capital to reach a final value with a given rate of interest. Parameters: * final-value - Final value to reach * present-value - Seed capital * rate - Rate of interest Examples: * (period :final-value 300 :present-value 150 :rate 0.05) => 14.206699082890463 * (period :final-value 500 :present-value 180 :rate 0.1) => 10.719224847014937 * (period :final-value 800 :present-value 230 :rate 0.15) => 8.918968909280778" [:final-value :present-value :rate] {:pre [(number? final-value) (number? present-value) (number? rate)]} (/ (- (ln final-value) (ln present-value)) (ln (inc rate)))) (defnk actual-value "Calculates the actual/360 value for a given seed capital with a given rate of interest over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * start-part - Length of 'broken' start period * period - Number of periods * end-part - Length of 'broken' end period Examples: * (actual-value :present-value 150 :rate 0.05 :start-part 0.3 :period 5 :end-part 0.5) => 199.17171458789062 * (actual-value :present-value 150 :rate 0.05 :start-part 0 :period 3 :end-part 0) => 173.64375 * (actual-value :present-value 150 :rate 0.05 :start-part 1 :period 5 :end-part 1) => 211.06506339843756" [:present-value :rate :start-part :period :end-part] (* present-value (inc (* rate start-part)) (pow (inc rate) period) (inc (* rate end-part)))) (defnk final-annual-value "Calculates the final value for a given investment with a given rate over a given period of time using during the periods return on investments. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods * in-year-period - Number of compounding periods per year Examples: * (final-annual-value :present-value 100 :rate 0.05 :period 5 :in-year-period 12) => 128.33586785035118 * (final-annual-value :present-value 500 :rate 0.1 :period 8 :in-year-period 12) => 1109.0878155189757 * (final-annual-value :present-value 800 :rate 0.15 :period 12 :in-year-period 4) => 4682.9448738035235" [:present-value :rate :period :in-year-period] {:pre [(number? present-value) (number? rate) (number? period) (number? in-year-period)]} (* present-value (pow (inc (/ rate in-year-period)) (* period in-year-period)))) (defnk relative-annual-rate "Calculates the relative, annual rate of interest. Parameters: * rate - Rate of interest * in-year-period - Number of compounding periods per year Examples: * (relative-annual-rate :rate 0.05 :in-year-period 12) => 0.004166666666666667 * (relative-annual-rate :rate 0.1 :in-year-period 4) => 0.025 * (relative-annual-rate :rate 0.15 :in-year-period 6) => 0.024999999999999998" [:rate :in-year-period] {:pre [(number? rate) (number? in-year-period)]} (/ rate in-year-period)) (defnk conformal-annual-rate "Calculates the conformal, annual rate of interest. Parameters: * rate - Rate of interest * in-year-period - Number of compounding periods per year Examples: * (conformal-annual-rate :rate 0.05 :in-year-period 12) => 0.0040741237836483535 * (conformal-annual-rate :rate 0.1 :in-year-period 4) => 0.02411368908444511 * (conformal-annual-rate :rate 0.15 :in-year-period 6) => 0.023567073118145654" [:rate :in-year-period] {:pre [(number? rate) (number? in-year-period)]} (dec (root in-year-period (inc rate)))) (defnk effective-annual-rate "Calculates the effective, annual rate of interest. Parameters: * relative-annual-rate - Relative annual rate of interest * in-year-period - Number of compounding periods per year Examples: * (effective-annual-rate :relative-annual-rate 0.05 :in-year-period 12) => 0.7958563260221301 * (effective-annual-rate :relative-annual-rate 0.1 :in-year-period 4) => 0.4641000000000006 * (effective-annual-rate :relative-annual-rate 0.15 :in-year-period 6) => 1.313060765624999 References: * https://en.wikipedia.org/wiki/Effective_annual_rate" [:relative-annual-rate :in-year-period] {:pre [(number? relative-annual-rate) (number? in-year-period)]} (dec (pow (inc relative-annual-rate) in-year-period))) (defnk final-continuous-value "Calculates the final value using continuous interests. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of periods Examples: * (final-continuous-value :present-value 100 :rate 0.05 :period 5) => 128.40254166877415 * (final-continuous-value :present-value 150 :rate 0.1 :period 8) => 333.8311392738702 * (final-continuous-value :present-value 180 :rate 0.15 :period 12) => 1088.93654359433" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (* present-value (exp (* rate period)))) (defnk intensity "Calculates the interest intensity. Parameters: * rate - Rate of interest Examples: * (intensity :rate 0.05) => 0.04879016416943205 * (intensity :rate 0.1) => 0.09531017980432493 * (intensity :rate 0.15) => 0.13976194237515863" [:rate] {:pre [(number? rate)]} (ln (inc rate))) (defnk rate "Calculates the rate of interest. Parameters: * intensity - The interest intensity Examples: * (rate :intensity 0.23) => 0.25860000992947785 * (rate :intensity 0.098) => 0.10296278510850776 * (rate :intensity 0.74) => 1.0959355144943643" [:intensity] {:pre [(number? intensity)]} (dec (exp intensity)))
69664
; ; Copyright © 2013 <NAME> <<EMAIL>> ; This work is free. You can redistribute it and/or modify it under the ; terms of the Do What The Fuck You Want To Public License, Version 2, ; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. ; (ns finj.compound-interest "Compound interest arises when interest is added to the principal, so that, from that moment on, the interest that has been added also earns interest. This addition of interest to the principal is called compounding. Definitions: * p - Rate per cent * rate - Rate of interest (= p/100) * period - Multiple of a interest period or point in time * days-per-year - Number of days per year * amount - Generated amount of interest * present-value - Present value of a investment or seed capital * final-value - Final value of a investment or capital at a certain point in time * days - Number of interest days References: * http://en.wikipedia.org/wiki/Compound_interest" (:require [com.github.sebhoss.math :refer :all] [com.github.sebhoss.def :refer :all])) (defnk final-value "Calculates the final value for a given investment with a given rate over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods Examples: * (final-value :present-value 100 :rate 0.05 :period 5) => 127.62815625000003 * (final-value :present-value 500 :rate 0.1 :period 8) => 1071.7944050000008 * (final-value :present-value 800 :rate 0.15 :period 12) => 4280.200084378965" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (* present-value (pow (inc rate) period))) (defnk amount "Calculates the generated amount of interest for a given investment with a given rate over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods Examples: * (amount :present-value 100 :rate 0.05 :period 5) => 27.628156250000032 * (amount :present-value 500 :rate 0.1 :period 8) => 571.7944050000008 * (amount :present-value 800 :rate 0.15 :period 12) => 3480.2000843789647" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (- (final-value :present-value present-value :rate rate :period period) present-value)) (defnk present-value "Calculates the present value for a given final value with a given rate over a given period of time. Parameters: * final-value - Final value of a investment * rate - Rate of interest of final value * period - Number of periods of final value Examples: * (present-value :final-value 250 :rate 0.05 :period 5) => 195.8815416171147 * (present-value :final-value 400 :rate 0.1 :period 8) => 186.60295208389323 * (present-value :final-value 750 :rate 0.15 :period 12) => 140.18036263999954" [:final-value :rate :period] {:pre [(number? final-value) (number? rate) (number? period)]} (/ final-value (pow (inc rate) period))) (defnk yield "Calculates the yield for a given seed capital to reach a given final value within a given period of time. Parameters: * final-value - Final value to reach * present-value - Seed capital * period - Number of periods Examples: * (yield :final-value 300 :present-value 150 :period 5) => 14.869835499703509 * (yield :final-value 500 :present-value 180 :period 8) => 13.621936646749933 * (yield :final-value 800 :present-value 230 :period 12) => 10.946476081096757" [:final-value :present-value :period] {:pre [(number? final-value) (number? present-value) (number? period)]} (* 100 (dec (root period (/ final-value present-value))))) (defnk period "Calculates the number of periods for a given seed capital to reach a final value with a given rate of interest. Parameters: * final-value - Final value to reach * present-value - Seed capital * rate - Rate of interest Examples: * (period :final-value 300 :present-value 150 :rate 0.05) => 14.206699082890463 * (period :final-value 500 :present-value 180 :rate 0.1) => 10.719224847014937 * (period :final-value 800 :present-value 230 :rate 0.15) => 8.918968909280778" [:final-value :present-value :rate] {:pre [(number? final-value) (number? present-value) (number? rate)]} (/ (- (ln final-value) (ln present-value)) (ln (inc rate)))) (defnk actual-value "Calculates the actual/360 value for a given seed capital with a given rate of interest over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * start-part - Length of 'broken' start period * period - Number of periods * end-part - Length of 'broken' end period Examples: * (actual-value :present-value 150 :rate 0.05 :start-part 0.3 :period 5 :end-part 0.5) => 199.17171458789062 * (actual-value :present-value 150 :rate 0.05 :start-part 0 :period 3 :end-part 0) => 173.64375 * (actual-value :present-value 150 :rate 0.05 :start-part 1 :period 5 :end-part 1) => 211.06506339843756" [:present-value :rate :start-part :period :end-part] (* present-value (inc (* rate start-part)) (pow (inc rate) period) (inc (* rate end-part)))) (defnk final-annual-value "Calculates the final value for a given investment with a given rate over a given period of time using during the periods return on investments. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods * in-year-period - Number of compounding periods per year Examples: * (final-annual-value :present-value 100 :rate 0.05 :period 5 :in-year-period 12) => 128.33586785035118 * (final-annual-value :present-value 500 :rate 0.1 :period 8 :in-year-period 12) => 1109.0878155189757 * (final-annual-value :present-value 800 :rate 0.15 :period 12 :in-year-period 4) => 4682.9448738035235" [:present-value :rate :period :in-year-period] {:pre [(number? present-value) (number? rate) (number? period) (number? in-year-period)]} (* present-value (pow (inc (/ rate in-year-period)) (* period in-year-period)))) (defnk relative-annual-rate "Calculates the relative, annual rate of interest. Parameters: * rate - Rate of interest * in-year-period - Number of compounding periods per year Examples: * (relative-annual-rate :rate 0.05 :in-year-period 12) => 0.004166666666666667 * (relative-annual-rate :rate 0.1 :in-year-period 4) => 0.025 * (relative-annual-rate :rate 0.15 :in-year-period 6) => 0.024999999999999998" [:rate :in-year-period] {:pre [(number? rate) (number? in-year-period)]} (/ rate in-year-period)) (defnk conformal-annual-rate "Calculates the conformal, annual rate of interest. Parameters: * rate - Rate of interest * in-year-period - Number of compounding periods per year Examples: * (conformal-annual-rate :rate 0.05 :in-year-period 12) => 0.0040741237836483535 * (conformal-annual-rate :rate 0.1 :in-year-period 4) => 0.02411368908444511 * (conformal-annual-rate :rate 0.15 :in-year-period 6) => 0.023567073118145654" [:rate :in-year-period] {:pre [(number? rate) (number? in-year-period)]} (dec (root in-year-period (inc rate)))) (defnk effective-annual-rate "Calculates the effective, annual rate of interest. Parameters: * relative-annual-rate - Relative annual rate of interest * in-year-period - Number of compounding periods per year Examples: * (effective-annual-rate :relative-annual-rate 0.05 :in-year-period 12) => 0.7958563260221301 * (effective-annual-rate :relative-annual-rate 0.1 :in-year-period 4) => 0.4641000000000006 * (effective-annual-rate :relative-annual-rate 0.15 :in-year-period 6) => 1.313060765624999 References: * https://en.wikipedia.org/wiki/Effective_annual_rate" [:relative-annual-rate :in-year-period] {:pre [(number? relative-annual-rate) (number? in-year-period)]} (dec (pow (inc relative-annual-rate) in-year-period))) (defnk final-continuous-value "Calculates the final value using continuous interests. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of periods Examples: * (final-continuous-value :present-value 100 :rate 0.05 :period 5) => 128.40254166877415 * (final-continuous-value :present-value 150 :rate 0.1 :period 8) => 333.8311392738702 * (final-continuous-value :present-value 180 :rate 0.15 :period 12) => 1088.93654359433" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (* present-value (exp (* rate period)))) (defnk intensity "Calculates the interest intensity. Parameters: * rate - Rate of interest Examples: * (intensity :rate 0.05) => 0.04879016416943205 * (intensity :rate 0.1) => 0.09531017980432493 * (intensity :rate 0.15) => 0.13976194237515863" [:rate] {:pre [(number? rate)]} (ln (inc rate))) (defnk rate "Calculates the rate of interest. Parameters: * intensity - The interest intensity Examples: * (rate :intensity 0.23) => 0.25860000992947785 * (rate :intensity 0.098) => 0.10296278510850776 * (rate :intensity 0.74) => 1.0959355144943643" [:intensity] {:pre [(number? intensity)]} (dec (exp intensity)))
true
; ; Copyright © 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ; This work is free. You can redistribute it and/or modify it under the ; terms of the Do What The Fuck You Want To Public License, Version 2, ; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. ; (ns finj.compound-interest "Compound interest arises when interest is added to the principal, so that, from that moment on, the interest that has been added also earns interest. This addition of interest to the principal is called compounding. Definitions: * p - Rate per cent * rate - Rate of interest (= p/100) * period - Multiple of a interest period or point in time * days-per-year - Number of days per year * amount - Generated amount of interest * present-value - Present value of a investment or seed capital * final-value - Final value of a investment or capital at a certain point in time * days - Number of interest days References: * http://en.wikipedia.org/wiki/Compound_interest" (:require [com.github.sebhoss.math :refer :all] [com.github.sebhoss.def :refer :all])) (defnk final-value "Calculates the final value for a given investment with a given rate over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods Examples: * (final-value :present-value 100 :rate 0.05 :period 5) => 127.62815625000003 * (final-value :present-value 500 :rate 0.1 :period 8) => 1071.7944050000008 * (final-value :present-value 800 :rate 0.15 :period 12) => 4280.200084378965" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (* present-value (pow (inc rate) period))) (defnk amount "Calculates the generated amount of interest for a given investment with a given rate over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods Examples: * (amount :present-value 100 :rate 0.05 :period 5) => 27.628156250000032 * (amount :present-value 500 :rate 0.1 :period 8) => 571.7944050000008 * (amount :present-value 800 :rate 0.15 :period 12) => 3480.2000843789647" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (- (final-value :present-value present-value :rate rate :period period) present-value)) (defnk present-value "Calculates the present value for a given final value with a given rate over a given period of time. Parameters: * final-value - Final value of a investment * rate - Rate of interest of final value * period - Number of periods of final value Examples: * (present-value :final-value 250 :rate 0.05 :period 5) => 195.8815416171147 * (present-value :final-value 400 :rate 0.1 :period 8) => 186.60295208389323 * (present-value :final-value 750 :rate 0.15 :period 12) => 140.18036263999954" [:final-value :rate :period] {:pre [(number? final-value) (number? rate) (number? period)]} (/ final-value (pow (inc rate) period))) (defnk yield "Calculates the yield for a given seed capital to reach a given final value within a given period of time. Parameters: * final-value - Final value to reach * present-value - Seed capital * period - Number of periods Examples: * (yield :final-value 300 :present-value 150 :period 5) => 14.869835499703509 * (yield :final-value 500 :present-value 180 :period 8) => 13.621936646749933 * (yield :final-value 800 :present-value 230 :period 12) => 10.946476081096757" [:final-value :present-value :period] {:pre [(number? final-value) (number? present-value) (number? period)]} (* 100 (dec (root period (/ final-value present-value))))) (defnk period "Calculates the number of periods for a given seed capital to reach a final value with a given rate of interest. Parameters: * final-value - Final value to reach * present-value - Seed capital * rate - Rate of interest Examples: * (period :final-value 300 :present-value 150 :rate 0.05) => 14.206699082890463 * (period :final-value 500 :present-value 180 :rate 0.1) => 10.719224847014937 * (period :final-value 800 :present-value 230 :rate 0.15) => 8.918968909280778" [:final-value :present-value :rate] {:pre [(number? final-value) (number? present-value) (number? rate)]} (/ (- (ln final-value) (ln present-value)) (ln (inc rate)))) (defnk actual-value "Calculates the actual/360 value for a given seed capital with a given rate of interest over a given period of time. Parameters: * present-value - Seed capital * rate - Rate of interest * start-part - Length of 'broken' start period * period - Number of periods * end-part - Length of 'broken' end period Examples: * (actual-value :present-value 150 :rate 0.05 :start-part 0.3 :period 5 :end-part 0.5) => 199.17171458789062 * (actual-value :present-value 150 :rate 0.05 :start-part 0 :period 3 :end-part 0) => 173.64375 * (actual-value :present-value 150 :rate 0.05 :start-part 1 :period 5 :end-part 1) => 211.06506339843756" [:present-value :rate :start-part :period :end-part] (* present-value (inc (* rate start-part)) (pow (inc rate) period) (inc (* rate end-part)))) (defnk final-annual-value "Calculates the final value for a given investment with a given rate over a given period of time using during the periods return on investments. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of interest periods * in-year-period - Number of compounding periods per year Examples: * (final-annual-value :present-value 100 :rate 0.05 :period 5 :in-year-period 12) => 128.33586785035118 * (final-annual-value :present-value 500 :rate 0.1 :period 8 :in-year-period 12) => 1109.0878155189757 * (final-annual-value :present-value 800 :rate 0.15 :period 12 :in-year-period 4) => 4682.9448738035235" [:present-value :rate :period :in-year-period] {:pre [(number? present-value) (number? rate) (number? period) (number? in-year-period)]} (* present-value (pow (inc (/ rate in-year-period)) (* period in-year-period)))) (defnk relative-annual-rate "Calculates the relative, annual rate of interest. Parameters: * rate - Rate of interest * in-year-period - Number of compounding periods per year Examples: * (relative-annual-rate :rate 0.05 :in-year-period 12) => 0.004166666666666667 * (relative-annual-rate :rate 0.1 :in-year-period 4) => 0.025 * (relative-annual-rate :rate 0.15 :in-year-period 6) => 0.024999999999999998" [:rate :in-year-period] {:pre [(number? rate) (number? in-year-period)]} (/ rate in-year-period)) (defnk conformal-annual-rate "Calculates the conformal, annual rate of interest. Parameters: * rate - Rate of interest * in-year-period - Number of compounding periods per year Examples: * (conformal-annual-rate :rate 0.05 :in-year-period 12) => 0.0040741237836483535 * (conformal-annual-rate :rate 0.1 :in-year-period 4) => 0.02411368908444511 * (conformal-annual-rate :rate 0.15 :in-year-period 6) => 0.023567073118145654" [:rate :in-year-period] {:pre [(number? rate) (number? in-year-period)]} (dec (root in-year-period (inc rate)))) (defnk effective-annual-rate "Calculates the effective, annual rate of interest. Parameters: * relative-annual-rate - Relative annual rate of interest * in-year-period - Number of compounding periods per year Examples: * (effective-annual-rate :relative-annual-rate 0.05 :in-year-period 12) => 0.7958563260221301 * (effective-annual-rate :relative-annual-rate 0.1 :in-year-period 4) => 0.4641000000000006 * (effective-annual-rate :relative-annual-rate 0.15 :in-year-period 6) => 1.313060765624999 References: * https://en.wikipedia.org/wiki/Effective_annual_rate" [:relative-annual-rate :in-year-period] {:pre [(number? relative-annual-rate) (number? in-year-period)]} (dec (pow (inc relative-annual-rate) in-year-period))) (defnk final-continuous-value "Calculates the final value using continuous interests. Parameters: * present-value - Seed capital * rate - Rate of interest * period - Number of periods Examples: * (final-continuous-value :present-value 100 :rate 0.05 :period 5) => 128.40254166877415 * (final-continuous-value :present-value 150 :rate 0.1 :period 8) => 333.8311392738702 * (final-continuous-value :present-value 180 :rate 0.15 :period 12) => 1088.93654359433" [:present-value :rate :period] {:pre [(number? present-value) (number? rate) (number? period)]} (* present-value (exp (* rate period)))) (defnk intensity "Calculates the interest intensity. Parameters: * rate - Rate of interest Examples: * (intensity :rate 0.05) => 0.04879016416943205 * (intensity :rate 0.1) => 0.09531017980432493 * (intensity :rate 0.15) => 0.13976194237515863" [:rate] {:pre [(number? rate)]} (ln (inc rate))) (defnk rate "Calculates the rate of interest. Parameters: * intensity - The interest intensity Examples: * (rate :intensity 0.23) => 0.25860000992947785 * (rate :intensity 0.098) => 0.10296278510850776 * (rate :intensity 0.74) => 1.0959355144943643" [:intensity] {:pre [(number? intensity)]} (dec (exp intensity)))
[ { "context": "st test-insert-all!\n (let [example-data [{:name \"John\", :surname \"Doe\", :phone \"123-45-67\"}\n ", "end": 276, "score": 0.9998165965080261, "start": 272, "tag": "NAME", "value": "John" }, { "context": "l!\n (let [example-data [{:name \"John\", :surname \"Doe\", :phone \"123-45-67\"}\n {:nam", "end": 292, "score": 0.9995090961456299, "start": 289, "tag": "NAME", "value": "Doe" }, { "context": ":phone \"123-45-67\"}\n {:name \"Donald\", :surname \"Covfefe\", :phone \"666-66-66\"}]\n ", "end": 351, "score": 0.9995490908622742, "start": 345, "tag": "NAME", "value": "Donald" }, { "context": "fe\", :phone \"666-66-66\"}]\n update [{:name \"John\", :surname \"Doe\", :phone \"765-43-21\"}]]\n (test", "end": 423, "score": 0.9998341798782349, "start": 419, "tag": "NAME", "value": "John" }, { "context": "66-66\"}]\n update [{:name \"John\", :surname \"Doe\", :phone \"765-43-21\"}]]\n (testing \"basic useca", "end": 439, "score": 0.9989914298057556, "start": 436, "tag": "NAME", "value": "Doe" } ]
test/skyscraper/db_test.clj
nathell/skyscraper
356
(ns skyscraper.db-test (:require [clojure.java.jdbc :as jdbc] [clojure.test :as test :refer [deftest is testing]] [skyscraper.db :as db] [skyscraper.test-utils :refer [with-temporary-sqlite-db]])) (deftest test-insert-all! (let [example-data [{:name "John", :surname "Doe", :phone "123-45-67"} {:name "Donald", :surname "Covfefe", :phone "666-66-66"}] update [{:name "John", :surname "Doe", :phone "765-43-21"}]] (testing "basic usecase" (with-temporary-sqlite-db db (db/upsert-contexts db :example-data nil [:name :surname :phone] example-data) (is (= (jdbc/query db "SELECT name, surname, phone FROM example_data ORDER BY id") example-data)))) (testing "multiple inserts duplicate data" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data nil [:name :surname :phone] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 10}]))) (testing "unless key is supplied" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 2}]))))) (testing "updates" (with-temporary-sqlite-db db (doseq [data [example-data update]] (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] data)) (is (= (jdbc/query db "SELECT name, surname, phone FROM example_data ORDER BY id") [(first update) (second example-data)])))) (testing "upsert empty contexts is a no-op" (with-temporary-sqlite-db db (is (empty? (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] []))))) (testing "columns same as key-columns" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data [:name :surname] [:name :surname] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 2}]))))))
101631
(ns skyscraper.db-test (:require [clojure.java.jdbc :as jdbc] [clojure.test :as test :refer [deftest is testing]] [skyscraper.db :as db] [skyscraper.test-utils :refer [with-temporary-sqlite-db]])) (deftest test-insert-all! (let [example-data [{:name "<NAME>", :surname "<NAME>", :phone "123-45-67"} {:name "<NAME>", :surname "Covfefe", :phone "666-66-66"}] update [{:name "<NAME>", :surname "<NAME>", :phone "765-43-21"}]] (testing "basic usecase" (with-temporary-sqlite-db db (db/upsert-contexts db :example-data nil [:name :surname :phone] example-data) (is (= (jdbc/query db "SELECT name, surname, phone FROM example_data ORDER BY id") example-data)))) (testing "multiple inserts duplicate data" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data nil [:name :surname :phone] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 10}]))) (testing "unless key is supplied" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 2}]))))) (testing "updates" (with-temporary-sqlite-db db (doseq [data [example-data update]] (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] data)) (is (= (jdbc/query db "SELECT name, surname, phone FROM example_data ORDER BY id") [(first update) (second example-data)])))) (testing "upsert empty contexts is a no-op" (with-temporary-sqlite-db db (is (empty? (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] []))))) (testing "columns same as key-columns" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data [:name :surname] [:name :surname] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 2}]))))))
true
(ns skyscraper.db-test (:require [clojure.java.jdbc :as jdbc] [clojure.test :as test :refer [deftest is testing]] [skyscraper.db :as db] [skyscraper.test-utils :refer [with-temporary-sqlite-db]])) (deftest test-insert-all! (let [example-data [{:name "PI:NAME:<NAME>END_PI", :surname "PI:NAME:<NAME>END_PI", :phone "123-45-67"} {:name "PI:NAME:<NAME>END_PI", :surname "Covfefe", :phone "666-66-66"}] update [{:name "PI:NAME:<NAME>END_PI", :surname "PI:NAME:<NAME>END_PI", :phone "765-43-21"}]] (testing "basic usecase" (with-temporary-sqlite-db db (db/upsert-contexts db :example-data nil [:name :surname :phone] example-data) (is (= (jdbc/query db "SELECT name, surname, phone FROM example_data ORDER BY id") example-data)))) (testing "multiple inserts duplicate data" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data nil [:name :surname :phone] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 10}]))) (testing "unless key is supplied" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 2}]))))) (testing "updates" (with-temporary-sqlite-db db (doseq [data [example-data update]] (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] data)) (is (= (jdbc/query db "SELECT name, surname, phone FROM example_data ORDER BY id") [(first update) (second example-data)])))) (testing "upsert empty contexts is a no-op" (with-temporary-sqlite-db db (is (empty? (db/upsert-contexts db :example-data [:name :surname] [:name :surname :phone] []))))) (testing "columns same as key-columns" (with-temporary-sqlite-db db (dotimes [_ 5] (db/upsert-contexts db :example-data [:name :surname] [:name :surname] example-data)) (is (= (jdbc/query db "SELECT count(*) cnt FROM example_data") [{:cnt 2}]))))))
[ { "context": "n [s] (apply str (take (count s) (repeat \"@\")))) \"Amsterdam Aardvarks\") \"@msterd@m @@rdv@rks\"))\n (is (= (select [(s/re", "end": 45740, "score": 0.996465265750885, "start": 45721, "tag": "NAME", "value": "Amsterdam Aardvarks" }, { "context": "e (count s) (repeat \"@\")))) \"Amsterdam Aardvarks\") \"@msterd@m @@rdv@rks\"))\n (is (= (select [(s/regex-nav #\"(\\S", "end": 45753, "score": 0.9597030282020569, "start": 45743, "tag": "USERNAME", "value": "\"@msterd@m" }, { "context": "t [(s/regex-nav #\"(\\S+):\\ (\\d+)\") (s/nthpath 2)] \"Mary: 1st George: 2nd Arthur: 3rd\") [\"1\" \"2\" \"3\"]))\n ", "end": 45836, "score": 0.988455057144165, "start": 45832, "tag": "NAME", "value": "Mary" }, { "context": "orm (s/subselect (s/regex-nav #\"\\d\\w+\")) reverse \"Mary: 1st George: 2nd Arthur: 3rd\") \"Mary: 3rd George:", "end": 45954, "score": 0.9880475997924805, "start": 45950, "tag": "NAME", "value": "Mary" }, { "context": "\")) reverse \"Mary: 1st George: 2nd Arthur: 3rd\") \"Mary: 3rd George: 2nd Arthur: 1st\"))\n )\n\n(deftest sin", "end": 45991, "score": 0.9909566640853882, "start": 45987, "tag": "NAME", "value": "Mary" } ]
test/com/rpl/specter/core_test.cljc
IGJoshua/specter
0
(ns com.rpl.specter.core-test #?(:cljs (:require-macros [cljs.test :refer [is deftest testing]] [clojure.test.check.clojure-test :refer [defspec]] [com.rpl.specter.cljs-test-helpers :refer [for-all+]] [com.rpl.specter.test-helpers :refer [ic-test]] [com.rpl.specter :refer [defprotocolpath defnav extend-protocolpath nav declarepath providepath select select-one select-one! select-first transform setval replace-in select-any selected-any? collected? traverse multi-transform path dynamicnav recursive-path defdynamicnav traverse-all satisfies-protpath? end-fn vtransform]])) (:use #?(:clj [clojure.test :only [deftest is testing]]) #?(:clj [clojure.test.check.clojure-test :only [defspec]]) #?(:clj [com.rpl.specter.test-helpers :only [for-all+ ic-test]]) #?(:clj [com.rpl.specter :only [defprotocolpath defnav extend-protocolpath nav declarepath providepath select select-one select-one! select-first transform setval replace-in select-any selected-any? collected? traverse multi-transform path dynamicnav recursive-path defdynamicnav traverse-all satisfies-protpath? end-fn vtransform]])) (:require #?(:clj [clojure.test.check.generators :as gen]) #?(:clj [clojure.test.check.properties :as prop]) #?(:cljs [clojure.test.check :as tc]) #?(:cljs [clojure.test.check.generators :as gen]) #?(:cljs [clojure.test.check.properties :as prop :include-macros true]) [com.rpl.specter :as s] [com.rpl.specter.transients :as t] [clojure.set :as set])) ;;TODO: ;; test walk, codewalk (defn limit-size [n {gen :gen}] (gen/->Generator (fn [rnd _size] (gen rnd (if (< _size n) _size n))))) (defn gen-map-with-keys [key-gen val-gen & keys] (gen/bind (gen/map key-gen val-gen) (fn [m] (gen/bind (apply gen/hash-map (mapcat (fn [k] [k val-gen]) keys)) (fn [m2] (gen/return (merge m m2))))))) (defspec select-all-keyword-filter (for-all+ [kw gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int kw))) pred (gen/elements [odd? even?])] (= (select [s/ALL kw pred] v) (->> v (map kw) (filter pred))))) (defspec select-pos-extreme-pred (for-all+ [v (gen/vector gen/int) pred (gen/elements [odd? even?]) pos (gen/elements [[s/FIRST first] [s/LAST last]])] (= (select-one [(s/filterer pred) (first pos)] v) (->> v (filter pred) ((last pos)))))) (defspec select-all-on-map (for-all+ [m (limit-size 5 (gen/map gen/keyword gen/int)) p (gen/elements [s/MAP-VALS [s/ALL s/LAST]])] (= (select p m) (for [[k v] m] v)))) (deftest select-one-test (is (thrown? #?(:clj Exception :cljs js/Error) (select-one [s/ALL even?] [1 2 3 4]))) (is (= 1 (select-one [s/ALL odd?] [2 4 1 6])))) (deftest select-first-test (is (= 7 (select-first [(s/filterer odd?) s/ALL #(> % 4)] [3 4 2 3 7 5 9 8]))) (is (nil? (select-first [s/ALL even?] [1 3 5 9])))) (defspec transform-all-on-map (for-all+ [m (limit-size 5 (gen/map gen/keyword gen/int)) p (gen/elements [s/MAP-VALS [s/ALL s/LAST]])] (= (transform p inc m) (into {} (for [[k v] m] [k (inc v)]))))) (defspec transform-all (for-all+ [v (gen/vector gen/int)] (let [v2 (transform [s/ALL] inc v)] (and (vector? v2) (= v2 (map inc v)))))) (defspec transform-all-list (for-all+ [v (gen/list gen/int)] (let [v2 (transform [s/ALL] inc v)] (and (seq? v2) (= v2 (map inc v)))))) (defspec transform-all-filter (for-all+ [v (gen/vector gen/int) pred (gen/elements [odd? even?]) action (gen/elements [inc dec])] (let [v2 (transform [s/ALL pred] action v)] (= v2 (map (fn [v] (if (pred v) (action v) v)) v))))) (defspec transform-last (for-all+ [v (gen/not-empty (gen/vector gen/int)) pred (gen/elements [inc dec])] (let [v2 (transform [s/LAST] pred v)] (= v2 (concat (butlast v) [(pred (last v))]))))) (defspec transform-first (for-all+ [v (gen/not-empty (gen/vector gen/int)) pred (gen/elements [inc dec])] (let [v2 (transform [s/FIRST] pred v)] (= v2 (concat [(pred (first v))] (rest v)))))) (defspec transform-filterer-all-equivalency (prop/for-all [s (gen/vector gen/int) target-type (gen/elements ['() []]) pred (gen/elements [even? odd?]) updater (gen/elements [inc dec])] (let [v (into target-type s) v2 (transform [(s/filterer pred) s/ALL] updater v) v3 (transform [s/ALL pred] updater v)] (and (= v2 v3) (= (type v2) (type v3)))))) (defspec transform-with-context (for-all+ [kw1 gen/keyword kw2 gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw1 kw2)) pred (gen/elements [odd? even?])] (= (transform [(s/collect-one kw2) kw1 pred] + m) (if (pred (kw1 m)) (assoc m kw1 (+ (kw1 m) (kw2 m))) m)))) (defn differing-elements [v1 v2] (->> (map vector v1 v2) (map-indexed (fn [i [e1 e2]] (if (not= e1 e2) i))) (filter identity))) (defspec transform-last-compound (for-all+ [pred (gen/elements [odd? even?]) v (gen/such-that #(some pred %) (gen/vector gen/int))] (let [v2 (transform [(s/filterer pred) s/LAST] inc v) differing-elems (differing-elements v v2)] (and (= (count v2) (count v)) (= (count differing-elems) 1) (every? (complement pred) (drop (first differing-elems) v2)))))) ;; max sizes prevent too much data from being generated and keeps test from taking forever (defspec transform-keyword (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m1 (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1)) pred (gen/elements [inc dec])] (let [m2 (transform [k1 k2] pred m1)] (and (= (assoc-in m1 [k1 k2] nil) (assoc-in m2 [k1 k2] nil)) (= (pred (get-in m1 [k1 k2])) (get-in m2 [k1 k2])))))) (defspec replace-in-test (for-all+ [v (gen/vector gen/int)] (let [res (->> v (map (fn [v] (if (even? v) (inc v) v)))) user-ret (->> v (filter even?) (map (fn [v] [v v])) (apply concat)) user-ret (if (empty? user-ret) nil user-ret)] (= (replace-in [s/ALL even?] (fn [v] [(inc v) [v v]]) v) [res user-ret])))) (defspec replace-in-custom-merge (for-all+ [v (gen/vector gen/int)] (let [res (->> v (map (fn [v] (if (even? v) (inc v) v)))) last-even (->> v (filter even?) last) user-ret (if last-even {:a last-even})] (= (replace-in [s/ALL even?] (fn [v] [(inc v) v]) v :merge-fn (fn [curr new] (assoc curr :a new))) [res user-ret])))) (defspec srange-extremes-test (for-all+ [v (gen/vector gen/int) v2 (gen/vector gen/int)] (let [b (setval s/BEGINNING v2 v) e (setval s/END v2 v)] (and (= b (concat v2 v)) (= e (concat v v2)))))) (defspec srange-test (for-all+ [v (gen/vector gen/int) b (gen/elements (-> v count inc range)) e (gen/elements (range b (-> v count inc)))] (let [sv (subvec v b e) predcount (fn [pred v] (->> v (filter pred) count)) even-count (partial predcount even?) odd-count (partial predcount odd?) b (transform (s/srange b e) (fn [r] (filter odd? r)) v)] (and (= (odd-count v) (odd-count b)) (= (+ (even-count b) (even-count sv)) (even-count v)))))) (deftest structure-path-directly-test (is (= 3 (select-one :b {:a 1 :b 3}))) (is (= 5 (select-one (s/comp-paths :a :b) {:a {:b 5}})))) (deftest atom-test (let [v (transform s/ATOM inc (atom 1))] (is (instance? #?(:clj clojure.lang.Atom :cljs cljs.core/Atom) v)) (is (= 2 (select-one s/ATOM v) @v)))) (defspec view-test (for-all+ [i gen/int afn (gen/elements [inc dec])] (= (first (select (s/view afn) i)) (afn i) (transform (s/view afn) identity i)))) (defspec must-test (for-all+ [k1 gen/int k2 (gen/such-that #(not= k1 %) gen/int) m (gen-map-with-keys gen/int gen/int k1) op (gen/elements [inc dec])] (let [m (dissoc m k2)] (and (= (transform (s/must k1) op m) (transform (s/keypath k1) op m)) (= (transform (s/must k2) op m) m) (= (select (s/must k1) m) (select (s/keypath k1) m)) (empty? (select (s/must k2) m)))))) (defspec parser-test (for-all+ [i gen/int afn (gen/elements [inc dec #(* % 2)]) bfn (gen/elements [inc dec #(* % 2)]) cfn (gen/elements [inc dec #(* % 2)])] (and (= (select-one! (s/parser afn bfn) i) (afn i)) (= (transform (s/parser afn bfn) cfn i) (-> i afn cfn bfn))))) (deftest selected?-test (is (= [[1 3 5] [2 :a] [7 11 4 2 :a] [10 1 :a] []] (setval [s/ALL (s/selected? s/ALL even?) s/END] [:a] [[1 3 5] [2] [7 11 4 2] [10 1] []]))) (is (= [2 4] (select [s/ALL (s/selected? even?)] [1 2 3 4]))) (is (= [1 3] (select [s/ALL (s/not-selected? even?)] [1 2 3 4])))) (defspec identity-test (for-all+ [i gen/int afn (gen/elements [inc dec])] (and (= [i] (select nil i)) (= (afn i) (transform nil afn i))))) (deftest nil-comp-test (is (= [5] (select (com.rpl.specter.impl/comp-paths* nil) 5)))) (defspec putval-test (for-all+ [kw gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw)) c gen/int] (= (transform [(s/putval c) kw] + m) (transform [kw (s/putval c)] + m) (assoc m kw (+ c (get m kw)))))) (defspec empty-selector-test (for-all+ [v (gen/vector gen/int)] (= [v] (select [] v) (select nil v) (select (s/comp-paths) v) (select (s/comp-paths nil) v) (select [nil nil nil] v)))) (defspec empty-selector-transform-test (for-all+ [kw gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw))] (and (= m (transform nil identity m) (transform [] identity m) (transform (s/comp-paths []) identity m) (transform (s/comp-paths nil nil) identity m)) (= (transform kw inc m) (transform [nil kw] inc m) (transform (s/comp-paths kw nil) inc m) (transform (s/comp-paths nil kw nil) inc m))))) (deftest compose-empty-comp-path-test (let [m {:a 1}] (is (= [1] (select [:a (s/comp-paths)] m) (select [(s/comp-paths) :a] m))))) (defspec mixed-selector-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1))] (= [(-> m k1 k2)] (select [k1 (s/comp-paths k2)] m) (select [(s/comp-paths k1) k2] m) (select [(s/comp-paths k1 k2) nil] m) (select [(s/comp-paths) k1 k2] m) (select [k1 (s/comp-paths) k2] m)))) (deftest cond-path-test (is (= [4 2 6 8 10] (select [s/ALL (s/cond-path even? [(s/view inc) (s/view inc)] #(= 3 %) (s/view dec))] [1 2 3 4 5 6 7 8]))) (is (empty? (select (s/if-path odd? (s/view inc)) 2))) (is (= [6 2 10 6 14] (transform [(s/putval 2) s/ALL (s/if-path odd? [(s/view inc) (s/view inc)] (s/view dec))] * [1 2 3 4 5]))) (is (= 2 (transform [(s/putval 2) (s/if-path odd? (s/view inc))] * 2)))) (defspec cond-path-selector-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) k3 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2 k3)) pred (gen/elements [odd? even?])] (let [v1 (get m k1) k (if (pred v1) k2 k3)] (and (= (transform (s/if-path [k1 pred] k2 k3) inc m) (transform k inc m)) (= (select (s/if-path [k1 pred] k2 k3) m) (select k m)))))) (deftest optimized-if-path-test (is (= [-4 -2] (select [s/ALL (s/if-path [even? neg?] s/STAY)] [1 2 -3 -4 0 -2]))) (is (= [1 2 -3 4 0 2] (transform [s/ALL (s/if-path [even? neg?] s/STAY)] - [1 2 -3 -4 0 -2])))) (defspec multi-path-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2))] (= (transform (s/multi-path k1 k2) inc m) (->> m (transform k1 inc) (transform k2 inc))))) (deftest empty-pos-transform (is (empty? (select s/FIRST []))) (is (empty? (select s/LAST []))) (is (= [] (transform s/FIRST inc []))) (is (= [] (transform s/LAST inc [])))) (defspec set-filter-test (for-all+ [k1 gen/keyword k2 (gen/such-that #(not= k1 %) gen/keyword) k3 (gen/such-that (complement #{k1 k2}) gen/keyword) v (gen/vector (gen/elements [k1 k2 k3]))] (= (filter #{k1 k2} v) (select [s/ALL #{k1 k2}] v)))) (deftest nil-select-one-test (is (= nil (select-one! s/ALL [nil]))) (is (thrown? #?(:clj Exception :cljs js/Error) (select-one! s/ALL [])))) (defspec transformed-test (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?]) op (gen/elements [inc dec])] (= (select-one (s/transformed [s/ALL pred] op) v) (transform [s/ALL pred] op v)))) (defspec basic-parameterized-composition-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m1 (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1)) pred (gen/elements [inc dec])] (let [p (dynamicnav [a b] (path (s/keypath a) (s/keypath b)))] (and (= (s/compiled-select (p k1 k2) m1) (select [k1 k2] m1)) (= (s/compiled-transform (p k1 k2) pred m1) (transform [k1 k2] pred m1)))))) (defspec filterer-param-test (for-all+ [k gen/keyword k2 gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int k k2))) pred (gen/elements [odd? even?]) updater (gen/elements [inc dec])] (and (= (select (s/filterer (s/keypath k) pred) v) (select (s/filterer k pred) v)) (= (transform [(s/filterer (s/keypath k) pred) s/ALL k2] updater v) (transform [(s/filterer k pred) s/ALL k2] updater v))))) (deftest nested-param-paths (let [p (fn [a b c] (path (s/filterer (s/keypath a) (s/selected? s/ALL (s/keypath b) (s/filterer (s/keypath c) even?) s/ALL)))) p2 (p :a :b :c) p3 (s/filterer :a (s/selected? s/ALL :b (s/filterer :c even?) s/ALL)) data [{:a [{:b [{:c 4 :d 5}]}]} {:a [{:c 3}]} {:a [{:b [{:c 7}] :e [1]}]}]] (is (= (select p2 data) (select p3 data) [[{:a [{:b [{:c 4 :d 5}]}]}]])))) (defspec subselect-nested-vectors (for-all+ [v1 (gen/vector (gen/vector gen/int))] (let [path (s/comp-paths (s/subselect s/ALL s/ALL)) v2 (s/compiled-transform path reverse v1)] (and (= (s/compiled-select path v1) [(flatten v1)]) (= (flatten v1) (reverse (flatten v2))) (= (map count v1) (map count v2)))))) (defspec subselect-param-test (for-all+ [k gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int k)))] (and (= (s/compiled-select (s/subselect s/ALL (s/keypath k)) v) [(map k v)]) (let [v2 (s/compiled-transform (s/comp-paths (s/subselect s/ALL (s/keypath k))) reverse v)] (and (= (map k v) (reverse (map k v2))) (= (map #(dissoc % k) v) (map #(dissoc % k) v2))))))) ; only key k was touched in any of the maps (defspec param-multi-path-test (for-all+ [k1 gen/keyword k2 gen/keyword k3 gen/keyword m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2 k3)) pred1 (gen/elements [odd? even?]) pred2 (gen/elements [odd? even?]) updater (gen/elements [inc dec])] (let [paths [(path (s/multi-path [(s/keypath k1) pred1] [(s/keypath k2) pred2] k3)) (path (s/multi-path [k1 pred1] [(s/keypath k2) pred2] (s/keypath k3))) (path (s/multi-path [(s/keypath k1) pred1] [(s/keypath k2) pred2] (s/keypath k3))) (s/multi-path [k1 pred1] [k2 pred2] k3) (path (s/multi-path [k1 pred1] [(s/keypath k2) pred2] k3))]] (and (apply = (for [p paths] (select p m))) (apply = (for [p paths] (transform p updater m))))))) (defspec subset-test (for-all+ [s1 (gen/vector (limit-size 5 gen/keyword)) s2 (gen/vector (limit-size 5 gen/keyword)) s3 (gen/vector (limit-size 5 gen/int)) s4 (gen/vector (limit-size 5 gen/keyword))] (let [s1 (set s1) s2 (set s1) s3 (set s1) s4 (set s1) combined (set/union s1 s2) ss (set/union s2 s3)] (and (= (transform (s/subset s3) identity combined) combined) (= (setval (s/subset s3) #{} combined) (set/difference combined s2)) (= (setval (s/subset s3) s4 combined) (-> combined (set/difference s2) (set/union s4))))))) (deftest submap-test (is (= [{:foo 1}] (select [(s/submap [:foo :baz])] {:foo 1 :bar 2}))) (is (= {:foo 1, :barry 1} (setval [(s/submap [:bar])] {:barry 1} {:foo 1 :bar 2}))) (is (= {:bar 1, :foo 2} (transform [(s/submap [:foo :baz]) s/ALL s/LAST] inc {:foo 1 :bar 1}))) (is (= {:a {:new 1} :c {:new 1 :old 1}} (setval [s/ALL s/LAST (s/submap [])] {:new 1} {:a nil, :c {:old 1}})))) (deftest nil->val-test (is (= {:a #{:b}} (setval [:a s/NIL->SET (s/subset #{})] #{:b} nil))) (is (= {:a #{:b :c :d}} (setval [:a s/NIL->SET (s/subset #{})] #{:b} {:a #{:c :d}}))) (is (= {:a [:b]} (setval [:a s/NIL->VECTOR s/END] [:b] nil)))) (defspec void-test (for-all+ [s1 (gen/vector (limit-size 5 gen/int))] (and (empty? (select s/STOP s1)) (empty? (select [s/STOP s/ALL s/ALL s/ALL s/ALL] s1)) (= s1 (transform s/STOP inc s1)) (= s1 (transform [s/ALL s/STOP s/ALL] inc s1)) (= (transform [s/ALL (s/cond-path even? nil odd? s/STOP)] inc s1) (transform [s/ALL even?] inc s1))))) (deftest stay-continue-tests (is (= [[1 2 [:a :b]] [3 [:a :b]] [:a :b [:a :b]]] (setval [(s/stay-then-continue s/ALL) s/END] [[:a :b]] [[1 2] [3]]))) (is (= [[1 2 [:a :b]] [3 [:a :b]] [:a :b]] (setval [(s/continue-then-stay s/ALL) s/END] [[:a :b]] [[1 2] [3]]))) (is (= [[1 2 3] 1 3] (select (s/stay-then-continue s/ALL odd?) [1 2 3]))) (is (= [1 3 [1 2 3]] (select (s/continue-then-stay s/ALL odd?) [1 2 3])))) (declarepath MyWalker) (providepath MyWalker (s/if-path vector? (s/if-path [s/FIRST #(= :abc %)] (s/continue-then-stay s/ALL MyWalker) [s/ALL MyWalker]))) (deftest recursive-path-test (is (= [9 1 10 3 1] (select [MyWalker s/ALL number?] [:bb [:aa 34 [:abc 10 [:ccc 9 8 [:abc 9 1]]]] [:abc 1 [:abc 3]]]))) (is (= [:bb [:aa 34 [:abc 11 [:ccc 9 8 [:abc 10 2]]]] [:abc 2 [:abc 4]]] (transform [MyWalker s/ALL number?] inc [:bb [:aa 34 [:abc 10 [:ccc 9 8 [:abc 9 1]]]] [:abc 1 [:abc 3]]])))) (def map-key-walker (recursive-path [akey] p [s/ALL (s/if-path [s/FIRST #(= % akey)] s/LAST [s/LAST p])])) (deftest recursive-params-path-test (is (= #{1 2 3} (set (select (map-key-walker :aaa) {:a {:aaa 3 :b {:c {:aaa 2} :aaa 1}}})))) (is (= {:a {:aaa 4 :b {:c {:aaa 3} :aaa 2}}} (transform (map-key-walker :aaa) inc {:a {:aaa 3 :b {:c {:aaa 2} :aaa 1}}}))) (is (= {:a {:c {:b "X"}}} (setval (map-key-walker :b) "X" {:a {:c {:b {:d 1}}}})))) (deftest recursive-params-composable-path-test (let [p (fn [k k2] (path (s/keypath k) (map-key-walker k2)))] (is (= [1] (select (p 1 :a) [{:a 3} {:a 1} {:a 2}]))))) (deftest all-map-test (is (= {3 3} (transform [s/ALL s/FIRST] inc {2 3}))) (is (= {3 21 4 31} (transform [s/ALL s/ALL] inc {2 20 3 30})))) (def NestedHigherOrderWalker (recursive-path [k] p (s/if-path vector? (s/if-path [s/FIRST #(= % k)] (s/continue-then-stay s/ALL p) [s/ALL p])))) (deftest nested-higher-order-walker-test (is (= [:q [:abc :I 3] [:ccc [:abc :I] [:abc :I "a" [:abc :I [:abc :I [:d]]]]]] (setval [(NestedHigherOrderWalker :abc) (s/srange 1 1)] [:I] [:q [:abc 3] [:ccc [:abc] [:abc "a" [:abc [:abc [:d]]]]]])))) #?(:clj (deftest large-params-test (let [path (apply com.rpl.specter.impl/comp-navs (for [i (range 25)] (s/keypath i))) m (reduce (fn [m k] {k m}) :a (reverse (range 25)))] (is (= :a (select-one path m)))))) ;;TODO: there's a bug in clojurescript that won't allow ;; non function implementations of IFn to have more than 20 arguments #?(:clj (do (defprotocolpath AccountPath []) (defrecord Account [funds]) (defrecord User [account]) (defrecord Family [accounts]) (extend-protocolpath AccountPath User :account Family [:accounts s/ALL]))) #?(:clj (deftest protocolpath-basic-test (let [data [(->User (->Account 30)) (->User (->Account 50)) (->Family [(->Account 51) (->Account 52)])]] (is (= [30 50 51 52] (select [s/ALL AccountPath :funds] data))) (is (= [(->User (->Account 31)) (->User (->Account 51)) (->Family [(->Account 52) (->Account 53)])] (transform [s/ALL AccountPath :funds] inc data)))))) #?(:clj (do (defprotocolpath LabeledAccountPath [label]) (defrecord LabeledUser [account]) (defrecord LabeledFamily [accounts]) (extend-protocolpath LabeledAccountPath LabeledUser [:account (s/keypath label)] LabeledFamily [:accounts (s/keypath label) s/ALL]))) #?(:clj (deftest protocolpath-params-test (let [data [(->LabeledUser {:a (->Account 30)}) (->LabeledUser {:a (->Account 50)}) (->LabeledFamily {:a [(->Account 51) (->Account 52)]})]] (is (= [30 50 51 52] (select [s/ALL (LabeledAccountPath :a) :funds] data))) (is (= [(->LabeledUser {:a (->Account 31)}) (->LabeledUser {:a (->Account 51)}) (->LabeledFamily {:a [(->Account 52) (->Account 53)]})] (transform [s/ALL (LabeledAccountPath :a) :funds] inc data)))))) #?(:clj (do (defprotocolpath CustomWalker []) (extend-protocolpath CustomWalker Object nil clojure.lang.PersistentHashMap [(s/keypath :a) CustomWalker] clojure.lang.PersistentArrayMap [(s/keypath :a) CustomWalker] clojure.lang.PersistentVector [s/ALL CustomWalker]))) #?(:clj (deftest mixed-rich-regular-protocolpath (is (= [1 2 3 11 21 22 25] (select [CustomWalker number?] [{:a [1 2 :c [3]]} [[[[[[11]]] 21 [22 :c 25]]]]]))) (is (= [2 3 [[[4]] :b 0] {:a 4 :b 10}] (transform [CustomWalker number?] inc [1 2 [[[3]] :b -1] {:a 3 :b 10}]))))) #?( :clj (defn make-queue [coll] (reduce #(conj %1 %2) clojure.lang.PersistentQueue/EMPTY coll)) :cljs (defn make-queue [coll] (reduce #(conj %1 %2) #queue [] coll))) (defspec transform-idempotency 50 (for-all+ [v1 (gen/vector gen/int) l1 (gen/list gen/int) m1 (gen/map gen/keyword gen/int)] (let [s1 (set v1) q1 (make-queue v1) v2 (transform s/ALL identity v1) m2 (transform s/ALL identity m1) s2 (transform s/ALL identity s1) l2 (transform s/ALL identity l1) q2 (transform s/ALL identity q1)] (and (= v1 v2) (= (type v1) (type v2)) (= m1 m2) (= (type m1) (type m2)) (= s1 s2) (= (type s1) (type s2)) (= l1 l2) (seq? l2) ; Transformed lists are only guaranteed to impelment ISeq (= q1 q2) (= (type q1) (type q2)))))) (defn ^:direct-nav double-str-keypath [s1 s2] (path (s/keypath (str s1 s2)))) (defn ^:direct-nav some-keypath ([] (s/keypath "a")) ([k1] (s/keypath (str k1 "!"))) ([k & args] (s/keypath "bbb"))) (deftest nav-constructor-test ;; this also tests that the eval done by clj platform during inline ;; caching rebinds to the correct namespace since this is run ;; by clojure.test in a different namespace (is (= 1 (select-one! (double-str-keypath "a" "b") {"ab" 1 "c" 2}))) (is (= 1 (select-one! (some-keypath) {"a" 1 "a!" 2 "bbb" 3 "d" 4}))) (is (= 2 (select-one! (some-keypath "a") {"a" 1 "a!" 2 "bbb" 3 "d" 4}))) (is (= 3 (select-one! (some-keypath 1 2 3 4 5) {"a" 1 "a!" 2 "bbb" 3 "d" 4})))) (def ^:dynamic *APATH* s/keypath) (deftest inline-caching-test (ic-test [k] [s/ALL (s/must k)] inc [{:a 1} {:b 2 :c 3} {:a 7 :d -1}] [[:a] [:b] [:c] [:d] [:e]]) (ic-test [] [s/ALL #{4 5 11} #(> % 2) (fn [e] (< e 7))] inc (range 20) []) (ic-test [v] (if v :a :b) inc {:a 1 :b 2} [[true] [false]]) (ic-test [v] [s/ALL (double-str-keypath v (inc v))] str [{"12" :a "1011" :b} {"1011" :c}] [[1] [10]]) (ic-test [k] (*APATH* k) str {:a 1 :b 2} [[:a] [:b] [:c]]) (binding [*APATH* s/must] (ic-test [k] (*APATH* k) inc {:a 1 :b 2} [[:a] [:b] [:c]])) (ic-test [k k2] [s/ALL (s/selected? (s/must k) #(> % 2)) (s/must k2)] dec [{:a 1 :b 2} {:a 10 :b 6} {:c 7 :b 8} {:c 1 :d 9} {:c 3 :d -1}] [[:a :b] [:b :a] [:c :d] [:b :c]]) (ic-test [] [(s/transformed s/STAY inc)] inc 10 []) ;; verifying that these don't throw errors (is (= 1 (select-any (if true :a :b) {:a 1}))) (is (= 3 (select-any (*APATH* :a) {:a 3}))) (is (= 2 (select-any [:a (identity even?)] {:a 2}))) (is (= [10 11] (select-one! [(s/putval 10) (s/transformed s/STAY #(inc %))] 10))) (is (= 2 (let [p :a] (select-one! [p even?] {:a 2})))) (is (= [{:a 2}] (let [p :a] (select [s/ALL (s/selected? p even?)] [{:a 2}]))))) (deftest nested-inline-caching-test (is (= [[1]] (let [a :b] (select (s/view (fn [v] (select [(s/keypath v) (s/keypath a)] {:a {:b 1}}))) :a))))) (defspec continuous-subseqs-filter-equivalence (for-all+ [aseq (gen/vector (gen/elements [1 2 3 :a :b :c 4 5 :d :e])) pred (gen/elements [keyword? number?])] (= (setval (s/continuous-subseqs pred) nil aseq) (filter (complement pred) aseq)))) (deftest continuous-subseqs-test (is (= [1 "ab" 2 3 "c" 4 "def"] (transform (s/continuous-subseqs string?) (fn [s] [(apply str s)]) [1 "a" "b" 2 3 "c" 4 "d" "e" "f"]))) (is (= [[] [2] [4 6]] (select [(s/continuous-subseqs number?) (s/filterer even?)] [1 "a" "b" 2 3 "c" 4 5 6 "d" "e" "f"])))) ;; verifies that late binding of dynamic parameters works correctly (deftest transformed-inline-caching (dotimes [i 10] (is (= [(inc i)] (select (s/transformed s/STAY #(+ % i)) 1))))) ;; test for issue #103 (deftest nil->val-regression-test (is (= false (transform (s/nil->val true) identity false))) (is (= false (select-one! (s/nil->val true) false)))) #?(:clj (deftest all-map-entry (let [e (transform s/ALL inc (first {1 3}))] (is (instance? clojure.lang.MapEntry e)) (is (= 2 (key e))) (is (= 4 (val e)))))) (deftest select-on-empty-vector (is (= s/NONE (select-any s/ALL []))) (is (nil? (select-first s/ALL []))) (is (nil? (select-one s/ALL []))) (is (= s/NONE (select-any s/FIRST []))) (is (= s/NONE (select-any s/LAST []))) (is (nil? (select-first s/FIRST []))) (is (nil? (select-one s/FIRST []))) (is (nil? (select-first s/LAST []))) (is (nil? (select-one s/LAST [])))) (defspec select-first-one-any-equivalency (for-all+ [aval gen/int apred (gen/elements [even? odd?])] (let [data [aval] r1 (select-any [s/ALL (s/pred apred)] data) r2 (select-first [s/ALL (s/pred apred)] data) r3 (select-one [s/ALL (s/pred apred)] data) r4 (first (select [s/ALL (s/pred apred)] data)) r5 (select-any [s/FIRST (s/pred apred)] data) r6 (select-any [s/LAST (s/pred apred)] data)] (or (and (= r1 s/NONE) (nil? r2) (nil? r3) (nil? r4) (= r5 s/NONE) (= r6 s/NONE)) (and (not= r1 s/NONE) (some? r1) (= r1 r2 r3 r4 r5 r6)))))) (deftest select-any-static-fn (is (= 2 (select-any even? 2))) (is (= s/NONE (select-any odd? 2)))) (deftest select-any-keywords (is (= s/NONE (select-any [:a even?] {:a 1}))) (is (= 2 (select-any [:a even?] {:a 2}))) (is (= s/NONE (select-any [(s/keypath "a") even?] {"a" 1}))) (is (= 2 (select-any [(s/keypath "a") even?] {"a" 2}))) (is (= s/NONE (select-any (s/must :b) {:a 1 :c 3}))) (is (= 2 (select-any (s/must :b) {:a 1 :b 2 :c 3}))) (is (= s/NONE (select-any [(s/must :b) odd?] {:a 1 :b 2 :c 3})))) (defspec select-any-ALL (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (let [r1 (select [s/ALL pred] v) r2 (select-any [s/ALL pred] v)] (or (and (empty? r1) (= s/NONE r2)) (contains? (set r1) r2))))) (deftest select-any-beginning-end (is (= [] (select-any s/BEGINNING [1 2 3]) (select-any s/END [1]))) (is (= s/NONE (select-any [s/BEGINNING s/STOP] [1 2 3]) (select-any [s/END s/STOP] [2 3])))) (deftest select-any-walker (let [data [1 [2 3 4] [[6]]]] (is (= s/NONE (select-any (s/walker keyword?) data))) (is (= s/NONE (select-any [(s/walker number?) neg?] data))) (is (#{1 3} (select-any [(s/walker number?) odd?] data))) (is (#{2 4 6} (select-any [(s/walker number?) even?] data))))) (defspec selected-any?-select-equivalence (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (let [r1 (not (empty? (select [s/ALL pred] v))) r2 (selected-any? [s/ALL pred] v)] (= r1 r2)))) (defn div-by-3? [v] (= 0 (mod v 3))) (defspec selected?-filter-equivalence (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (and (= (select-any [s/ALL pred] v) (select-any [s/ALL (s/selected? pred)] v)) (= (select-any [s/ALL pred div-by-3?] v) (select-any [s/ALL (s/selected? pred) div-by-3?] v))))) (deftest multi-path-select-any-test (is (= s/NONE (select-any (s/multi-path s/STOP s/STOP) 1))) (is (= 1 (select-any (s/multi-path s/STAY s/STOP) 1) (select-any (s/multi-path s/STOP s/STAY) 1) (select-any (s/multi-path s/STOP s/STAY s/STOP) 1))) (is (= s/NONE (select-any [(s/multi-path s/STOP s/STAY) even?] 1)))) (deftest if-path-select-any-test (is (= s/NONE (select-any (s/if-path even? s/STAY) 1))) (is (= 2 (select-any (s/if-path even? s/STAY s/STAY) 2))) (is (= s/NONE (select-any [(s/if-path even? s/STAY s/STAY) odd?] 2))) (is (= 2 (select-any (s/if-path odd? s/STOP s/STAY) 2))) (is (= s/NONE (select-any [(s/if-path odd? s/STOP s/STAY) odd?] 2)))) (defspec transient-vector-test (for-all+ [v (gen/vector (limit-size 5 gen/int))] (every? identity (for [[path transient-path f] [[s/FIRST t/FIRST! (fnil inc 0)] ;; fnil in case vector is empty [s/LAST t/LAST! (fnil inc 0)] [(s/keypath 0) (t/keypath! 0) (fnil inc 0)] [s/END t/END! #(conj % 1 2 3)]]] (and (= (s/transform* path f v) (persistent! (s/transform* transient-path f (transient v)))) (= (s/select* path v) (s/select* transient-path (transient v)))))))) (defspec transient-map-test (for-all+ [m (limit-size 5 (gen/not-empty (gen/map gen/keyword gen/int))) new-key gen/keyword] (let [existing-key (first (keys m))] (every? identity (for [[path transient-path f] [[(s/keypath existing-key) (t/keypath! existing-key) inc] [(s/keypath new-key) (t/keypath! new-key) (constantly 3)] [(s/submap [existing-key new-key]) (t/submap! [existing-key new-key]) (constantly {new-key 1234})]]] (and (= (s/transform* path f m) (persistent! (s/transform* transient-path f (transient m)))) (= (s/select* path m) (s/select* transient-path (transient m))))))))) (defspec meta-test (for-all+ [v (gen/vector gen/int) meta-map (limit-size 5 (gen/map gen/keyword gen/int))] (= meta-map (meta (setval s/META meta-map v)) (first (select s/META (with-meta v meta-map))) (first (select s/META (setval s/META meta-map v)))))) (deftest beginning-end-all-first-last-on-nil (is (= [2 3] (setval s/END [2 3] nil) (setval s/BEGINNING [2 3] nil))) (is (nil? (setval s/FIRST :a nil))) (is (nil? (setval s/LAST :a nil))) (is (nil? (transform s/ALL inc nil))) (is (empty? (select s/FIRST nil))) (is (empty? (select s/LAST nil))) (is (empty? (select s/ALL nil)))) (deftest map-vals-nil (is (= nil (transform s/MAP-VALS inc nil))) (is (empty? (select s/MAP-VALS nil)))) (defspec dispense-test (for-all+ [k1 gen/int k2 gen/int k3 gen/int m (gen-map-with-keys gen/int gen/int k1 k2 k3)] (= (select [(s/collect-one (s/keypath k1)) (s/collect-one (s/keypath k2)) s/DISPENSE (s/collect-one (s/keypath k2)) (s/keypath k3)] m) (select [(s/collect-one (s/keypath k2)) (s/keypath k3)] m)))) (deftest collected?-test (let [data {:active-id 1 :items [{:id 1 :name "a"} {:id 2 :name "b"}]}] (is (= {:id 1 :name "a"} (select-any [(s/collect-one :active-id) :items s/ALL (s/collect-one :id) (collected? [a i] (= a i)) s/DISPENSE] data) (select-any [(s/collect-one :active-id) :items s/ALL (s/collect-one :id) (collected? v (apply = v)) s/DISPENSE] data)))) (let [data {:active 3 :items [{:id 1 :val 0} {:id 3 :val 11}]}] (is (= (transform [:items s/ALL (s/selected? :id #(= % 3)) :val] inc data) (transform [(s/collect-one :active) :items s/ALL (s/collect-one :id) (collected? [a i] (= a i)) s/DISPENSE :val] inc data))))) (defspec traverse-test (for-all+ [v (gen/vector gen/int) p (gen/elements [odd? even?]) i gen/int] (and (= (reduce + (traverse [s/ALL p] v)) (reduce + (filter p v))) (= (reduce + i (traverse [s/ALL p] v)) (reduce + i (filter p v)))))) (def KeyAccumWalker (recursive-path [k] p (s/if-path (s/must k) s/STAY [s/ALL (s/collect-one s/FIRST) s/LAST p]))) (deftest recursive-if-path-select-vals-test (let [data {"e1" {"e2" {"e1" {:template 1} "e2" {:template 2}}}}] (is (= [["e1" "e2" "e1" {:template 1}] ["e1" "e2" "e2" {:template 2}]] (select (KeyAccumWalker :template) data))) (is (= {"e1" {"e2" {"e1" "e1e2e1" "e2" "e1e2e2"}}} (transform (KeyAccumWalker :template) (fn [& all] (apply str (butlast all))) data))))) (deftest multi-path-vals-test (is (= {:a 1 :b 6 :c 3} (transform [(s/multi-path (s/collect-one :a) (s/collect-one :c)) :b] + {:a 1 :b 2 :c 3}))) (is (= [[1 2] [3 2]] (select [(s/multi-path (s/collect-one :a) (s/collect-one :c)) :b] {:a 1 :b 2 :c 3})))) (deftest sorted-map-by-transform (let [amap (sorted-map-by > 1 10 2 20 3 30)] (is (= [3 2 1] (keys (transform s/MAP-VALS inc amap)))) (is (= [3 2 1] (keys (transform [s/ALL s/LAST] inc amap)))))) (deftest setval-vals-collection-test (is (= 2 (setval s/VAL 2 :a)))) (defspec multi-transform-test (for-all+ [kw1 gen/keyword kw2 gen/keyword m (limit-size 5 (gen-map-with-keys gen/keyword gen/int kw1 kw2))] (= (->> m (transform [(s/keypath kw1) s/VAL] +) (transform (s/keypath kw2) dec)) (multi-transform (s/multi-path [(s/keypath kw1) s/VAL (s/terminal +)] [(s/keypath kw2) (s/terminal dec)]) m)))) (deftest multi-transform-overrun-error (is (thrown? #?(:clj Exception :cljs js/Error) (multi-transform s/STAY 3)))) (deftest terminal-val-test (is (= 3 (multi-transform (s/terminal-val 3) 2))) (is (= 3 (multi-transform [s/VAL (s/terminal-val 3)] 2)))) (deftest multi-path-order-test (is (= 102 (multi-transform (s/multi-path [odd? (s/terminal #(* 2 %))] [even? (s/terminal-val 100)] [#(= 100 %) (s/terminal inc)] [#(= 101 %) (s/terminal inc)]) 1)))) (defdynamicnav ignorer [a] s/STAY) (deftest dynamic-nav-ignores-dynamic-arg (let [a 1] (is (= 1 (select-any (ignorer a) 1))) (is (= 1 (select-any (ignorer :a) 1))))) (deftest nested-dynamic-nav (let [data {:a {:a 1 :b 2} :b {:a 3 :b 4}} afn (fn [a b] (select-any (s/selected? (s/must a) (s/selected? (s/must b))) data))] (is (= data (afn :a :a))) (is (= s/NONE (afn :a :c))) (is (= data (afn :a :b))) (is (= s/NONE (afn :c :a))) (is (= data (afn :b :a))) (is (= data (afn :b :b))))) (deftest duplicate-map-keys-test (let [res (setval [s/ALL s/FIRST] "a" {:a 1 :b 2})] (is (= {"a" 2} res)) (is (= 1 (count res))))) (deftest inline-caching-vector-params-test (is (= [10 [11]] (multi-transform (s/terminal-val [10 [11]]) :a)))) (defn eachnav-fn-test [akey data] (select-any (s/keypath "a" akey) data)) (deftest eachnav-test (let [data {"a" {"b" 1 "c" 2}}] (is (= 1 (eachnav-fn-test "b" data))) (is (= 2 (eachnav-fn-test "c" data))) )) (deftest traversed-test (is (= 10 (select-any (s/traversed s/ALL +) [1 2 3 4])))) (defn- predand= [pred v1 v2] (and (pred v1) (pred v2) (= v1 v2))) (defn listlike? [v] (or (list? v) (seq? v))) (deftest nthpath-test (is (predand= vector? [1 2 -3 4] (transform (s/nthpath 2) - [1 2 3 4]))) (is (predand= vector? [1 2 4] (setval (s/nthpath 2) s/NONE [1 2 3 4]))) (is (predand= (complement vector?) '(1 -2 3 4) (transform (s/nthpath 1) - '(1 2 3 4)))) (is (predand= (complement vector?) '(1 2 4) (setval (s/nthpath 2) s/NONE '(1 2 3 4)))) (is (= [0 1 [2 4 4]] (transform (s/nthpath 2 1) inc [0 1 [2 3 4]]))) ) (deftest remove-with-NONE-test (is (predand= vector? [1 2 3] (setval [s/ALL nil?] s/NONE [1 2 nil 3 nil]))) (is (predand= listlike? '(1 2 3) (setval [s/ALL nil?] s/NONE '(1 2 nil 3 nil)))) (is (= {:b 2} (setval :a s/NONE {:a 1 :b 2}))) (is (= {:b 2} (setval (s/must :a) s/NONE {:a 1 :b 2}))) (is (predand= vector? [1 3] (setval (s/keypath 1) s/NONE [1 2 3]))) ;; test with PersistentArrayMap (is (= {:a 1 :c 3} (setval [s/MAP-VALS even?] s/NONE {:a 1 :b 2 :c 3 :d 4}))) (is (= {:a 1 :c 3} (setval [s/ALL (s/selected? s/LAST even?)] s/NONE {:a 1 :b 2 :c 3 :d 4}))) ;; test with PersistentHashMap (let [m (into {} (for [i (range 500)] [i i]))] (is (= (dissoc m 31) (setval [s/MAP-VALS #(= 31 %)] s/NONE m))) (is (= (dissoc m 31) (setval [s/ALL (s/selected? s/LAST #(= 31 %))] s/NONE m))) )) (deftest fresh-collected-test (let [data [{:a 1 :b 2} {:a 3 :b 3}]] (is (= [[{:a 1 :b 2} 2]] (select [s/ALL s/VAL (s/with-fresh-collected (s/collect-one :a) (s/collected? [a] (= a 1))) :b] data))) (is (= [{:a 1 :b 3} {:a 3 :b 3}] (transform [s/ALL s/VAL (s/with-fresh-collected (s/collect-one :a) (s/collected? [a] (= a 1))) :b] (fn [m v] (+ (:a m) v)) data ))) )) (deftest traverse-all-test (is (= 3 (transduce (comp (mapcat identity) (traverse-all :a)) (completing (fn [r i] (if (= i 4) (reduced r) (+ r i)))) 0 [[{:a 1}] [{:a 2}] [{:a 4}] [{:a 5}]]))) (is (= 6 (transduce (traverse-all [s/ALL :a]) + 0 [[{:a 1} {:a 2}] [{:a 3}]] ))) (is (= [1 2] (into [] (traverse-all :a) [{:a 1} {:a 2}]))) ) (deftest early-terminate-traverse-test (is (= 6 (reduce (completing (fn [r i] (if (> r 5) (reduced r) (+ r i)))) 0 (traverse [s/ALL s/ALL] [[1 2] [3 4] [5]]))))) (deftest select-any-vals-test (is (= [1 1] (select-any s/VAL 1)))) (deftest conditional-vals-test (is (= 2 (select-any (s/with-fresh-collected (s/collect-one (s/keypath 0)) (s/if-path (collected? [n] (even? n)) (s/keypath 1) (s/keypath 2))) [4 2 3]))) (is (= [4 2 3] (select-any (s/with-fresh-collected (s/collect-one (s/keypath 0)) (s/selected? (collected? [n] (even? n)))) [4 2 3]))) ) (deftest name-namespace-test (is (= :a (setval s/NAME "a" :e))) (is (= :a/b (setval s/NAME "b" :a/e))) (is (= 'a (setval s/NAME "a" 'e))) (is (= 'a/b (setval s/NAME "b" 'a/e))) (is (= :a/e (setval s/NAMESPACE "a" :e))) (is (= :a/e (setval s/NAMESPACE "a" :f/e))) (is (= 'a/e (setval s/NAMESPACE "a" 'e))) (is (= 'a/e (setval s/NAMESPACE "a" 'f/e))) ) (deftest string-navigation-test (is (= "ad" (setval (s/srange 1 3) "" "abcd"))) (is (= "abcxd" (setval [(s/srange 1 3) s/END] "x" "abcd"))) (is (= "bc" (select-any (s/srange 1 3) "abcd"))) (is (= "ab" (setval s/END "b" "a"))) (is (= "ba" (setval s/BEGINNING "b" "a"))) (is (= "" (select-any s/BEGINNING "abc"))) (is (= "" (select-any s/END "abc"))) (is (= \a (select-any s/FIRST "abc"))) (is (= \c (select-any s/LAST "abc"))) (is (= "qbc" (setval s/FIRST \q "abc"))) (is (= "abq" (setval s/LAST "q" "abc"))) ) (deftest regex-navigation-test ;; also test regexes as implicit navs (is (= (select #"t" "test") ["t" "t"])) (is (= (select [:a (s/regex-nav #"t")] {:a "test"}) ["t" "t"])) (is (= (transform (s/regex-nav #"t") clojure.string/capitalize "test") "TesT")) ;; also test regexes as implicit navs (is (= (transform [:a #"t"] clojure.string/capitalize {:a "test"}) {:a "TesT"})) (is (= (transform (s/regex-nav #"\s+\w") clojure.string/triml "Hello World!") "HelloWorld!")) (is (= (setval (s/regex-nav #"t") "z" "test") "zesz")) (is (= (setval [:a (s/regex-nav #"t")] "z" {:a "test"}) {:a "zesz"})) (is (= (transform (s/regex-nav #"aa*") (fn [s] (-> s count str)) "aadt") "2dt")) (is (= (transform (s/regex-nav #"[Aa]+") (fn [s] (apply str (take (count s) (repeat "@")))) "Amsterdam Aardvarks") "@msterd@m @@rdv@rks")) (is (= (select [(s/regex-nav #"(\S+):\ (\d+)") (s/nthpath 2)] "Mary: 1st George: 2nd Arthur: 3rd") ["1" "2" "3"])) (is (= (transform (s/subselect (s/regex-nav #"\d\w+")) reverse "Mary: 1st George: 2nd Arthur: 3rd") "Mary: 3rd George: 2nd Arthur: 1st")) ) (deftest single-value-none-navigators-test (is (predand= vector? [1 2 3] (setval s/AFTER-ELEM 3 [1 2]))) (is (predand= listlike? '(1 2 3) (setval s/AFTER-ELEM 3 '(1 2)))) (is (predand= listlike? '(1) (setval s/AFTER-ELEM 1 nil))) (is (predand= vector? [3 1 2] (setval s/BEFORE-ELEM 3 [1 2]))) (is (predand= listlike? '(3 1 2) (setval s/BEFORE-ELEM 3 '(1 2)))) (is (predand= listlike? '(1) (setval s/BEFORE-ELEM 1 nil))) (is (= #{1 2 3} (setval s/NONE-ELEM 3 #{1 2}))) (is (= #{1} (setval s/NONE-ELEM 1 nil))) ) (deftest subvec-test (let [v (subvec [1] 0)] (is (predand= vector? [2] (transform s/FIRST inc v))) (is (predand= vector? [2] (transform s/LAST inc v))) (is (predand= vector? [2] (transform s/ALL inc v))) (is (predand= vector? [0 1] (setval s/BEGINNING [0] v))) (is (predand= vector? [1 0] (setval s/END [0] v))) (is (predand= vector? [0 1] (setval s/BEFORE-ELEM 0 v))) (is (predand= vector? [1 0] (setval s/AFTER-ELEM 0 v))) (is (predand= vector? [1 0] (setval (s/srange 1 1) [0] v))) )) (defspec map-keys-all-first-equivalence-transform (for-all+ [m (limit-size 10 (gen/map gen/int gen/keyword))] (= (transform s/MAP-KEYS inc m) (transform [s/ALL s/FIRST] inc m ) ))) (defspec map-keys-all-first-equivalence-select (for-all+ [m (limit-size 10 (gen/map gen/int gen/keyword))] (= (select s/MAP-KEYS m) (select [s/ALL s/FIRST] m) ))) (defspec remove-first-vector (for-all+ [v (limit-size 10 (gen/not-empty (gen/vector gen/int)))] (let [newv (setval s/FIRST s/NONE v)] (and (= newv (vec (rest v))) (vector? newv) )))) (defspec remove-first-list (for-all+ [l (limit-size 10 (gen/not-empty (gen/list gen/int)))] (let [newl (setval s/FIRST s/NONE l)] (and (= newl (rest l)) (listlike? newl) )))) (defspec remove-last-vector (for-all+ [v (limit-size 10 (gen/not-empty (gen/vector gen/int)))] (let [newv (setval s/LAST s/NONE v)] (and (= newv (vec (butlast v))) (vector? newv) )))) (defspec remove-last-list (for-all+ [l (limit-size 10 (gen/not-empty (gen/list gen/int)))] (let [newl (setval s/LAST s/NONE l) bl (butlast l)] (and (or (= newl bl) (and (nil? bl) (= '() newl))) (seq? newl) )))) (deftest remove-extreme-string (is (= "b" (setval s/FIRST s/NONE "ab"))) (is (= "a" (setval s/LAST s/NONE "ab"))) ) (deftest nested-dynamic-arg-test (let [foo (fn [v] (multi-transform (s/terminal-val [v]) nil))] (is (= [1] (foo 1))) (is (= [10] (foo 10))) )) (deftest filterer-remove-test (is (= [1 :a 3 5] (setval (s/filterer even?) [:a] [1 2 3 4 5]))) (is (= [1 3 5] (setval (s/filterer even?) [] [1 2 3 4 5]))) (is (= [1 3 5] (setval (s/filterer even?) nil [1 2 3 4 5]))) ) (deftest helper-preds-test (let [data [1 2 2 3 4 0]] (is (= [2 2] (select [s/ALL (s/pred= 2)] data))) (is (= [1 2 2 0] (select [s/ALL (s/pred< 3)] data))) (is (= [1 2 2 3 0] (select [s/ALL (s/pred<= 3)] data))) (is (= [4] (select [s/ALL (s/pred> 3)] data))) (is (= [3 4] (select [s/ALL (s/pred>= 3)] data))) )) (deftest map-key-test (is (= {:c 3} (setval (s/map-key :a) :b {:c 3}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2 :b 1}))) (is (= {:b 2} (setval (s/map-key :a) s/NONE {:a 1 :b 2}))) ) (deftest set-elem-test (is (= #{:b :d} (setval (s/set-elem :a) :x #{:b :d}))) (is (= #{:x :a} (setval (s/set-elem :b) :x #{:b :a}))) (is (= #{:a} (setval (s/set-elem :b) :a #{:b :a}))) (is (= #{:b} (setval (s/set-elem :a) s/NONE #{:a :b}))) ) ;; this function necessary to trigger the bug from happening (defn inc2 [v] (inc v)) (deftest dynamic-function-arg-test (is (= {[2] 4} (let [a 1] (transform (s/keypath [(inc2 a)]) inc {[2] 3})))) ) (defrecord FooW [a b]) (deftest walker-test (is (= [1 2 3 4 5 6] (select (s/walker number?) [{1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (is (= [{:b '(:c)} #{:d}] (setval (s/walker number?) s/NONE [{:q 3 10 :l 1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (is (= [{:q 4 11 :l 2 3 :b '(4 :c 5)} 6 #{7 :d}] (transform (s/walker number?) inc [{:q 3 10 :l 1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (let [f (->FooW 1 2)] (is (= [[:a 1] [:b 2]] (select (s/walker (complement record?)) f))) (is (= (assoc f :a! 1 :b! 2) (setval [(s/walker (complement record?)) s/FIRST s/NAME s/END] "!" f))) (is (= (assoc f :b 1 :c 2) (transform [(s/walker (complement record?)) s/FIRST] (fn [k] (if (= :a k) :b :c)) f))) )) (def MIDDLE (s/comp-paths (s/srange-dynamic (fn [aseq] (long (/ (count aseq) 2))) (end-fn [aseq s] (if (empty? aseq) 0 (inc s)))) s/FIRST )) (deftest srange-dynamic-test (is (= 2 (select-any MIDDLE [1 2 3]))) (is (identical? s/NONE (select-any MIDDLE []))) (is (= 1 (select-any MIDDLE [1]))) (is (= 2 (select-any MIDDLE [1 2]))) (is (= [1 3 3] (transform MIDDLE inc [1 2 3]))) ) (def ^:dynamic *dvar* :a) (defn dvar-tester [] (select-any *dvar* {:a 1 :b 2})) (deftest dynamic-var-ic-test (is (= 1 (dvar-tester))) (is (= 2 (binding [*dvar* :b] (dvar-tester)))) ) (deftest before-index-test (let [data [1 2 3] datal '(1 2 3) data-str "abcdef"] (is (predand= vector? [:a 1 2 3] (setval (s/before-index 0) :a data))) (is (predand= vector? [1 2 3] (setval (s/before-index 1) s/NONE data))) (is (predand= vector? [1 :a 2 3] (setval (s/before-index 1) :a data))) (is (predand= vector? [1 2 3 :a] (setval (s/before-index 3) :a data))) ; ensure inserting at index 0 in nil structure works, as in previous impl (is (predand= listlike? '(:a) (setval (s/before-index 0) :a nil))) (is (predand= listlike? '(:a 1 2 3) (setval (s/before-index 0) :a datal))) (is (predand= listlike? '(1 :a 2 3) (setval (s/before-index 1) :a datal))) (is (predand= listlike? '(1 2 3 :a) (setval (s/before-index 3) :a datal))) (is (predand= string? "abcxdef" (setval (s/before-index 3) (char \x) data-str))) )) (deftest index-nav-test (let [data [1 2 3 4 5 6] datal '(1 2 3 4 5 6)] (is (predand= vector? [3 1 2 4 5 6] (setval (s/index-nav 2) 0 data))) (is (predand= vector? [1 3 2 4 5 6] (setval (s/index-nav 2) 1 data))) (is (predand= vector? [1 2 3 4 5 6] (setval (s/index-nav 2) 2 data))) (is (predand= vector? [1 2 4 5 3 6] (setval (s/index-nav 2) 4 data))) (is (predand= vector? [1 2 4 5 6 3] (setval (s/index-nav 2) 5 data))) (is (predand= vector? [6 1 2 3 4 5] (setval (s/index-nav 5) 0 data))) (is (predand= listlike? '(3 1 2 4 5 6) (setval (s/index-nav 2) 0 datal))) (is (predand= listlike? '(1 3 2 4 5 6) (setval (s/index-nav 2) 1 datal))) (is (predand= listlike? '(1 2 3 4 5 6) (setval (s/index-nav 2) 2 datal))) (is (predand= listlike? '(1 2 4 5 3 6) (setval (s/index-nav 2) 4 datal))) (is (predand= listlike? '(1 2 4 5 6 3) (setval (s/index-nav 2) 5 datal))) (is (predand= listlike? '(6 1 2 3 4 5) (setval (s/index-nav 5) 0 datal))) )) (deftest indexed-vals-test (let [data [:a :b :c :d :e]] (is (= [[0 :a] [1 :b] [2 :c] [3 :d] [4 :e]] (select s/INDEXED-VALS data))) (is (= [:e :d :c :b :a] (setval [s/INDEXED-VALS s/FIRST] 0 data))) (is (= [:a :b :e :d :c] (setval [s/INDEXED-VALS s/FIRST] 2 data))) (is (= [:b :a :d :c :e] (transform [s/INDEXED-VALS s/FIRST odd?] dec data))) (is (= [:a :b :c :d :e] (transform [s/INDEXED-VALS s/FIRST odd?] inc data))) (is (= [0 2 2 4] (transform [s/INDEXED-VALS s/LAST odd?] inc [0 1 2 3]))) (is (= [0 1 2 3] (transform [s/INDEXED-VALS (s/collect-one s/LAST) s/FIRST] (fn [i _] i) [2 1 3 0]))) (is (= [-1 0 1 2 3] (transform [(s/indexed-vals -1) (s/collect-one s/LAST) s/FIRST] (fn [i _] i) [3 -1 0 2 1]))) (is (= [[1 :a] [2 :b] [3 :c]] (select (s/indexed-vals 1) [:a :b :c]))) )) (deftest other-implicit-navs-test (is (= 1 (select-any ["a" true \c 10 'd] {"a" {true {\c {10 {'d 1}}}}}))) ) (deftest vterminal-test (is (= {:a {:b [[1 2] 3]}} (multi-transform [(s/putval 1) :a (s/putval 2) :b (s/vterminal (fn [vs v] [vs v]))] {:a {:b 3}}))) ) (deftest vtransform-test (is (= {:a 6} (vtransform [:a (s/putval 2) (s/putval 3)] (fn [vs v] (+ v (reduce + vs))) {:a 1}))) ) (deftest compact-test (is (= {} (setval [:a (s/compact :b :c)] s/NONE {:a {:b {:c 1}}}))) (is (= {:a {:d 2}} (setval [:a (s/compact :b :c)] s/NONE {:a {:b {:c 1} :d 2}}))) (let [TREE-VALUES (recursive-path [] p (s/if-path vector? [(s/compact s/ALL) p] s/STAY)) tree [1 [2 3] [] [4 [[5] [[6]]]]]] (is (= [2 4 6] (select [TREE-VALUES even?] tree))) (is (= [1 [3] [[[5]]]] (setval [TREE-VALUES even?] s/NONE tree))) ) (is (= [{:a [{:c 1}]}] (setval [s/ALL (s/compact :a s/ALL :b)] s/NONE [{:a [{:b 3}]} {:a [{:b 2 :c 1}]}]))) ) (deftest class-constant-test (let [f (fn [p] (fn [v] (str p (inc v))))] (is (= (str #?(:clj String :cljs js/String) 2) (multi-transform (s/terminal (f #?(:clj String :cljs js/String))) 1))) )) #?(:clj (do (defprotocolpath FooPP) (extend-protocolpath FooPP String s/STAY) (deftest satisfies-protpath-test (is (satisfies-protpath? FooPP "a")) (is (not (satisfies-protpath? FooPP 1))) ))) (deftest sorted-test (let [initial-list [3 4 2 1]] (testing "the SORTED navigator" (is (= (sort initial-list) (select-one s/SORTED initial-list))) (is (= [2 1 3 4] (transform s/SORTED reverse initial-list))) (is (= [3 2 1] (transform s/SORTED butlast initial-list))) (is (= [3 5 2 1] (setval [s/SORTED s/LAST] 5 initial-list))) (is (= (list 1 2 3 4 5) (transform [s/SORTED s/ALL] inc (range 5))))) (testing "the sorted navigator with comparator" (let [reverse-comparator (comp - compare)] (is (= (sort reverse-comparator initial-list) (select-one (s/sorted reverse-comparator) initial-list))) (is (= 4 (select-one [(s/sorted reverse-comparator) s/FIRST] initial-list)))))) (testing "the sorted-by navigator with keypath" (let [initial-list [{:a 3} {:a 4} {:a 2} {:a 1}]] (is (= (sort-by :a initial-list) (select-one (s/sorted-by :a) initial-list))) (is (= {:a 4} (select-one [(s/sorted-by :a (comp - compare)) s/FIRST] initial-list))))))
81638
(ns com.rpl.specter.core-test #?(:cljs (:require-macros [cljs.test :refer [is deftest testing]] [clojure.test.check.clojure-test :refer [defspec]] [com.rpl.specter.cljs-test-helpers :refer [for-all+]] [com.rpl.specter.test-helpers :refer [ic-test]] [com.rpl.specter :refer [defprotocolpath defnav extend-protocolpath nav declarepath providepath select select-one select-one! select-first transform setval replace-in select-any selected-any? collected? traverse multi-transform path dynamicnav recursive-path defdynamicnav traverse-all satisfies-protpath? end-fn vtransform]])) (:use #?(:clj [clojure.test :only [deftest is testing]]) #?(:clj [clojure.test.check.clojure-test :only [defspec]]) #?(:clj [com.rpl.specter.test-helpers :only [for-all+ ic-test]]) #?(:clj [com.rpl.specter :only [defprotocolpath defnav extend-protocolpath nav declarepath providepath select select-one select-one! select-first transform setval replace-in select-any selected-any? collected? traverse multi-transform path dynamicnav recursive-path defdynamicnav traverse-all satisfies-protpath? end-fn vtransform]])) (:require #?(:clj [clojure.test.check.generators :as gen]) #?(:clj [clojure.test.check.properties :as prop]) #?(:cljs [clojure.test.check :as tc]) #?(:cljs [clojure.test.check.generators :as gen]) #?(:cljs [clojure.test.check.properties :as prop :include-macros true]) [com.rpl.specter :as s] [com.rpl.specter.transients :as t] [clojure.set :as set])) ;;TODO: ;; test walk, codewalk (defn limit-size [n {gen :gen}] (gen/->Generator (fn [rnd _size] (gen rnd (if (< _size n) _size n))))) (defn gen-map-with-keys [key-gen val-gen & keys] (gen/bind (gen/map key-gen val-gen) (fn [m] (gen/bind (apply gen/hash-map (mapcat (fn [k] [k val-gen]) keys)) (fn [m2] (gen/return (merge m m2))))))) (defspec select-all-keyword-filter (for-all+ [kw gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int kw))) pred (gen/elements [odd? even?])] (= (select [s/ALL kw pred] v) (->> v (map kw) (filter pred))))) (defspec select-pos-extreme-pred (for-all+ [v (gen/vector gen/int) pred (gen/elements [odd? even?]) pos (gen/elements [[s/FIRST first] [s/LAST last]])] (= (select-one [(s/filterer pred) (first pos)] v) (->> v (filter pred) ((last pos)))))) (defspec select-all-on-map (for-all+ [m (limit-size 5 (gen/map gen/keyword gen/int)) p (gen/elements [s/MAP-VALS [s/ALL s/LAST]])] (= (select p m) (for [[k v] m] v)))) (deftest select-one-test (is (thrown? #?(:clj Exception :cljs js/Error) (select-one [s/ALL even?] [1 2 3 4]))) (is (= 1 (select-one [s/ALL odd?] [2 4 1 6])))) (deftest select-first-test (is (= 7 (select-first [(s/filterer odd?) s/ALL #(> % 4)] [3 4 2 3 7 5 9 8]))) (is (nil? (select-first [s/ALL even?] [1 3 5 9])))) (defspec transform-all-on-map (for-all+ [m (limit-size 5 (gen/map gen/keyword gen/int)) p (gen/elements [s/MAP-VALS [s/ALL s/LAST]])] (= (transform p inc m) (into {} (for [[k v] m] [k (inc v)]))))) (defspec transform-all (for-all+ [v (gen/vector gen/int)] (let [v2 (transform [s/ALL] inc v)] (and (vector? v2) (= v2 (map inc v)))))) (defspec transform-all-list (for-all+ [v (gen/list gen/int)] (let [v2 (transform [s/ALL] inc v)] (and (seq? v2) (= v2 (map inc v)))))) (defspec transform-all-filter (for-all+ [v (gen/vector gen/int) pred (gen/elements [odd? even?]) action (gen/elements [inc dec])] (let [v2 (transform [s/ALL pred] action v)] (= v2 (map (fn [v] (if (pred v) (action v) v)) v))))) (defspec transform-last (for-all+ [v (gen/not-empty (gen/vector gen/int)) pred (gen/elements [inc dec])] (let [v2 (transform [s/LAST] pred v)] (= v2 (concat (butlast v) [(pred (last v))]))))) (defspec transform-first (for-all+ [v (gen/not-empty (gen/vector gen/int)) pred (gen/elements [inc dec])] (let [v2 (transform [s/FIRST] pred v)] (= v2 (concat [(pred (first v))] (rest v)))))) (defspec transform-filterer-all-equivalency (prop/for-all [s (gen/vector gen/int) target-type (gen/elements ['() []]) pred (gen/elements [even? odd?]) updater (gen/elements [inc dec])] (let [v (into target-type s) v2 (transform [(s/filterer pred) s/ALL] updater v) v3 (transform [s/ALL pred] updater v)] (and (= v2 v3) (= (type v2) (type v3)))))) (defspec transform-with-context (for-all+ [kw1 gen/keyword kw2 gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw1 kw2)) pred (gen/elements [odd? even?])] (= (transform [(s/collect-one kw2) kw1 pred] + m) (if (pred (kw1 m)) (assoc m kw1 (+ (kw1 m) (kw2 m))) m)))) (defn differing-elements [v1 v2] (->> (map vector v1 v2) (map-indexed (fn [i [e1 e2]] (if (not= e1 e2) i))) (filter identity))) (defspec transform-last-compound (for-all+ [pred (gen/elements [odd? even?]) v (gen/such-that #(some pred %) (gen/vector gen/int))] (let [v2 (transform [(s/filterer pred) s/LAST] inc v) differing-elems (differing-elements v v2)] (and (= (count v2) (count v)) (= (count differing-elems) 1) (every? (complement pred) (drop (first differing-elems) v2)))))) ;; max sizes prevent too much data from being generated and keeps test from taking forever (defspec transform-keyword (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m1 (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1)) pred (gen/elements [inc dec])] (let [m2 (transform [k1 k2] pred m1)] (and (= (assoc-in m1 [k1 k2] nil) (assoc-in m2 [k1 k2] nil)) (= (pred (get-in m1 [k1 k2])) (get-in m2 [k1 k2])))))) (defspec replace-in-test (for-all+ [v (gen/vector gen/int)] (let [res (->> v (map (fn [v] (if (even? v) (inc v) v)))) user-ret (->> v (filter even?) (map (fn [v] [v v])) (apply concat)) user-ret (if (empty? user-ret) nil user-ret)] (= (replace-in [s/ALL even?] (fn [v] [(inc v) [v v]]) v) [res user-ret])))) (defspec replace-in-custom-merge (for-all+ [v (gen/vector gen/int)] (let [res (->> v (map (fn [v] (if (even? v) (inc v) v)))) last-even (->> v (filter even?) last) user-ret (if last-even {:a last-even})] (= (replace-in [s/ALL even?] (fn [v] [(inc v) v]) v :merge-fn (fn [curr new] (assoc curr :a new))) [res user-ret])))) (defspec srange-extremes-test (for-all+ [v (gen/vector gen/int) v2 (gen/vector gen/int)] (let [b (setval s/BEGINNING v2 v) e (setval s/END v2 v)] (and (= b (concat v2 v)) (= e (concat v v2)))))) (defspec srange-test (for-all+ [v (gen/vector gen/int) b (gen/elements (-> v count inc range)) e (gen/elements (range b (-> v count inc)))] (let [sv (subvec v b e) predcount (fn [pred v] (->> v (filter pred) count)) even-count (partial predcount even?) odd-count (partial predcount odd?) b (transform (s/srange b e) (fn [r] (filter odd? r)) v)] (and (= (odd-count v) (odd-count b)) (= (+ (even-count b) (even-count sv)) (even-count v)))))) (deftest structure-path-directly-test (is (= 3 (select-one :b {:a 1 :b 3}))) (is (= 5 (select-one (s/comp-paths :a :b) {:a {:b 5}})))) (deftest atom-test (let [v (transform s/ATOM inc (atom 1))] (is (instance? #?(:clj clojure.lang.Atom :cljs cljs.core/Atom) v)) (is (= 2 (select-one s/ATOM v) @v)))) (defspec view-test (for-all+ [i gen/int afn (gen/elements [inc dec])] (= (first (select (s/view afn) i)) (afn i) (transform (s/view afn) identity i)))) (defspec must-test (for-all+ [k1 gen/int k2 (gen/such-that #(not= k1 %) gen/int) m (gen-map-with-keys gen/int gen/int k1) op (gen/elements [inc dec])] (let [m (dissoc m k2)] (and (= (transform (s/must k1) op m) (transform (s/keypath k1) op m)) (= (transform (s/must k2) op m) m) (= (select (s/must k1) m) (select (s/keypath k1) m)) (empty? (select (s/must k2) m)))))) (defspec parser-test (for-all+ [i gen/int afn (gen/elements [inc dec #(* % 2)]) bfn (gen/elements [inc dec #(* % 2)]) cfn (gen/elements [inc dec #(* % 2)])] (and (= (select-one! (s/parser afn bfn) i) (afn i)) (= (transform (s/parser afn bfn) cfn i) (-> i afn cfn bfn))))) (deftest selected?-test (is (= [[1 3 5] [2 :a] [7 11 4 2 :a] [10 1 :a] []] (setval [s/ALL (s/selected? s/ALL even?) s/END] [:a] [[1 3 5] [2] [7 11 4 2] [10 1] []]))) (is (= [2 4] (select [s/ALL (s/selected? even?)] [1 2 3 4]))) (is (= [1 3] (select [s/ALL (s/not-selected? even?)] [1 2 3 4])))) (defspec identity-test (for-all+ [i gen/int afn (gen/elements [inc dec])] (and (= [i] (select nil i)) (= (afn i) (transform nil afn i))))) (deftest nil-comp-test (is (= [5] (select (com.rpl.specter.impl/comp-paths* nil) 5)))) (defspec putval-test (for-all+ [kw gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw)) c gen/int] (= (transform [(s/putval c) kw] + m) (transform [kw (s/putval c)] + m) (assoc m kw (+ c (get m kw)))))) (defspec empty-selector-test (for-all+ [v (gen/vector gen/int)] (= [v] (select [] v) (select nil v) (select (s/comp-paths) v) (select (s/comp-paths nil) v) (select [nil nil nil] v)))) (defspec empty-selector-transform-test (for-all+ [kw gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw))] (and (= m (transform nil identity m) (transform [] identity m) (transform (s/comp-paths []) identity m) (transform (s/comp-paths nil nil) identity m)) (= (transform kw inc m) (transform [nil kw] inc m) (transform (s/comp-paths kw nil) inc m) (transform (s/comp-paths nil kw nil) inc m))))) (deftest compose-empty-comp-path-test (let [m {:a 1}] (is (= [1] (select [:a (s/comp-paths)] m) (select [(s/comp-paths) :a] m))))) (defspec mixed-selector-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1))] (= [(-> m k1 k2)] (select [k1 (s/comp-paths k2)] m) (select [(s/comp-paths k1) k2] m) (select [(s/comp-paths k1 k2) nil] m) (select [(s/comp-paths) k1 k2] m) (select [k1 (s/comp-paths) k2] m)))) (deftest cond-path-test (is (= [4 2 6 8 10] (select [s/ALL (s/cond-path even? [(s/view inc) (s/view inc)] #(= 3 %) (s/view dec))] [1 2 3 4 5 6 7 8]))) (is (empty? (select (s/if-path odd? (s/view inc)) 2))) (is (= [6 2 10 6 14] (transform [(s/putval 2) s/ALL (s/if-path odd? [(s/view inc) (s/view inc)] (s/view dec))] * [1 2 3 4 5]))) (is (= 2 (transform [(s/putval 2) (s/if-path odd? (s/view inc))] * 2)))) (defspec cond-path-selector-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) k3 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2 k3)) pred (gen/elements [odd? even?])] (let [v1 (get m k1) k (if (pred v1) k2 k3)] (and (= (transform (s/if-path [k1 pred] k2 k3) inc m) (transform k inc m)) (= (select (s/if-path [k1 pred] k2 k3) m) (select k m)))))) (deftest optimized-if-path-test (is (= [-4 -2] (select [s/ALL (s/if-path [even? neg?] s/STAY)] [1 2 -3 -4 0 -2]))) (is (= [1 2 -3 4 0 2] (transform [s/ALL (s/if-path [even? neg?] s/STAY)] - [1 2 -3 -4 0 -2])))) (defspec multi-path-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2))] (= (transform (s/multi-path k1 k2) inc m) (->> m (transform k1 inc) (transform k2 inc))))) (deftest empty-pos-transform (is (empty? (select s/FIRST []))) (is (empty? (select s/LAST []))) (is (= [] (transform s/FIRST inc []))) (is (= [] (transform s/LAST inc [])))) (defspec set-filter-test (for-all+ [k1 gen/keyword k2 (gen/such-that #(not= k1 %) gen/keyword) k3 (gen/such-that (complement #{k1 k2}) gen/keyword) v (gen/vector (gen/elements [k1 k2 k3]))] (= (filter #{k1 k2} v) (select [s/ALL #{k1 k2}] v)))) (deftest nil-select-one-test (is (= nil (select-one! s/ALL [nil]))) (is (thrown? #?(:clj Exception :cljs js/Error) (select-one! s/ALL [])))) (defspec transformed-test (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?]) op (gen/elements [inc dec])] (= (select-one (s/transformed [s/ALL pred] op) v) (transform [s/ALL pred] op v)))) (defspec basic-parameterized-composition-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m1 (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1)) pred (gen/elements [inc dec])] (let [p (dynamicnav [a b] (path (s/keypath a) (s/keypath b)))] (and (= (s/compiled-select (p k1 k2) m1) (select [k1 k2] m1)) (= (s/compiled-transform (p k1 k2) pred m1) (transform [k1 k2] pred m1)))))) (defspec filterer-param-test (for-all+ [k gen/keyword k2 gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int k k2))) pred (gen/elements [odd? even?]) updater (gen/elements [inc dec])] (and (= (select (s/filterer (s/keypath k) pred) v) (select (s/filterer k pred) v)) (= (transform [(s/filterer (s/keypath k) pred) s/ALL k2] updater v) (transform [(s/filterer k pred) s/ALL k2] updater v))))) (deftest nested-param-paths (let [p (fn [a b c] (path (s/filterer (s/keypath a) (s/selected? s/ALL (s/keypath b) (s/filterer (s/keypath c) even?) s/ALL)))) p2 (p :a :b :c) p3 (s/filterer :a (s/selected? s/ALL :b (s/filterer :c even?) s/ALL)) data [{:a [{:b [{:c 4 :d 5}]}]} {:a [{:c 3}]} {:a [{:b [{:c 7}] :e [1]}]}]] (is (= (select p2 data) (select p3 data) [[{:a [{:b [{:c 4 :d 5}]}]}]])))) (defspec subselect-nested-vectors (for-all+ [v1 (gen/vector (gen/vector gen/int))] (let [path (s/comp-paths (s/subselect s/ALL s/ALL)) v2 (s/compiled-transform path reverse v1)] (and (= (s/compiled-select path v1) [(flatten v1)]) (= (flatten v1) (reverse (flatten v2))) (= (map count v1) (map count v2)))))) (defspec subselect-param-test (for-all+ [k gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int k)))] (and (= (s/compiled-select (s/subselect s/ALL (s/keypath k)) v) [(map k v)]) (let [v2 (s/compiled-transform (s/comp-paths (s/subselect s/ALL (s/keypath k))) reverse v)] (and (= (map k v) (reverse (map k v2))) (= (map #(dissoc % k) v) (map #(dissoc % k) v2))))))) ; only key k was touched in any of the maps (defspec param-multi-path-test (for-all+ [k1 gen/keyword k2 gen/keyword k3 gen/keyword m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2 k3)) pred1 (gen/elements [odd? even?]) pred2 (gen/elements [odd? even?]) updater (gen/elements [inc dec])] (let [paths [(path (s/multi-path [(s/keypath k1) pred1] [(s/keypath k2) pred2] k3)) (path (s/multi-path [k1 pred1] [(s/keypath k2) pred2] (s/keypath k3))) (path (s/multi-path [(s/keypath k1) pred1] [(s/keypath k2) pred2] (s/keypath k3))) (s/multi-path [k1 pred1] [k2 pred2] k3) (path (s/multi-path [k1 pred1] [(s/keypath k2) pred2] k3))]] (and (apply = (for [p paths] (select p m))) (apply = (for [p paths] (transform p updater m))))))) (defspec subset-test (for-all+ [s1 (gen/vector (limit-size 5 gen/keyword)) s2 (gen/vector (limit-size 5 gen/keyword)) s3 (gen/vector (limit-size 5 gen/int)) s4 (gen/vector (limit-size 5 gen/keyword))] (let [s1 (set s1) s2 (set s1) s3 (set s1) s4 (set s1) combined (set/union s1 s2) ss (set/union s2 s3)] (and (= (transform (s/subset s3) identity combined) combined) (= (setval (s/subset s3) #{} combined) (set/difference combined s2)) (= (setval (s/subset s3) s4 combined) (-> combined (set/difference s2) (set/union s4))))))) (deftest submap-test (is (= [{:foo 1}] (select [(s/submap [:foo :baz])] {:foo 1 :bar 2}))) (is (= {:foo 1, :barry 1} (setval [(s/submap [:bar])] {:barry 1} {:foo 1 :bar 2}))) (is (= {:bar 1, :foo 2} (transform [(s/submap [:foo :baz]) s/ALL s/LAST] inc {:foo 1 :bar 1}))) (is (= {:a {:new 1} :c {:new 1 :old 1}} (setval [s/ALL s/LAST (s/submap [])] {:new 1} {:a nil, :c {:old 1}})))) (deftest nil->val-test (is (= {:a #{:b}} (setval [:a s/NIL->SET (s/subset #{})] #{:b} nil))) (is (= {:a #{:b :c :d}} (setval [:a s/NIL->SET (s/subset #{})] #{:b} {:a #{:c :d}}))) (is (= {:a [:b]} (setval [:a s/NIL->VECTOR s/END] [:b] nil)))) (defspec void-test (for-all+ [s1 (gen/vector (limit-size 5 gen/int))] (and (empty? (select s/STOP s1)) (empty? (select [s/STOP s/ALL s/ALL s/ALL s/ALL] s1)) (= s1 (transform s/STOP inc s1)) (= s1 (transform [s/ALL s/STOP s/ALL] inc s1)) (= (transform [s/ALL (s/cond-path even? nil odd? s/STOP)] inc s1) (transform [s/ALL even?] inc s1))))) (deftest stay-continue-tests (is (= [[1 2 [:a :b]] [3 [:a :b]] [:a :b [:a :b]]] (setval [(s/stay-then-continue s/ALL) s/END] [[:a :b]] [[1 2] [3]]))) (is (= [[1 2 [:a :b]] [3 [:a :b]] [:a :b]] (setval [(s/continue-then-stay s/ALL) s/END] [[:a :b]] [[1 2] [3]]))) (is (= [[1 2 3] 1 3] (select (s/stay-then-continue s/ALL odd?) [1 2 3]))) (is (= [1 3 [1 2 3]] (select (s/continue-then-stay s/ALL odd?) [1 2 3])))) (declarepath MyWalker) (providepath MyWalker (s/if-path vector? (s/if-path [s/FIRST #(= :abc %)] (s/continue-then-stay s/ALL MyWalker) [s/ALL MyWalker]))) (deftest recursive-path-test (is (= [9 1 10 3 1] (select [MyWalker s/ALL number?] [:bb [:aa 34 [:abc 10 [:ccc 9 8 [:abc 9 1]]]] [:abc 1 [:abc 3]]]))) (is (= [:bb [:aa 34 [:abc 11 [:ccc 9 8 [:abc 10 2]]]] [:abc 2 [:abc 4]]] (transform [MyWalker s/ALL number?] inc [:bb [:aa 34 [:abc 10 [:ccc 9 8 [:abc 9 1]]]] [:abc 1 [:abc 3]]])))) (def map-key-walker (recursive-path [akey] p [s/ALL (s/if-path [s/FIRST #(= % akey)] s/LAST [s/LAST p])])) (deftest recursive-params-path-test (is (= #{1 2 3} (set (select (map-key-walker :aaa) {:a {:aaa 3 :b {:c {:aaa 2} :aaa 1}}})))) (is (= {:a {:aaa 4 :b {:c {:aaa 3} :aaa 2}}} (transform (map-key-walker :aaa) inc {:a {:aaa 3 :b {:c {:aaa 2} :aaa 1}}}))) (is (= {:a {:c {:b "X"}}} (setval (map-key-walker :b) "X" {:a {:c {:b {:d 1}}}})))) (deftest recursive-params-composable-path-test (let [p (fn [k k2] (path (s/keypath k) (map-key-walker k2)))] (is (= [1] (select (p 1 :a) [{:a 3} {:a 1} {:a 2}]))))) (deftest all-map-test (is (= {3 3} (transform [s/ALL s/FIRST] inc {2 3}))) (is (= {3 21 4 31} (transform [s/ALL s/ALL] inc {2 20 3 30})))) (def NestedHigherOrderWalker (recursive-path [k] p (s/if-path vector? (s/if-path [s/FIRST #(= % k)] (s/continue-then-stay s/ALL p) [s/ALL p])))) (deftest nested-higher-order-walker-test (is (= [:q [:abc :I 3] [:ccc [:abc :I] [:abc :I "a" [:abc :I [:abc :I [:d]]]]]] (setval [(NestedHigherOrderWalker :abc) (s/srange 1 1)] [:I] [:q [:abc 3] [:ccc [:abc] [:abc "a" [:abc [:abc [:d]]]]]])))) #?(:clj (deftest large-params-test (let [path (apply com.rpl.specter.impl/comp-navs (for [i (range 25)] (s/keypath i))) m (reduce (fn [m k] {k m}) :a (reverse (range 25)))] (is (= :a (select-one path m)))))) ;;TODO: there's a bug in clojurescript that won't allow ;; non function implementations of IFn to have more than 20 arguments #?(:clj (do (defprotocolpath AccountPath []) (defrecord Account [funds]) (defrecord User [account]) (defrecord Family [accounts]) (extend-protocolpath AccountPath User :account Family [:accounts s/ALL]))) #?(:clj (deftest protocolpath-basic-test (let [data [(->User (->Account 30)) (->User (->Account 50)) (->Family [(->Account 51) (->Account 52)])]] (is (= [30 50 51 52] (select [s/ALL AccountPath :funds] data))) (is (= [(->User (->Account 31)) (->User (->Account 51)) (->Family [(->Account 52) (->Account 53)])] (transform [s/ALL AccountPath :funds] inc data)))))) #?(:clj (do (defprotocolpath LabeledAccountPath [label]) (defrecord LabeledUser [account]) (defrecord LabeledFamily [accounts]) (extend-protocolpath LabeledAccountPath LabeledUser [:account (s/keypath label)] LabeledFamily [:accounts (s/keypath label) s/ALL]))) #?(:clj (deftest protocolpath-params-test (let [data [(->LabeledUser {:a (->Account 30)}) (->LabeledUser {:a (->Account 50)}) (->LabeledFamily {:a [(->Account 51) (->Account 52)]})]] (is (= [30 50 51 52] (select [s/ALL (LabeledAccountPath :a) :funds] data))) (is (= [(->LabeledUser {:a (->Account 31)}) (->LabeledUser {:a (->Account 51)}) (->LabeledFamily {:a [(->Account 52) (->Account 53)]})] (transform [s/ALL (LabeledAccountPath :a) :funds] inc data)))))) #?(:clj (do (defprotocolpath CustomWalker []) (extend-protocolpath CustomWalker Object nil clojure.lang.PersistentHashMap [(s/keypath :a) CustomWalker] clojure.lang.PersistentArrayMap [(s/keypath :a) CustomWalker] clojure.lang.PersistentVector [s/ALL CustomWalker]))) #?(:clj (deftest mixed-rich-regular-protocolpath (is (= [1 2 3 11 21 22 25] (select [CustomWalker number?] [{:a [1 2 :c [3]]} [[[[[[11]]] 21 [22 :c 25]]]]]))) (is (= [2 3 [[[4]] :b 0] {:a 4 :b 10}] (transform [CustomWalker number?] inc [1 2 [[[3]] :b -1] {:a 3 :b 10}]))))) #?( :clj (defn make-queue [coll] (reduce #(conj %1 %2) clojure.lang.PersistentQueue/EMPTY coll)) :cljs (defn make-queue [coll] (reduce #(conj %1 %2) #queue [] coll))) (defspec transform-idempotency 50 (for-all+ [v1 (gen/vector gen/int) l1 (gen/list gen/int) m1 (gen/map gen/keyword gen/int)] (let [s1 (set v1) q1 (make-queue v1) v2 (transform s/ALL identity v1) m2 (transform s/ALL identity m1) s2 (transform s/ALL identity s1) l2 (transform s/ALL identity l1) q2 (transform s/ALL identity q1)] (and (= v1 v2) (= (type v1) (type v2)) (= m1 m2) (= (type m1) (type m2)) (= s1 s2) (= (type s1) (type s2)) (= l1 l2) (seq? l2) ; Transformed lists are only guaranteed to impelment ISeq (= q1 q2) (= (type q1) (type q2)))))) (defn ^:direct-nav double-str-keypath [s1 s2] (path (s/keypath (str s1 s2)))) (defn ^:direct-nav some-keypath ([] (s/keypath "a")) ([k1] (s/keypath (str k1 "!"))) ([k & args] (s/keypath "bbb"))) (deftest nav-constructor-test ;; this also tests that the eval done by clj platform during inline ;; caching rebinds to the correct namespace since this is run ;; by clojure.test in a different namespace (is (= 1 (select-one! (double-str-keypath "a" "b") {"ab" 1 "c" 2}))) (is (= 1 (select-one! (some-keypath) {"a" 1 "a!" 2 "bbb" 3 "d" 4}))) (is (= 2 (select-one! (some-keypath "a") {"a" 1 "a!" 2 "bbb" 3 "d" 4}))) (is (= 3 (select-one! (some-keypath 1 2 3 4 5) {"a" 1 "a!" 2 "bbb" 3 "d" 4})))) (def ^:dynamic *APATH* s/keypath) (deftest inline-caching-test (ic-test [k] [s/ALL (s/must k)] inc [{:a 1} {:b 2 :c 3} {:a 7 :d -1}] [[:a] [:b] [:c] [:d] [:e]]) (ic-test [] [s/ALL #{4 5 11} #(> % 2) (fn [e] (< e 7))] inc (range 20) []) (ic-test [v] (if v :a :b) inc {:a 1 :b 2} [[true] [false]]) (ic-test [v] [s/ALL (double-str-keypath v (inc v))] str [{"12" :a "1011" :b} {"1011" :c}] [[1] [10]]) (ic-test [k] (*APATH* k) str {:a 1 :b 2} [[:a] [:b] [:c]]) (binding [*APATH* s/must] (ic-test [k] (*APATH* k) inc {:a 1 :b 2} [[:a] [:b] [:c]])) (ic-test [k k2] [s/ALL (s/selected? (s/must k) #(> % 2)) (s/must k2)] dec [{:a 1 :b 2} {:a 10 :b 6} {:c 7 :b 8} {:c 1 :d 9} {:c 3 :d -1}] [[:a :b] [:b :a] [:c :d] [:b :c]]) (ic-test [] [(s/transformed s/STAY inc)] inc 10 []) ;; verifying that these don't throw errors (is (= 1 (select-any (if true :a :b) {:a 1}))) (is (= 3 (select-any (*APATH* :a) {:a 3}))) (is (= 2 (select-any [:a (identity even?)] {:a 2}))) (is (= [10 11] (select-one! [(s/putval 10) (s/transformed s/STAY #(inc %))] 10))) (is (= 2 (let [p :a] (select-one! [p even?] {:a 2})))) (is (= [{:a 2}] (let [p :a] (select [s/ALL (s/selected? p even?)] [{:a 2}]))))) (deftest nested-inline-caching-test (is (= [[1]] (let [a :b] (select (s/view (fn [v] (select [(s/keypath v) (s/keypath a)] {:a {:b 1}}))) :a))))) (defspec continuous-subseqs-filter-equivalence (for-all+ [aseq (gen/vector (gen/elements [1 2 3 :a :b :c 4 5 :d :e])) pred (gen/elements [keyword? number?])] (= (setval (s/continuous-subseqs pred) nil aseq) (filter (complement pred) aseq)))) (deftest continuous-subseqs-test (is (= [1 "ab" 2 3 "c" 4 "def"] (transform (s/continuous-subseqs string?) (fn [s] [(apply str s)]) [1 "a" "b" 2 3 "c" 4 "d" "e" "f"]))) (is (= [[] [2] [4 6]] (select [(s/continuous-subseqs number?) (s/filterer even?)] [1 "a" "b" 2 3 "c" 4 5 6 "d" "e" "f"])))) ;; verifies that late binding of dynamic parameters works correctly (deftest transformed-inline-caching (dotimes [i 10] (is (= [(inc i)] (select (s/transformed s/STAY #(+ % i)) 1))))) ;; test for issue #103 (deftest nil->val-regression-test (is (= false (transform (s/nil->val true) identity false))) (is (= false (select-one! (s/nil->val true) false)))) #?(:clj (deftest all-map-entry (let [e (transform s/ALL inc (first {1 3}))] (is (instance? clojure.lang.MapEntry e)) (is (= 2 (key e))) (is (= 4 (val e)))))) (deftest select-on-empty-vector (is (= s/NONE (select-any s/ALL []))) (is (nil? (select-first s/ALL []))) (is (nil? (select-one s/ALL []))) (is (= s/NONE (select-any s/FIRST []))) (is (= s/NONE (select-any s/LAST []))) (is (nil? (select-first s/FIRST []))) (is (nil? (select-one s/FIRST []))) (is (nil? (select-first s/LAST []))) (is (nil? (select-one s/LAST [])))) (defspec select-first-one-any-equivalency (for-all+ [aval gen/int apred (gen/elements [even? odd?])] (let [data [aval] r1 (select-any [s/ALL (s/pred apred)] data) r2 (select-first [s/ALL (s/pred apred)] data) r3 (select-one [s/ALL (s/pred apred)] data) r4 (first (select [s/ALL (s/pred apred)] data)) r5 (select-any [s/FIRST (s/pred apred)] data) r6 (select-any [s/LAST (s/pred apred)] data)] (or (and (= r1 s/NONE) (nil? r2) (nil? r3) (nil? r4) (= r5 s/NONE) (= r6 s/NONE)) (and (not= r1 s/NONE) (some? r1) (= r1 r2 r3 r4 r5 r6)))))) (deftest select-any-static-fn (is (= 2 (select-any even? 2))) (is (= s/NONE (select-any odd? 2)))) (deftest select-any-keywords (is (= s/NONE (select-any [:a even?] {:a 1}))) (is (= 2 (select-any [:a even?] {:a 2}))) (is (= s/NONE (select-any [(s/keypath "a") even?] {"a" 1}))) (is (= 2 (select-any [(s/keypath "a") even?] {"a" 2}))) (is (= s/NONE (select-any (s/must :b) {:a 1 :c 3}))) (is (= 2 (select-any (s/must :b) {:a 1 :b 2 :c 3}))) (is (= s/NONE (select-any [(s/must :b) odd?] {:a 1 :b 2 :c 3})))) (defspec select-any-ALL (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (let [r1 (select [s/ALL pred] v) r2 (select-any [s/ALL pred] v)] (or (and (empty? r1) (= s/NONE r2)) (contains? (set r1) r2))))) (deftest select-any-beginning-end (is (= [] (select-any s/BEGINNING [1 2 3]) (select-any s/END [1]))) (is (= s/NONE (select-any [s/BEGINNING s/STOP] [1 2 3]) (select-any [s/END s/STOP] [2 3])))) (deftest select-any-walker (let [data [1 [2 3 4] [[6]]]] (is (= s/NONE (select-any (s/walker keyword?) data))) (is (= s/NONE (select-any [(s/walker number?) neg?] data))) (is (#{1 3} (select-any [(s/walker number?) odd?] data))) (is (#{2 4 6} (select-any [(s/walker number?) even?] data))))) (defspec selected-any?-select-equivalence (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (let [r1 (not (empty? (select [s/ALL pred] v))) r2 (selected-any? [s/ALL pred] v)] (= r1 r2)))) (defn div-by-3? [v] (= 0 (mod v 3))) (defspec selected?-filter-equivalence (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (and (= (select-any [s/ALL pred] v) (select-any [s/ALL (s/selected? pred)] v)) (= (select-any [s/ALL pred div-by-3?] v) (select-any [s/ALL (s/selected? pred) div-by-3?] v))))) (deftest multi-path-select-any-test (is (= s/NONE (select-any (s/multi-path s/STOP s/STOP) 1))) (is (= 1 (select-any (s/multi-path s/STAY s/STOP) 1) (select-any (s/multi-path s/STOP s/STAY) 1) (select-any (s/multi-path s/STOP s/STAY s/STOP) 1))) (is (= s/NONE (select-any [(s/multi-path s/STOP s/STAY) even?] 1)))) (deftest if-path-select-any-test (is (= s/NONE (select-any (s/if-path even? s/STAY) 1))) (is (= 2 (select-any (s/if-path even? s/STAY s/STAY) 2))) (is (= s/NONE (select-any [(s/if-path even? s/STAY s/STAY) odd?] 2))) (is (= 2 (select-any (s/if-path odd? s/STOP s/STAY) 2))) (is (= s/NONE (select-any [(s/if-path odd? s/STOP s/STAY) odd?] 2)))) (defspec transient-vector-test (for-all+ [v (gen/vector (limit-size 5 gen/int))] (every? identity (for [[path transient-path f] [[s/FIRST t/FIRST! (fnil inc 0)] ;; fnil in case vector is empty [s/LAST t/LAST! (fnil inc 0)] [(s/keypath 0) (t/keypath! 0) (fnil inc 0)] [s/END t/END! #(conj % 1 2 3)]]] (and (= (s/transform* path f v) (persistent! (s/transform* transient-path f (transient v)))) (= (s/select* path v) (s/select* transient-path (transient v)))))))) (defspec transient-map-test (for-all+ [m (limit-size 5 (gen/not-empty (gen/map gen/keyword gen/int))) new-key gen/keyword] (let [existing-key (first (keys m))] (every? identity (for [[path transient-path f] [[(s/keypath existing-key) (t/keypath! existing-key) inc] [(s/keypath new-key) (t/keypath! new-key) (constantly 3)] [(s/submap [existing-key new-key]) (t/submap! [existing-key new-key]) (constantly {new-key 1234})]]] (and (= (s/transform* path f m) (persistent! (s/transform* transient-path f (transient m)))) (= (s/select* path m) (s/select* transient-path (transient m))))))))) (defspec meta-test (for-all+ [v (gen/vector gen/int) meta-map (limit-size 5 (gen/map gen/keyword gen/int))] (= meta-map (meta (setval s/META meta-map v)) (first (select s/META (with-meta v meta-map))) (first (select s/META (setval s/META meta-map v)))))) (deftest beginning-end-all-first-last-on-nil (is (= [2 3] (setval s/END [2 3] nil) (setval s/BEGINNING [2 3] nil))) (is (nil? (setval s/FIRST :a nil))) (is (nil? (setval s/LAST :a nil))) (is (nil? (transform s/ALL inc nil))) (is (empty? (select s/FIRST nil))) (is (empty? (select s/LAST nil))) (is (empty? (select s/ALL nil)))) (deftest map-vals-nil (is (= nil (transform s/MAP-VALS inc nil))) (is (empty? (select s/MAP-VALS nil)))) (defspec dispense-test (for-all+ [k1 gen/int k2 gen/int k3 gen/int m (gen-map-with-keys gen/int gen/int k1 k2 k3)] (= (select [(s/collect-one (s/keypath k1)) (s/collect-one (s/keypath k2)) s/DISPENSE (s/collect-one (s/keypath k2)) (s/keypath k3)] m) (select [(s/collect-one (s/keypath k2)) (s/keypath k3)] m)))) (deftest collected?-test (let [data {:active-id 1 :items [{:id 1 :name "a"} {:id 2 :name "b"}]}] (is (= {:id 1 :name "a"} (select-any [(s/collect-one :active-id) :items s/ALL (s/collect-one :id) (collected? [a i] (= a i)) s/DISPENSE] data) (select-any [(s/collect-one :active-id) :items s/ALL (s/collect-one :id) (collected? v (apply = v)) s/DISPENSE] data)))) (let [data {:active 3 :items [{:id 1 :val 0} {:id 3 :val 11}]}] (is (= (transform [:items s/ALL (s/selected? :id #(= % 3)) :val] inc data) (transform [(s/collect-one :active) :items s/ALL (s/collect-one :id) (collected? [a i] (= a i)) s/DISPENSE :val] inc data))))) (defspec traverse-test (for-all+ [v (gen/vector gen/int) p (gen/elements [odd? even?]) i gen/int] (and (= (reduce + (traverse [s/ALL p] v)) (reduce + (filter p v))) (= (reduce + i (traverse [s/ALL p] v)) (reduce + i (filter p v)))))) (def KeyAccumWalker (recursive-path [k] p (s/if-path (s/must k) s/STAY [s/ALL (s/collect-one s/FIRST) s/LAST p]))) (deftest recursive-if-path-select-vals-test (let [data {"e1" {"e2" {"e1" {:template 1} "e2" {:template 2}}}}] (is (= [["e1" "e2" "e1" {:template 1}] ["e1" "e2" "e2" {:template 2}]] (select (KeyAccumWalker :template) data))) (is (= {"e1" {"e2" {"e1" "e1e2e1" "e2" "e1e2e2"}}} (transform (KeyAccumWalker :template) (fn [& all] (apply str (butlast all))) data))))) (deftest multi-path-vals-test (is (= {:a 1 :b 6 :c 3} (transform [(s/multi-path (s/collect-one :a) (s/collect-one :c)) :b] + {:a 1 :b 2 :c 3}))) (is (= [[1 2] [3 2]] (select [(s/multi-path (s/collect-one :a) (s/collect-one :c)) :b] {:a 1 :b 2 :c 3})))) (deftest sorted-map-by-transform (let [amap (sorted-map-by > 1 10 2 20 3 30)] (is (= [3 2 1] (keys (transform s/MAP-VALS inc amap)))) (is (= [3 2 1] (keys (transform [s/ALL s/LAST] inc amap)))))) (deftest setval-vals-collection-test (is (= 2 (setval s/VAL 2 :a)))) (defspec multi-transform-test (for-all+ [kw1 gen/keyword kw2 gen/keyword m (limit-size 5 (gen-map-with-keys gen/keyword gen/int kw1 kw2))] (= (->> m (transform [(s/keypath kw1) s/VAL] +) (transform (s/keypath kw2) dec)) (multi-transform (s/multi-path [(s/keypath kw1) s/VAL (s/terminal +)] [(s/keypath kw2) (s/terminal dec)]) m)))) (deftest multi-transform-overrun-error (is (thrown? #?(:clj Exception :cljs js/Error) (multi-transform s/STAY 3)))) (deftest terminal-val-test (is (= 3 (multi-transform (s/terminal-val 3) 2))) (is (= 3 (multi-transform [s/VAL (s/terminal-val 3)] 2)))) (deftest multi-path-order-test (is (= 102 (multi-transform (s/multi-path [odd? (s/terminal #(* 2 %))] [even? (s/terminal-val 100)] [#(= 100 %) (s/terminal inc)] [#(= 101 %) (s/terminal inc)]) 1)))) (defdynamicnav ignorer [a] s/STAY) (deftest dynamic-nav-ignores-dynamic-arg (let [a 1] (is (= 1 (select-any (ignorer a) 1))) (is (= 1 (select-any (ignorer :a) 1))))) (deftest nested-dynamic-nav (let [data {:a {:a 1 :b 2} :b {:a 3 :b 4}} afn (fn [a b] (select-any (s/selected? (s/must a) (s/selected? (s/must b))) data))] (is (= data (afn :a :a))) (is (= s/NONE (afn :a :c))) (is (= data (afn :a :b))) (is (= s/NONE (afn :c :a))) (is (= data (afn :b :a))) (is (= data (afn :b :b))))) (deftest duplicate-map-keys-test (let [res (setval [s/ALL s/FIRST] "a" {:a 1 :b 2})] (is (= {"a" 2} res)) (is (= 1 (count res))))) (deftest inline-caching-vector-params-test (is (= [10 [11]] (multi-transform (s/terminal-val [10 [11]]) :a)))) (defn eachnav-fn-test [akey data] (select-any (s/keypath "a" akey) data)) (deftest eachnav-test (let [data {"a" {"b" 1 "c" 2}}] (is (= 1 (eachnav-fn-test "b" data))) (is (= 2 (eachnav-fn-test "c" data))) )) (deftest traversed-test (is (= 10 (select-any (s/traversed s/ALL +) [1 2 3 4])))) (defn- predand= [pred v1 v2] (and (pred v1) (pred v2) (= v1 v2))) (defn listlike? [v] (or (list? v) (seq? v))) (deftest nthpath-test (is (predand= vector? [1 2 -3 4] (transform (s/nthpath 2) - [1 2 3 4]))) (is (predand= vector? [1 2 4] (setval (s/nthpath 2) s/NONE [1 2 3 4]))) (is (predand= (complement vector?) '(1 -2 3 4) (transform (s/nthpath 1) - '(1 2 3 4)))) (is (predand= (complement vector?) '(1 2 4) (setval (s/nthpath 2) s/NONE '(1 2 3 4)))) (is (= [0 1 [2 4 4]] (transform (s/nthpath 2 1) inc [0 1 [2 3 4]]))) ) (deftest remove-with-NONE-test (is (predand= vector? [1 2 3] (setval [s/ALL nil?] s/NONE [1 2 nil 3 nil]))) (is (predand= listlike? '(1 2 3) (setval [s/ALL nil?] s/NONE '(1 2 nil 3 nil)))) (is (= {:b 2} (setval :a s/NONE {:a 1 :b 2}))) (is (= {:b 2} (setval (s/must :a) s/NONE {:a 1 :b 2}))) (is (predand= vector? [1 3] (setval (s/keypath 1) s/NONE [1 2 3]))) ;; test with PersistentArrayMap (is (= {:a 1 :c 3} (setval [s/MAP-VALS even?] s/NONE {:a 1 :b 2 :c 3 :d 4}))) (is (= {:a 1 :c 3} (setval [s/ALL (s/selected? s/LAST even?)] s/NONE {:a 1 :b 2 :c 3 :d 4}))) ;; test with PersistentHashMap (let [m (into {} (for [i (range 500)] [i i]))] (is (= (dissoc m 31) (setval [s/MAP-VALS #(= 31 %)] s/NONE m))) (is (= (dissoc m 31) (setval [s/ALL (s/selected? s/LAST #(= 31 %))] s/NONE m))) )) (deftest fresh-collected-test (let [data [{:a 1 :b 2} {:a 3 :b 3}]] (is (= [[{:a 1 :b 2} 2]] (select [s/ALL s/VAL (s/with-fresh-collected (s/collect-one :a) (s/collected? [a] (= a 1))) :b] data))) (is (= [{:a 1 :b 3} {:a 3 :b 3}] (transform [s/ALL s/VAL (s/with-fresh-collected (s/collect-one :a) (s/collected? [a] (= a 1))) :b] (fn [m v] (+ (:a m) v)) data ))) )) (deftest traverse-all-test (is (= 3 (transduce (comp (mapcat identity) (traverse-all :a)) (completing (fn [r i] (if (= i 4) (reduced r) (+ r i)))) 0 [[{:a 1}] [{:a 2}] [{:a 4}] [{:a 5}]]))) (is (= 6 (transduce (traverse-all [s/ALL :a]) + 0 [[{:a 1} {:a 2}] [{:a 3}]] ))) (is (= [1 2] (into [] (traverse-all :a) [{:a 1} {:a 2}]))) ) (deftest early-terminate-traverse-test (is (= 6 (reduce (completing (fn [r i] (if (> r 5) (reduced r) (+ r i)))) 0 (traverse [s/ALL s/ALL] [[1 2] [3 4] [5]]))))) (deftest select-any-vals-test (is (= [1 1] (select-any s/VAL 1)))) (deftest conditional-vals-test (is (= 2 (select-any (s/with-fresh-collected (s/collect-one (s/keypath 0)) (s/if-path (collected? [n] (even? n)) (s/keypath 1) (s/keypath 2))) [4 2 3]))) (is (= [4 2 3] (select-any (s/with-fresh-collected (s/collect-one (s/keypath 0)) (s/selected? (collected? [n] (even? n)))) [4 2 3]))) ) (deftest name-namespace-test (is (= :a (setval s/NAME "a" :e))) (is (= :a/b (setval s/NAME "b" :a/e))) (is (= 'a (setval s/NAME "a" 'e))) (is (= 'a/b (setval s/NAME "b" 'a/e))) (is (= :a/e (setval s/NAMESPACE "a" :e))) (is (= :a/e (setval s/NAMESPACE "a" :f/e))) (is (= 'a/e (setval s/NAMESPACE "a" 'e))) (is (= 'a/e (setval s/NAMESPACE "a" 'f/e))) ) (deftest string-navigation-test (is (= "ad" (setval (s/srange 1 3) "" "abcd"))) (is (= "abcxd" (setval [(s/srange 1 3) s/END] "x" "abcd"))) (is (= "bc" (select-any (s/srange 1 3) "abcd"))) (is (= "ab" (setval s/END "b" "a"))) (is (= "ba" (setval s/BEGINNING "b" "a"))) (is (= "" (select-any s/BEGINNING "abc"))) (is (= "" (select-any s/END "abc"))) (is (= \a (select-any s/FIRST "abc"))) (is (= \c (select-any s/LAST "abc"))) (is (= "qbc" (setval s/FIRST \q "abc"))) (is (= "abq" (setval s/LAST "q" "abc"))) ) (deftest regex-navigation-test ;; also test regexes as implicit navs (is (= (select #"t" "test") ["t" "t"])) (is (= (select [:a (s/regex-nav #"t")] {:a "test"}) ["t" "t"])) (is (= (transform (s/regex-nav #"t") clojure.string/capitalize "test") "TesT")) ;; also test regexes as implicit navs (is (= (transform [:a #"t"] clojure.string/capitalize {:a "test"}) {:a "TesT"})) (is (= (transform (s/regex-nav #"\s+\w") clojure.string/triml "Hello World!") "HelloWorld!")) (is (= (setval (s/regex-nav #"t") "z" "test") "zesz")) (is (= (setval [:a (s/regex-nav #"t")] "z" {:a "test"}) {:a "zesz"})) (is (= (transform (s/regex-nav #"aa*") (fn [s] (-> s count str)) "aadt") "2dt")) (is (= (transform (s/regex-nav #"[Aa]+") (fn [s] (apply str (take (count s) (repeat "@")))) "<NAME>") "@msterd@m @@rdv@rks")) (is (= (select [(s/regex-nav #"(\S+):\ (\d+)") (s/nthpath 2)] "<NAME>: 1st George: 2nd Arthur: 3rd") ["1" "2" "3"])) (is (= (transform (s/subselect (s/regex-nav #"\d\w+")) reverse "<NAME>: 1st George: 2nd Arthur: 3rd") "<NAME>: 3rd George: 2nd Arthur: 1st")) ) (deftest single-value-none-navigators-test (is (predand= vector? [1 2 3] (setval s/AFTER-ELEM 3 [1 2]))) (is (predand= listlike? '(1 2 3) (setval s/AFTER-ELEM 3 '(1 2)))) (is (predand= listlike? '(1) (setval s/AFTER-ELEM 1 nil))) (is (predand= vector? [3 1 2] (setval s/BEFORE-ELEM 3 [1 2]))) (is (predand= listlike? '(3 1 2) (setval s/BEFORE-ELEM 3 '(1 2)))) (is (predand= listlike? '(1) (setval s/BEFORE-ELEM 1 nil))) (is (= #{1 2 3} (setval s/NONE-ELEM 3 #{1 2}))) (is (= #{1} (setval s/NONE-ELEM 1 nil))) ) (deftest subvec-test (let [v (subvec [1] 0)] (is (predand= vector? [2] (transform s/FIRST inc v))) (is (predand= vector? [2] (transform s/LAST inc v))) (is (predand= vector? [2] (transform s/ALL inc v))) (is (predand= vector? [0 1] (setval s/BEGINNING [0] v))) (is (predand= vector? [1 0] (setval s/END [0] v))) (is (predand= vector? [0 1] (setval s/BEFORE-ELEM 0 v))) (is (predand= vector? [1 0] (setval s/AFTER-ELEM 0 v))) (is (predand= vector? [1 0] (setval (s/srange 1 1) [0] v))) )) (defspec map-keys-all-first-equivalence-transform (for-all+ [m (limit-size 10 (gen/map gen/int gen/keyword))] (= (transform s/MAP-KEYS inc m) (transform [s/ALL s/FIRST] inc m ) ))) (defspec map-keys-all-first-equivalence-select (for-all+ [m (limit-size 10 (gen/map gen/int gen/keyword))] (= (select s/MAP-KEYS m) (select [s/ALL s/FIRST] m) ))) (defspec remove-first-vector (for-all+ [v (limit-size 10 (gen/not-empty (gen/vector gen/int)))] (let [newv (setval s/FIRST s/NONE v)] (and (= newv (vec (rest v))) (vector? newv) )))) (defspec remove-first-list (for-all+ [l (limit-size 10 (gen/not-empty (gen/list gen/int)))] (let [newl (setval s/FIRST s/NONE l)] (and (= newl (rest l)) (listlike? newl) )))) (defspec remove-last-vector (for-all+ [v (limit-size 10 (gen/not-empty (gen/vector gen/int)))] (let [newv (setval s/LAST s/NONE v)] (and (= newv (vec (butlast v))) (vector? newv) )))) (defspec remove-last-list (for-all+ [l (limit-size 10 (gen/not-empty (gen/list gen/int)))] (let [newl (setval s/LAST s/NONE l) bl (butlast l)] (and (or (= newl bl) (and (nil? bl) (= '() newl))) (seq? newl) )))) (deftest remove-extreme-string (is (= "b" (setval s/FIRST s/NONE "ab"))) (is (= "a" (setval s/LAST s/NONE "ab"))) ) (deftest nested-dynamic-arg-test (let [foo (fn [v] (multi-transform (s/terminal-val [v]) nil))] (is (= [1] (foo 1))) (is (= [10] (foo 10))) )) (deftest filterer-remove-test (is (= [1 :a 3 5] (setval (s/filterer even?) [:a] [1 2 3 4 5]))) (is (= [1 3 5] (setval (s/filterer even?) [] [1 2 3 4 5]))) (is (= [1 3 5] (setval (s/filterer even?) nil [1 2 3 4 5]))) ) (deftest helper-preds-test (let [data [1 2 2 3 4 0]] (is (= [2 2] (select [s/ALL (s/pred= 2)] data))) (is (= [1 2 2 0] (select [s/ALL (s/pred< 3)] data))) (is (= [1 2 2 3 0] (select [s/ALL (s/pred<= 3)] data))) (is (= [4] (select [s/ALL (s/pred> 3)] data))) (is (= [3 4] (select [s/ALL (s/pred>= 3)] data))) )) (deftest map-key-test (is (= {:c 3} (setval (s/map-key :a) :b {:c 3}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2 :b 1}))) (is (= {:b 2} (setval (s/map-key :a) s/NONE {:a 1 :b 2}))) ) (deftest set-elem-test (is (= #{:b :d} (setval (s/set-elem :a) :x #{:b :d}))) (is (= #{:x :a} (setval (s/set-elem :b) :x #{:b :a}))) (is (= #{:a} (setval (s/set-elem :b) :a #{:b :a}))) (is (= #{:b} (setval (s/set-elem :a) s/NONE #{:a :b}))) ) ;; this function necessary to trigger the bug from happening (defn inc2 [v] (inc v)) (deftest dynamic-function-arg-test (is (= {[2] 4} (let [a 1] (transform (s/keypath [(inc2 a)]) inc {[2] 3})))) ) (defrecord FooW [a b]) (deftest walker-test (is (= [1 2 3 4 5 6] (select (s/walker number?) [{1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (is (= [{:b '(:c)} #{:d}] (setval (s/walker number?) s/NONE [{:q 3 10 :l 1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (is (= [{:q 4 11 :l 2 3 :b '(4 :c 5)} 6 #{7 :d}] (transform (s/walker number?) inc [{:q 3 10 :l 1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (let [f (->FooW 1 2)] (is (= [[:a 1] [:b 2]] (select (s/walker (complement record?)) f))) (is (= (assoc f :a! 1 :b! 2) (setval [(s/walker (complement record?)) s/FIRST s/NAME s/END] "!" f))) (is (= (assoc f :b 1 :c 2) (transform [(s/walker (complement record?)) s/FIRST] (fn [k] (if (= :a k) :b :c)) f))) )) (def MIDDLE (s/comp-paths (s/srange-dynamic (fn [aseq] (long (/ (count aseq) 2))) (end-fn [aseq s] (if (empty? aseq) 0 (inc s)))) s/FIRST )) (deftest srange-dynamic-test (is (= 2 (select-any MIDDLE [1 2 3]))) (is (identical? s/NONE (select-any MIDDLE []))) (is (= 1 (select-any MIDDLE [1]))) (is (= 2 (select-any MIDDLE [1 2]))) (is (= [1 3 3] (transform MIDDLE inc [1 2 3]))) ) (def ^:dynamic *dvar* :a) (defn dvar-tester [] (select-any *dvar* {:a 1 :b 2})) (deftest dynamic-var-ic-test (is (= 1 (dvar-tester))) (is (= 2 (binding [*dvar* :b] (dvar-tester)))) ) (deftest before-index-test (let [data [1 2 3] datal '(1 2 3) data-str "abcdef"] (is (predand= vector? [:a 1 2 3] (setval (s/before-index 0) :a data))) (is (predand= vector? [1 2 3] (setval (s/before-index 1) s/NONE data))) (is (predand= vector? [1 :a 2 3] (setval (s/before-index 1) :a data))) (is (predand= vector? [1 2 3 :a] (setval (s/before-index 3) :a data))) ; ensure inserting at index 0 in nil structure works, as in previous impl (is (predand= listlike? '(:a) (setval (s/before-index 0) :a nil))) (is (predand= listlike? '(:a 1 2 3) (setval (s/before-index 0) :a datal))) (is (predand= listlike? '(1 :a 2 3) (setval (s/before-index 1) :a datal))) (is (predand= listlike? '(1 2 3 :a) (setval (s/before-index 3) :a datal))) (is (predand= string? "abcxdef" (setval (s/before-index 3) (char \x) data-str))) )) (deftest index-nav-test (let [data [1 2 3 4 5 6] datal '(1 2 3 4 5 6)] (is (predand= vector? [3 1 2 4 5 6] (setval (s/index-nav 2) 0 data))) (is (predand= vector? [1 3 2 4 5 6] (setval (s/index-nav 2) 1 data))) (is (predand= vector? [1 2 3 4 5 6] (setval (s/index-nav 2) 2 data))) (is (predand= vector? [1 2 4 5 3 6] (setval (s/index-nav 2) 4 data))) (is (predand= vector? [1 2 4 5 6 3] (setval (s/index-nav 2) 5 data))) (is (predand= vector? [6 1 2 3 4 5] (setval (s/index-nav 5) 0 data))) (is (predand= listlike? '(3 1 2 4 5 6) (setval (s/index-nav 2) 0 datal))) (is (predand= listlike? '(1 3 2 4 5 6) (setval (s/index-nav 2) 1 datal))) (is (predand= listlike? '(1 2 3 4 5 6) (setval (s/index-nav 2) 2 datal))) (is (predand= listlike? '(1 2 4 5 3 6) (setval (s/index-nav 2) 4 datal))) (is (predand= listlike? '(1 2 4 5 6 3) (setval (s/index-nav 2) 5 datal))) (is (predand= listlike? '(6 1 2 3 4 5) (setval (s/index-nav 5) 0 datal))) )) (deftest indexed-vals-test (let [data [:a :b :c :d :e]] (is (= [[0 :a] [1 :b] [2 :c] [3 :d] [4 :e]] (select s/INDEXED-VALS data))) (is (= [:e :d :c :b :a] (setval [s/INDEXED-VALS s/FIRST] 0 data))) (is (= [:a :b :e :d :c] (setval [s/INDEXED-VALS s/FIRST] 2 data))) (is (= [:b :a :d :c :e] (transform [s/INDEXED-VALS s/FIRST odd?] dec data))) (is (= [:a :b :c :d :e] (transform [s/INDEXED-VALS s/FIRST odd?] inc data))) (is (= [0 2 2 4] (transform [s/INDEXED-VALS s/LAST odd?] inc [0 1 2 3]))) (is (= [0 1 2 3] (transform [s/INDEXED-VALS (s/collect-one s/LAST) s/FIRST] (fn [i _] i) [2 1 3 0]))) (is (= [-1 0 1 2 3] (transform [(s/indexed-vals -1) (s/collect-one s/LAST) s/FIRST] (fn [i _] i) [3 -1 0 2 1]))) (is (= [[1 :a] [2 :b] [3 :c]] (select (s/indexed-vals 1) [:a :b :c]))) )) (deftest other-implicit-navs-test (is (= 1 (select-any ["a" true \c 10 'd] {"a" {true {\c {10 {'d 1}}}}}))) ) (deftest vterminal-test (is (= {:a {:b [[1 2] 3]}} (multi-transform [(s/putval 1) :a (s/putval 2) :b (s/vterminal (fn [vs v] [vs v]))] {:a {:b 3}}))) ) (deftest vtransform-test (is (= {:a 6} (vtransform [:a (s/putval 2) (s/putval 3)] (fn [vs v] (+ v (reduce + vs))) {:a 1}))) ) (deftest compact-test (is (= {} (setval [:a (s/compact :b :c)] s/NONE {:a {:b {:c 1}}}))) (is (= {:a {:d 2}} (setval [:a (s/compact :b :c)] s/NONE {:a {:b {:c 1} :d 2}}))) (let [TREE-VALUES (recursive-path [] p (s/if-path vector? [(s/compact s/ALL) p] s/STAY)) tree [1 [2 3] [] [4 [[5] [[6]]]]]] (is (= [2 4 6] (select [TREE-VALUES even?] tree))) (is (= [1 [3] [[[5]]]] (setval [TREE-VALUES even?] s/NONE tree))) ) (is (= [{:a [{:c 1}]}] (setval [s/ALL (s/compact :a s/ALL :b)] s/NONE [{:a [{:b 3}]} {:a [{:b 2 :c 1}]}]))) ) (deftest class-constant-test (let [f (fn [p] (fn [v] (str p (inc v))))] (is (= (str #?(:clj String :cljs js/String) 2) (multi-transform (s/terminal (f #?(:clj String :cljs js/String))) 1))) )) #?(:clj (do (defprotocolpath FooPP) (extend-protocolpath FooPP String s/STAY) (deftest satisfies-protpath-test (is (satisfies-protpath? FooPP "a")) (is (not (satisfies-protpath? FooPP 1))) ))) (deftest sorted-test (let [initial-list [3 4 2 1]] (testing "the SORTED navigator" (is (= (sort initial-list) (select-one s/SORTED initial-list))) (is (= [2 1 3 4] (transform s/SORTED reverse initial-list))) (is (= [3 2 1] (transform s/SORTED butlast initial-list))) (is (= [3 5 2 1] (setval [s/SORTED s/LAST] 5 initial-list))) (is (= (list 1 2 3 4 5) (transform [s/SORTED s/ALL] inc (range 5))))) (testing "the sorted navigator with comparator" (let [reverse-comparator (comp - compare)] (is (= (sort reverse-comparator initial-list) (select-one (s/sorted reverse-comparator) initial-list))) (is (= 4 (select-one [(s/sorted reverse-comparator) s/FIRST] initial-list)))))) (testing "the sorted-by navigator with keypath" (let [initial-list [{:a 3} {:a 4} {:a 2} {:a 1}]] (is (= (sort-by :a initial-list) (select-one (s/sorted-by :a) initial-list))) (is (= {:a 4} (select-one [(s/sorted-by :a (comp - compare)) s/FIRST] initial-list))))))
true
(ns com.rpl.specter.core-test #?(:cljs (:require-macros [cljs.test :refer [is deftest testing]] [clojure.test.check.clojure-test :refer [defspec]] [com.rpl.specter.cljs-test-helpers :refer [for-all+]] [com.rpl.specter.test-helpers :refer [ic-test]] [com.rpl.specter :refer [defprotocolpath defnav extend-protocolpath nav declarepath providepath select select-one select-one! select-first transform setval replace-in select-any selected-any? collected? traverse multi-transform path dynamicnav recursive-path defdynamicnav traverse-all satisfies-protpath? end-fn vtransform]])) (:use #?(:clj [clojure.test :only [deftest is testing]]) #?(:clj [clojure.test.check.clojure-test :only [defspec]]) #?(:clj [com.rpl.specter.test-helpers :only [for-all+ ic-test]]) #?(:clj [com.rpl.specter :only [defprotocolpath defnav extend-protocolpath nav declarepath providepath select select-one select-one! select-first transform setval replace-in select-any selected-any? collected? traverse multi-transform path dynamicnav recursive-path defdynamicnav traverse-all satisfies-protpath? end-fn vtransform]])) (:require #?(:clj [clojure.test.check.generators :as gen]) #?(:clj [clojure.test.check.properties :as prop]) #?(:cljs [clojure.test.check :as tc]) #?(:cljs [clojure.test.check.generators :as gen]) #?(:cljs [clojure.test.check.properties :as prop :include-macros true]) [com.rpl.specter :as s] [com.rpl.specter.transients :as t] [clojure.set :as set])) ;;TODO: ;; test walk, codewalk (defn limit-size [n {gen :gen}] (gen/->Generator (fn [rnd _size] (gen rnd (if (< _size n) _size n))))) (defn gen-map-with-keys [key-gen val-gen & keys] (gen/bind (gen/map key-gen val-gen) (fn [m] (gen/bind (apply gen/hash-map (mapcat (fn [k] [k val-gen]) keys)) (fn [m2] (gen/return (merge m m2))))))) (defspec select-all-keyword-filter (for-all+ [kw gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int kw))) pred (gen/elements [odd? even?])] (= (select [s/ALL kw pred] v) (->> v (map kw) (filter pred))))) (defspec select-pos-extreme-pred (for-all+ [v (gen/vector gen/int) pred (gen/elements [odd? even?]) pos (gen/elements [[s/FIRST first] [s/LAST last]])] (= (select-one [(s/filterer pred) (first pos)] v) (->> v (filter pred) ((last pos)))))) (defspec select-all-on-map (for-all+ [m (limit-size 5 (gen/map gen/keyword gen/int)) p (gen/elements [s/MAP-VALS [s/ALL s/LAST]])] (= (select p m) (for [[k v] m] v)))) (deftest select-one-test (is (thrown? #?(:clj Exception :cljs js/Error) (select-one [s/ALL even?] [1 2 3 4]))) (is (= 1 (select-one [s/ALL odd?] [2 4 1 6])))) (deftest select-first-test (is (= 7 (select-first [(s/filterer odd?) s/ALL #(> % 4)] [3 4 2 3 7 5 9 8]))) (is (nil? (select-first [s/ALL even?] [1 3 5 9])))) (defspec transform-all-on-map (for-all+ [m (limit-size 5 (gen/map gen/keyword gen/int)) p (gen/elements [s/MAP-VALS [s/ALL s/LAST]])] (= (transform p inc m) (into {} (for [[k v] m] [k (inc v)]))))) (defspec transform-all (for-all+ [v (gen/vector gen/int)] (let [v2 (transform [s/ALL] inc v)] (and (vector? v2) (= v2 (map inc v)))))) (defspec transform-all-list (for-all+ [v (gen/list gen/int)] (let [v2 (transform [s/ALL] inc v)] (and (seq? v2) (= v2 (map inc v)))))) (defspec transform-all-filter (for-all+ [v (gen/vector gen/int) pred (gen/elements [odd? even?]) action (gen/elements [inc dec])] (let [v2 (transform [s/ALL pred] action v)] (= v2 (map (fn [v] (if (pred v) (action v) v)) v))))) (defspec transform-last (for-all+ [v (gen/not-empty (gen/vector gen/int)) pred (gen/elements [inc dec])] (let [v2 (transform [s/LAST] pred v)] (= v2 (concat (butlast v) [(pred (last v))]))))) (defspec transform-first (for-all+ [v (gen/not-empty (gen/vector gen/int)) pred (gen/elements [inc dec])] (let [v2 (transform [s/FIRST] pred v)] (= v2 (concat [(pred (first v))] (rest v)))))) (defspec transform-filterer-all-equivalency (prop/for-all [s (gen/vector gen/int) target-type (gen/elements ['() []]) pred (gen/elements [even? odd?]) updater (gen/elements [inc dec])] (let [v (into target-type s) v2 (transform [(s/filterer pred) s/ALL] updater v) v3 (transform [s/ALL pred] updater v)] (and (= v2 v3) (= (type v2) (type v3)))))) (defspec transform-with-context (for-all+ [kw1 gen/keyword kw2 gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw1 kw2)) pred (gen/elements [odd? even?])] (= (transform [(s/collect-one kw2) kw1 pred] + m) (if (pred (kw1 m)) (assoc m kw1 (+ (kw1 m) (kw2 m))) m)))) (defn differing-elements [v1 v2] (->> (map vector v1 v2) (map-indexed (fn [i [e1 e2]] (if (not= e1 e2) i))) (filter identity))) (defspec transform-last-compound (for-all+ [pred (gen/elements [odd? even?]) v (gen/such-that #(some pred %) (gen/vector gen/int))] (let [v2 (transform [(s/filterer pred) s/LAST] inc v) differing-elems (differing-elements v v2)] (and (= (count v2) (count v)) (= (count differing-elems) 1) (every? (complement pred) (drop (first differing-elems) v2)))))) ;; max sizes prevent too much data from being generated and keeps test from taking forever (defspec transform-keyword (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m1 (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1)) pred (gen/elements [inc dec])] (let [m2 (transform [k1 k2] pred m1)] (and (= (assoc-in m1 [k1 k2] nil) (assoc-in m2 [k1 k2] nil)) (= (pred (get-in m1 [k1 k2])) (get-in m2 [k1 k2])))))) (defspec replace-in-test (for-all+ [v (gen/vector gen/int)] (let [res (->> v (map (fn [v] (if (even? v) (inc v) v)))) user-ret (->> v (filter even?) (map (fn [v] [v v])) (apply concat)) user-ret (if (empty? user-ret) nil user-ret)] (= (replace-in [s/ALL even?] (fn [v] [(inc v) [v v]]) v) [res user-ret])))) (defspec replace-in-custom-merge (for-all+ [v (gen/vector gen/int)] (let [res (->> v (map (fn [v] (if (even? v) (inc v) v)))) last-even (->> v (filter even?) last) user-ret (if last-even {:a last-even})] (= (replace-in [s/ALL even?] (fn [v] [(inc v) v]) v :merge-fn (fn [curr new] (assoc curr :a new))) [res user-ret])))) (defspec srange-extremes-test (for-all+ [v (gen/vector gen/int) v2 (gen/vector gen/int)] (let [b (setval s/BEGINNING v2 v) e (setval s/END v2 v)] (and (= b (concat v2 v)) (= e (concat v v2)))))) (defspec srange-test (for-all+ [v (gen/vector gen/int) b (gen/elements (-> v count inc range)) e (gen/elements (range b (-> v count inc)))] (let [sv (subvec v b e) predcount (fn [pred v] (->> v (filter pred) count)) even-count (partial predcount even?) odd-count (partial predcount odd?) b (transform (s/srange b e) (fn [r] (filter odd? r)) v)] (and (= (odd-count v) (odd-count b)) (= (+ (even-count b) (even-count sv)) (even-count v)))))) (deftest structure-path-directly-test (is (= 3 (select-one :b {:a 1 :b 3}))) (is (= 5 (select-one (s/comp-paths :a :b) {:a {:b 5}})))) (deftest atom-test (let [v (transform s/ATOM inc (atom 1))] (is (instance? #?(:clj clojure.lang.Atom :cljs cljs.core/Atom) v)) (is (= 2 (select-one s/ATOM v) @v)))) (defspec view-test (for-all+ [i gen/int afn (gen/elements [inc dec])] (= (first (select (s/view afn) i)) (afn i) (transform (s/view afn) identity i)))) (defspec must-test (for-all+ [k1 gen/int k2 (gen/such-that #(not= k1 %) gen/int) m (gen-map-with-keys gen/int gen/int k1) op (gen/elements [inc dec])] (let [m (dissoc m k2)] (and (= (transform (s/must k1) op m) (transform (s/keypath k1) op m)) (= (transform (s/must k2) op m) m) (= (select (s/must k1) m) (select (s/keypath k1) m)) (empty? (select (s/must k2) m)))))) (defspec parser-test (for-all+ [i gen/int afn (gen/elements [inc dec #(* % 2)]) bfn (gen/elements [inc dec #(* % 2)]) cfn (gen/elements [inc dec #(* % 2)])] (and (= (select-one! (s/parser afn bfn) i) (afn i)) (= (transform (s/parser afn bfn) cfn i) (-> i afn cfn bfn))))) (deftest selected?-test (is (= [[1 3 5] [2 :a] [7 11 4 2 :a] [10 1 :a] []] (setval [s/ALL (s/selected? s/ALL even?) s/END] [:a] [[1 3 5] [2] [7 11 4 2] [10 1] []]))) (is (= [2 4] (select [s/ALL (s/selected? even?)] [1 2 3 4]))) (is (= [1 3] (select [s/ALL (s/not-selected? even?)] [1 2 3 4])))) (defspec identity-test (for-all+ [i gen/int afn (gen/elements [inc dec])] (and (= [i] (select nil i)) (= (afn i) (transform nil afn i))))) (deftest nil-comp-test (is (= [5] (select (com.rpl.specter.impl/comp-paths* nil) 5)))) (defspec putval-test (for-all+ [kw gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw)) c gen/int] (= (transform [(s/putval c) kw] + m) (transform [kw (s/putval c)] + m) (assoc m kw (+ c (get m kw)))))) (defspec empty-selector-test (for-all+ [v (gen/vector gen/int)] (= [v] (select [] v) (select nil v) (select (s/comp-paths) v) (select (s/comp-paths nil) v) (select [nil nil nil] v)))) (defspec empty-selector-transform-test (for-all+ [kw gen/keyword m (limit-size 10 (gen-map-with-keys gen/keyword gen/int kw))] (and (= m (transform nil identity m) (transform [] identity m) (transform (s/comp-paths []) identity m) (transform (s/comp-paths nil nil) identity m)) (= (transform kw inc m) (transform [nil kw] inc m) (transform (s/comp-paths kw nil) inc m) (transform (s/comp-paths nil kw nil) inc m))))) (deftest compose-empty-comp-path-test (let [m {:a 1}] (is (= [1] (select [:a (s/comp-paths)] m) (select [(s/comp-paths) :a] m))))) (defspec mixed-selector-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1))] (= [(-> m k1 k2)] (select [k1 (s/comp-paths k2)] m) (select [(s/comp-paths k1) k2] m) (select [(s/comp-paths k1 k2) nil] m) (select [(s/comp-paths) k1 k2] m) (select [k1 (s/comp-paths) k2] m)))) (deftest cond-path-test (is (= [4 2 6 8 10] (select [s/ALL (s/cond-path even? [(s/view inc) (s/view inc)] #(= 3 %) (s/view dec))] [1 2 3 4 5 6 7 8]))) (is (empty? (select (s/if-path odd? (s/view inc)) 2))) (is (= [6 2 10 6 14] (transform [(s/putval 2) s/ALL (s/if-path odd? [(s/view inc) (s/view inc)] (s/view dec))] * [1 2 3 4 5]))) (is (= 2 (transform [(s/putval 2) (s/if-path odd? (s/view inc))] * 2)))) (defspec cond-path-selector-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) k3 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2 k3)) pred (gen/elements [odd? even?])] (let [v1 (get m k1) k (if (pred v1) k2 k3)] (and (= (transform (s/if-path [k1 pred] k2 k3) inc m) (transform k inc m)) (= (select (s/if-path [k1 pred] k2 k3) m) (select k m)))))) (deftest optimized-if-path-test (is (= [-4 -2] (select [s/ALL (s/if-path [even? neg?] s/STAY)] [1 2 -3 -4 0 -2]))) (is (= [1 2 -3 4 0 2] (transform [s/ALL (s/if-path [even? neg?] s/STAY)] - [1 2 -3 -4 0 -2])))) (defspec multi-path-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2))] (= (transform (s/multi-path k1 k2) inc m) (->> m (transform k1 inc) (transform k2 inc))))) (deftest empty-pos-transform (is (empty? (select s/FIRST []))) (is (empty? (select s/LAST []))) (is (= [] (transform s/FIRST inc []))) (is (= [] (transform s/LAST inc [])))) (defspec set-filter-test (for-all+ [k1 gen/keyword k2 (gen/such-that #(not= k1 %) gen/keyword) k3 (gen/such-that (complement #{k1 k2}) gen/keyword) v (gen/vector (gen/elements [k1 k2 k3]))] (= (filter #{k1 k2} v) (select [s/ALL #{k1 k2}] v)))) (deftest nil-select-one-test (is (= nil (select-one! s/ALL [nil]))) (is (thrown? #?(:clj Exception :cljs js/Error) (select-one! s/ALL [])))) (defspec transformed-test (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?]) op (gen/elements [inc dec])] (= (select-one (s/transformed [s/ALL pred] op) v) (transform [s/ALL pred] op v)))) (defspec basic-parameterized-composition-test (for-all+ [k1 (limit-size 3 gen/keyword) k2 (limit-size 3 gen/keyword) m1 (limit-size 5 (gen-map-with-keys gen/keyword (gen-map-with-keys gen/keyword gen/int k2) k1)) pred (gen/elements [inc dec])] (let [p (dynamicnav [a b] (path (s/keypath a) (s/keypath b)))] (and (= (s/compiled-select (p k1 k2) m1) (select [k1 k2] m1)) (= (s/compiled-transform (p k1 k2) pred m1) (transform [k1 k2] pred m1)))))) (defspec filterer-param-test (for-all+ [k gen/keyword k2 gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int k k2))) pred (gen/elements [odd? even?]) updater (gen/elements [inc dec])] (and (= (select (s/filterer (s/keypath k) pred) v) (select (s/filterer k pred) v)) (= (transform [(s/filterer (s/keypath k) pred) s/ALL k2] updater v) (transform [(s/filterer k pred) s/ALL k2] updater v))))) (deftest nested-param-paths (let [p (fn [a b c] (path (s/filterer (s/keypath a) (s/selected? s/ALL (s/keypath b) (s/filterer (s/keypath c) even?) s/ALL)))) p2 (p :a :b :c) p3 (s/filterer :a (s/selected? s/ALL :b (s/filterer :c even?) s/ALL)) data [{:a [{:b [{:c 4 :d 5}]}]} {:a [{:c 3}]} {:a [{:b [{:c 7}] :e [1]}]}]] (is (= (select p2 data) (select p3 data) [[{:a [{:b [{:c 4 :d 5}]}]}]])))) (defspec subselect-nested-vectors (for-all+ [v1 (gen/vector (gen/vector gen/int))] (let [path (s/comp-paths (s/subselect s/ALL s/ALL)) v2 (s/compiled-transform path reverse v1)] (and (= (s/compiled-select path v1) [(flatten v1)]) (= (flatten v1) (reverse (flatten v2))) (= (map count v1) (map count v2)))))) (defspec subselect-param-test (for-all+ [k gen/keyword v (gen/vector (limit-size 5 (gen-map-with-keys gen/keyword gen/int k)))] (and (= (s/compiled-select (s/subselect s/ALL (s/keypath k)) v) [(map k v)]) (let [v2 (s/compiled-transform (s/comp-paths (s/subselect s/ALL (s/keypath k))) reverse v)] (and (= (map k v) (reverse (map k v2))) (= (map #(dissoc % k) v) (map #(dissoc % k) v2))))))) ; only key k was touched in any of the maps (defspec param-multi-path-test (for-all+ [k1 gen/keyword k2 gen/keyword k3 gen/keyword m (limit-size 5 (gen-map-with-keys gen/keyword gen/int k1 k2 k3)) pred1 (gen/elements [odd? even?]) pred2 (gen/elements [odd? even?]) updater (gen/elements [inc dec])] (let [paths [(path (s/multi-path [(s/keypath k1) pred1] [(s/keypath k2) pred2] k3)) (path (s/multi-path [k1 pred1] [(s/keypath k2) pred2] (s/keypath k3))) (path (s/multi-path [(s/keypath k1) pred1] [(s/keypath k2) pred2] (s/keypath k3))) (s/multi-path [k1 pred1] [k2 pred2] k3) (path (s/multi-path [k1 pred1] [(s/keypath k2) pred2] k3))]] (and (apply = (for [p paths] (select p m))) (apply = (for [p paths] (transform p updater m))))))) (defspec subset-test (for-all+ [s1 (gen/vector (limit-size 5 gen/keyword)) s2 (gen/vector (limit-size 5 gen/keyword)) s3 (gen/vector (limit-size 5 gen/int)) s4 (gen/vector (limit-size 5 gen/keyword))] (let [s1 (set s1) s2 (set s1) s3 (set s1) s4 (set s1) combined (set/union s1 s2) ss (set/union s2 s3)] (and (= (transform (s/subset s3) identity combined) combined) (= (setval (s/subset s3) #{} combined) (set/difference combined s2)) (= (setval (s/subset s3) s4 combined) (-> combined (set/difference s2) (set/union s4))))))) (deftest submap-test (is (= [{:foo 1}] (select [(s/submap [:foo :baz])] {:foo 1 :bar 2}))) (is (= {:foo 1, :barry 1} (setval [(s/submap [:bar])] {:barry 1} {:foo 1 :bar 2}))) (is (= {:bar 1, :foo 2} (transform [(s/submap [:foo :baz]) s/ALL s/LAST] inc {:foo 1 :bar 1}))) (is (= {:a {:new 1} :c {:new 1 :old 1}} (setval [s/ALL s/LAST (s/submap [])] {:new 1} {:a nil, :c {:old 1}})))) (deftest nil->val-test (is (= {:a #{:b}} (setval [:a s/NIL->SET (s/subset #{})] #{:b} nil))) (is (= {:a #{:b :c :d}} (setval [:a s/NIL->SET (s/subset #{})] #{:b} {:a #{:c :d}}))) (is (= {:a [:b]} (setval [:a s/NIL->VECTOR s/END] [:b] nil)))) (defspec void-test (for-all+ [s1 (gen/vector (limit-size 5 gen/int))] (and (empty? (select s/STOP s1)) (empty? (select [s/STOP s/ALL s/ALL s/ALL s/ALL] s1)) (= s1 (transform s/STOP inc s1)) (= s1 (transform [s/ALL s/STOP s/ALL] inc s1)) (= (transform [s/ALL (s/cond-path even? nil odd? s/STOP)] inc s1) (transform [s/ALL even?] inc s1))))) (deftest stay-continue-tests (is (= [[1 2 [:a :b]] [3 [:a :b]] [:a :b [:a :b]]] (setval [(s/stay-then-continue s/ALL) s/END] [[:a :b]] [[1 2] [3]]))) (is (= [[1 2 [:a :b]] [3 [:a :b]] [:a :b]] (setval [(s/continue-then-stay s/ALL) s/END] [[:a :b]] [[1 2] [3]]))) (is (= [[1 2 3] 1 3] (select (s/stay-then-continue s/ALL odd?) [1 2 3]))) (is (= [1 3 [1 2 3]] (select (s/continue-then-stay s/ALL odd?) [1 2 3])))) (declarepath MyWalker) (providepath MyWalker (s/if-path vector? (s/if-path [s/FIRST #(= :abc %)] (s/continue-then-stay s/ALL MyWalker) [s/ALL MyWalker]))) (deftest recursive-path-test (is (= [9 1 10 3 1] (select [MyWalker s/ALL number?] [:bb [:aa 34 [:abc 10 [:ccc 9 8 [:abc 9 1]]]] [:abc 1 [:abc 3]]]))) (is (= [:bb [:aa 34 [:abc 11 [:ccc 9 8 [:abc 10 2]]]] [:abc 2 [:abc 4]]] (transform [MyWalker s/ALL number?] inc [:bb [:aa 34 [:abc 10 [:ccc 9 8 [:abc 9 1]]]] [:abc 1 [:abc 3]]])))) (def map-key-walker (recursive-path [akey] p [s/ALL (s/if-path [s/FIRST #(= % akey)] s/LAST [s/LAST p])])) (deftest recursive-params-path-test (is (= #{1 2 3} (set (select (map-key-walker :aaa) {:a {:aaa 3 :b {:c {:aaa 2} :aaa 1}}})))) (is (= {:a {:aaa 4 :b {:c {:aaa 3} :aaa 2}}} (transform (map-key-walker :aaa) inc {:a {:aaa 3 :b {:c {:aaa 2} :aaa 1}}}))) (is (= {:a {:c {:b "X"}}} (setval (map-key-walker :b) "X" {:a {:c {:b {:d 1}}}})))) (deftest recursive-params-composable-path-test (let [p (fn [k k2] (path (s/keypath k) (map-key-walker k2)))] (is (= [1] (select (p 1 :a) [{:a 3} {:a 1} {:a 2}]))))) (deftest all-map-test (is (= {3 3} (transform [s/ALL s/FIRST] inc {2 3}))) (is (= {3 21 4 31} (transform [s/ALL s/ALL] inc {2 20 3 30})))) (def NestedHigherOrderWalker (recursive-path [k] p (s/if-path vector? (s/if-path [s/FIRST #(= % k)] (s/continue-then-stay s/ALL p) [s/ALL p])))) (deftest nested-higher-order-walker-test (is (= [:q [:abc :I 3] [:ccc [:abc :I] [:abc :I "a" [:abc :I [:abc :I [:d]]]]]] (setval [(NestedHigherOrderWalker :abc) (s/srange 1 1)] [:I] [:q [:abc 3] [:ccc [:abc] [:abc "a" [:abc [:abc [:d]]]]]])))) #?(:clj (deftest large-params-test (let [path (apply com.rpl.specter.impl/comp-navs (for [i (range 25)] (s/keypath i))) m (reduce (fn [m k] {k m}) :a (reverse (range 25)))] (is (= :a (select-one path m)))))) ;;TODO: there's a bug in clojurescript that won't allow ;; non function implementations of IFn to have more than 20 arguments #?(:clj (do (defprotocolpath AccountPath []) (defrecord Account [funds]) (defrecord User [account]) (defrecord Family [accounts]) (extend-protocolpath AccountPath User :account Family [:accounts s/ALL]))) #?(:clj (deftest protocolpath-basic-test (let [data [(->User (->Account 30)) (->User (->Account 50)) (->Family [(->Account 51) (->Account 52)])]] (is (= [30 50 51 52] (select [s/ALL AccountPath :funds] data))) (is (= [(->User (->Account 31)) (->User (->Account 51)) (->Family [(->Account 52) (->Account 53)])] (transform [s/ALL AccountPath :funds] inc data)))))) #?(:clj (do (defprotocolpath LabeledAccountPath [label]) (defrecord LabeledUser [account]) (defrecord LabeledFamily [accounts]) (extend-protocolpath LabeledAccountPath LabeledUser [:account (s/keypath label)] LabeledFamily [:accounts (s/keypath label) s/ALL]))) #?(:clj (deftest protocolpath-params-test (let [data [(->LabeledUser {:a (->Account 30)}) (->LabeledUser {:a (->Account 50)}) (->LabeledFamily {:a [(->Account 51) (->Account 52)]})]] (is (= [30 50 51 52] (select [s/ALL (LabeledAccountPath :a) :funds] data))) (is (= [(->LabeledUser {:a (->Account 31)}) (->LabeledUser {:a (->Account 51)}) (->LabeledFamily {:a [(->Account 52) (->Account 53)]})] (transform [s/ALL (LabeledAccountPath :a) :funds] inc data)))))) #?(:clj (do (defprotocolpath CustomWalker []) (extend-protocolpath CustomWalker Object nil clojure.lang.PersistentHashMap [(s/keypath :a) CustomWalker] clojure.lang.PersistentArrayMap [(s/keypath :a) CustomWalker] clojure.lang.PersistentVector [s/ALL CustomWalker]))) #?(:clj (deftest mixed-rich-regular-protocolpath (is (= [1 2 3 11 21 22 25] (select [CustomWalker number?] [{:a [1 2 :c [3]]} [[[[[[11]]] 21 [22 :c 25]]]]]))) (is (= [2 3 [[[4]] :b 0] {:a 4 :b 10}] (transform [CustomWalker number?] inc [1 2 [[[3]] :b -1] {:a 3 :b 10}]))))) #?( :clj (defn make-queue [coll] (reduce #(conj %1 %2) clojure.lang.PersistentQueue/EMPTY coll)) :cljs (defn make-queue [coll] (reduce #(conj %1 %2) #queue [] coll))) (defspec transform-idempotency 50 (for-all+ [v1 (gen/vector gen/int) l1 (gen/list gen/int) m1 (gen/map gen/keyword gen/int)] (let [s1 (set v1) q1 (make-queue v1) v2 (transform s/ALL identity v1) m2 (transform s/ALL identity m1) s2 (transform s/ALL identity s1) l2 (transform s/ALL identity l1) q2 (transform s/ALL identity q1)] (and (= v1 v2) (= (type v1) (type v2)) (= m1 m2) (= (type m1) (type m2)) (= s1 s2) (= (type s1) (type s2)) (= l1 l2) (seq? l2) ; Transformed lists are only guaranteed to impelment ISeq (= q1 q2) (= (type q1) (type q2)))))) (defn ^:direct-nav double-str-keypath [s1 s2] (path (s/keypath (str s1 s2)))) (defn ^:direct-nav some-keypath ([] (s/keypath "a")) ([k1] (s/keypath (str k1 "!"))) ([k & args] (s/keypath "bbb"))) (deftest nav-constructor-test ;; this also tests that the eval done by clj platform during inline ;; caching rebinds to the correct namespace since this is run ;; by clojure.test in a different namespace (is (= 1 (select-one! (double-str-keypath "a" "b") {"ab" 1 "c" 2}))) (is (= 1 (select-one! (some-keypath) {"a" 1 "a!" 2 "bbb" 3 "d" 4}))) (is (= 2 (select-one! (some-keypath "a") {"a" 1 "a!" 2 "bbb" 3 "d" 4}))) (is (= 3 (select-one! (some-keypath 1 2 3 4 5) {"a" 1 "a!" 2 "bbb" 3 "d" 4})))) (def ^:dynamic *APATH* s/keypath) (deftest inline-caching-test (ic-test [k] [s/ALL (s/must k)] inc [{:a 1} {:b 2 :c 3} {:a 7 :d -1}] [[:a] [:b] [:c] [:d] [:e]]) (ic-test [] [s/ALL #{4 5 11} #(> % 2) (fn [e] (< e 7))] inc (range 20) []) (ic-test [v] (if v :a :b) inc {:a 1 :b 2} [[true] [false]]) (ic-test [v] [s/ALL (double-str-keypath v (inc v))] str [{"12" :a "1011" :b} {"1011" :c}] [[1] [10]]) (ic-test [k] (*APATH* k) str {:a 1 :b 2} [[:a] [:b] [:c]]) (binding [*APATH* s/must] (ic-test [k] (*APATH* k) inc {:a 1 :b 2} [[:a] [:b] [:c]])) (ic-test [k k2] [s/ALL (s/selected? (s/must k) #(> % 2)) (s/must k2)] dec [{:a 1 :b 2} {:a 10 :b 6} {:c 7 :b 8} {:c 1 :d 9} {:c 3 :d -1}] [[:a :b] [:b :a] [:c :d] [:b :c]]) (ic-test [] [(s/transformed s/STAY inc)] inc 10 []) ;; verifying that these don't throw errors (is (= 1 (select-any (if true :a :b) {:a 1}))) (is (= 3 (select-any (*APATH* :a) {:a 3}))) (is (= 2 (select-any [:a (identity even?)] {:a 2}))) (is (= [10 11] (select-one! [(s/putval 10) (s/transformed s/STAY #(inc %))] 10))) (is (= 2 (let [p :a] (select-one! [p even?] {:a 2})))) (is (= [{:a 2}] (let [p :a] (select [s/ALL (s/selected? p even?)] [{:a 2}]))))) (deftest nested-inline-caching-test (is (= [[1]] (let [a :b] (select (s/view (fn [v] (select [(s/keypath v) (s/keypath a)] {:a {:b 1}}))) :a))))) (defspec continuous-subseqs-filter-equivalence (for-all+ [aseq (gen/vector (gen/elements [1 2 3 :a :b :c 4 5 :d :e])) pred (gen/elements [keyword? number?])] (= (setval (s/continuous-subseqs pred) nil aseq) (filter (complement pred) aseq)))) (deftest continuous-subseqs-test (is (= [1 "ab" 2 3 "c" 4 "def"] (transform (s/continuous-subseqs string?) (fn [s] [(apply str s)]) [1 "a" "b" 2 3 "c" 4 "d" "e" "f"]))) (is (= [[] [2] [4 6]] (select [(s/continuous-subseqs number?) (s/filterer even?)] [1 "a" "b" 2 3 "c" 4 5 6 "d" "e" "f"])))) ;; verifies that late binding of dynamic parameters works correctly (deftest transformed-inline-caching (dotimes [i 10] (is (= [(inc i)] (select (s/transformed s/STAY #(+ % i)) 1))))) ;; test for issue #103 (deftest nil->val-regression-test (is (= false (transform (s/nil->val true) identity false))) (is (= false (select-one! (s/nil->val true) false)))) #?(:clj (deftest all-map-entry (let [e (transform s/ALL inc (first {1 3}))] (is (instance? clojure.lang.MapEntry e)) (is (= 2 (key e))) (is (= 4 (val e)))))) (deftest select-on-empty-vector (is (= s/NONE (select-any s/ALL []))) (is (nil? (select-first s/ALL []))) (is (nil? (select-one s/ALL []))) (is (= s/NONE (select-any s/FIRST []))) (is (= s/NONE (select-any s/LAST []))) (is (nil? (select-first s/FIRST []))) (is (nil? (select-one s/FIRST []))) (is (nil? (select-first s/LAST []))) (is (nil? (select-one s/LAST [])))) (defspec select-first-one-any-equivalency (for-all+ [aval gen/int apred (gen/elements [even? odd?])] (let [data [aval] r1 (select-any [s/ALL (s/pred apred)] data) r2 (select-first [s/ALL (s/pred apred)] data) r3 (select-one [s/ALL (s/pred apred)] data) r4 (first (select [s/ALL (s/pred apred)] data)) r5 (select-any [s/FIRST (s/pred apred)] data) r6 (select-any [s/LAST (s/pred apred)] data)] (or (and (= r1 s/NONE) (nil? r2) (nil? r3) (nil? r4) (= r5 s/NONE) (= r6 s/NONE)) (and (not= r1 s/NONE) (some? r1) (= r1 r2 r3 r4 r5 r6)))))) (deftest select-any-static-fn (is (= 2 (select-any even? 2))) (is (= s/NONE (select-any odd? 2)))) (deftest select-any-keywords (is (= s/NONE (select-any [:a even?] {:a 1}))) (is (= 2 (select-any [:a even?] {:a 2}))) (is (= s/NONE (select-any [(s/keypath "a") even?] {"a" 1}))) (is (= 2 (select-any [(s/keypath "a") even?] {"a" 2}))) (is (= s/NONE (select-any (s/must :b) {:a 1 :c 3}))) (is (= 2 (select-any (s/must :b) {:a 1 :b 2 :c 3}))) (is (= s/NONE (select-any [(s/must :b) odd?] {:a 1 :b 2 :c 3})))) (defspec select-any-ALL (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (let [r1 (select [s/ALL pred] v) r2 (select-any [s/ALL pred] v)] (or (and (empty? r1) (= s/NONE r2)) (contains? (set r1) r2))))) (deftest select-any-beginning-end (is (= [] (select-any s/BEGINNING [1 2 3]) (select-any s/END [1]))) (is (= s/NONE (select-any [s/BEGINNING s/STOP] [1 2 3]) (select-any [s/END s/STOP] [2 3])))) (deftest select-any-walker (let [data [1 [2 3 4] [[6]]]] (is (= s/NONE (select-any (s/walker keyword?) data))) (is (= s/NONE (select-any [(s/walker number?) neg?] data))) (is (#{1 3} (select-any [(s/walker number?) odd?] data))) (is (#{2 4 6} (select-any [(s/walker number?) even?] data))))) (defspec selected-any?-select-equivalence (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (let [r1 (not (empty? (select [s/ALL pred] v))) r2 (selected-any? [s/ALL pred] v)] (= r1 r2)))) (defn div-by-3? [v] (= 0 (mod v 3))) (defspec selected?-filter-equivalence (for-all+ [v (gen/vector gen/int) pred (gen/elements [even? odd?])] (and (= (select-any [s/ALL pred] v) (select-any [s/ALL (s/selected? pred)] v)) (= (select-any [s/ALL pred div-by-3?] v) (select-any [s/ALL (s/selected? pred) div-by-3?] v))))) (deftest multi-path-select-any-test (is (= s/NONE (select-any (s/multi-path s/STOP s/STOP) 1))) (is (= 1 (select-any (s/multi-path s/STAY s/STOP) 1) (select-any (s/multi-path s/STOP s/STAY) 1) (select-any (s/multi-path s/STOP s/STAY s/STOP) 1))) (is (= s/NONE (select-any [(s/multi-path s/STOP s/STAY) even?] 1)))) (deftest if-path-select-any-test (is (= s/NONE (select-any (s/if-path even? s/STAY) 1))) (is (= 2 (select-any (s/if-path even? s/STAY s/STAY) 2))) (is (= s/NONE (select-any [(s/if-path even? s/STAY s/STAY) odd?] 2))) (is (= 2 (select-any (s/if-path odd? s/STOP s/STAY) 2))) (is (= s/NONE (select-any [(s/if-path odd? s/STOP s/STAY) odd?] 2)))) (defspec transient-vector-test (for-all+ [v (gen/vector (limit-size 5 gen/int))] (every? identity (for [[path transient-path f] [[s/FIRST t/FIRST! (fnil inc 0)] ;; fnil in case vector is empty [s/LAST t/LAST! (fnil inc 0)] [(s/keypath 0) (t/keypath! 0) (fnil inc 0)] [s/END t/END! #(conj % 1 2 3)]]] (and (= (s/transform* path f v) (persistent! (s/transform* transient-path f (transient v)))) (= (s/select* path v) (s/select* transient-path (transient v)))))))) (defspec transient-map-test (for-all+ [m (limit-size 5 (gen/not-empty (gen/map gen/keyword gen/int))) new-key gen/keyword] (let [existing-key (first (keys m))] (every? identity (for [[path transient-path f] [[(s/keypath existing-key) (t/keypath! existing-key) inc] [(s/keypath new-key) (t/keypath! new-key) (constantly 3)] [(s/submap [existing-key new-key]) (t/submap! [existing-key new-key]) (constantly {new-key 1234})]]] (and (= (s/transform* path f m) (persistent! (s/transform* transient-path f (transient m)))) (= (s/select* path m) (s/select* transient-path (transient m))))))))) (defspec meta-test (for-all+ [v (gen/vector gen/int) meta-map (limit-size 5 (gen/map gen/keyword gen/int))] (= meta-map (meta (setval s/META meta-map v)) (first (select s/META (with-meta v meta-map))) (first (select s/META (setval s/META meta-map v)))))) (deftest beginning-end-all-first-last-on-nil (is (= [2 3] (setval s/END [2 3] nil) (setval s/BEGINNING [2 3] nil))) (is (nil? (setval s/FIRST :a nil))) (is (nil? (setval s/LAST :a nil))) (is (nil? (transform s/ALL inc nil))) (is (empty? (select s/FIRST nil))) (is (empty? (select s/LAST nil))) (is (empty? (select s/ALL nil)))) (deftest map-vals-nil (is (= nil (transform s/MAP-VALS inc nil))) (is (empty? (select s/MAP-VALS nil)))) (defspec dispense-test (for-all+ [k1 gen/int k2 gen/int k3 gen/int m (gen-map-with-keys gen/int gen/int k1 k2 k3)] (= (select [(s/collect-one (s/keypath k1)) (s/collect-one (s/keypath k2)) s/DISPENSE (s/collect-one (s/keypath k2)) (s/keypath k3)] m) (select [(s/collect-one (s/keypath k2)) (s/keypath k3)] m)))) (deftest collected?-test (let [data {:active-id 1 :items [{:id 1 :name "a"} {:id 2 :name "b"}]}] (is (= {:id 1 :name "a"} (select-any [(s/collect-one :active-id) :items s/ALL (s/collect-one :id) (collected? [a i] (= a i)) s/DISPENSE] data) (select-any [(s/collect-one :active-id) :items s/ALL (s/collect-one :id) (collected? v (apply = v)) s/DISPENSE] data)))) (let [data {:active 3 :items [{:id 1 :val 0} {:id 3 :val 11}]}] (is (= (transform [:items s/ALL (s/selected? :id #(= % 3)) :val] inc data) (transform [(s/collect-one :active) :items s/ALL (s/collect-one :id) (collected? [a i] (= a i)) s/DISPENSE :val] inc data))))) (defspec traverse-test (for-all+ [v (gen/vector gen/int) p (gen/elements [odd? even?]) i gen/int] (and (= (reduce + (traverse [s/ALL p] v)) (reduce + (filter p v))) (= (reduce + i (traverse [s/ALL p] v)) (reduce + i (filter p v)))))) (def KeyAccumWalker (recursive-path [k] p (s/if-path (s/must k) s/STAY [s/ALL (s/collect-one s/FIRST) s/LAST p]))) (deftest recursive-if-path-select-vals-test (let [data {"e1" {"e2" {"e1" {:template 1} "e2" {:template 2}}}}] (is (= [["e1" "e2" "e1" {:template 1}] ["e1" "e2" "e2" {:template 2}]] (select (KeyAccumWalker :template) data))) (is (= {"e1" {"e2" {"e1" "e1e2e1" "e2" "e1e2e2"}}} (transform (KeyAccumWalker :template) (fn [& all] (apply str (butlast all))) data))))) (deftest multi-path-vals-test (is (= {:a 1 :b 6 :c 3} (transform [(s/multi-path (s/collect-one :a) (s/collect-one :c)) :b] + {:a 1 :b 2 :c 3}))) (is (= [[1 2] [3 2]] (select [(s/multi-path (s/collect-one :a) (s/collect-one :c)) :b] {:a 1 :b 2 :c 3})))) (deftest sorted-map-by-transform (let [amap (sorted-map-by > 1 10 2 20 3 30)] (is (= [3 2 1] (keys (transform s/MAP-VALS inc amap)))) (is (= [3 2 1] (keys (transform [s/ALL s/LAST] inc amap)))))) (deftest setval-vals-collection-test (is (= 2 (setval s/VAL 2 :a)))) (defspec multi-transform-test (for-all+ [kw1 gen/keyword kw2 gen/keyword m (limit-size 5 (gen-map-with-keys gen/keyword gen/int kw1 kw2))] (= (->> m (transform [(s/keypath kw1) s/VAL] +) (transform (s/keypath kw2) dec)) (multi-transform (s/multi-path [(s/keypath kw1) s/VAL (s/terminal +)] [(s/keypath kw2) (s/terminal dec)]) m)))) (deftest multi-transform-overrun-error (is (thrown? #?(:clj Exception :cljs js/Error) (multi-transform s/STAY 3)))) (deftest terminal-val-test (is (= 3 (multi-transform (s/terminal-val 3) 2))) (is (= 3 (multi-transform [s/VAL (s/terminal-val 3)] 2)))) (deftest multi-path-order-test (is (= 102 (multi-transform (s/multi-path [odd? (s/terminal #(* 2 %))] [even? (s/terminal-val 100)] [#(= 100 %) (s/terminal inc)] [#(= 101 %) (s/terminal inc)]) 1)))) (defdynamicnav ignorer [a] s/STAY) (deftest dynamic-nav-ignores-dynamic-arg (let [a 1] (is (= 1 (select-any (ignorer a) 1))) (is (= 1 (select-any (ignorer :a) 1))))) (deftest nested-dynamic-nav (let [data {:a {:a 1 :b 2} :b {:a 3 :b 4}} afn (fn [a b] (select-any (s/selected? (s/must a) (s/selected? (s/must b))) data))] (is (= data (afn :a :a))) (is (= s/NONE (afn :a :c))) (is (= data (afn :a :b))) (is (= s/NONE (afn :c :a))) (is (= data (afn :b :a))) (is (= data (afn :b :b))))) (deftest duplicate-map-keys-test (let [res (setval [s/ALL s/FIRST] "a" {:a 1 :b 2})] (is (= {"a" 2} res)) (is (= 1 (count res))))) (deftest inline-caching-vector-params-test (is (= [10 [11]] (multi-transform (s/terminal-val [10 [11]]) :a)))) (defn eachnav-fn-test [akey data] (select-any (s/keypath "a" akey) data)) (deftest eachnav-test (let [data {"a" {"b" 1 "c" 2}}] (is (= 1 (eachnav-fn-test "b" data))) (is (= 2 (eachnav-fn-test "c" data))) )) (deftest traversed-test (is (= 10 (select-any (s/traversed s/ALL +) [1 2 3 4])))) (defn- predand= [pred v1 v2] (and (pred v1) (pred v2) (= v1 v2))) (defn listlike? [v] (or (list? v) (seq? v))) (deftest nthpath-test (is (predand= vector? [1 2 -3 4] (transform (s/nthpath 2) - [1 2 3 4]))) (is (predand= vector? [1 2 4] (setval (s/nthpath 2) s/NONE [1 2 3 4]))) (is (predand= (complement vector?) '(1 -2 3 4) (transform (s/nthpath 1) - '(1 2 3 4)))) (is (predand= (complement vector?) '(1 2 4) (setval (s/nthpath 2) s/NONE '(1 2 3 4)))) (is (= [0 1 [2 4 4]] (transform (s/nthpath 2 1) inc [0 1 [2 3 4]]))) ) (deftest remove-with-NONE-test (is (predand= vector? [1 2 3] (setval [s/ALL nil?] s/NONE [1 2 nil 3 nil]))) (is (predand= listlike? '(1 2 3) (setval [s/ALL nil?] s/NONE '(1 2 nil 3 nil)))) (is (= {:b 2} (setval :a s/NONE {:a 1 :b 2}))) (is (= {:b 2} (setval (s/must :a) s/NONE {:a 1 :b 2}))) (is (predand= vector? [1 3] (setval (s/keypath 1) s/NONE [1 2 3]))) ;; test with PersistentArrayMap (is (= {:a 1 :c 3} (setval [s/MAP-VALS even?] s/NONE {:a 1 :b 2 :c 3 :d 4}))) (is (= {:a 1 :c 3} (setval [s/ALL (s/selected? s/LAST even?)] s/NONE {:a 1 :b 2 :c 3 :d 4}))) ;; test with PersistentHashMap (let [m (into {} (for [i (range 500)] [i i]))] (is (= (dissoc m 31) (setval [s/MAP-VALS #(= 31 %)] s/NONE m))) (is (= (dissoc m 31) (setval [s/ALL (s/selected? s/LAST #(= 31 %))] s/NONE m))) )) (deftest fresh-collected-test (let [data [{:a 1 :b 2} {:a 3 :b 3}]] (is (= [[{:a 1 :b 2} 2]] (select [s/ALL s/VAL (s/with-fresh-collected (s/collect-one :a) (s/collected? [a] (= a 1))) :b] data))) (is (= [{:a 1 :b 3} {:a 3 :b 3}] (transform [s/ALL s/VAL (s/with-fresh-collected (s/collect-one :a) (s/collected? [a] (= a 1))) :b] (fn [m v] (+ (:a m) v)) data ))) )) (deftest traverse-all-test (is (= 3 (transduce (comp (mapcat identity) (traverse-all :a)) (completing (fn [r i] (if (= i 4) (reduced r) (+ r i)))) 0 [[{:a 1}] [{:a 2}] [{:a 4}] [{:a 5}]]))) (is (= 6 (transduce (traverse-all [s/ALL :a]) + 0 [[{:a 1} {:a 2}] [{:a 3}]] ))) (is (= [1 2] (into [] (traverse-all :a) [{:a 1} {:a 2}]))) ) (deftest early-terminate-traverse-test (is (= 6 (reduce (completing (fn [r i] (if (> r 5) (reduced r) (+ r i)))) 0 (traverse [s/ALL s/ALL] [[1 2] [3 4] [5]]))))) (deftest select-any-vals-test (is (= [1 1] (select-any s/VAL 1)))) (deftest conditional-vals-test (is (= 2 (select-any (s/with-fresh-collected (s/collect-one (s/keypath 0)) (s/if-path (collected? [n] (even? n)) (s/keypath 1) (s/keypath 2))) [4 2 3]))) (is (= [4 2 3] (select-any (s/with-fresh-collected (s/collect-one (s/keypath 0)) (s/selected? (collected? [n] (even? n)))) [4 2 3]))) ) (deftest name-namespace-test (is (= :a (setval s/NAME "a" :e))) (is (= :a/b (setval s/NAME "b" :a/e))) (is (= 'a (setval s/NAME "a" 'e))) (is (= 'a/b (setval s/NAME "b" 'a/e))) (is (= :a/e (setval s/NAMESPACE "a" :e))) (is (= :a/e (setval s/NAMESPACE "a" :f/e))) (is (= 'a/e (setval s/NAMESPACE "a" 'e))) (is (= 'a/e (setval s/NAMESPACE "a" 'f/e))) ) (deftest string-navigation-test (is (= "ad" (setval (s/srange 1 3) "" "abcd"))) (is (= "abcxd" (setval [(s/srange 1 3) s/END] "x" "abcd"))) (is (= "bc" (select-any (s/srange 1 3) "abcd"))) (is (= "ab" (setval s/END "b" "a"))) (is (= "ba" (setval s/BEGINNING "b" "a"))) (is (= "" (select-any s/BEGINNING "abc"))) (is (= "" (select-any s/END "abc"))) (is (= \a (select-any s/FIRST "abc"))) (is (= \c (select-any s/LAST "abc"))) (is (= "qbc" (setval s/FIRST \q "abc"))) (is (= "abq" (setval s/LAST "q" "abc"))) ) (deftest regex-navigation-test ;; also test regexes as implicit navs (is (= (select #"t" "test") ["t" "t"])) (is (= (select [:a (s/regex-nav #"t")] {:a "test"}) ["t" "t"])) (is (= (transform (s/regex-nav #"t") clojure.string/capitalize "test") "TesT")) ;; also test regexes as implicit navs (is (= (transform [:a #"t"] clojure.string/capitalize {:a "test"}) {:a "TesT"})) (is (= (transform (s/regex-nav #"\s+\w") clojure.string/triml "Hello World!") "HelloWorld!")) (is (= (setval (s/regex-nav #"t") "z" "test") "zesz")) (is (= (setval [:a (s/regex-nav #"t")] "z" {:a "test"}) {:a "zesz"})) (is (= (transform (s/regex-nav #"aa*") (fn [s] (-> s count str)) "aadt") "2dt")) (is (= (transform (s/regex-nav #"[Aa]+") (fn [s] (apply str (take (count s) (repeat "@")))) "PI:NAME:<NAME>END_PI") "@msterd@m @@rdv@rks")) (is (= (select [(s/regex-nav #"(\S+):\ (\d+)") (s/nthpath 2)] "PI:NAME:<NAME>END_PI: 1st George: 2nd Arthur: 3rd") ["1" "2" "3"])) (is (= (transform (s/subselect (s/regex-nav #"\d\w+")) reverse "PI:NAME:<NAME>END_PI: 1st George: 2nd Arthur: 3rd") "PI:NAME:<NAME>END_PI: 3rd George: 2nd Arthur: 1st")) ) (deftest single-value-none-navigators-test (is (predand= vector? [1 2 3] (setval s/AFTER-ELEM 3 [1 2]))) (is (predand= listlike? '(1 2 3) (setval s/AFTER-ELEM 3 '(1 2)))) (is (predand= listlike? '(1) (setval s/AFTER-ELEM 1 nil))) (is (predand= vector? [3 1 2] (setval s/BEFORE-ELEM 3 [1 2]))) (is (predand= listlike? '(3 1 2) (setval s/BEFORE-ELEM 3 '(1 2)))) (is (predand= listlike? '(1) (setval s/BEFORE-ELEM 1 nil))) (is (= #{1 2 3} (setval s/NONE-ELEM 3 #{1 2}))) (is (= #{1} (setval s/NONE-ELEM 1 nil))) ) (deftest subvec-test (let [v (subvec [1] 0)] (is (predand= vector? [2] (transform s/FIRST inc v))) (is (predand= vector? [2] (transform s/LAST inc v))) (is (predand= vector? [2] (transform s/ALL inc v))) (is (predand= vector? [0 1] (setval s/BEGINNING [0] v))) (is (predand= vector? [1 0] (setval s/END [0] v))) (is (predand= vector? [0 1] (setval s/BEFORE-ELEM 0 v))) (is (predand= vector? [1 0] (setval s/AFTER-ELEM 0 v))) (is (predand= vector? [1 0] (setval (s/srange 1 1) [0] v))) )) (defspec map-keys-all-first-equivalence-transform (for-all+ [m (limit-size 10 (gen/map gen/int gen/keyword))] (= (transform s/MAP-KEYS inc m) (transform [s/ALL s/FIRST] inc m ) ))) (defspec map-keys-all-first-equivalence-select (for-all+ [m (limit-size 10 (gen/map gen/int gen/keyword))] (= (select s/MAP-KEYS m) (select [s/ALL s/FIRST] m) ))) (defspec remove-first-vector (for-all+ [v (limit-size 10 (gen/not-empty (gen/vector gen/int)))] (let [newv (setval s/FIRST s/NONE v)] (and (= newv (vec (rest v))) (vector? newv) )))) (defspec remove-first-list (for-all+ [l (limit-size 10 (gen/not-empty (gen/list gen/int)))] (let [newl (setval s/FIRST s/NONE l)] (and (= newl (rest l)) (listlike? newl) )))) (defspec remove-last-vector (for-all+ [v (limit-size 10 (gen/not-empty (gen/vector gen/int)))] (let [newv (setval s/LAST s/NONE v)] (and (= newv (vec (butlast v))) (vector? newv) )))) (defspec remove-last-list (for-all+ [l (limit-size 10 (gen/not-empty (gen/list gen/int)))] (let [newl (setval s/LAST s/NONE l) bl (butlast l)] (and (or (= newl bl) (and (nil? bl) (= '() newl))) (seq? newl) )))) (deftest remove-extreme-string (is (= "b" (setval s/FIRST s/NONE "ab"))) (is (= "a" (setval s/LAST s/NONE "ab"))) ) (deftest nested-dynamic-arg-test (let [foo (fn [v] (multi-transform (s/terminal-val [v]) nil))] (is (= [1] (foo 1))) (is (= [10] (foo 10))) )) (deftest filterer-remove-test (is (= [1 :a 3 5] (setval (s/filterer even?) [:a] [1 2 3 4 5]))) (is (= [1 3 5] (setval (s/filterer even?) [] [1 2 3 4 5]))) (is (= [1 3 5] (setval (s/filterer even?) nil [1 2 3 4 5]))) ) (deftest helper-preds-test (let [data [1 2 2 3 4 0]] (is (= [2 2] (select [s/ALL (s/pred= 2)] data))) (is (= [1 2 2 0] (select [s/ALL (s/pred< 3)] data))) (is (= [1 2 2 3 0] (select [s/ALL (s/pred<= 3)] data))) (is (= [4] (select [s/ALL (s/pred> 3)] data))) (is (= [3 4] (select [s/ALL (s/pred>= 3)] data))) )) (deftest map-key-test (is (= {:c 3} (setval (s/map-key :a) :b {:c 3}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2 :b 1}))) (is (= {:b 2} (setval (s/map-key :a) s/NONE {:a 1 :b 2}))) ) (deftest set-elem-test (is (= #{:b :d} (setval (s/set-elem :a) :x #{:b :d}))) (is (= #{:x :a} (setval (s/set-elem :b) :x #{:b :a}))) (is (= #{:a} (setval (s/set-elem :b) :a #{:b :a}))) (is (= #{:b} (setval (s/set-elem :a) s/NONE #{:a :b}))) ) ;; this function necessary to trigger the bug from happening (defn inc2 [v] (inc v)) (deftest dynamic-function-arg-test (is (= {[2] 4} (let [a 1] (transform (s/keypath [(inc2 a)]) inc {[2] 3})))) ) (defrecord FooW [a b]) (deftest walker-test (is (= [1 2 3 4 5 6] (select (s/walker number?) [{1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (is (= [{:b '(:c)} #{:d}] (setval (s/walker number?) s/NONE [{:q 3 10 :l 1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (is (= [{:q 4 11 :l 2 3 :b '(4 :c 5)} 6 #{7 :d}] (transform (s/walker number?) inc [{:q 3 10 :l 1 2 :b '(3 :c 4)} 5 #{6 :d}]))) (let [f (->FooW 1 2)] (is (= [[:a 1] [:b 2]] (select (s/walker (complement record?)) f))) (is (= (assoc f :a! 1 :b! 2) (setval [(s/walker (complement record?)) s/FIRST s/NAME s/END] "!" f))) (is (= (assoc f :b 1 :c 2) (transform [(s/walker (complement record?)) s/FIRST] (fn [k] (if (= :a k) :b :c)) f))) )) (def MIDDLE (s/comp-paths (s/srange-dynamic (fn [aseq] (long (/ (count aseq) 2))) (end-fn [aseq s] (if (empty? aseq) 0 (inc s)))) s/FIRST )) (deftest srange-dynamic-test (is (= 2 (select-any MIDDLE [1 2 3]))) (is (identical? s/NONE (select-any MIDDLE []))) (is (= 1 (select-any MIDDLE [1]))) (is (= 2 (select-any MIDDLE [1 2]))) (is (= [1 3 3] (transform MIDDLE inc [1 2 3]))) ) (def ^:dynamic *dvar* :a) (defn dvar-tester [] (select-any *dvar* {:a 1 :b 2})) (deftest dynamic-var-ic-test (is (= 1 (dvar-tester))) (is (= 2 (binding [*dvar* :b] (dvar-tester)))) ) (deftest before-index-test (let [data [1 2 3] datal '(1 2 3) data-str "abcdef"] (is (predand= vector? [:a 1 2 3] (setval (s/before-index 0) :a data))) (is (predand= vector? [1 2 3] (setval (s/before-index 1) s/NONE data))) (is (predand= vector? [1 :a 2 3] (setval (s/before-index 1) :a data))) (is (predand= vector? [1 2 3 :a] (setval (s/before-index 3) :a data))) ; ensure inserting at index 0 in nil structure works, as in previous impl (is (predand= listlike? '(:a) (setval (s/before-index 0) :a nil))) (is (predand= listlike? '(:a 1 2 3) (setval (s/before-index 0) :a datal))) (is (predand= listlike? '(1 :a 2 3) (setval (s/before-index 1) :a datal))) (is (predand= listlike? '(1 2 3 :a) (setval (s/before-index 3) :a datal))) (is (predand= string? "abcxdef" (setval (s/before-index 3) (char \x) data-str))) )) (deftest index-nav-test (let [data [1 2 3 4 5 6] datal '(1 2 3 4 5 6)] (is (predand= vector? [3 1 2 4 5 6] (setval (s/index-nav 2) 0 data))) (is (predand= vector? [1 3 2 4 5 6] (setval (s/index-nav 2) 1 data))) (is (predand= vector? [1 2 3 4 5 6] (setval (s/index-nav 2) 2 data))) (is (predand= vector? [1 2 4 5 3 6] (setval (s/index-nav 2) 4 data))) (is (predand= vector? [1 2 4 5 6 3] (setval (s/index-nav 2) 5 data))) (is (predand= vector? [6 1 2 3 4 5] (setval (s/index-nav 5) 0 data))) (is (predand= listlike? '(3 1 2 4 5 6) (setval (s/index-nav 2) 0 datal))) (is (predand= listlike? '(1 3 2 4 5 6) (setval (s/index-nav 2) 1 datal))) (is (predand= listlike? '(1 2 3 4 5 6) (setval (s/index-nav 2) 2 datal))) (is (predand= listlike? '(1 2 4 5 3 6) (setval (s/index-nav 2) 4 datal))) (is (predand= listlike? '(1 2 4 5 6 3) (setval (s/index-nav 2) 5 datal))) (is (predand= listlike? '(6 1 2 3 4 5) (setval (s/index-nav 5) 0 datal))) )) (deftest indexed-vals-test (let [data [:a :b :c :d :e]] (is (= [[0 :a] [1 :b] [2 :c] [3 :d] [4 :e]] (select s/INDEXED-VALS data))) (is (= [:e :d :c :b :a] (setval [s/INDEXED-VALS s/FIRST] 0 data))) (is (= [:a :b :e :d :c] (setval [s/INDEXED-VALS s/FIRST] 2 data))) (is (= [:b :a :d :c :e] (transform [s/INDEXED-VALS s/FIRST odd?] dec data))) (is (= [:a :b :c :d :e] (transform [s/INDEXED-VALS s/FIRST odd?] inc data))) (is (= [0 2 2 4] (transform [s/INDEXED-VALS s/LAST odd?] inc [0 1 2 3]))) (is (= [0 1 2 3] (transform [s/INDEXED-VALS (s/collect-one s/LAST) s/FIRST] (fn [i _] i) [2 1 3 0]))) (is (= [-1 0 1 2 3] (transform [(s/indexed-vals -1) (s/collect-one s/LAST) s/FIRST] (fn [i _] i) [3 -1 0 2 1]))) (is (= [[1 :a] [2 :b] [3 :c]] (select (s/indexed-vals 1) [:a :b :c]))) )) (deftest other-implicit-navs-test (is (= 1 (select-any ["a" true \c 10 'd] {"a" {true {\c {10 {'d 1}}}}}))) ) (deftest vterminal-test (is (= {:a {:b [[1 2] 3]}} (multi-transform [(s/putval 1) :a (s/putval 2) :b (s/vterminal (fn [vs v] [vs v]))] {:a {:b 3}}))) ) (deftest vtransform-test (is (= {:a 6} (vtransform [:a (s/putval 2) (s/putval 3)] (fn [vs v] (+ v (reduce + vs))) {:a 1}))) ) (deftest compact-test (is (= {} (setval [:a (s/compact :b :c)] s/NONE {:a {:b {:c 1}}}))) (is (= {:a {:d 2}} (setval [:a (s/compact :b :c)] s/NONE {:a {:b {:c 1} :d 2}}))) (let [TREE-VALUES (recursive-path [] p (s/if-path vector? [(s/compact s/ALL) p] s/STAY)) tree [1 [2 3] [] [4 [[5] [[6]]]]]] (is (= [2 4 6] (select [TREE-VALUES even?] tree))) (is (= [1 [3] [[[5]]]] (setval [TREE-VALUES even?] s/NONE tree))) ) (is (= [{:a [{:c 1}]}] (setval [s/ALL (s/compact :a s/ALL :b)] s/NONE [{:a [{:b 3}]} {:a [{:b 2 :c 1}]}]))) ) (deftest class-constant-test (let [f (fn [p] (fn [v] (str p (inc v))))] (is (= (str #?(:clj String :cljs js/String) 2) (multi-transform (s/terminal (f #?(:clj String :cljs js/String))) 1))) )) #?(:clj (do (defprotocolpath FooPP) (extend-protocolpath FooPP String s/STAY) (deftest satisfies-protpath-test (is (satisfies-protpath? FooPP "a")) (is (not (satisfies-protpath? FooPP 1))) ))) (deftest sorted-test (let [initial-list [3 4 2 1]] (testing "the SORTED navigator" (is (= (sort initial-list) (select-one s/SORTED initial-list))) (is (= [2 1 3 4] (transform s/SORTED reverse initial-list))) (is (= [3 2 1] (transform s/SORTED butlast initial-list))) (is (= [3 5 2 1] (setval [s/SORTED s/LAST] 5 initial-list))) (is (= (list 1 2 3 4 5) (transform [s/SORTED s/ALL] inc (range 5))))) (testing "the sorted navigator with comparator" (let [reverse-comparator (comp - compare)] (is (= (sort reverse-comparator initial-list) (select-one (s/sorted reverse-comparator) initial-list))) (is (= 4 (select-one [(s/sorted reverse-comparator) s/FIRST] initial-list)))))) (testing "the sorted-by navigator with keypath" (let [initial-list [{:a 3} {:a 4} {:a 2} {:a 1}]] (is (= (sort-by :a initial-list) (select-one (s/sorted-by :a) initial-list))) (is (= {:a 4} (select-one [(s/sorted-by :a (comp - compare)) s/FIRST] initial-list))))))
[ { "context": " company-iban {:iban \"NL66OPEN0000000000\" :token \"00000000000000000000\"})\n(def ah \"Albert Heijn BV\")\n(def cash-amounts (", "end": 885, "score": 0.8413799405097961, "start": 865, "tag": "PASSWORD", "value": "00000000000000000000" }, { "context": "0000000\" :token \"00000000000000000000\"})\n(def ah \"Albert Heijn BV\")\n(def cash-amounts (mapv #(* 1000 %) [2 2 2 3", "end": 910, "score": 0.9998217225074768, "start": 898, "tag": "NAME", "value": "Albert Heijn" } ]
command-generator/src/nl/openweb/command_generator/core.clj
gklijs/obm_confluent_blog
2
(ns nl.openweb.command-generator.core (:require [clj-time.local :as time-local] [nl.openweb.topology.clients :as clients] [nl.openweb.topology.value-generator :as vg]) (:import (java.util UUID) (org.apache.kafka.clients.consumer ConsumerRecord) (nl.openweb.data AccountCreationConfirmed Uuid Atype ConfirmMoneyTransfer ConfirmAccountCreation)) (:gen-class)) (def heartbeat-topic (or (System/getenv "KAFKA_HEARTBEAT_TOPIC") "heartbeat")) (def cac-topic (or (System/getenv "KAFKA_CAC_TOPIC") "confirm_account_creation")) (def acf-topic (or (System/getenv "KAFKA_ACF_TOPIC") "account_creation_feedback")) (def cmt-topic (or (System/getenv "KAFKA_CMT_TOPIC") "confirm_money_transfer")) (def client-id (or (System/getenv "KAFKA_CLIENT_ID") "command-generator")) (def company-iban {:iban "NL66OPEN0000000000" :token "00000000000000000000"}) (def ah "Albert Heijn BV") (def cash-amounts (mapv #(* 1000 %) [2 2 2 3 5 5 10 20])) (def accounts (atom [])) (defn get-iban [] (if (not-empty @accounts) (rand-nth @accounts) company-iban)) (defn get-type [] (let [rand (rand-int 70)] (cond (zero? rand) :salary (< rand 4) :deposit (< rand 14) :withdraw (< rand 54) :ah-pin :else :something-else))) (def description-map {:salary "salary" :deposit "deposit" :withdraw "withdraw" :ah-pin "ah pin" :something-else "transfer"}) (defn get-description [rand-helper] (str (rand-helper description-map) " " (time-local/to-local-date-time (time-local/local-now)))) (defn create-transfer-map ([] (let [some-type (get-type) to (cond (= some-type :withdraw) "cash" (= some-type :ah-pin) ah :else (:iban (get-iban)))] (create-transfer-map some-type to))) ([some-type to] (let [from-iban (if (= some-type :salary) company-iban (get-iban))] (-> {} (assoc :id (vg/uuid->bytes (UUID/randomUUID))) (assoc :token (if (= some-type :deposit) "cash" (:token from-iban))) (assoc :amount (cond (= some-type :salary) (+ 220000 (rand-int 50000)) (or (= some-type :deposit) (= some-type :withdraw)) (rand-nth cash-amounts) :else (+ 1000 (rand-int 10000)))) (assoc :from (if (= some-type :deposit) "cash" (:iban from-iban))) (assoc :to to) (assoc :description (get-description some-type)))))) (defn get-cmt [t] (ConfirmMoneyTransfer. (Uuid. (:id t)) (:token t) (:amount t) (:from t) (:to t) (:description t))) (defn add-account [producer ^ConsumerRecord consumer-record] (let [^AccountCreationConfirmed value (.value consumer-record)] (when (and (instance? AccountCreationConfirmed value)(= Atype/AUTO (.getAType value))) (swap! accounts conj (-> {} (assoc :token (.getToken value)) (assoc :iban (.getIban value)))) (clients/produce producer cmt-topic (get-cmt (create-transfer-map :salary (.getIban value))))))) (defn generate-command [producer consumer-record] (if-let [beat (.getBeat (.value consumer-record))] (if (or (< beat 20) (zero? (mod beat 200))) (clients/produce producer cac-topic (ConfirmAccountCreation. (Uuid. (vg/uuid->bytes (UUID/randomUUID))) Atype/AUTO)) (clients/produce producer cmt-topic (get-cmt (create-transfer-map)))))) (defn -main [] (let [producer (clients/get-producer client-id)] (clients/consume (str client-id "-hb") client-id heartbeat-topic (partial generate-command producer)) (clients/consume (str client-id "-acc") client-id acf-topic (partial add-account producer))))
26982
(ns nl.openweb.command-generator.core (:require [clj-time.local :as time-local] [nl.openweb.topology.clients :as clients] [nl.openweb.topology.value-generator :as vg]) (:import (java.util UUID) (org.apache.kafka.clients.consumer ConsumerRecord) (nl.openweb.data AccountCreationConfirmed Uuid Atype ConfirmMoneyTransfer ConfirmAccountCreation)) (:gen-class)) (def heartbeat-topic (or (System/getenv "KAFKA_HEARTBEAT_TOPIC") "heartbeat")) (def cac-topic (or (System/getenv "KAFKA_CAC_TOPIC") "confirm_account_creation")) (def acf-topic (or (System/getenv "KAFKA_ACF_TOPIC") "account_creation_feedback")) (def cmt-topic (or (System/getenv "KAFKA_CMT_TOPIC") "confirm_money_transfer")) (def client-id (or (System/getenv "KAFKA_CLIENT_ID") "command-generator")) (def company-iban {:iban "NL66OPEN0000000000" :token "<PASSWORD>"}) (def ah "<NAME> BV") (def cash-amounts (mapv #(* 1000 %) [2 2 2 3 5 5 10 20])) (def accounts (atom [])) (defn get-iban [] (if (not-empty @accounts) (rand-nth @accounts) company-iban)) (defn get-type [] (let [rand (rand-int 70)] (cond (zero? rand) :salary (< rand 4) :deposit (< rand 14) :withdraw (< rand 54) :ah-pin :else :something-else))) (def description-map {:salary "salary" :deposit "deposit" :withdraw "withdraw" :ah-pin "ah pin" :something-else "transfer"}) (defn get-description [rand-helper] (str (rand-helper description-map) " " (time-local/to-local-date-time (time-local/local-now)))) (defn create-transfer-map ([] (let [some-type (get-type) to (cond (= some-type :withdraw) "cash" (= some-type :ah-pin) ah :else (:iban (get-iban)))] (create-transfer-map some-type to))) ([some-type to] (let [from-iban (if (= some-type :salary) company-iban (get-iban))] (-> {} (assoc :id (vg/uuid->bytes (UUID/randomUUID))) (assoc :token (if (= some-type :deposit) "cash" (:token from-iban))) (assoc :amount (cond (= some-type :salary) (+ 220000 (rand-int 50000)) (or (= some-type :deposit) (= some-type :withdraw)) (rand-nth cash-amounts) :else (+ 1000 (rand-int 10000)))) (assoc :from (if (= some-type :deposit) "cash" (:iban from-iban))) (assoc :to to) (assoc :description (get-description some-type)))))) (defn get-cmt [t] (ConfirmMoneyTransfer. (Uuid. (:id t)) (:token t) (:amount t) (:from t) (:to t) (:description t))) (defn add-account [producer ^ConsumerRecord consumer-record] (let [^AccountCreationConfirmed value (.value consumer-record)] (when (and (instance? AccountCreationConfirmed value)(= Atype/AUTO (.getAType value))) (swap! accounts conj (-> {} (assoc :token (.getToken value)) (assoc :iban (.getIban value)))) (clients/produce producer cmt-topic (get-cmt (create-transfer-map :salary (.getIban value))))))) (defn generate-command [producer consumer-record] (if-let [beat (.getBeat (.value consumer-record))] (if (or (< beat 20) (zero? (mod beat 200))) (clients/produce producer cac-topic (ConfirmAccountCreation. (Uuid. (vg/uuid->bytes (UUID/randomUUID))) Atype/AUTO)) (clients/produce producer cmt-topic (get-cmt (create-transfer-map)))))) (defn -main [] (let [producer (clients/get-producer client-id)] (clients/consume (str client-id "-hb") client-id heartbeat-topic (partial generate-command producer)) (clients/consume (str client-id "-acc") client-id acf-topic (partial add-account producer))))
true
(ns nl.openweb.command-generator.core (:require [clj-time.local :as time-local] [nl.openweb.topology.clients :as clients] [nl.openweb.topology.value-generator :as vg]) (:import (java.util UUID) (org.apache.kafka.clients.consumer ConsumerRecord) (nl.openweb.data AccountCreationConfirmed Uuid Atype ConfirmMoneyTransfer ConfirmAccountCreation)) (:gen-class)) (def heartbeat-topic (or (System/getenv "KAFKA_HEARTBEAT_TOPIC") "heartbeat")) (def cac-topic (or (System/getenv "KAFKA_CAC_TOPIC") "confirm_account_creation")) (def acf-topic (or (System/getenv "KAFKA_ACF_TOPIC") "account_creation_feedback")) (def cmt-topic (or (System/getenv "KAFKA_CMT_TOPIC") "confirm_money_transfer")) (def client-id (or (System/getenv "KAFKA_CLIENT_ID") "command-generator")) (def company-iban {:iban "NL66OPEN0000000000" :token "PI:PASSWORD:<PASSWORD>END_PI"}) (def ah "PI:NAME:<NAME>END_PI BV") (def cash-amounts (mapv #(* 1000 %) [2 2 2 3 5 5 10 20])) (def accounts (atom [])) (defn get-iban [] (if (not-empty @accounts) (rand-nth @accounts) company-iban)) (defn get-type [] (let [rand (rand-int 70)] (cond (zero? rand) :salary (< rand 4) :deposit (< rand 14) :withdraw (< rand 54) :ah-pin :else :something-else))) (def description-map {:salary "salary" :deposit "deposit" :withdraw "withdraw" :ah-pin "ah pin" :something-else "transfer"}) (defn get-description [rand-helper] (str (rand-helper description-map) " " (time-local/to-local-date-time (time-local/local-now)))) (defn create-transfer-map ([] (let [some-type (get-type) to (cond (= some-type :withdraw) "cash" (= some-type :ah-pin) ah :else (:iban (get-iban)))] (create-transfer-map some-type to))) ([some-type to] (let [from-iban (if (= some-type :salary) company-iban (get-iban))] (-> {} (assoc :id (vg/uuid->bytes (UUID/randomUUID))) (assoc :token (if (= some-type :deposit) "cash" (:token from-iban))) (assoc :amount (cond (= some-type :salary) (+ 220000 (rand-int 50000)) (or (= some-type :deposit) (= some-type :withdraw)) (rand-nth cash-amounts) :else (+ 1000 (rand-int 10000)))) (assoc :from (if (= some-type :deposit) "cash" (:iban from-iban))) (assoc :to to) (assoc :description (get-description some-type)))))) (defn get-cmt [t] (ConfirmMoneyTransfer. (Uuid. (:id t)) (:token t) (:amount t) (:from t) (:to t) (:description t))) (defn add-account [producer ^ConsumerRecord consumer-record] (let [^AccountCreationConfirmed value (.value consumer-record)] (when (and (instance? AccountCreationConfirmed value)(= Atype/AUTO (.getAType value))) (swap! accounts conj (-> {} (assoc :token (.getToken value)) (assoc :iban (.getIban value)))) (clients/produce producer cmt-topic (get-cmt (create-transfer-map :salary (.getIban value))))))) (defn generate-command [producer consumer-record] (if-let [beat (.getBeat (.value consumer-record))] (if (or (< beat 20) (zero? (mod beat 200))) (clients/produce producer cac-topic (ConfirmAccountCreation. (Uuid. (vg/uuid->bytes (UUID/randomUUID))) Atype/AUTO)) (clients/produce producer cmt-topic (get-cmt (create-transfer-map)))))) (defn -main [] (let [producer (clients/get-producer client-id)] (clients/consume (str client-id "-hb") client-id heartbeat-topic (partial generate-command producer)) (clients/consume (str client-id "-acc") client-id acf-topic (partial add-account producer))))
[ { "context": " :type \"text\"\n :placeholder \"Your Name\"\n :on-change #(do\n ", "end": 7610, "score": 0.9982984066009521, "start": 7601, "tag": "NAME", "value": "Your Name" }, { "context": " :object-fit \"cover\"}}]] {:key \"sfmsbi\"})\n (with-meta (modal-body @stage) {:key ", "end": 9993, "score": 0.7074100971221924, "start": 9989, "tag": "KEY", "value": "sfms" } ]
src/cljs/cocdan/modals/stage_find.cljs
chaomi1998/cocdan
3
(ns cocdan.modals.stage-find (:require [reagent.core :as r] [clojure.string :as str] [cljs-http.client :as http] [clojure.core.async :refer [go <!]] [markdown.core :refer [md->html]] [re-frame.core :as rf] [cats.monad.either :as either] [cats.core :as m] [cocdan.core.stage :refer [posh-stage-by-id query-all-stages]] [cocdan.db :as gdb] [cocdan.auxiliary :refer [init-page]] [cocdan.core.avatar :refer [posh-avatar-by-id posh-my-avatars]])) (defonce active? (r/atom false)) (defonce join-status (r/atom "is-disabled")) (defonce search-status (r/atom "fa-search")) (defonce input-search (r/atom "")) (defonce select-avatar (r/atom 0)) (defonce avatar-name-input (r/atom "")) (defonce avatar-name-check-msg (r/atom "")) (defonce avatar-transform-option (r/atom "copy")) (defonce avatar-transform-limit (r/atom false)) (defonce stage (r/atom nil)) (defonce stage-avatars (r/atom nil)) (init-page {} {:event/modal-find-stage-active (fn [{:keys [db]}] (swap! active? not) {:db db})}) (defn- close-modal [] (reset! active? false)) (defn- on-cancel [] (reset! active? false) (reset! stage nil) (reset! join-status "is-disabled")) (declare option-check) (defn- refresh-stage-avatars! [] (go (let [res (<! (http/get (str "api/stage/s" (:id @stage) "/list/avatar") {:query-params {:code @input-search}}))] (cond (= 200 (:status res)) (do (reset! stage-avatars (:body res)) (option-check)))))) (defn- do-search [] (go (let [res (<! (http/get "api/stage/get-by-code" {:query-params {:code @input-search}}))] (cond (= 200 (:status res)) (do (reset! stage (:body res)) (refresh-stage-avatars!) (reset! join-status "is-primary")) :else (js/console.log res))))) (defn- generate-avatar-select-option [avatar] [:option {:value (:id avatar)} (str (:name avatar) (if (nil? (:on_stage avatar)) "" (let [stage (->> @(posh-stage-by-id gdb/db (:on_stage avatar)) (gdb/pull-eid gdb/db))] (str " @ " (:title stage)))))]) (defn- join-stage [] (reset! join-status "is-loading") (go (let [avatar-created (cond (= 0 @select-avatar) (let [res (<! (http/post "api/avatar/create" {:json-params {:name @avatar-name-input}}))] (if (= 201 (:status res)) (:body res) (js/console.log res))) (= "copy" @avatar-transform-option) (let [res (<! (http/post (str "api/avatar/a" @select-avatar "/duplicate")))] (if (= 201 (:status res)) (:body res) (js/console.log res))) (= "move" @avatar-transform-option) {:id @select-avatar}) _ (js/console.log avatar-created) stage-joined (when (not (nil? avatar-created)) (let [res (<! (http/post "api/stage/join-by-code" {:json-params {:avatar (:id avatar-created)} :query-params {:code @input-search}}))] (if (= 200 (:status res)) res (js/console.log res))))] (if (nil? stage-joined) (reset! join-status "is-danger") (do (reset! join-status "is-success") (rf/dispatch [:event/refresh-my-avatars]) (js/setTimeout #(reset! active? false) 1000)))))) (defn- check-name-len [name] (let [errmsg (cond (str/blank? name) "name is required" (< (count name) 2) "name is too short" :else "")] (if (str/blank? errmsg) (either/right "") (do (reset! avatar-name-check-msg errmsg) (either/left errmsg))))) (defn- check-name-conflict [name stage-avatars] (let [res (filter #(= (str/lower-case (:name %)) name) stage-avatars)] (if (empty? res) (do (reset! avatar-name-check-msg "") (either/right "")) (do (reset! avatar-name-check-msg "conflict with character name on stage") (either/left ""))))) (defn- check-transform-option [] (let [kp-ids (set (filter #(not (nil? %)) (map :owned_by (query-all-stages @gdb/db))))] (if (contains? kp-ids @select-avatar) (do (reset! avatar-transform-option "copy") (reset! avatar-transform-limit true)) (reset! avatar-transform-limit false)))) (defn- option-check [] (when (nil? @stage-avatars) (refresh-stage-avatars!)) (reset! join-status "is-disabled") (check-transform-option) (m/mlet [name (either/right (str/lower-case @avatar-name-input)) _ (m/do-let (check-name-len name) (check-name-conflict name @stage-avatars))] (reset! join-status "is-primary"))) (defn- move-button [disabled?] (let [[title class] (if disabled? ["The avatar cannot be moved because it is the stage host " "is-disabled"] ["this will move the avatar to this stage from previous one" (if (= @avatar-transform-option "move") "is-primary" "")])] [:button.button {:title title :on-click #(reset! avatar-transform-option "move") :class class :disabled disabled?} "Move"])) (defn- on-avatar-change [id] (reset! select-avatar id) (if (not= 0 id) (reset! avatar-name-input (:name (->> @(posh-avatar-by-id gdb/db id) (gdb/pull-eid gdb/db)))) (reset! avatar-name-input "")) (option-check)) (defn- modal-body [{stage-id :id :as stage}] [:div.modal-card-body [:div.content {:dangerouslySetInnerHTML {:__html (md->html (:introduction stage))}}] [:hr] [:label.label "Options" [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label "Avatar"]] [:div.field-body>div.field>div.control>div.select [:select {:class "modal-stage-input" :on-change #(on-avatar-change (js/parseInt (-> % .-target .-value)))} [:option {:value 0} "create a new avatar"] (doall (map-indexed (fn [i x] (if (= stage-id (:on_stage x)) nil (with-meta (generate-avatar-select-option x) {:key (str "ss" i)}))) (->> @(posh-my-avatars gdb/db) (gdb/pull-eids gdb/db))))]]] [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label " Name"]] [:div.field-body>div.field {:class "has-addons"} [:div.control {:class "modal-stage-input has-icons-right"} [:input {:class (str "input " (if (str/blank? @avatar-name-check-msg) "is-primary" "is-danger")) :type "text" :placeholder "Your Name" :on-change #(do (reset! avatar-name-input (-> % .-target .-value)) (option-check)) :value @avatar-name-input}] [:span {:class "icon is-small is-right"} [:i {:class (if (str/blank? @avatar-name-check-msg) "fas fa-check" "fas fa-times")}]]] [:div.control {:class "columns is-vcentered"} (if (str/blank? @avatar-name-check-msg) nil [:p {:style {:padding-left "3em"} :class "help is-danger"} @avatar-name-check-msg])]]] (when (not= 0 @select-avatar) [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label "Transform"]] [:div.field-body [:div {:class "buttons has-addons"} [:button.button {:title "this will make a copy of avatar and join this stage" :on-click #(reset! avatar-transform-option "copy") :class (if (= @avatar-transform-option "copy") "is-primary" "")} "Copy"] (move-button @avatar-transform-limit) ]]])]]) (defn stage-find [] [:div.modal {:class (if @active? "is-active" "")} [:div.modal-background {:on-click close-modal}] [:div.modal-card [:header.modal-card-head [:span {:class "subtitle is-5" :style {:width "10em"}} "Search Stage"] [:div {:class "field has-addons"} [:div.control [:input.input {:placeholder "paste code here" :value @input-search :on-change #(reset! input-search (-> % .-target .-value))}]] [:div.control [:button.button {:style {:margin-right "8em"} :on-click do-search} [:span {:class "icon is-small"} [:i {:class (str "fa " @search-status)}]]]]] [:button.delete {:on-click close-modal}]] (when (not (nil? (:banner @stage))) (list (with-meta [:div.modal-card-image {:class "modal-stage-banner-img"} [:img {:src (:banner @stage) :class "modal-stage-banner-img" :style {:height "100%" :width "100%" :object-fit "cover"}}]] {:key "sfmsbi"}) (with-meta (modal-body @stage) {:key "sfmsbd"}))) [:footer.modal-card-foot [:button.button (merge {:on-click join-stage :class @join-status} (if (= @join-status "is-disabled") {:disabled true} {})) "Join"] [:button.button {:on-click on-cancel} "close"]] [:button {:class "modal-close is-large" :on-click close-modal}]]])
78893
(ns cocdan.modals.stage-find (:require [reagent.core :as r] [clojure.string :as str] [cljs-http.client :as http] [clojure.core.async :refer [go <!]] [markdown.core :refer [md->html]] [re-frame.core :as rf] [cats.monad.either :as either] [cats.core :as m] [cocdan.core.stage :refer [posh-stage-by-id query-all-stages]] [cocdan.db :as gdb] [cocdan.auxiliary :refer [init-page]] [cocdan.core.avatar :refer [posh-avatar-by-id posh-my-avatars]])) (defonce active? (r/atom false)) (defonce join-status (r/atom "is-disabled")) (defonce search-status (r/atom "fa-search")) (defonce input-search (r/atom "")) (defonce select-avatar (r/atom 0)) (defonce avatar-name-input (r/atom "")) (defonce avatar-name-check-msg (r/atom "")) (defonce avatar-transform-option (r/atom "copy")) (defonce avatar-transform-limit (r/atom false)) (defonce stage (r/atom nil)) (defonce stage-avatars (r/atom nil)) (init-page {} {:event/modal-find-stage-active (fn [{:keys [db]}] (swap! active? not) {:db db})}) (defn- close-modal [] (reset! active? false)) (defn- on-cancel [] (reset! active? false) (reset! stage nil) (reset! join-status "is-disabled")) (declare option-check) (defn- refresh-stage-avatars! [] (go (let [res (<! (http/get (str "api/stage/s" (:id @stage) "/list/avatar") {:query-params {:code @input-search}}))] (cond (= 200 (:status res)) (do (reset! stage-avatars (:body res)) (option-check)))))) (defn- do-search [] (go (let [res (<! (http/get "api/stage/get-by-code" {:query-params {:code @input-search}}))] (cond (= 200 (:status res)) (do (reset! stage (:body res)) (refresh-stage-avatars!) (reset! join-status "is-primary")) :else (js/console.log res))))) (defn- generate-avatar-select-option [avatar] [:option {:value (:id avatar)} (str (:name avatar) (if (nil? (:on_stage avatar)) "" (let [stage (->> @(posh-stage-by-id gdb/db (:on_stage avatar)) (gdb/pull-eid gdb/db))] (str " @ " (:title stage)))))]) (defn- join-stage [] (reset! join-status "is-loading") (go (let [avatar-created (cond (= 0 @select-avatar) (let [res (<! (http/post "api/avatar/create" {:json-params {:name @avatar-name-input}}))] (if (= 201 (:status res)) (:body res) (js/console.log res))) (= "copy" @avatar-transform-option) (let [res (<! (http/post (str "api/avatar/a" @select-avatar "/duplicate")))] (if (= 201 (:status res)) (:body res) (js/console.log res))) (= "move" @avatar-transform-option) {:id @select-avatar}) _ (js/console.log avatar-created) stage-joined (when (not (nil? avatar-created)) (let [res (<! (http/post "api/stage/join-by-code" {:json-params {:avatar (:id avatar-created)} :query-params {:code @input-search}}))] (if (= 200 (:status res)) res (js/console.log res))))] (if (nil? stage-joined) (reset! join-status "is-danger") (do (reset! join-status "is-success") (rf/dispatch [:event/refresh-my-avatars]) (js/setTimeout #(reset! active? false) 1000)))))) (defn- check-name-len [name] (let [errmsg (cond (str/blank? name) "name is required" (< (count name) 2) "name is too short" :else "")] (if (str/blank? errmsg) (either/right "") (do (reset! avatar-name-check-msg errmsg) (either/left errmsg))))) (defn- check-name-conflict [name stage-avatars] (let [res (filter #(= (str/lower-case (:name %)) name) stage-avatars)] (if (empty? res) (do (reset! avatar-name-check-msg "") (either/right "")) (do (reset! avatar-name-check-msg "conflict with character name on stage") (either/left ""))))) (defn- check-transform-option [] (let [kp-ids (set (filter #(not (nil? %)) (map :owned_by (query-all-stages @gdb/db))))] (if (contains? kp-ids @select-avatar) (do (reset! avatar-transform-option "copy") (reset! avatar-transform-limit true)) (reset! avatar-transform-limit false)))) (defn- option-check [] (when (nil? @stage-avatars) (refresh-stage-avatars!)) (reset! join-status "is-disabled") (check-transform-option) (m/mlet [name (either/right (str/lower-case @avatar-name-input)) _ (m/do-let (check-name-len name) (check-name-conflict name @stage-avatars))] (reset! join-status "is-primary"))) (defn- move-button [disabled?] (let [[title class] (if disabled? ["The avatar cannot be moved because it is the stage host " "is-disabled"] ["this will move the avatar to this stage from previous one" (if (= @avatar-transform-option "move") "is-primary" "")])] [:button.button {:title title :on-click #(reset! avatar-transform-option "move") :class class :disabled disabled?} "Move"])) (defn- on-avatar-change [id] (reset! select-avatar id) (if (not= 0 id) (reset! avatar-name-input (:name (->> @(posh-avatar-by-id gdb/db id) (gdb/pull-eid gdb/db)))) (reset! avatar-name-input "")) (option-check)) (defn- modal-body [{stage-id :id :as stage}] [:div.modal-card-body [:div.content {:dangerouslySetInnerHTML {:__html (md->html (:introduction stage))}}] [:hr] [:label.label "Options" [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label "Avatar"]] [:div.field-body>div.field>div.control>div.select [:select {:class "modal-stage-input" :on-change #(on-avatar-change (js/parseInt (-> % .-target .-value)))} [:option {:value 0} "create a new avatar"] (doall (map-indexed (fn [i x] (if (= stage-id (:on_stage x)) nil (with-meta (generate-avatar-select-option x) {:key (str "ss" i)}))) (->> @(posh-my-avatars gdb/db) (gdb/pull-eids gdb/db))))]]] [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label " Name"]] [:div.field-body>div.field {:class "has-addons"} [:div.control {:class "modal-stage-input has-icons-right"} [:input {:class (str "input " (if (str/blank? @avatar-name-check-msg) "is-primary" "is-danger")) :type "text" :placeholder "<NAME>" :on-change #(do (reset! avatar-name-input (-> % .-target .-value)) (option-check)) :value @avatar-name-input}] [:span {:class "icon is-small is-right"} [:i {:class (if (str/blank? @avatar-name-check-msg) "fas fa-check" "fas fa-times")}]]] [:div.control {:class "columns is-vcentered"} (if (str/blank? @avatar-name-check-msg) nil [:p {:style {:padding-left "3em"} :class "help is-danger"} @avatar-name-check-msg])]]] (when (not= 0 @select-avatar) [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label "Transform"]] [:div.field-body [:div {:class "buttons has-addons"} [:button.button {:title "this will make a copy of avatar and join this stage" :on-click #(reset! avatar-transform-option "copy") :class (if (= @avatar-transform-option "copy") "is-primary" "")} "Copy"] (move-button @avatar-transform-limit) ]]])]]) (defn stage-find [] [:div.modal {:class (if @active? "is-active" "")} [:div.modal-background {:on-click close-modal}] [:div.modal-card [:header.modal-card-head [:span {:class "subtitle is-5" :style {:width "10em"}} "Search Stage"] [:div {:class "field has-addons"} [:div.control [:input.input {:placeholder "paste code here" :value @input-search :on-change #(reset! input-search (-> % .-target .-value))}]] [:div.control [:button.button {:style {:margin-right "8em"} :on-click do-search} [:span {:class "icon is-small"} [:i {:class (str "fa " @search-status)}]]]]] [:button.delete {:on-click close-modal}]] (when (not (nil? (:banner @stage))) (list (with-meta [:div.modal-card-image {:class "modal-stage-banner-img"} [:img {:src (:banner @stage) :class "modal-stage-banner-img" :style {:height "100%" :width "100%" :object-fit "cover"}}]] {:key "<KEY>bi"}) (with-meta (modal-body @stage) {:key "sfmsbd"}))) [:footer.modal-card-foot [:button.button (merge {:on-click join-stage :class @join-status} (if (= @join-status "is-disabled") {:disabled true} {})) "Join"] [:button.button {:on-click on-cancel} "close"]] [:button {:class "modal-close is-large" :on-click close-modal}]]])
true
(ns cocdan.modals.stage-find (:require [reagent.core :as r] [clojure.string :as str] [cljs-http.client :as http] [clojure.core.async :refer [go <!]] [markdown.core :refer [md->html]] [re-frame.core :as rf] [cats.monad.either :as either] [cats.core :as m] [cocdan.core.stage :refer [posh-stage-by-id query-all-stages]] [cocdan.db :as gdb] [cocdan.auxiliary :refer [init-page]] [cocdan.core.avatar :refer [posh-avatar-by-id posh-my-avatars]])) (defonce active? (r/atom false)) (defonce join-status (r/atom "is-disabled")) (defonce search-status (r/atom "fa-search")) (defonce input-search (r/atom "")) (defonce select-avatar (r/atom 0)) (defonce avatar-name-input (r/atom "")) (defonce avatar-name-check-msg (r/atom "")) (defonce avatar-transform-option (r/atom "copy")) (defonce avatar-transform-limit (r/atom false)) (defonce stage (r/atom nil)) (defonce stage-avatars (r/atom nil)) (init-page {} {:event/modal-find-stage-active (fn [{:keys [db]}] (swap! active? not) {:db db})}) (defn- close-modal [] (reset! active? false)) (defn- on-cancel [] (reset! active? false) (reset! stage nil) (reset! join-status "is-disabled")) (declare option-check) (defn- refresh-stage-avatars! [] (go (let [res (<! (http/get (str "api/stage/s" (:id @stage) "/list/avatar") {:query-params {:code @input-search}}))] (cond (= 200 (:status res)) (do (reset! stage-avatars (:body res)) (option-check)))))) (defn- do-search [] (go (let [res (<! (http/get "api/stage/get-by-code" {:query-params {:code @input-search}}))] (cond (= 200 (:status res)) (do (reset! stage (:body res)) (refresh-stage-avatars!) (reset! join-status "is-primary")) :else (js/console.log res))))) (defn- generate-avatar-select-option [avatar] [:option {:value (:id avatar)} (str (:name avatar) (if (nil? (:on_stage avatar)) "" (let [stage (->> @(posh-stage-by-id gdb/db (:on_stage avatar)) (gdb/pull-eid gdb/db))] (str " @ " (:title stage)))))]) (defn- join-stage [] (reset! join-status "is-loading") (go (let [avatar-created (cond (= 0 @select-avatar) (let [res (<! (http/post "api/avatar/create" {:json-params {:name @avatar-name-input}}))] (if (= 201 (:status res)) (:body res) (js/console.log res))) (= "copy" @avatar-transform-option) (let [res (<! (http/post (str "api/avatar/a" @select-avatar "/duplicate")))] (if (= 201 (:status res)) (:body res) (js/console.log res))) (= "move" @avatar-transform-option) {:id @select-avatar}) _ (js/console.log avatar-created) stage-joined (when (not (nil? avatar-created)) (let [res (<! (http/post "api/stage/join-by-code" {:json-params {:avatar (:id avatar-created)} :query-params {:code @input-search}}))] (if (= 200 (:status res)) res (js/console.log res))))] (if (nil? stage-joined) (reset! join-status "is-danger") (do (reset! join-status "is-success") (rf/dispatch [:event/refresh-my-avatars]) (js/setTimeout #(reset! active? false) 1000)))))) (defn- check-name-len [name] (let [errmsg (cond (str/blank? name) "name is required" (< (count name) 2) "name is too short" :else "")] (if (str/blank? errmsg) (either/right "") (do (reset! avatar-name-check-msg errmsg) (either/left errmsg))))) (defn- check-name-conflict [name stage-avatars] (let [res (filter #(= (str/lower-case (:name %)) name) stage-avatars)] (if (empty? res) (do (reset! avatar-name-check-msg "") (either/right "")) (do (reset! avatar-name-check-msg "conflict with character name on stage") (either/left ""))))) (defn- check-transform-option [] (let [kp-ids (set (filter #(not (nil? %)) (map :owned_by (query-all-stages @gdb/db))))] (if (contains? kp-ids @select-avatar) (do (reset! avatar-transform-option "copy") (reset! avatar-transform-limit true)) (reset! avatar-transform-limit false)))) (defn- option-check [] (when (nil? @stage-avatars) (refresh-stage-avatars!)) (reset! join-status "is-disabled") (check-transform-option) (m/mlet [name (either/right (str/lower-case @avatar-name-input)) _ (m/do-let (check-name-len name) (check-name-conflict name @stage-avatars))] (reset! join-status "is-primary"))) (defn- move-button [disabled?] (let [[title class] (if disabled? ["The avatar cannot be moved because it is the stage host " "is-disabled"] ["this will move the avatar to this stage from previous one" (if (= @avatar-transform-option "move") "is-primary" "")])] [:button.button {:title title :on-click #(reset! avatar-transform-option "move") :class class :disabled disabled?} "Move"])) (defn- on-avatar-change [id] (reset! select-avatar id) (if (not= 0 id) (reset! avatar-name-input (:name (->> @(posh-avatar-by-id gdb/db id) (gdb/pull-eid gdb/db)))) (reset! avatar-name-input "")) (option-check)) (defn- modal-body [{stage-id :id :as stage}] [:div.modal-card-body [:div.content {:dangerouslySetInnerHTML {:__html (md->html (:introduction stage))}}] [:hr] [:label.label "Options" [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label "Avatar"]] [:div.field-body>div.field>div.control>div.select [:select {:class "modal-stage-input" :on-change #(on-avatar-change (js/parseInt (-> % .-target .-value)))} [:option {:value 0} "create a new avatar"] (doall (map-indexed (fn [i x] (if (= stage-id (:on_stage x)) nil (with-meta (generate-avatar-select-option x) {:key (str "ss" i)}))) (->> @(posh-my-avatars gdb/db) (gdb/pull-eids gdb/db))))]]] [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label " Name"]] [:div.field-body>div.field {:class "has-addons"} [:div.control {:class "modal-stage-input has-icons-right"} [:input {:class (str "input " (if (str/blank? @avatar-name-check-msg) "is-primary" "is-danger")) :type "text" :placeholder "PI:NAME:<NAME>END_PI" :on-change #(do (reset! avatar-name-input (-> % .-target .-value)) (option-check)) :value @avatar-name-input}] [:span {:class "icon is-small is-right"} [:i {:class (if (str/blank? @avatar-name-check-msg) "fas fa-check" "fas fa-times")}]]] [:div.control {:class "columns is-vcentered"} (if (str/blank? @avatar-name-check-msg) nil [:p {:style {:padding-left "3em"} :class "help is-danger"} @avatar-name-check-msg])]]] (when (not= 0 @select-avatar) [:div.field {:class "is-horizontal"} [:div {:class "field-label is-normal"} [:label.label "Transform"]] [:div.field-body [:div {:class "buttons has-addons"} [:button.button {:title "this will make a copy of avatar and join this stage" :on-click #(reset! avatar-transform-option "copy") :class (if (= @avatar-transform-option "copy") "is-primary" "")} "Copy"] (move-button @avatar-transform-limit) ]]])]]) (defn stage-find [] [:div.modal {:class (if @active? "is-active" "")} [:div.modal-background {:on-click close-modal}] [:div.modal-card [:header.modal-card-head [:span {:class "subtitle is-5" :style {:width "10em"}} "Search Stage"] [:div {:class "field has-addons"} [:div.control [:input.input {:placeholder "paste code here" :value @input-search :on-change #(reset! input-search (-> % .-target .-value))}]] [:div.control [:button.button {:style {:margin-right "8em"} :on-click do-search} [:span {:class "icon is-small"} [:i {:class (str "fa " @search-status)}]]]]] [:button.delete {:on-click close-modal}]] (when (not (nil? (:banner @stage))) (list (with-meta [:div.modal-card-image {:class "modal-stage-banner-img"} [:img {:src (:banner @stage) :class "modal-stage-banner-img" :style {:height "100%" :width "100%" :object-fit "cover"}}]] {:key "PI:KEY:<KEY>END_PIbi"}) (with-meta (modal-body @stage) {:key "sfmsbd"}))) [:footer.modal-card-foot [:button.button (merge {:on-click join-stage :class @join-status} (if (= @join-status "is-disabled") {:disabled true} {})) "Join"] [:button.button {:on-click on-cancel} "close"]] [:button {:class "modal-close is-large" :on-click close-modal}]]])
[ { "context": "ses/MIT\"\n :year 2017\n :key \"mit\"}\n :plugins [[lein-gorilla \"0.4.0\"]]\n :depende", "end": 262, "score": 0.9877372980117798, "start": 259, "tag": "KEY", "value": "mit" } ]
project.clj
findmyway/Explorations-in-Monte-Carlo-Methods
2
(defproject emcm "0.1.0-SNAPSHOT" :description "Clojure code of examples and problems in EMCM" :url "http://example.com/FIXME" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :year 2017 :key "mit"} :plugins [[lein-gorilla "0.4.0"]] :dependencies [[org.clojure/clojure "1.8.0"] [net.mikera/core.matrix "0.60.3"] [lein-gorilla "0.4.0"]])
86454
(defproject emcm "0.1.0-SNAPSHOT" :description "Clojure code of examples and problems in EMCM" :url "http://example.com/FIXME" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :year 2017 :key "<KEY>"} :plugins [[lein-gorilla "0.4.0"]] :dependencies [[org.clojure/clojure "1.8.0"] [net.mikera/core.matrix "0.60.3"] [lein-gorilla "0.4.0"]])
true
(defproject emcm "0.1.0-SNAPSHOT" :description "Clojure code of examples and problems in EMCM" :url "http://example.com/FIXME" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :year 2017 :key "PI:KEY:<KEY>END_PI"} :plugins [[lein-gorilla "0.4.0"]] :dependencies [[org.clojure/clojure "1.8.0"] [net.mikera/core.matrix "0.60.3"] [lein-gorilla "0.4.0"]])
[ { "context": "nd therefore\n more CPU.\n\n These UGens are by Alex McLean (c) 2008.\"}\n\n {:name \"MembraneHexagon\"\n :sum", "end": 1003, "score": 0.9997401833534241, "start": 992, "tag": "NAME", "value": "Alex McLean" }, { "context": " out of triangular meshes.\n\n These UGens are by Alex McLean (c) 2008.\"}])\n", "end": 1707, "score": 0.9997842907905579, "start": 1696, "tag": "NAME", "value": "Alex McLean" } ]
src/overtone/sc/machinery/ugen/metadata/extras/membrane.clj
ABaldwinHunter/overtone
3,870
(ns overtone.sc.machinery.ugen.metadata.extras.membrane (:use [overtone.sc.machinery.ugen common check])) (def specs [ {:name "MembraneCircle" :summary "Waveguide mesh physical models of circular drum membrane." :args [{:name "excitation" :doc "sound in"} {:name "tension" :default 0.05 :doc "tension of the membrane"} {:name "loss" :default 0.99999 :doc "loss of the membrane"}] :rates #{:ar} :doc "Triangular waveguide meshes of a drum-like membrane. You input some excitation, such as a pulse of noise, and can adjust the tension and loss while it plays. Also see MembraneHexagon. The ugens are named after the shape made out of triangular meshes. Obviously you can't make a circle out of triangles, but it tries. At the moment MembraneCircle is a bit bigger than MembraneHexagon, using more waveguides and therefore more CPU. These UGens are by Alex McLean (c) 2008."} {:name "MembraneHexagon" :summary "Waveguide mesh physical models of hexagonal drum membrane." :args [{:name "excitation" :doc "sound in"} {:name "tension" :default 0.05 :doc "tension of the membrane"} {:name "loss" :default 0.99999 :doc "loss of the membrane"}] :rates #{:ar} :doc "Triangular waveguide meshes of a drum-like membrane. You input some excitation, such as a pulse of noise, and can adjust the tension and loss while it plays. Also see MembraneCircle. The ugens are named after the shape made out of triangular meshes. These UGens are by Alex McLean (c) 2008."}])
110219
(ns overtone.sc.machinery.ugen.metadata.extras.membrane (:use [overtone.sc.machinery.ugen common check])) (def specs [ {:name "MembraneCircle" :summary "Waveguide mesh physical models of circular drum membrane." :args [{:name "excitation" :doc "sound in"} {:name "tension" :default 0.05 :doc "tension of the membrane"} {:name "loss" :default 0.99999 :doc "loss of the membrane"}] :rates #{:ar} :doc "Triangular waveguide meshes of a drum-like membrane. You input some excitation, such as a pulse of noise, and can adjust the tension and loss while it plays. Also see MembraneHexagon. The ugens are named after the shape made out of triangular meshes. Obviously you can't make a circle out of triangles, but it tries. At the moment MembraneCircle is a bit bigger than MembraneHexagon, using more waveguides and therefore more CPU. These UGens are by <NAME> (c) 2008."} {:name "MembraneHexagon" :summary "Waveguide mesh physical models of hexagonal drum membrane." :args [{:name "excitation" :doc "sound in"} {:name "tension" :default 0.05 :doc "tension of the membrane"} {:name "loss" :default 0.99999 :doc "loss of the membrane"}] :rates #{:ar} :doc "Triangular waveguide meshes of a drum-like membrane. You input some excitation, such as a pulse of noise, and can adjust the tension and loss while it plays. Also see MembraneCircle. The ugens are named after the shape made out of triangular meshes. These UGens are by <NAME> (c) 2008."}])
true
(ns overtone.sc.machinery.ugen.metadata.extras.membrane (:use [overtone.sc.machinery.ugen common check])) (def specs [ {:name "MembraneCircle" :summary "Waveguide mesh physical models of circular drum membrane." :args [{:name "excitation" :doc "sound in"} {:name "tension" :default 0.05 :doc "tension of the membrane"} {:name "loss" :default 0.99999 :doc "loss of the membrane"}] :rates #{:ar} :doc "Triangular waveguide meshes of a drum-like membrane. You input some excitation, such as a pulse of noise, and can adjust the tension and loss while it plays. Also see MembraneHexagon. The ugens are named after the shape made out of triangular meshes. Obviously you can't make a circle out of triangles, but it tries. At the moment MembraneCircle is a bit bigger than MembraneHexagon, using more waveguides and therefore more CPU. These UGens are by PI:NAME:<NAME>END_PI (c) 2008."} {:name "MembraneHexagon" :summary "Waveguide mesh physical models of hexagonal drum membrane." :args [{:name "excitation" :doc "sound in"} {:name "tension" :default 0.05 :doc "tension of the membrane"} {:name "loss" :default 0.99999 :doc "loss of the membrane"}] :rates #{:ar} :doc "Triangular waveguide meshes of a drum-like membrane. You input some excitation, such as a pulse of noise, and can adjust the tension and loss while it plays. Also see MembraneCircle. The ugens are named after the shape made out of triangular meshes. These UGens are by PI:NAME:<NAME>END_PI (c) 2008."}])
[ { "context": "rl)]\n (:scientificName (first occurrences)) => \"Justicia scheidweileri\"\n (:recordedBy (last occurrences)) => \"Miranda,", "end": 1049, "score": 0.999843418598175, "start": 1027, "tag": "NAME", "value": "Justicia scheidweileri" } ]
test/dwc_io/archive_test.clj
biodivdev/dwc
0
(ns dwc-io.archive-test (:use dwc-io.archive) (:use midje.sweet)) (def test-url (clojure.java.io/resource "dwca-redlist_2013_occs.zip")) (def test-url2 "http://ipt.jbrj.gov.br/jbrj/archive.do?r=redlist_2013_taxons") (fact "Can find core tag, config of csv and fields." (let [zip (java.util.zip.ZipFile. ^java.io.File (download test-url)) core (get-core zip) dtype (get-type core) fields (get-fields core) file (get-file core) config (get-config core)] (:tag core) => :core dtype => "occurrence" file => "occurrence.txt" config => {:separator \tab :ignoreFirst true :quote \u0000} (first fields) => {:index 1 :name :language} (last fields) => {:index 23 :name :taxonomicStatus})) (fact "Types" (checklist? test-url) => false (checklist? test-url2) => true (occurrences? test-url2) => false (occurrences? test-url) => true) (fact "Can read DwC-A" (let [occurrences (read-archive test-url)] (:scientificName (first occurrences)) => "Justicia scheidweileri" (:recordedBy (last occurrences)) => "Miranda, A.M.")) (fact "Can read DwC-A taxons" (let [taxons (read-archive test-url2)] (:scientificName (first taxons)) => "Micropholis caudata"))
44632
(ns dwc-io.archive-test (:use dwc-io.archive) (:use midje.sweet)) (def test-url (clojure.java.io/resource "dwca-redlist_2013_occs.zip")) (def test-url2 "http://ipt.jbrj.gov.br/jbrj/archive.do?r=redlist_2013_taxons") (fact "Can find core tag, config of csv and fields." (let [zip (java.util.zip.ZipFile. ^java.io.File (download test-url)) core (get-core zip) dtype (get-type core) fields (get-fields core) file (get-file core) config (get-config core)] (:tag core) => :core dtype => "occurrence" file => "occurrence.txt" config => {:separator \tab :ignoreFirst true :quote \u0000} (first fields) => {:index 1 :name :language} (last fields) => {:index 23 :name :taxonomicStatus})) (fact "Types" (checklist? test-url) => false (checklist? test-url2) => true (occurrences? test-url2) => false (occurrences? test-url) => true) (fact "Can read DwC-A" (let [occurrences (read-archive test-url)] (:scientificName (first occurrences)) => "<NAME>" (:recordedBy (last occurrences)) => "Miranda, A.M.")) (fact "Can read DwC-A taxons" (let [taxons (read-archive test-url2)] (:scientificName (first taxons)) => "Micropholis caudata"))
true
(ns dwc-io.archive-test (:use dwc-io.archive) (:use midje.sweet)) (def test-url (clojure.java.io/resource "dwca-redlist_2013_occs.zip")) (def test-url2 "http://ipt.jbrj.gov.br/jbrj/archive.do?r=redlist_2013_taxons") (fact "Can find core tag, config of csv and fields." (let [zip (java.util.zip.ZipFile. ^java.io.File (download test-url)) core (get-core zip) dtype (get-type core) fields (get-fields core) file (get-file core) config (get-config core)] (:tag core) => :core dtype => "occurrence" file => "occurrence.txt" config => {:separator \tab :ignoreFirst true :quote \u0000} (first fields) => {:index 1 :name :language} (last fields) => {:index 23 :name :taxonomicStatus})) (fact "Types" (checklist? test-url) => false (checklist? test-url2) => true (occurrences? test-url2) => false (occurrences? test-url) => true) (fact "Can read DwC-A" (let [occurrences (read-archive test-url)] (:scientificName (first occurrences)) => "PI:NAME:<NAME>END_PI" (:recordedBy (last occurrences)) => "Miranda, A.M.")) (fact "Can read DwC-A taxons" (let [taxons (read-archive test-url2)] (:scientificName (first taxons)) => "Micropholis caudata"))
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.9633407592773438, "start": 30, "tag": "NAME", "value": "Net" }, { "context": " :id group0\n :keys [r0/a r1/b]\n :join-types [:requir", "end": 10726, "score": 0.9982483386993408, "start": 10717, "tag": "KEY", "value": "r0/a r1/b" }, { "context": " :id join0\n :keys [r0/a r1/b]\n :join-types [:requir", "end": 11273, "score": 0.9983579516410828, "start": 11264, "tag": "KEY", "value": "r0/a r1/b" }, { "context": " :id join0\n :keys [r0/a r1/b]\n :join-types [:requir", "end": 11826, "score": 0.9980394840240479, "start": 11817, "tag": "KEY", "value": "r0/a r1/b" } ]
pigpen-pig/src/test/clojure/pigpen/pig/script_test.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.script-test (:require [clojure.test :refer :all] [schema.test] [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [pigpen.pig.script :refer :all])) (use-fixtures :once schema.test/validate-schemas) (deftest test-format-field (is (= (#'pigpen.pig.script/format-field "abc") "'abc'")) (is (= (#'pigpen.pig.script/format-field "a'b'c") "'a\\'b\\'c'")) (is (= (#'pigpen.pig.script/format-field 'r0/foo) "foo"))) (deftest test-expr->script (is (= (#'pigpen.pig.script/expr->script nil) nil)) (is (= (#'pigpen.pig.script/expr->script "a'b\\c") "'a\\'b\\\\c'")) (is (= (#'pigpen.pig.script/expr->script 42) "42")) (is (= (#'pigpen.pig.script/expr->script 2147483648) "2147483648L")) (is (= (#'pigpen.pig.script/expr->script '?foo) "foo")) (is (= (#'pigpen.pig.script/expr->script '(clojure.core/let [foo '2] foo)) "2")) (is (= (#'pigpen.pig.script/expr->script '(clojure.core/let [foo '2] (and (= ?bar foo) (> ?baz 3)))) "((bar == 2) AND (baz > 3))"))) ;; ********** Util ********** (deftest test-code (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFn('(require (quote [pigpen.runtime]))','identity');\n\n" "udf1()"] (command->script '{:type :code :init (require '[pigpen.runtime]) :func identity :udf :seq :args []} {}))))) (deftest test-register (is (= "REGISTER foo.jar;\n\n" (command->script '{:type :register :jar "foo.jar"} {})))) (deftest test-option (is (= "SET pig.maxCombinedSplitSize 1000000;\n\n" (command->script '{:type :option :option "pig.maxCombinedSplitSize" :value 1000000} {})))) ;; ********** IO ********** (deftest test-load (is (= "load0 = LOAD 'foo'\n USING BinStorage();\n\n" (command->script '{:type :load :id load0 :location "foo" :storage :binary :fields [load0/a load0/b load0/c] :field-type :native :opts {:type :load-opts}} {}))) (is (= "load0 = LOAD 'foo' USING PigStorage('\\n') AS (a:chararray, b:chararray, c:chararray);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage :string :fields [load0/a load0/b load0/c] :field-type :native :opts {:type :load-opts}} {})))) (deftest test-store (is (= "STORE relation0 INTO 'foo'\n USING PigStorage();\n\n" (command->script '{:type :store :id store0 :ancestors [relation0] :location "foo" :args [relation0/value] :storage :string :opts {:type :store-opts}} {})))) ;; ********** Map ********** (deftest test-projection-field (is (= [nil "a AS (b)"] (command->script '{:type :projection :expr {:type :field :field r0/a} :flatten false :alias [r1/b]} {})))) (deftest test-projection-func (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFn('','(fn [x] (* x x))');\n\n" "udf1('a', a) AS (b)"] (command->script '{:type :projection :expr {:type :code :init nil :func (fn [x] (* x x)) :udf :seq :args ["a" r0/a]} :flatten false :alias [r1/b]} {}))))) (deftest test-project-flatten (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFn('','(fn [x] [x x])'); project0 = FOREACH relation0 GENERATE FLATTEN(udf1('a', a)) AS (b);\n\n" (command->script '{:type :project :id project0 :ancestors [relation0] :fields [r1/b] :field-type :frozen :projections [{:type :projection :expr {:type :code :init nil :func (fn [x] [x x]) :udf :seq :args ["a" r0/a]} :flatten true :alias [r1/b]}]} {}))))) (deftest test-sort (is (= "sort0 = ORDER relation0 BY key ASC PARALLEL 10;\n\n" (command->script '{:type :sort :id sort0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :key r0/key :comp :asc :opts {:type :sort-opts :parallel 10}} {})))) (deftest test-rank (is (= "rank0 = RANK relation0 BY key ASC DENSE;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :key r0/key :comp :asc :opts {:type :rank-opts :dense true}} {}))) (is (= "rank0 = RANK relation0;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :opts {:type :rank-opts}} {})))) ;; ********** Filter ********** (deftest test-filter (is (= "filter0 = FILTER relation0 BY ((foo == 1) AND (bar > 2));\n\n" (command->script '{:type :filter :id filter0 :fields [filter0/value] :field-type :native :ancestors [relation0] :expr '(and (= ?foo 1) (> ?bar 2))} {})))) (deftest test-take (is (= "take0 = LIMIT relation0 100;\n\n" (command->script '{:type :take :id take0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :n 100 :opts {}} {})))) (deftest test-sample (is (= "sample0 = SAMPLE relation0 0.01;\n\n" (command->script '{:type :sample :id sample0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :p 0.01 :opts {}} {})))) ;; ********** Join ********** (deftest test-reduce (is (= "group0 = COGROUP r0 ALL;\n\n" (command->script '{:type :reduce :id group0 :fields [group0/value] :field-type :frozen :arg r0/value :ancestors [r0] :opts {:type :group-opts}} {})))) (deftest test-group (is (= "group0 = COGROUP r0 BY a;\n\n" (command->script '{:type :group :id group0 :keys [r0/a] :join-types [:optional] :fields [group0/group r0/a] :field-type :frozen :field-dispatch :group :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY a, r1 BY b;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:optional :optional] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY a, r1 BY b USING 'merge' PARALLEL 2;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:optional :optional] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts :strategy :merge :parallel 2}} {}))) (is (= "group0 = COGROUP r0 BY a INNER, r1 BY b INNER;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:required :required] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts}} {})))) (deftest test-join (is (= "join0 = JOIN r0 BY a, r1 BY b;\n\n" (command->script '{:type :join :id join0 :keys [r0/a r1/b] :join-types [:required :required] :fields [r0/a r1/b] :field-type :frozen :field-dispatch :join :ancestors [r0 r1] :opts {:type :join-opts}} {}))) (is (= "join0 = JOIN r0 BY a LEFT OUTER, r1 BY b USING 'replicated' PARALLEL 2;\n\n" (command->script '{:type :join :id join0 :keys [r0/a r1/b] :join-types [:required :optional] :fields [r0/a r1/b] :field-type :frozen :field-dispatch :join :ancestors [r0 r1] :opts {:type :join-opts :strategy :replicated :parallel 2}} {})))) ;; ********** Set ********** (deftest test-distinct (let [state {:partitioner (atom -1)}] (testing "normal" (is (= "distinct0 = DISTINCT relation0 PARALLEL 20;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :parallel 20}} state)))) (testing "with partitioner" (is (= "SET PigPenPartitioner0_type 'frozen'; SET PigPenPartitioner0_init ''; SET PigPenPartitioner0_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner0;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n))}} state)))) (testing "with native partitioner" (is (= "SET PigPenPartitioner1_type 'native'; SET PigPenPartitioner1_init ''; SET PigPenPartitioner1_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner1;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n)) :partition-type :native}} state)))))) (deftest test-concat (is (= "concat0 = UNION r0, r1;\n\n" (command->script '{:type :concat :id concat0 :fields [r0/value] :field-type :frozen :ancestors [r0 r1] :opts {:type :concat-opts}} {})))) ;; ********** Script ********** ;; TODO test-store-many
121001
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.script-test (:require [clojure.test :refer :all] [schema.test] [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [pigpen.pig.script :refer :all])) (use-fixtures :once schema.test/validate-schemas) (deftest test-format-field (is (= (#'pigpen.pig.script/format-field "abc") "'abc'")) (is (= (#'pigpen.pig.script/format-field "a'b'c") "'a\\'b\\'c'")) (is (= (#'pigpen.pig.script/format-field 'r0/foo) "foo"))) (deftest test-expr->script (is (= (#'pigpen.pig.script/expr->script nil) nil)) (is (= (#'pigpen.pig.script/expr->script "a'b\\c") "'a\\'b\\\\c'")) (is (= (#'pigpen.pig.script/expr->script 42) "42")) (is (= (#'pigpen.pig.script/expr->script 2147483648) "2147483648L")) (is (= (#'pigpen.pig.script/expr->script '?foo) "foo")) (is (= (#'pigpen.pig.script/expr->script '(clojure.core/let [foo '2] foo)) "2")) (is (= (#'pigpen.pig.script/expr->script '(clojure.core/let [foo '2] (and (= ?bar foo) (> ?baz 3)))) "((bar == 2) AND (baz > 3))"))) ;; ********** Util ********** (deftest test-code (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFn('(require (quote [pigpen.runtime]))','identity');\n\n" "udf1()"] (command->script '{:type :code :init (require '[pigpen.runtime]) :func identity :udf :seq :args []} {}))))) (deftest test-register (is (= "REGISTER foo.jar;\n\n" (command->script '{:type :register :jar "foo.jar"} {})))) (deftest test-option (is (= "SET pig.maxCombinedSplitSize 1000000;\n\n" (command->script '{:type :option :option "pig.maxCombinedSplitSize" :value 1000000} {})))) ;; ********** IO ********** (deftest test-load (is (= "load0 = LOAD 'foo'\n USING BinStorage();\n\n" (command->script '{:type :load :id load0 :location "foo" :storage :binary :fields [load0/a load0/b load0/c] :field-type :native :opts {:type :load-opts}} {}))) (is (= "load0 = LOAD 'foo' USING PigStorage('\\n') AS (a:chararray, b:chararray, c:chararray);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage :string :fields [load0/a load0/b load0/c] :field-type :native :opts {:type :load-opts}} {})))) (deftest test-store (is (= "STORE relation0 INTO 'foo'\n USING PigStorage();\n\n" (command->script '{:type :store :id store0 :ancestors [relation0] :location "foo" :args [relation0/value] :storage :string :opts {:type :store-opts}} {})))) ;; ********** Map ********** (deftest test-projection-field (is (= [nil "a AS (b)"] (command->script '{:type :projection :expr {:type :field :field r0/a} :flatten false :alias [r1/b]} {})))) (deftest test-projection-func (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFn('','(fn [x] (* x x))');\n\n" "udf1('a', a) AS (b)"] (command->script '{:type :projection :expr {:type :code :init nil :func (fn [x] (* x x)) :udf :seq :args ["a" r0/a]} :flatten false :alias [r1/b]} {}))))) (deftest test-project-flatten (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFn('','(fn [x] [x x])'); project0 = FOREACH relation0 GENERATE FLATTEN(udf1('a', a)) AS (b);\n\n" (command->script '{:type :project :id project0 :ancestors [relation0] :fields [r1/b] :field-type :frozen :projections [{:type :projection :expr {:type :code :init nil :func (fn [x] [x x]) :udf :seq :args ["a" r0/a]} :flatten true :alias [r1/b]}]} {}))))) (deftest test-sort (is (= "sort0 = ORDER relation0 BY key ASC PARALLEL 10;\n\n" (command->script '{:type :sort :id sort0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :key r0/key :comp :asc :opts {:type :sort-opts :parallel 10}} {})))) (deftest test-rank (is (= "rank0 = RANK relation0 BY key ASC DENSE;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :key r0/key :comp :asc :opts {:type :rank-opts :dense true}} {}))) (is (= "rank0 = RANK relation0;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :opts {:type :rank-opts}} {})))) ;; ********** Filter ********** (deftest test-filter (is (= "filter0 = FILTER relation0 BY ((foo == 1) AND (bar > 2));\n\n" (command->script '{:type :filter :id filter0 :fields [filter0/value] :field-type :native :ancestors [relation0] :expr '(and (= ?foo 1) (> ?bar 2))} {})))) (deftest test-take (is (= "take0 = LIMIT relation0 100;\n\n" (command->script '{:type :take :id take0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :n 100 :opts {}} {})))) (deftest test-sample (is (= "sample0 = SAMPLE relation0 0.01;\n\n" (command->script '{:type :sample :id sample0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :p 0.01 :opts {}} {})))) ;; ********** Join ********** (deftest test-reduce (is (= "group0 = COGROUP r0 ALL;\n\n" (command->script '{:type :reduce :id group0 :fields [group0/value] :field-type :frozen :arg r0/value :ancestors [r0] :opts {:type :group-opts}} {})))) (deftest test-group (is (= "group0 = COGROUP r0 BY a;\n\n" (command->script '{:type :group :id group0 :keys [r0/a] :join-types [:optional] :fields [group0/group r0/a] :field-type :frozen :field-dispatch :group :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY a, r1 BY b;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:optional :optional] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY a, r1 BY b USING 'merge' PARALLEL 2;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:optional :optional] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts :strategy :merge :parallel 2}} {}))) (is (= "group0 = COGROUP r0 BY a INNER, r1 BY b INNER;\n\n" (command->script '{:type :group :id group0 :keys [<KEY>] :join-types [:required :required] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts}} {})))) (deftest test-join (is (= "join0 = JOIN r0 BY a, r1 BY b;\n\n" (command->script '{:type :join :id join0 :keys [<KEY>] :join-types [:required :required] :fields [r0/a r1/b] :field-type :frozen :field-dispatch :join :ancestors [r0 r1] :opts {:type :join-opts}} {}))) (is (= "join0 = JOIN r0 BY a LEFT OUTER, r1 BY b USING 'replicated' PARALLEL 2;\n\n" (command->script '{:type :join :id join0 :keys [<KEY>] :join-types [:required :optional] :fields [r0/a r1/b] :field-type :frozen :field-dispatch :join :ancestors [r0 r1] :opts {:type :join-opts :strategy :replicated :parallel 2}} {})))) ;; ********** Set ********** (deftest test-distinct (let [state {:partitioner (atom -1)}] (testing "normal" (is (= "distinct0 = DISTINCT relation0 PARALLEL 20;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :parallel 20}} state)))) (testing "with partitioner" (is (= "SET PigPenPartitioner0_type 'frozen'; SET PigPenPartitioner0_init ''; SET PigPenPartitioner0_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner0;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n))}} state)))) (testing "with native partitioner" (is (= "SET PigPenPartitioner1_type 'native'; SET PigPenPartitioner1_init ''; SET PigPenPartitioner1_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner1;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n)) :partition-type :native}} state)))))) (deftest test-concat (is (= "concat0 = UNION r0, r1;\n\n" (command->script '{:type :concat :id concat0 :fields [r0/value] :field-type :frozen :ancestors [r0 r1] :opts {:type :concat-opts}} {})))) ;; ********** Script ********** ;; TODO test-store-many
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.script-test (:require [clojure.test :refer :all] [schema.test] [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [pigpen.pig.script :refer :all])) (use-fixtures :once schema.test/validate-schemas) (deftest test-format-field (is (= (#'pigpen.pig.script/format-field "abc") "'abc'")) (is (= (#'pigpen.pig.script/format-field "a'b'c") "'a\\'b\\'c'")) (is (= (#'pigpen.pig.script/format-field 'r0/foo) "foo"))) (deftest test-expr->script (is (= (#'pigpen.pig.script/expr->script nil) nil)) (is (= (#'pigpen.pig.script/expr->script "a'b\\c") "'a\\'b\\\\c'")) (is (= (#'pigpen.pig.script/expr->script 42) "42")) (is (= (#'pigpen.pig.script/expr->script 2147483648) "2147483648L")) (is (= (#'pigpen.pig.script/expr->script '?foo) "foo")) (is (= (#'pigpen.pig.script/expr->script '(clojure.core/let [foo '2] foo)) "2")) (is (= (#'pigpen.pig.script/expr->script '(clojure.core/let [foo '2] (and (= ?bar foo) (> ?baz 3)))) "((bar == 2) AND (baz > 3))"))) ;; ********** Util ********** (deftest test-code (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFn('(require (quote [pigpen.runtime]))','identity');\n\n" "udf1()"] (command->script '{:type :code :init (require '[pigpen.runtime]) :func identity :udf :seq :args []} {}))))) (deftest test-register (is (= "REGISTER foo.jar;\n\n" (command->script '{:type :register :jar "foo.jar"} {})))) (deftest test-option (is (= "SET pig.maxCombinedSplitSize 1000000;\n\n" (command->script '{:type :option :option "pig.maxCombinedSplitSize" :value 1000000} {})))) ;; ********** IO ********** (deftest test-load (is (= "load0 = LOAD 'foo'\n USING BinStorage();\n\n" (command->script '{:type :load :id load0 :location "foo" :storage :binary :fields [load0/a load0/b load0/c] :field-type :native :opts {:type :load-opts}} {}))) (is (= "load0 = LOAD 'foo' USING PigStorage('\\n') AS (a:chararray, b:chararray, c:chararray);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage :string :fields [load0/a load0/b load0/c] :field-type :native :opts {:type :load-opts}} {})))) (deftest test-store (is (= "STORE relation0 INTO 'foo'\n USING PigStorage();\n\n" (command->script '{:type :store :id store0 :ancestors [relation0] :location "foo" :args [relation0/value] :storage :string :opts {:type :store-opts}} {})))) ;; ********** Map ********** (deftest test-projection-field (is (= [nil "a AS (b)"] (command->script '{:type :projection :expr {:type :field :field r0/a} :flatten false :alias [r1/b]} {})))) (deftest test-projection-func (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFn('','(fn [x] (* x x))');\n\n" "udf1('a', a) AS (b)"] (command->script '{:type :projection :expr {:type :code :init nil :func (fn [x] (* x x)) :udf :seq :args ["a" r0/a]} :flatten false :alias [r1/b]} {}))))) (deftest test-project-flatten (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFn('','(fn [x] [x x])'); project0 = FOREACH relation0 GENERATE FLATTEN(udf1('a', a)) AS (b);\n\n" (command->script '{:type :project :id project0 :ancestors [relation0] :fields [r1/b] :field-type :frozen :projections [{:type :projection :expr {:type :code :init nil :func (fn [x] [x x]) :udf :seq :args ["a" r0/a]} :flatten true :alias [r1/b]}]} {}))))) (deftest test-sort (is (= "sort0 = ORDER relation0 BY key ASC PARALLEL 10;\n\n" (command->script '{:type :sort :id sort0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :key r0/key :comp :asc :opts {:type :sort-opts :parallel 10}} {})))) (deftest test-rank (is (= "rank0 = RANK relation0 BY key ASC DENSE;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :key r0/key :comp :asc :opts {:type :rank-opts :dense true}} {}))) (is (= "rank0 = RANK relation0;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [r0/key r0/value] :field-type :frozen :opts {:type :rank-opts}} {})))) ;; ********** Filter ********** (deftest test-filter (is (= "filter0 = FILTER relation0 BY ((foo == 1) AND (bar > 2));\n\n" (command->script '{:type :filter :id filter0 :fields [filter0/value] :field-type :native :ancestors [relation0] :expr '(and (= ?foo 1) (> ?bar 2))} {})))) (deftest test-take (is (= "take0 = LIMIT relation0 100;\n\n" (command->script '{:type :take :id take0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :n 100 :opts {}} {})))) (deftest test-sample (is (= "sample0 = SAMPLE relation0 0.01;\n\n" (command->script '{:type :sample :id sample0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :p 0.01 :opts {}} {})))) ;; ********** Join ********** (deftest test-reduce (is (= "group0 = COGROUP r0 ALL;\n\n" (command->script '{:type :reduce :id group0 :fields [group0/value] :field-type :frozen :arg r0/value :ancestors [r0] :opts {:type :group-opts}} {})))) (deftest test-group (is (= "group0 = COGROUP r0 BY a;\n\n" (command->script '{:type :group :id group0 :keys [r0/a] :join-types [:optional] :fields [group0/group r0/a] :field-type :frozen :field-dispatch :group :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY a, r1 BY b;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:optional :optional] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY a, r1 BY b USING 'merge' PARALLEL 2;\n\n" (command->script '{:type :group :id group0 :keys [r0/a r1/b] :join-types [:optional :optional] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts :strategy :merge :parallel 2}} {}))) (is (= "group0 = COGROUP r0 BY a INNER, r1 BY b INNER;\n\n" (command->script '{:type :group :id group0 :keys [PI:KEY:<KEY>END_PI] :join-types [:required :required] :fields [group0/group r0/a r1/b] :field-type :frozen :field-dispatch :group :ancestors [r0 r1] :opts {:type :group-opts}} {})))) (deftest test-join (is (= "join0 = JOIN r0 BY a, r1 BY b;\n\n" (command->script '{:type :join :id join0 :keys [PI:KEY:<KEY>END_PI] :join-types [:required :required] :fields [r0/a r1/b] :field-type :frozen :field-dispatch :join :ancestors [r0 r1] :opts {:type :join-opts}} {}))) (is (= "join0 = JOIN r0 BY a LEFT OUTER, r1 BY b USING 'replicated' PARALLEL 2;\n\n" (command->script '{:type :join :id join0 :keys [PI:KEY:<KEY>END_PI] :join-types [:required :optional] :fields [r0/a r1/b] :field-type :frozen :field-dispatch :join :ancestors [r0 r1] :opts {:type :join-opts :strategy :replicated :parallel 2}} {})))) ;; ********** Set ********** (deftest test-distinct (let [state {:partitioner (atom -1)}] (testing "normal" (is (= "distinct0 = DISTINCT relation0 PARALLEL 20;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :parallel 20}} state)))) (testing "with partitioner" (is (= "SET PigPenPartitioner0_type 'frozen'; SET PigPenPartitioner0_init ''; SET PigPenPartitioner0_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner0;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n))}} state)))) (testing "with native partitioner" (is (= "SET PigPenPartitioner1_type 'native'; SET PigPenPartitioner1_init ''; SET PigPenPartitioner1_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner1;\n\n" (command->script '{:type :distinct :id distinct0 :fields [relation0/value] :field-type :frozen :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n)) :partition-type :native}} state)))))) (deftest test-concat (is (= "concat0 = UNION r0, r1;\n\n" (command->script '{:type :concat :id concat0 :fields [r0/value] :field-type :frozen :ancestors [r0 r1] :opts {:type :concat-opts}} {})))) ;; ********** Script ********** ;; TODO test-store-many
[ { "context": "tr-replace, reverse str-reverse}])\n\n(def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(deftest ", "end": 169, "score": 0.9921085238456726, "start": 156, "tag": "USERNAME", "value": "mr_paul smith" }, { "context": "rse str-reverse}])\n\n(def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(deftest string-replac", "end": 182, "score": 0.6432427763938904, "start": 172, "tag": "USERNAME", "value": "dr_john bl" }, { "context": "verse}])\n\n(def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(deftest string-replace-t", "end": 185, "score": 0.886807382106781, "start": 182, "tag": "NAME", "value": "ake" }, { "context": "def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(deftest string-replace-test\n ", "end": 196, "score": 0.5676368474960327, "start": 193, "tag": "USERNAME", "value": "kat" }, { "context": " users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(deftest string-replace-test\n (is (= ", "end": 205, "score": 0.7099918723106384, "start": 196, "tag": "NAME", "value": "ie hudson" }, { "context": "(str-replace % #\"_\" \" \") users)\n [\"mr paul smith\" \"miss katie hudson\" \"dr john blake\"])))\n\n(deftes", "end": 324, "score": 0.8849304914474487, "start": 311, "tag": "NAME", "value": "mr paul smith" }, { "context": "\"_\" \" \") users)\n [\"mr paul smith\" \"miss katie hudson\" \"dr john blake\"])))\n\n(deftest string-capitalize-", "end": 344, "score": 0.9173963665962219, "start": 327, "tag": "NAME", "value": "miss katie hudson" }, { "context": " [\"mr paul smith\" \"miss katie hudson\" \"dr john blake\"])))\n\n(deftest string-capitalize-test\n ", "end": 351, "score": 0.6852943301200867, "start": 350, "tag": "NAME", "value": "j" }, { "context": " [\"mr paul smith\" \"miss katie hudson\" \"dr john blake\"])))\n\n(deftest string-capitalize-test\n (i", "end": 360, "score": 0.55901700258255, "start": 357, "tag": "NAME", "value": "ake" }, { "context": " (= (map #(capitalize %) users)\n [\"Mr_paul smith\" \"Miss_katie hudson\" \"Dr_john blake\"])))\n\n(def", "end": 471, "score": 0.8027098178863525, "start": 461, "tag": "USERNAME", "value": "Mr_paul sm" }, { "context": "(capitalize %) users)\n [\"Mr_paul smith\" \"Miss_katie hudson\" \"Dr_john blake\"])))\n\n(def up", "end": 474, "score": 0.8151918053627014, "start": 471, "tag": "NAME", "value": "ith" }, { "context": " %) users)\n [\"Mr_paul smith\" \"Miss_katie hudson\" \"Dr_john blake\"])))\n\n(def updated-users (into #{", "end": 494, "score": 0.9735191464424133, "start": 482, "tag": "NAME", "value": "katie hudson" }, { "context": " [\"Mr_paul smith\" \"Miss_katie hudson\" \"Dr_john blake\"])))\n\n(def updated-users (into #{}\n ", "end": 510, "score": 0.9370341300964355, "start": 500, "tag": "NAME", "value": "john blake" }, { "context": "\n (is (= updated-users\n #{\"Mr Paul Smith\" \"Dr John Blake\" \"Miss Katie Hudson\"})))\n\n(def ad", "end": 876, "score": 0.9962790608406067, "start": 863, "tag": "NAME", "value": "Mr Paul Smith" }, { "context": " updated-users\n #{\"Mr Paul Smith\" \"Dr John Blake\" \"Miss Katie Hudson\"})))\n\n(def admins #{\"Mr Paul ", "end": 892, "score": 0.9879133105278015, "start": 879, "tag": "NAME", "value": "Dr John Blake" }, { "context": " #{\"Mr Paul Smith\" \"Dr John Blake\" \"Miss Katie Hudson\"})))\n\n(def admins #{\"Mr Paul Smith\" \"Miss Katie H", "end": 912, "score": 0.9949432611465454, "start": 895, "tag": "NAME", "value": "Miss Katie Hudson" }, { "context": "hn Blake\" \"Miss Katie Hudson\"})))\n\n(def admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Fo", "end": 947, "score": 0.9971351623535156, "start": 934, "tag": "NAME", "value": "Mr Paul Smith" }, { "context": "Katie Hudson\"})))\n\n(def admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(use '[clojur", "end": 967, "score": 0.9989965558052063, "start": 950, "tag": "NAME", "value": "Miss Katie Hudson" }, { "context": "def admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(use '[clojure.set :exclude ", "end": 982, "score": 0.9665837287902832, "start": 970, "tag": "NAME", "value": "Dr Mike Rose" }, { "context": "r Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(use '[clojure.set :exclude (join)])\n\n(deftes", "end": 999, "score": 0.9919447898864746, "start": 985, "tag": "NAME", "value": "Mrs Tracy Ford" } ]
Chapter08/tests/Activity8.01/repl.clj
transducer/The-Clojure-Workshop
55
(clojure.core/refer 'clojure.test :only '(deftest is run-tests)) (use '[clojure.string :rename {replace str-replace, reverse str-reverse}]) (def users #{"mr_paul smith" "dr_john blake" "miss_katie hudson"}) (deftest string-replace-test (is (= (map #(str-replace % #"_" " ") users) ["mr paul smith" "miss katie hudson" "dr john blake"]))) (deftest string-capitalize-test (is (= (map #(capitalize %) users) ["Mr_paul smith" "Miss_katie hudson" "Dr_john blake"]))) (def updated-users (into #{} (map #(join " " (map (fn [sub-str] (capitalize sub-str)) (split (str-replace % #"_" " ") #" "))) users))) (deftest update-users-test (is (= updated-users #{"Mr Paul Smith" "Dr John Blake" "Miss Katie Hudson"}))) (def admins #{"Mr Paul Smith" "Miss Katie Hudson" "Dr Mike Rose" "Mrs Tracy Ford"}) (use '[clojure.set :exclude (join)]) (deftest users-and-admins-subset-test (is (false? (subset? users admins)))) (run-tests)
28678
(clojure.core/refer 'clojure.test :only '(deftest is run-tests)) (use '[clojure.string :rename {replace str-replace, reverse str-reverse}]) (def users #{"mr_paul smith" "dr_john bl<NAME>" "miss_kat<NAME>"}) (deftest string-replace-test (is (= (map #(str-replace % #"_" " ") users) ["<NAME>" "<NAME>" "dr <NAME>ohn bl<NAME>"]))) (deftest string-capitalize-test (is (= (map #(capitalize %) users) ["Mr_paul sm<NAME>" "Miss_<NAME>" "Dr_<NAME>"]))) (def updated-users (into #{} (map #(join " " (map (fn [sub-str] (capitalize sub-str)) (split (str-replace % #"_" " ") #" "))) users))) (deftest update-users-test (is (= updated-users #{"<NAME>" "<NAME>" "<NAME>"}))) (def admins #{"<NAME>" "<NAME>" "<NAME>" "<NAME>"}) (use '[clojure.set :exclude (join)]) (deftest users-and-admins-subset-test (is (false? (subset? users admins)))) (run-tests)
true
(clojure.core/refer 'clojure.test :only '(deftest is run-tests)) (use '[clojure.string :rename {replace str-replace, reverse str-reverse}]) (def users #{"mr_paul smith" "dr_john blPI:NAME:<NAME>END_PI" "miss_katPI:NAME:<NAME>END_PI"}) (deftest string-replace-test (is (= (map #(str-replace % #"_" " ") users) ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "dr PI:NAME:<NAME>END_PIohn blPI:NAME:<NAME>END_PI"]))) (deftest string-capitalize-test (is (= (map #(capitalize %) users) ["Mr_paul smPI:NAME:<NAME>END_PI" "Miss_PI:NAME:<NAME>END_PI" "Dr_PI:NAME:<NAME>END_PI"]))) (def updated-users (into #{} (map #(join " " (map (fn [sub-str] (capitalize sub-str)) (split (str-replace % #"_" " ") #" "))) users))) (deftest update-users-test (is (= updated-users #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}))) (def admins #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}) (use '[clojure.set :exclude (join)]) (deftest users-and-admins-subset-test (is (false? (subset? users admins)))) (run-tests)
[ { "context": "ne using samples from freesound.org\"\n :author \"Karsten Schmidt\"}\n overtone.examples.workshops.resonate2013.ex04", "end": 153, "score": 0.9998682141304016, "start": 138, "tag": "NAME", "value": "Karsten Schmidt" } ]
src/overtone/examples/workshops/resonate2013/ex04_midi.clj
ABaldwinHunter/overtone
3,870
(ns ^{:doc "Mini example of using MIDI events to construct a baby drum machine using samples from freesound.org" :author "Karsten Schmidt"} overtone.examples.workshops.resonate2013.ex04_midi (:use [overtone.live])) ;; Here we define a map of MIDI notes to samples ;; You can use any freesound.org sample you wish, just change ;; the sample IDs found on the website ;; Samples will be downloaded automatically and cached in ;; the .overtone directory in your user/home folder (def drum-kit ;; c4 = kick, d4 = snare, d#4 = clap, e4 = closed hh, f4 = open hh, g4 = cowbell (->> {:c4 2086 :d4 26903 :d#4 147597 :e4 802 :f4 26657 :g4 9780} (map (fn [[n sample-id]] [(note n) (freesound sample-id)])) (into {}))) ;; First let's see which MIDI devices are connected... (midi-connected-devices) ;; MIDI is event based... ;; For drums we only are interested in :note-on events ;; emitted when a key on any connected device is pressed (on-event [:midi :note-on] ;; look up MIDI note in drumkit and only play if there's sample for it (fn [e] (when-let [drum (drum-kit (:note e))] (drum))) ::drumkit) ;; execute the below to remove the event handler later on... (comment (remove-event-handler ::drumkit))
77067
(ns ^{:doc "Mini example of using MIDI events to construct a baby drum machine using samples from freesound.org" :author "<NAME>"} overtone.examples.workshops.resonate2013.ex04_midi (:use [overtone.live])) ;; Here we define a map of MIDI notes to samples ;; You can use any freesound.org sample you wish, just change ;; the sample IDs found on the website ;; Samples will be downloaded automatically and cached in ;; the .overtone directory in your user/home folder (def drum-kit ;; c4 = kick, d4 = snare, d#4 = clap, e4 = closed hh, f4 = open hh, g4 = cowbell (->> {:c4 2086 :d4 26903 :d#4 147597 :e4 802 :f4 26657 :g4 9780} (map (fn [[n sample-id]] [(note n) (freesound sample-id)])) (into {}))) ;; First let's see which MIDI devices are connected... (midi-connected-devices) ;; MIDI is event based... ;; For drums we only are interested in :note-on events ;; emitted when a key on any connected device is pressed (on-event [:midi :note-on] ;; look up MIDI note in drumkit and only play if there's sample for it (fn [e] (when-let [drum (drum-kit (:note e))] (drum))) ::drumkit) ;; execute the below to remove the event handler later on... (comment (remove-event-handler ::drumkit))
true
(ns ^{:doc "Mini example of using MIDI events to construct a baby drum machine using samples from freesound.org" :author "PI:NAME:<NAME>END_PI"} overtone.examples.workshops.resonate2013.ex04_midi (:use [overtone.live])) ;; Here we define a map of MIDI notes to samples ;; You can use any freesound.org sample you wish, just change ;; the sample IDs found on the website ;; Samples will be downloaded automatically and cached in ;; the .overtone directory in your user/home folder (def drum-kit ;; c4 = kick, d4 = snare, d#4 = clap, e4 = closed hh, f4 = open hh, g4 = cowbell (->> {:c4 2086 :d4 26903 :d#4 147597 :e4 802 :f4 26657 :g4 9780} (map (fn [[n sample-id]] [(note n) (freesound sample-id)])) (into {}))) ;; First let's see which MIDI devices are connected... (midi-connected-devices) ;; MIDI is event based... ;; For drums we only are interested in :note-on events ;; emitted when a key on any connected device is pressed (on-event [:midi :note-on] ;; look up MIDI note in drumkit and only play if there's sample for it (fn [e] (when-let [drum (drum-kit (:note e))] (drum))) ::drumkit) ;; execute the below to remove the event handler later on... (comment (remove-event-handler ::drumkit))
[ { "context": "birds take over, I'll have friends!\"\n \"As usual, Bob's gonna do a big tree.\"\n ;; Series 9, Episode 6", "end": 8396, "score": 0.9988999962806702, "start": 8393, "tag": "NAME", "value": "Bob" } ]
src/bobrosslipsum/quotes.cljs
rusty-software/bobrosslipsum
3
(ns bobrosslipsum.quotes) (def lines [;; Series 1, Episode 1 "I think each of us, at some point during our life, has wanted to paint a picture." "We start with a vision in our heart, and we put it on canvas." "These little son-of-a-guns hide in your brush, and you just have to push them out." "You can do it! I know you can!" "Beauty is everywhere; you only have to look to see it." ;; Series 1, Episode 2 "Sometimes the brush is lazy." "Just sorta let this brush dance and play and have fun." "This is the lazy man's way of painting." "We don't wanna take it out; we just wanna mix it up." "Use what happens naturally." "Don't want to set these clouds on fire." "You can end up with great big cotton balls in the sky if you're not careful." "Learn to control it." "Dance in all these areas and just let 'em play in the sky." "Every highlight needs its own private shadow." "Scary to have this much power -- that you can move mountains!" ;; Series 1, Episode 4 "Make big billowy, fluffy clouds." "Just sorta work it around and around here." "We want this swirling, churning actions here." "Keep this brush moving all the time." "Now we're ready to start working it." "Always doing the things furthest away first and working forward." "Always follow the angles here." "It's cold, but it's beautiful." ;; Series 2, Episode 1 "See how easy that was?" "It's very easy to make a sky darker, but it's a son of a gun to make it lighter." "Another thing that seems to give us a lot of problems is almighty clouds." "Now we'll fluff it." "Now, very gently, we'll hypnotize it." "Everybody likes mountains." "Always follow the angles." "See? I knew you could do it!" "Talent is a pursued interest." "Anything you are willing to practice, you can do!" ;; Series 2, Episode 2 "I used to work for weeks to make a tree." "We are really trying to teach you a technique. We're not trying to teach you to copy." "Let your imagination be your guide." "Do whatever feels right." "There's no big secret to this." "Oh, the agony! I remember it." "I'm a nature freak." "You need to understand nature." "We spend so much of our lives looking, but never, never seeing." ;; Series 2, Episode 4 "Anyone can paint!" "Let's take the almighty brush here." "Really work it into the bristles." "Let's start with an almighty sky here." "Just let it work around and play." "Just let them fall right out of your brush." "We're gonna have a light source right in here." "Maybe we'll do some almighty mountains today." "Gentle, swirling motions here." "Let it continually go in circles, otherwise it'll look like it's raining up." "Once again: circular patterns." "Drop in a fantastic, big ol' mountain." "We take off all the excess paint." "Scrape that canvas hard! All you want to remain on there is the value." "Follow the contour of the mountain." "Let your imagination wander around while you're doing these things." "Mountains are so simple that they're hard!" "Don't want to destroy, just diffuse." ;; Series 3, Episode 4 "That's the most fun of all." "Just mix it up real good." "Now let's use the fan brush." "You just sort of have to make almighty decisions." ;; Series 3, Episode 10 "Every series, we need to have a crazy day." "We're ready to get serious with this." "See how far away that looks already?" "We'll start playing a little bit." "I love to make trees." "Use your imagination." "We're gonna give him some buns to sit on." "Talent is nothing more than a pursued interest." "It should give you a lot of ideas of a lot of crazy things you can do." ;; Series 4, Episode 2 "Just let it bounce around and play." "Let's build a happy little cloud in the sky." "You can do all this blending without becoming a mud-mixer." "It's too far away." "Painting used to drive me crazy." "It takes a very, very little bit." "Every time you add another plane, you create more depth." "Just walk right back into this painting." "Look at all those... thousands of leaves!" "You could sit there with your one-haired brush for a week trying to do that, or you can do it in one stroke with an almighty brush!" "Don't be afraid of it." "Don't worry about it; have fun with it!" "All you need is a dream in your heart." ;; Series 4, Episode 3 "Get a nice, even distribution of paint all through the bristles." "Let's just sort of play a little color here and there." "I'm always looking for a nice, easy way to do this." "If you're gonna do mountains, it's fun to have little bumps on them here and there." "All you're doing here is whisper-light." "If you over-mix it, you just get one dead color." ;; Series 5, Episode 4 "We never duplicate anything exactly." "You can always add more if you want it." "Brush mix!" "Don't let your trees get too symmetrical... too even." "All these little things make it interesting." "Find out which one works best for you, and that's the one that you want to use." "Angles are very, very important." "This is your dirt, so you put it where you want it." ;; Series 5, Episode 10 "I want to do something that's just a little bit different, and I think you'll find it's fun." "Start with a small amount and blend upward." "You can begin making all kinds of beautiful shapes up in the sky." "Let the brush play and have fun -- let it go!" "Chickens need a place to live too." "Use a color that's a little more muted and quiet." "Let's have some fun today." "Give this ol' windmill a leg!" "Don't be afraid of this big brush." "Let us know, and we'll do some more crazy things for you." ;; Series 6, Episode 2 "Ready to go!" "Just let it go, have fun." "Leave some open spots here and there." "Only takes a minute." "He lives right there -- that's his home." "Try not to kill it." "However you want to change this, that's the way it should be." "Now we can start picking out some individual things." "Here and there and there and here." "Let's work on that tree right there." "You don't want it to be flat." ;; Series 6, Episode 7 "All these fantastic things... they just sorta happen." "You can blend this until it absolutely goes away and leaves you." "Get it to where you want it, and leave it alone." "Don't piddle with them -- don't worry about them." "It's always trying to go somewhere that it can be level." "Feel the power of the water." "We'll make those decisions later." ;; Series 7, Episode 4 "Take right off today!" "Let some little things just shine through." "Leave a little area open here." "That's why I like it so much." "Just dance it around." "Keep it moving." "We're looking for happy little clouds." "Sort of mix it up." "Get tough with it." "We planned this son-of-a-gun right from the beginning." "You wouldn't buy somebody else's mistakes; nobody's going to buy yours." "Think like a tree when you do these." ;; Series 7, Episode 8 "I want some happy little things happening up here in the sky." "Help them make a happy buck or two." "That knife's a little big... let me get my small knife." "Let 'em have it!" "Follow these angles." "Don't want to overkill." "That gives us a general idea of how that mountain was made." "That son-of-a-gun is growing on us!" "Give him some arms -- a tree needs some arms." ;; Series 8, Episode 1 "Blend color right here on the canvas." "Don't want to set the sky on fire." "Be sure it's odorless or you'll be working by yourself." "You do it the way that you want it." "Use a lot of pressure." "All you're worried about is this nice outside shape." "Very soft, very quiet." "We all need a friend." "Make friends with trees." "Don't get carried away." ;; Series 8, Episode 8 "Let it sort of bounce around and play." "Be... so... careful!" "Let's build us a mountain!" "We'll make some big ol' huge mountains!" "Pretend you're a whisper floating across here." "Wiggle it, then sharpen it." "Oh dear, here comes a tree!" "When the birds take over, I'll have friends!" "As usual, Bob's gonna do a big tree." ;; Series 9, Episode 6 "Just leave that space open." "Drop in some happy little shadows." "He's a healthy cloud." "Just sorta stir it up, don't overdo -- just enough to bring it together." "We're just looking for a nice, basic, outside shape. We could care less what's going on inside here." "Water breaks, and it churns, and it has fun!" "Hit it, and get away from it." ;; Series 9, Episode 10 "We're looking for a nice, even distribution of color." "Let's have some big, fluffy clouds in this painting." "We'll just sort of slip in some clouds." "You have to sort of plan these clouds." "You do whatever works for you." "Create that little fuzzy look." "Don't worry about it -- just sort of throw it in." "Big buildings are just little buildings that had a shot of vitamins." "We don't know where that goes." "Go out and spend some time talking to a tree." "Trees are nice people." ;; Series 10, Episode 1 "Just make little X's, and we'll put in a happy little sky." "Pull from the outside in." "Let's make some big, fluffy clouds today!" "You have to make an almighty decision." "They are restricted only by your imagination." "Pretend that if you're not careful your hand will literally just float away." "It's just a game of angles." "If there's a secret to anything, it's practice." "Just practice, and you really can do this." "And that easy, we've got a happy mountain." "Painting does not have to be difficult." ;; Series 11, Episode 1 "Dance in a happy little sky." "One of our golden rules is that thin paint will stick to thick paint." "Be careful with this bright red -- it'll eat up your whole world in a heartbeat." "Think like a cloud." "Don't overwork -- be lazy!" "Get strong with it." "If there's any secret to this technique, or any other technique: it's practice." "It doesn't take much, but you have to devote that time." ;; Series 11, Episode 4 "Let's go on up here and let's get started." "Just sorta twist in a little sky." "Blend it all together and have fun with it." "Tongue got over my teeth there and I couldn't see what I was saying." "I would put water in just about everything." "Wind this up and blend it together." "Clouds could very well be the freest things in nature." "Let 'em have fun." "The round brush is so fun, let's go back to that." "As long as you have fun and learn from it, nothing is wasted." "If you want to be good at anything, you have to practice." ;; Series 12, Episode 1 "Let's put in a happy little sky." "Just make little criss-cross strokes." "See how easy that is?" "This piece of canvas is your world." "They just sort of bounce around and have fun up there." "You really cannot make a mistake here." ;; Series 13, Episode 4 "Today, we have to make a big decision." "They think you're magic!" "Just sorta rock back and forth." "Just sorta make these things up in your mind, and let them drop in." "We use darkness to make those colors stand out!" "That's one of those happy accidents." "Your artist license gives you complete freedom." "A place you want to go and run through bare-footed." ;; Series 13, Episode 9 "This is such a super day!" "These are far away, and I'm not looking for a lot of detail." "I don't know if you can ever make a pet out of an alligator, but I had an alligator who lived with me." "It helps, when you're doing these kinds of things, make up little stories in your mind." "This is where the whole ecosystem starts." "We're like drug dealers -- we come into town and get people absolutely addicted to painting." "It doesn't hurt anybody, everybody's happy, and it brings a lot of joy to people." "We have to have some fun." ;; Series 14, Episode 13 "It takes very little color." "Drop in a happy little sky here." "Everything should get lighter toward the horizon." "I think we'll put a happy little cloud up in the sky." "Maybe this is the same cloud." "There's some little stringy ones that live down here." "Give it a lift-upper." "Show it who's boss!" "You're limited only by your imagination." "I like to be able to create my own world." ;; Series 15, Episode 9 "All kinds of beautiful little things just happen." "Sing along as you're doing this." "That's the job I want in my next life -- I wanna come back and be a cloud and just float around and have a good time." "That's a fantastic little cloud." "Create the illusion." "It'll open whole new worlds for you once you learn to make friends with this knife." "Cover a couple of cameramen, and we're in business!" ;; Series 16, Episode 5 "Son of a gun, it looks like we've got two big eyes on there." "This is how you make a giant cartoon figure." "That's what makes it fun! Just enjoy!" "I just like to wash brushes." "Where do the clouds live in your world?" "Everybody needs to sing in the sunshine!" "Just like baking a cake!" "Learn to work with anything that happens." "You knew it was there all the time." "Let's make this a little more interesting." ;; Series 17, Episode 2 "We don't want to overload it, just a little bit." "I'm lazy... I look for easy ways to do things." "That blue is so strong, it'll eat up your whole world in a heartbeat." "...three hairs and some air..." "Don't let this get too strong or it'll stand out." "You have unlimited power here." "You can create any illusion that you can conceive in your mind." "Don't fight these things -- allow them to happen." "Just tap. Give it that little push." "If you're going to knock a wasp's nest down, you run." "Have to have dark in order to show light." ;; Series 18, Episode 3 "A thin, and let me say that again, a THIN layer of liquid clear." "Always keep the brush moving." "Use that to your advantage." "Don't just cover it all up -- leave these spots!" "Mountains come in all shapes and sizes." "Learn to use this knife, and you won't believe what it can do!" "You have to make friends with it." "Devote a little time to working with it." ;; Series 19, Episode 12 "Maybe we will have a little moon up here." "People are so excited when they see this happen." "Always start with a clean brush in a light area and work outward." "We'll just take the brush strokes out." "The other thing that is so fantastic about painting is that it teaches you to see." "Don't over do it -- be careful. Be careful." "Just follow your imagination." "We can stir this up a little bit." "You can continue to blend it until it just goes away." "Begin laying in just some beautiful little highlights." "There's nothing worse than an angry tree." "I want this one a little bit darker." "Do you want to get crazy?" ;; Series 20, Episode 1 "I think we'll just do a happy little picture today." "We'll have a super time." "Let's make some happy little clouds in our world." "Wherever you think they should be, then that's exactly where they should be." "Wind it up, blend it together." "I am a fanatic for water." "(chuckles) Just beat the devil out of it." "This is where you take out all your frustrations and all your hostilities, and just have a good time." "All we're trying to do is teach you a technique and turn you loose on the world." "We use no patterns, and no tracings." "All we do is just sorta have an idea in our mind, and we just sorta let it happen." "You learn to take advantage of whatever happens and use it to make your painting special." "Mix it up, just like you're making a cake or something." "...two hairs and some air..." "Let's get crazy." "I don't want a lot of mountains today." "That's about all we need." "Look at your painting and make a decision." "I lived in Alaska for many, many years." "This is a very individual thing, painting is." ;; Series 21, Episode 1 "It's easy to add more color, but it's a son of a gun to take it away." "Very gently go across the entire sky." "...right on the edge of the blade..." "Everybody will see nature through different eyes" "Everybody has their own idea of what a mountain should look like." "Let it float right down the side of the mountain." "Zooooom... you've gotta make the little noises or it doesn't work right." "Painting is as individual as people are." "At some point in between, you have to reach a happy medium." "I'll bet you didn't realize you had that much power." "You can do anything that you want to do... you can move mountains!" "You can determine what your world is like." ;; Series 22, Episode 7 "A very, very small amount." "Just like it wasn't even there." "That little painter man is so cute!" "We'll put a little mountain here." "We're gonna play some games here with different planes." "I wanna be careful to not let the color go past the tape." "Just any old thing that'll stick to the canvas." "Always have that little roll of paint." "Sometimes it's fun to play little games in your mountains." "'Course I make some mistakes at home, and we call those \"abstracts\"." "Let's play some games!" "Soft as a meadow." "It's time we got strong here." "Truly the joy of painting is the friends that you make doing it." ;; Series 22, Episode 9 "Let's just have a good time." "Today's such a wonderful day, let's just make a happy little painting." "Nothing to it." "A very quiet little sky." "You know me -- I like water." "Think about form and shape -- how do you want this thing to be?" "A half a hair and some air." "Beautiful little roundy-hill-type things." "A flock of trees? I don't know... a STAND of trees. That's what you call them!" ;; Series 23, Episode 2 "Let's really have some fun." "Now things are going to start happening." "You'll be amazed at some of the effects you can achieve." "It's very hard to see your painting when you're right up against it." "We become mud-mixers." "Maybe there's a happy little tree... he lives right there." "The more that you practice, the more you're able to visualize things." "You know me, I get crazy." ;; Series 23, Episode 3 "I want to darken the edges." "Fun time! Now we wash the ol' brush!" "Let's build us a little cloud." "Don't just throw it up there and think that a cloud will appear." "That was so much fun! Let's get crazy!" "You want to be able to control these rascals." "Just make it up." "You've got to have a little sadness once in awhile to let you know when the good times come." ;; Series 24, Episode 3 "I thought today, this would be our crazy painting." "I think you'll be tickled with what you can do with something that starts out looking this bad." "Just gonna start any ol' where." "You'll be amazed at what you can do if you'll just try." "Practice visualizing things in your mind." "Don't be afraid to experiment." "You're gonna have one WILD day!" "The birds would get sort of crazy." "Stir them up a little, then blend them." "If everything was good all the time, pretty soon you'd be accepting that as normal." "You decide where all these things are." "There's too many complicated things in our life already." ;; Series 24, Episode 7 "That's the fun part of this whole technique." "Really be stingy with it." "The just do nice things for you." "You don't have to tell them you did this with a paper towel." "Enough of that." "They are very special. Take care of those!" "Quiet, quiet little bushes." "A place for all the little creatures to put their money." "We don't know exactly where this is gonna go, and we don't care at this point." "In the woods, you have all different colors of green." "Don't be afraid to have a lot of greens." ;; Series 25, Episode 3 " That's pretty already, shoot... but we're not gonna stop there." "Just let it sorta dance around in the sky." "We'll put a few little nicety things in there." "Clouds have form and shape and life and are interesting, they're not just ol' dull clouds." "When I finally got to Alaska, whew boy, I just went crazy" "The only thing I'm good at is falling down." "I look for easy ways to do things." ;; Series 25, Episode 6 "Say all that with a mouthful of rocks." "I'll show you exactly the kind of messes we get into sometimes." "I really don't know what we're gonna do except have some fun." "Painters are expected to be different." "Remember where your finger's been before you scratch your nose." "Don't be afraid to experiment." "Don't be afraid to go out on a limb once in a while." "Where are we going with this?" "Just have a good feeling... be happy, and in love with your life and your world." ;; Series 26, Episode 1 "Let's get right to it." "This is one that you can do." "That simple, that easy!" "We'll just sort of see what happens." "That'll be a challenge!" "Let's have a big cloud!" "It's a lot of fun." "Nothing to it!" "It's bad when you have to tie a bucket on the side of your painting." "Time to get crazy now!" ;; Series 26, Episode 6 "You'd better get out your big coat and put it on." "You know I'm crazy about water." "Let's have some fun!" "Make your own mind up about where your clouds should live." "Looks like there's a storm coming already." "You have to make these big decisions in your world." "You have unlimited power here." "You can do anything that you believe you can do." "Don't think there's anybody that doesn't like mountains. Well, maybe there is." "Time to get crazy." "Everybody should have a friend." "If you learn to make one tree, you can make a million trees." "It's the contrast in this painting that makes it so pretty." ;; Series 27, Episode 5 "Very, very... let me say that one more time: very." "The smallest, very little amount." "Tell you what: let's get crazy today." "You can change your mind right mid stream." "I want a very gentle, quiet little sky." "Today, I want softness in our world... tranquility, quiet, peaceful." "Whatever works is good." ;; Series 27, Episode 11 "Let's do a winter scene, what the heck." "Maybe I'll have a big mountain today." "Life's wonderful, isn't it?" "Let's make a wild mountain today." "If we make a boo-boo, it's right here -- but that's alright, because we don't make mistakes in our world." "You know what? Let's get crazy." "He's got the leanies!" ;; Series 28, Episode 3 "Let's just do a painting that's fun." "Allow the colors to blend together." "It'll just eat up all the crimson in the world." "We don't care." "He just hangs around back there and has a good time all day." "Just a nice little mountain, a little friendly guy." "It doesn't matter in our world where it goes." "I like the mountains -- they're my favorite." "You can just go on and on and on." "Absolutely no limits!" "The joy of painting really is universal." "We've got a conglomeration going on there!" "Sometimes we get crazy here." "Now a little rabbit can hide down there and look over at us!" ;; Series 28, Episode 10 "Let's just have some fun today." "Let me put a little on the other side too, we don't want it to feel left out." "Just sort of blend it around." "I want this to be very bright right in here." "I don't know exactly what they are, and I don't really care at this point." "Just let your imagination take you to anywhere you want to be." "Shh... our secret! Don't tell, just enjoy!" "Who knows? Get crazy!" ;; Series 29, Episode 1 "Please let me thank you." "Let me tell you what I've got going on up here." "Just making little X's, little criss-cross strokes." "Quickly drop in just a little warm part of the sky here." "I sorta like that." "Doesn't take too long when you're using a brush that's two inches wide." "It's a very warm blue, very nice." "Be careful, be careful." "That's really the most fun part of it." "We'll blend it all together." "That's working so well." "You create any illusion that you want." "Sometimes it's a lot of fun to put several layers." "We don't know where that goes -- it doesn't matter at this point." "Take care of it -- treasure it!" "Let's have some MORE fun!" "Be brave!" "Save your detail for the foreground." "You don't always have to have a perfect vision in your mind." "Even a tree needs a friend." ;; Series 29, Episode 5 "Let's just enjoy today." "Anything that happens here, we can live with and we can turn it into something that looks pretty good most of the time." "Fun time!" ;; Series 29, Episode 9 "That's exactly where it should be." "That's about enough right there." "Isn't life wonderful?" "Throw in some happy little things wherever you want them." "You make the big decisions where all these things live in your world." "Take your time and play with these things." "We don't know where it goes." "Let's do another one -- what the heck!" "All you do is just go back with it." "You don't have to work at it hardly at all." "Highlight a few of these rascals." "Great time!" ;; Series 30, Episode 2 "Get nervous." "You know me -- I love water." "Let's do a happy little mountain." "Just let it float." "You make the big decisions." "We're not too worried about it today." "Painting offers freedom." "Bravery test!" "Shoot, I've got to get a little crazy." ;; Series 30, Episode 3 "It's a fantastic day here!" "A winter scene that's very warm, very pretty, and will just make you feel good." "We'll just have a firecracker of a sky up here." "Let them have a good time in your world." "The cloud needs a little friend." "Just let it sort of run across here, wherever you want it to go." "Cherish it! Take care of it!" "Think about some basic shapes and forms in this -- don't just throw them on at random." "Do a cabin-ectomy." "I like big trees." ;; Series 31, Episode 3 "It's a fantastic day here, and I hope it is wherever you're at." "We'll let our imaginations take us wherever we want to go today." "Anything that happens here, you can work with it." "You can do anything you desire on this canvas." "You can do it!" "You have to make all these big decisions when you have power." "You didn't know you had so much power, did you?" "Art is an expression of self." "If you comply with that rule, how can you go wrong?" "So many things you can create." ;; Series 31, Episode 7 "Sort of an orangy-yellowish color." "OK, let's have some fun!" "Just decide basically where you wanna start, and off you go!" "The titles comes out of there, it sounds like an old car." "He's like the rest of us -- he's about half crazy." "Just go around and try them all." "That rascal's sneaky!" "You decide -- you have to make these big decisions." "Let's get crazy here." "Don't want much... don't want much..." "Everybody should paint what they see and what they feel." "A lot of things happening right here." ])
17553
(ns bobrosslipsum.quotes) (def lines [;; Series 1, Episode 1 "I think each of us, at some point during our life, has wanted to paint a picture." "We start with a vision in our heart, and we put it on canvas." "These little son-of-a-guns hide in your brush, and you just have to push them out." "You can do it! I know you can!" "Beauty is everywhere; you only have to look to see it." ;; Series 1, Episode 2 "Sometimes the brush is lazy." "Just sorta let this brush dance and play and have fun." "This is the lazy man's way of painting." "We don't wanna take it out; we just wanna mix it up." "Use what happens naturally." "Don't want to set these clouds on fire." "You can end up with great big cotton balls in the sky if you're not careful." "Learn to control it." "Dance in all these areas and just let 'em play in the sky." "Every highlight needs its own private shadow." "Scary to have this much power -- that you can move mountains!" ;; Series 1, Episode 4 "Make big billowy, fluffy clouds." "Just sorta work it around and around here." "We want this swirling, churning actions here." "Keep this brush moving all the time." "Now we're ready to start working it." "Always doing the things furthest away first and working forward." "Always follow the angles here." "It's cold, but it's beautiful." ;; Series 2, Episode 1 "See how easy that was?" "It's very easy to make a sky darker, but it's a son of a gun to make it lighter." "Another thing that seems to give us a lot of problems is almighty clouds." "Now we'll fluff it." "Now, very gently, we'll hypnotize it." "Everybody likes mountains." "Always follow the angles." "See? I knew you could do it!" "Talent is a pursued interest." "Anything you are willing to practice, you can do!" ;; Series 2, Episode 2 "I used to work for weeks to make a tree." "We are really trying to teach you a technique. We're not trying to teach you to copy." "Let your imagination be your guide." "Do whatever feels right." "There's no big secret to this." "Oh, the agony! I remember it." "I'm a nature freak." "You need to understand nature." "We spend so much of our lives looking, but never, never seeing." ;; Series 2, Episode 4 "Anyone can paint!" "Let's take the almighty brush here." "Really work it into the bristles." "Let's start with an almighty sky here." "Just let it work around and play." "Just let them fall right out of your brush." "We're gonna have a light source right in here." "Maybe we'll do some almighty mountains today." "Gentle, swirling motions here." "Let it continually go in circles, otherwise it'll look like it's raining up." "Once again: circular patterns." "Drop in a fantastic, big ol' mountain." "We take off all the excess paint." "Scrape that canvas hard! All you want to remain on there is the value." "Follow the contour of the mountain." "Let your imagination wander around while you're doing these things." "Mountains are so simple that they're hard!" "Don't want to destroy, just diffuse." ;; Series 3, Episode 4 "That's the most fun of all." "Just mix it up real good." "Now let's use the fan brush." "You just sort of have to make almighty decisions." ;; Series 3, Episode 10 "Every series, we need to have a crazy day." "We're ready to get serious with this." "See how far away that looks already?" "We'll start playing a little bit." "I love to make trees." "Use your imagination." "We're gonna give him some buns to sit on." "Talent is nothing more than a pursued interest." "It should give you a lot of ideas of a lot of crazy things you can do." ;; Series 4, Episode 2 "Just let it bounce around and play." "Let's build a happy little cloud in the sky." "You can do all this blending without becoming a mud-mixer." "It's too far away." "Painting used to drive me crazy." "It takes a very, very little bit." "Every time you add another plane, you create more depth." "Just walk right back into this painting." "Look at all those... thousands of leaves!" "You could sit there with your one-haired brush for a week trying to do that, or you can do it in one stroke with an almighty brush!" "Don't be afraid of it." "Don't worry about it; have fun with it!" "All you need is a dream in your heart." ;; Series 4, Episode 3 "Get a nice, even distribution of paint all through the bristles." "Let's just sort of play a little color here and there." "I'm always looking for a nice, easy way to do this." "If you're gonna do mountains, it's fun to have little bumps on them here and there." "All you're doing here is whisper-light." "If you over-mix it, you just get one dead color." ;; Series 5, Episode 4 "We never duplicate anything exactly." "You can always add more if you want it." "Brush mix!" "Don't let your trees get too symmetrical... too even." "All these little things make it interesting." "Find out which one works best for you, and that's the one that you want to use." "Angles are very, very important." "This is your dirt, so you put it where you want it." ;; Series 5, Episode 10 "I want to do something that's just a little bit different, and I think you'll find it's fun." "Start with a small amount and blend upward." "You can begin making all kinds of beautiful shapes up in the sky." "Let the brush play and have fun -- let it go!" "Chickens need a place to live too." "Use a color that's a little more muted and quiet." "Let's have some fun today." "Give this ol' windmill a leg!" "Don't be afraid of this big brush." "Let us know, and we'll do some more crazy things for you." ;; Series 6, Episode 2 "Ready to go!" "Just let it go, have fun." "Leave some open spots here and there." "Only takes a minute." "He lives right there -- that's his home." "Try not to kill it." "However you want to change this, that's the way it should be." "Now we can start picking out some individual things." "Here and there and there and here." "Let's work on that tree right there." "You don't want it to be flat." ;; Series 6, Episode 7 "All these fantastic things... they just sorta happen." "You can blend this until it absolutely goes away and leaves you." "Get it to where you want it, and leave it alone." "Don't piddle with them -- don't worry about them." "It's always trying to go somewhere that it can be level." "Feel the power of the water." "We'll make those decisions later." ;; Series 7, Episode 4 "Take right off today!" "Let some little things just shine through." "Leave a little area open here." "That's why I like it so much." "Just dance it around." "Keep it moving." "We're looking for happy little clouds." "Sort of mix it up." "Get tough with it." "We planned this son-of-a-gun right from the beginning." "You wouldn't buy somebody else's mistakes; nobody's going to buy yours." "Think like a tree when you do these." ;; Series 7, Episode 8 "I want some happy little things happening up here in the sky." "Help them make a happy buck or two." "That knife's a little big... let me get my small knife." "Let 'em have it!" "Follow these angles." "Don't want to overkill." "That gives us a general idea of how that mountain was made." "That son-of-a-gun is growing on us!" "Give him some arms -- a tree needs some arms." ;; Series 8, Episode 1 "Blend color right here on the canvas." "Don't want to set the sky on fire." "Be sure it's odorless or you'll be working by yourself." "You do it the way that you want it." "Use a lot of pressure." "All you're worried about is this nice outside shape." "Very soft, very quiet." "We all need a friend." "Make friends with trees." "Don't get carried away." ;; Series 8, Episode 8 "Let it sort of bounce around and play." "Be... so... careful!" "Let's build us a mountain!" "We'll make some big ol' huge mountains!" "Pretend you're a whisper floating across here." "Wiggle it, then sharpen it." "Oh dear, here comes a tree!" "When the birds take over, I'll have friends!" "As usual, <NAME>'s gonna do a big tree." ;; Series 9, Episode 6 "Just leave that space open." "Drop in some happy little shadows." "He's a healthy cloud." "Just sorta stir it up, don't overdo -- just enough to bring it together." "We're just looking for a nice, basic, outside shape. We could care less what's going on inside here." "Water breaks, and it churns, and it has fun!" "Hit it, and get away from it." ;; Series 9, Episode 10 "We're looking for a nice, even distribution of color." "Let's have some big, fluffy clouds in this painting." "We'll just sort of slip in some clouds." "You have to sort of plan these clouds." "You do whatever works for you." "Create that little fuzzy look." "Don't worry about it -- just sort of throw it in." "Big buildings are just little buildings that had a shot of vitamins." "We don't know where that goes." "Go out and spend some time talking to a tree." "Trees are nice people." ;; Series 10, Episode 1 "Just make little X's, and we'll put in a happy little sky." "Pull from the outside in." "Let's make some big, fluffy clouds today!" "You have to make an almighty decision." "They are restricted only by your imagination." "Pretend that if you're not careful your hand will literally just float away." "It's just a game of angles." "If there's a secret to anything, it's practice." "Just practice, and you really can do this." "And that easy, we've got a happy mountain." "Painting does not have to be difficult." ;; Series 11, Episode 1 "Dance in a happy little sky." "One of our golden rules is that thin paint will stick to thick paint." "Be careful with this bright red -- it'll eat up your whole world in a heartbeat." "Think like a cloud." "Don't overwork -- be lazy!" "Get strong with it." "If there's any secret to this technique, or any other technique: it's practice." "It doesn't take much, but you have to devote that time." ;; Series 11, Episode 4 "Let's go on up here and let's get started." "Just sorta twist in a little sky." "Blend it all together and have fun with it." "Tongue got over my teeth there and I couldn't see what I was saying." "I would put water in just about everything." "Wind this up and blend it together." "Clouds could very well be the freest things in nature." "Let 'em have fun." "The round brush is so fun, let's go back to that." "As long as you have fun and learn from it, nothing is wasted." "If you want to be good at anything, you have to practice." ;; Series 12, Episode 1 "Let's put in a happy little sky." "Just make little criss-cross strokes." "See how easy that is?" "This piece of canvas is your world." "They just sort of bounce around and have fun up there." "You really cannot make a mistake here." ;; Series 13, Episode 4 "Today, we have to make a big decision." "They think you're magic!" "Just sorta rock back and forth." "Just sorta make these things up in your mind, and let them drop in." "We use darkness to make those colors stand out!" "That's one of those happy accidents." "Your artist license gives you complete freedom." "A place you want to go and run through bare-footed." ;; Series 13, Episode 9 "This is such a super day!" "These are far away, and I'm not looking for a lot of detail." "I don't know if you can ever make a pet out of an alligator, but I had an alligator who lived with me." "It helps, when you're doing these kinds of things, make up little stories in your mind." "This is where the whole ecosystem starts." "We're like drug dealers -- we come into town and get people absolutely addicted to painting." "It doesn't hurt anybody, everybody's happy, and it brings a lot of joy to people." "We have to have some fun." ;; Series 14, Episode 13 "It takes very little color." "Drop in a happy little sky here." "Everything should get lighter toward the horizon." "I think we'll put a happy little cloud up in the sky." "Maybe this is the same cloud." "There's some little stringy ones that live down here." "Give it a lift-upper." "Show it who's boss!" "You're limited only by your imagination." "I like to be able to create my own world." ;; Series 15, Episode 9 "All kinds of beautiful little things just happen." "Sing along as you're doing this." "That's the job I want in my next life -- I wanna come back and be a cloud and just float around and have a good time." "That's a fantastic little cloud." "Create the illusion." "It'll open whole new worlds for you once you learn to make friends with this knife." "Cover a couple of cameramen, and we're in business!" ;; Series 16, Episode 5 "Son of a gun, it looks like we've got two big eyes on there." "This is how you make a giant cartoon figure." "That's what makes it fun! Just enjoy!" "I just like to wash brushes." "Where do the clouds live in your world?" "Everybody needs to sing in the sunshine!" "Just like baking a cake!" "Learn to work with anything that happens." "You knew it was there all the time." "Let's make this a little more interesting." ;; Series 17, Episode 2 "We don't want to overload it, just a little bit." "I'm lazy... I look for easy ways to do things." "That blue is so strong, it'll eat up your whole world in a heartbeat." "...three hairs and some air..." "Don't let this get too strong or it'll stand out." "You have unlimited power here." "You can create any illusion that you can conceive in your mind." "Don't fight these things -- allow them to happen." "Just tap. Give it that little push." "If you're going to knock a wasp's nest down, you run." "Have to have dark in order to show light." ;; Series 18, Episode 3 "A thin, and let me say that again, a THIN layer of liquid clear." "Always keep the brush moving." "Use that to your advantage." "Don't just cover it all up -- leave these spots!" "Mountains come in all shapes and sizes." "Learn to use this knife, and you won't believe what it can do!" "You have to make friends with it." "Devote a little time to working with it." ;; Series 19, Episode 12 "Maybe we will have a little moon up here." "People are so excited when they see this happen." "Always start with a clean brush in a light area and work outward." "We'll just take the brush strokes out." "The other thing that is so fantastic about painting is that it teaches you to see." "Don't over do it -- be careful. Be careful." "Just follow your imagination." "We can stir this up a little bit." "You can continue to blend it until it just goes away." "Begin laying in just some beautiful little highlights." "There's nothing worse than an angry tree." "I want this one a little bit darker." "Do you want to get crazy?" ;; Series 20, Episode 1 "I think we'll just do a happy little picture today." "We'll have a super time." "Let's make some happy little clouds in our world." "Wherever you think they should be, then that's exactly where they should be." "Wind it up, blend it together." "I am a fanatic for water." "(chuckles) Just beat the devil out of it." "This is where you take out all your frustrations and all your hostilities, and just have a good time." "All we're trying to do is teach you a technique and turn you loose on the world." "We use no patterns, and no tracings." "All we do is just sorta have an idea in our mind, and we just sorta let it happen." "You learn to take advantage of whatever happens and use it to make your painting special." "Mix it up, just like you're making a cake or something." "...two hairs and some air..." "Let's get crazy." "I don't want a lot of mountains today." "That's about all we need." "Look at your painting and make a decision." "I lived in Alaska for many, many years." "This is a very individual thing, painting is." ;; Series 21, Episode 1 "It's easy to add more color, but it's a son of a gun to take it away." "Very gently go across the entire sky." "...right on the edge of the blade..." "Everybody will see nature through different eyes" "Everybody has their own idea of what a mountain should look like." "Let it float right down the side of the mountain." "Zooooom... you've gotta make the little noises or it doesn't work right." "Painting is as individual as people are." "At some point in between, you have to reach a happy medium." "I'll bet you didn't realize you had that much power." "You can do anything that you want to do... you can move mountains!" "You can determine what your world is like." ;; Series 22, Episode 7 "A very, very small amount." "Just like it wasn't even there." "That little painter man is so cute!" "We'll put a little mountain here." "We're gonna play some games here with different planes." "I wanna be careful to not let the color go past the tape." "Just any old thing that'll stick to the canvas." "Always have that little roll of paint." "Sometimes it's fun to play little games in your mountains." "'Course I make some mistakes at home, and we call those \"abstracts\"." "Let's play some games!" "Soft as a meadow." "It's time we got strong here." "Truly the joy of painting is the friends that you make doing it." ;; Series 22, Episode 9 "Let's just have a good time." "Today's such a wonderful day, let's just make a happy little painting." "Nothing to it." "A very quiet little sky." "You know me -- I like water." "Think about form and shape -- how do you want this thing to be?" "A half a hair and some air." "Beautiful little roundy-hill-type things." "A flock of trees? I don't know... a STAND of trees. That's what you call them!" ;; Series 23, Episode 2 "Let's really have some fun." "Now things are going to start happening." "You'll be amazed at some of the effects you can achieve." "It's very hard to see your painting when you're right up against it." "We become mud-mixers." "Maybe there's a happy little tree... he lives right there." "The more that you practice, the more you're able to visualize things." "You know me, I get crazy." ;; Series 23, Episode 3 "I want to darken the edges." "Fun time! Now we wash the ol' brush!" "Let's build us a little cloud." "Don't just throw it up there and think that a cloud will appear." "That was so much fun! Let's get crazy!" "You want to be able to control these rascals." "Just make it up." "You've got to have a little sadness once in awhile to let you know when the good times come." ;; Series 24, Episode 3 "I thought today, this would be our crazy painting." "I think you'll be tickled with what you can do with something that starts out looking this bad." "Just gonna start any ol' where." "You'll be amazed at what you can do if you'll just try." "Practice visualizing things in your mind." "Don't be afraid to experiment." "You're gonna have one WILD day!" "The birds would get sort of crazy." "Stir them up a little, then blend them." "If everything was good all the time, pretty soon you'd be accepting that as normal." "You decide where all these things are." "There's too many complicated things in our life already." ;; Series 24, Episode 7 "That's the fun part of this whole technique." "Really be stingy with it." "The just do nice things for you." "You don't have to tell them you did this with a paper towel." "Enough of that." "They are very special. Take care of those!" "Quiet, quiet little bushes." "A place for all the little creatures to put their money." "We don't know exactly where this is gonna go, and we don't care at this point." "In the woods, you have all different colors of green." "Don't be afraid to have a lot of greens." ;; Series 25, Episode 3 " That's pretty already, shoot... but we're not gonna stop there." "Just let it sorta dance around in the sky." "We'll put a few little nicety things in there." "Clouds have form and shape and life and are interesting, they're not just ol' dull clouds." "When I finally got to Alaska, whew boy, I just went crazy" "The only thing I'm good at is falling down." "I look for easy ways to do things." ;; Series 25, Episode 6 "Say all that with a mouthful of rocks." "I'll show you exactly the kind of messes we get into sometimes." "I really don't know what we're gonna do except have some fun." "Painters are expected to be different." "Remember where your finger's been before you scratch your nose." "Don't be afraid to experiment." "Don't be afraid to go out on a limb once in a while." "Where are we going with this?" "Just have a good feeling... be happy, and in love with your life and your world." ;; Series 26, Episode 1 "Let's get right to it." "This is one that you can do." "That simple, that easy!" "We'll just sort of see what happens." "That'll be a challenge!" "Let's have a big cloud!" "It's a lot of fun." "Nothing to it!" "It's bad when you have to tie a bucket on the side of your painting." "Time to get crazy now!" ;; Series 26, Episode 6 "You'd better get out your big coat and put it on." "You know I'm crazy about water." "Let's have some fun!" "Make your own mind up about where your clouds should live." "Looks like there's a storm coming already." "You have to make these big decisions in your world." "You have unlimited power here." "You can do anything that you believe you can do." "Don't think there's anybody that doesn't like mountains. Well, maybe there is." "Time to get crazy." "Everybody should have a friend." "If you learn to make one tree, you can make a million trees." "It's the contrast in this painting that makes it so pretty." ;; Series 27, Episode 5 "Very, very... let me say that one more time: very." "The smallest, very little amount." "Tell you what: let's get crazy today." "You can change your mind right mid stream." "I want a very gentle, quiet little sky." "Today, I want softness in our world... tranquility, quiet, peaceful." "Whatever works is good." ;; Series 27, Episode 11 "Let's do a winter scene, what the heck." "Maybe I'll have a big mountain today." "Life's wonderful, isn't it?" "Let's make a wild mountain today." "If we make a boo-boo, it's right here -- but that's alright, because we don't make mistakes in our world." "You know what? Let's get crazy." "He's got the leanies!" ;; Series 28, Episode 3 "Let's just do a painting that's fun." "Allow the colors to blend together." "It'll just eat up all the crimson in the world." "We don't care." "He just hangs around back there and has a good time all day." "Just a nice little mountain, a little friendly guy." "It doesn't matter in our world where it goes." "I like the mountains -- they're my favorite." "You can just go on and on and on." "Absolutely no limits!" "The joy of painting really is universal." "We've got a conglomeration going on there!" "Sometimes we get crazy here." "Now a little rabbit can hide down there and look over at us!" ;; Series 28, Episode 10 "Let's just have some fun today." "Let me put a little on the other side too, we don't want it to feel left out." "Just sort of blend it around." "I want this to be very bright right in here." "I don't know exactly what they are, and I don't really care at this point." "Just let your imagination take you to anywhere you want to be." "Shh... our secret! Don't tell, just enjoy!" "Who knows? Get crazy!" ;; Series 29, Episode 1 "Please let me thank you." "Let me tell you what I've got going on up here." "Just making little X's, little criss-cross strokes." "Quickly drop in just a little warm part of the sky here." "I sorta like that." "Doesn't take too long when you're using a brush that's two inches wide." "It's a very warm blue, very nice." "Be careful, be careful." "That's really the most fun part of it." "We'll blend it all together." "That's working so well." "You create any illusion that you want." "Sometimes it's a lot of fun to put several layers." "We don't know where that goes -- it doesn't matter at this point." "Take care of it -- treasure it!" "Let's have some MORE fun!" "Be brave!" "Save your detail for the foreground." "You don't always have to have a perfect vision in your mind." "Even a tree needs a friend." ;; Series 29, Episode 5 "Let's just enjoy today." "Anything that happens here, we can live with and we can turn it into something that looks pretty good most of the time." "Fun time!" ;; Series 29, Episode 9 "That's exactly where it should be." "That's about enough right there." "Isn't life wonderful?" "Throw in some happy little things wherever you want them." "You make the big decisions where all these things live in your world." "Take your time and play with these things." "We don't know where it goes." "Let's do another one -- what the heck!" "All you do is just go back with it." "You don't have to work at it hardly at all." "Highlight a few of these rascals." "Great time!" ;; Series 30, Episode 2 "Get nervous." "You know me -- I love water." "Let's do a happy little mountain." "Just let it float." "You make the big decisions." "We're not too worried about it today." "Painting offers freedom." "Bravery test!" "Shoot, I've got to get a little crazy." ;; Series 30, Episode 3 "It's a fantastic day here!" "A winter scene that's very warm, very pretty, and will just make you feel good." "We'll just have a firecracker of a sky up here." "Let them have a good time in your world." "The cloud needs a little friend." "Just let it sort of run across here, wherever you want it to go." "Cherish it! Take care of it!" "Think about some basic shapes and forms in this -- don't just throw them on at random." "Do a cabin-ectomy." "I like big trees." ;; Series 31, Episode 3 "It's a fantastic day here, and I hope it is wherever you're at." "We'll let our imaginations take us wherever we want to go today." "Anything that happens here, you can work with it." "You can do anything you desire on this canvas." "You can do it!" "You have to make all these big decisions when you have power." "You didn't know you had so much power, did you?" "Art is an expression of self." "If you comply with that rule, how can you go wrong?" "So many things you can create." ;; Series 31, Episode 7 "Sort of an orangy-yellowish color." "OK, let's have some fun!" "Just decide basically where you wanna start, and off you go!" "The titles comes out of there, it sounds like an old car." "He's like the rest of us -- he's about half crazy." "Just go around and try them all." "That rascal's sneaky!" "You decide -- you have to make these big decisions." "Let's get crazy here." "Don't want much... don't want much..." "Everybody should paint what they see and what they feel." "A lot of things happening right here." ])
true
(ns bobrosslipsum.quotes) (def lines [;; Series 1, Episode 1 "I think each of us, at some point during our life, has wanted to paint a picture." "We start with a vision in our heart, and we put it on canvas." "These little son-of-a-guns hide in your brush, and you just have to push them out." "You can do it! I know you can!" "Beauty is everywhere; you only have to look to see it." ;; Series 1, Episode 2 "Sometimes the brush is lazy." "Just sorta let this brush dance and play and have fun." "This is the lazy man's way of painting." "We don't wanna take it out; we just wanna mix it up." "Use what happens naturally." "Don't want to set these clouds on fire." "You can end up with great big cotton balls in the sky if you're not careful." "Learn to control it." "Dance in all these areas and just let 'em play in the sky." "Every highlight needs its own private shadow." "Scary to have this much power -- that you can move mountains!" ;; Series 1, Episode 4 "Make big billowy, fluffy clouds." "Just sorta work it around and around here." "We want this swirling, churning actions here." "Keep this brush moving all the time." "Now we're ready to start working it." "Always doing the things furthest away first and working forward." "Always follow the angles here." "It's cold, but it's beautiful." ;; Series 2, Episode 1 "See how easy that was?" "It's very easy to make a sky darker, but it's a son of a gun to make it lighter." "Another thing that seems to give us a lot of problems is almighty clouds." "Now we'll fluff it." "Now, very gently, we'll hypnotize it." "Everybody likes mountains." "Always follow the angles." "See? I knew you could do it!" "Talent is a pursued interest." "Anything you are willing to practice, you can do!" ;; Series 2, Episode 2 "I used to work for weeks to make a tree." "We are really trying to teach you a technique. We're not trying to teach you to copy." "Let your imagination be your guide." "Do whatever feels right." "There's no big secret to this." "Oh, the agony! I remember it." "I'm a nature freak." "You need to understand nature." "We spend so much of our lives looking, but never, never seeing." ;; Series 2, Episode 4 "Anyone can paint!" "Let's take the almighty brush here." "Really work it into the bristles." "Let's start with an almighty sky here." "Just let it work around and play." "Just let them fall right out of your brush." "We're gonna have a light source right in here." "Maybe we'll do some almighty mountains today." "Gentle, swirling motions here." "Let it continually go in circles, otherwise it'll look like it's raining up." "Once again: circular patterns." "Drop in a fantastic, big ol' mountain." "We take off all the excess paint." "Scrape that canvas hard! All you want to remain on there is the value." "Follow the contour of the mountain." "Let your imagination wander around while you're doing these things." "Mountains are so simple that they're hard!" "Don't want to destroy, just diffuse." ;; Series 3, Episode 4 "That's the most fun of all." "Just mix it up real good." "Now let's use the fan brush." "You just sort of have to make almighty decisions." ;; Series 3, Episode 10 "Every series, we need to have a crazy day." "We're ready to get serious with this." "See how far away that looks already?" "We'll start playing a little bit." "I love to make trees." "Use your imagination." "We're gonna give him some buns to sit on." "Talent is nothing more than a pursued interest." "It should give you a lot of ideas of a lot of crazy things you can do." ;; Series 4, Episode 2 "Just let it bounce around and play." "Let's build a happy little cloud in the sky." "You can do all this blending without becoming a mud-mixer." "It's too far away." "Painting used to drive me crazy." "It takes a very, very little bit." "Every time you add another plane, you create more depth." "Just walk right back into this painting." "Look at all those... thousands of leaves!" "You could sit there with your one-haired brush for a week trying to do that, or you can do it in one stroke with an almighty brush!" "Don't be afraid of it." "Don't worry about it; have fun with it!" "All you need is a dream in your heart." ;; Series 4, Episode 3 "Get a nice, even distribution of paint all through the bristles." "Let's just sort of play a little color here and there." "I'm always looking for a nice, easy way to do this." "If you're gonna do mountains, it's fun to have little bumps on them here and there." "All you're doing here is whisper-light." "If you over-mix it, you just get one dead color." ;; Series 5, Episode 4 "We never duplicate anything exactly." "You can always add more if you want it." "Brush mix!" "Don't let your trees get too symmetrical... too even." "All these little things make it interesting." "Find out which one works best for you, and that's the one that you want to use." "Angles are very, very important." "This is your dirt, so you put it where you want it." ;; Series 5, Episode 10 "I want to do something that's just a little bit different, and I think you'll find it's fun." "Start with a small amount and blend upward." "You can begin making all kinds of beautiful shapes up in the sky." "Let the brush play and have fun -- let it go!" "Chickens need a place to live too." "Use a color that's a little more muted and quiet." "Let's have some fun today." "Give this ol' windmill a leg!" "Don't be afraid of this big brush." "Let us know, and we'll do some more crazy things for you." ;; Series 6, Episode 2 "Ready to go!" "Just let it go, have fun." "Leave some open spots here and there." "Only takes a minute." "He lives right there -- that's his home." "Try not to kill it." "However you want to change this, that's the way it should be." "Now we can start picking out some individual things." "Here and there and there and here." "Let's work on that tree right there." "You don't want it to be flat." ;; Series 6, Episode 7 "All these fantastic things... they just sorta happen." "You can blend this until it absolutely goes away and leaves you." "Get it to where you want it, and leave it alone." "Don't piddle with them -- don't worry about them." "It's always trying to go somewhere that it can be level." "Feel the power of the water." "We'll make those decisions later." ;; Series 7, Episode 4 "Take right off today!" "Let some little things just shine through." "Leave a little area open here." "That's why I like it so much." "Just dance it around." "Keep it moving." "We're looking for happy little clouds." "Sort of mix it up." "Get tough with it." "We planned this son-of-a-gun right from the beginning." "You wouldn't buy somebody else's mistakes; nobody's going to buy yours." "Think like a tree when you do these." ;; Series 7, Episode 8 "I want some happy little things happening up here in the sky." "Help them make a happy buck or two." "That knife's a little big... let me get my small knife." "Let 'em have it!" "Follow these angles." "Don't want to overkill." "That gives us a general idea of how that mountain was made." "That son-of-a-gun is growing on us!" "Give him some arms -- a tree needs some arms." ;; Series 8, Episode 1 "Blend color right here on the canvas." "Don't want to set the sky on fire." "Be sure it's odorless or you'll be working by yourself." "You do it the way that you want it." "Use a lot of pressure." "All you're worried about is this nice outside shape." "Very soft, very quiet." "We all need a friend." "Make friends with trees." "Don't get carried away." ;; Series 8, Episode 8 "Let it sort of bounce around and play." "Be... so... careful!" "Let's build us a mountain!" "We'll make some big ol' huge mountains!" "Pretend you're a whisper floating across here." "Wiggle it, then sharpen it." "Oh dear, here comes a tree!" "When the birds take over, I'll have friends!" "As usual, PI:NAME:<NAME>END_PI's gonna do a big tree." ;; Series 9, Episode 6 "Just leave that space open." "Drop in some happy little shadows." "He's a healthy cloud." "Just sorta stir it up, don't overdo -- just enough to bring it together." "We're just looking for a nice, basic, outside shape. We could care less what's going on inside here." "Water breaks, and it churns, and it has fun!" "Hit it, and get away from it." ;; Series 9, Episode 10 "We're looking for a nice, even distribution of color." "Let's have some big, fluffy clouds in this painting." "We'll just sort of slip in some clouds." "You have to sort of plan these clouds." "You do whatever works for you." "Create that little fuzzy look." "Don't worry about it -- just sort of throw it in." "Big buildings are just little buildings that had a shot of vitamins." "We don't know where that goes." "Go out and spend some time talking to a tree." "Trees are nice people." ;; Series 10, Episode 1 "Just make little X's, and we'll put in a happy little sky." "Pull from the outside in." "Let's make some big, fluffy clouds today!" "You have to make an almighty decision." "They are restricted only by your imagination." "Pretend that if you're not careful your hand will literally just float away." "It's just a game of angles." "If there's a secret to anything, it's practice." "Just practice, and you really can do this." "And that easy, we've got a happy mountain." "Painting does not have to be difficult." ;; Series 11, Episode 1 "Dance in a happy little sky." "One of our golden rules is that thin paint will stick to thick paint." "Be careful with this bright red -- it'll eat up your whole world in a heartbeat." "Think like a cloud." "Don't overwork -- be lazy!" "Get strong with it." "If there's any secret to this technique, or any other technique: it's practice." "It doesn't take much, but you have to devote that time." ;; Series 11, Episode 4 "Let's go on up here and let's get started." "Just sorta twist in a little sky." "Blend it all together and have fun with it." "Tongue got over my teeth there and I couldn't see what I was saying." "I would put water in just about everything." "Wind this up and blend it together." "Clouds could very well be the freest things in nature." "Let 'em have fun." "The round brush is so fun, let's go back to that." "As long as you have fun and learn from it, nothing is wasted." "If you want to be good at anything, you have to practice." ;; Series 12, Episode 1 "Let's put in a happy little sky." "Just make little criss-cross strokes." "See how easy that is?" "This piece of canvas is your world." "They just sort of bounce around and have fun up there." "You really cannot make a mistake here." ;; Series 13, Episode 4 "Today, we have to make a big decision." "They think you're magic!" "Just sorta rock back and forth." "Just sorta make these things up in your mind, and let them drop in." "We use darkness to make those colors stand out!" "That's one of those happy accidents." "Your artist license gives you complete freedom." "A place you want to go and run through bare-footed." ;; Series 13, Episode 9 "This is such a super day!" "These are far away, and I'm not looking for a lot of detail." "I don't know if you can ever make a pet out of an alligator, but I had an alligator who lived with me." "It helps, when you're doing these kinds of things, make up little stories in your mind." "This is where the whole ecosystem starts." "We're like drug dealers -- we come into town and get people absolutely addicted to painting." "It doesn't hurt anybody, everybody's happy, and it brings a lot of joy to people." "We have to have some fun." ;; Series 14, Episode 13 "It takes very little color." "Drop in a happy little sky here." "Everything should get lighter toward the horizon." "I think we'll put a happy little cloud up in the sky." "Maybe this is the same cloud." "There's some little stringy ones that live down here." "Give it a lift-upper." "Show it who's boss!" "You're limited only by your imagination." "I like to be able to create my own world." ;; Series 15, Episode 9 "All kinds of beautiful little things just happen." "Sing along as you're doing this." "That's the job I want in my next life -- I wanna come back and be a cloud and just float around and have a good time." "That's a fantastic little cloud." "Create the illusion." "It'll open whole new worlds for you once you learn to make friends with this knife." "Cover a couple of cameramen, and we're in business!" ;; Series 16, Episode 5 "Son of a gun, it looks like we've got two big eyes on there." "This is how you make a giant cartoon figure." "That's what makes it fun! Just enjoy!" "I just like to wash brushes." "Where do the clouds live in your world?" "Everybody needs to sing in the sunshine!" "Just like baking a cake!" "Learn to work with anything that happens." "You knew it was there all the time." "Let's make this a little more interesting." ;; Series 17, Episode 2 "We don't want to overload it, just a little bit." "I'm lazy... I look for easy ways to do things." "That blue is so strong, it'll eat up your whole world in a heartbeat." "...three hairs and some air..." "Don't let this get too strong or it'll stand out." "You have unlimited power here." "You can create any illusion that you can conceive in your mind." "Don't fight these things -- allow them to happen." "Just tap. Give it that little push." "If you're going to knock a wasp's nest down, you run." "Have to have dark in order to show light." ;; Series 18, Episode 3 "A thin, and let me say that again, a THIN layer of liquid clear." "Always keep the brush moving." "Use that to your advantage." "Don't just cover it all up -- leave these spots!" "Mountains come in all shapes and sizes." "Learn to use this knife, and you won't believe what it can do!" "You have to make friends with it." "Devote a little time to working with it." ;; Series 19, Episode 12 "Maybe we will have a little moon up here." "People are so excited when they see this happen." "Always start with a clean brush in a light area and work outward." "We'll just take the brush strokes out." "The other thing that is so fantastic about painting is that it teaches you to see." "Don't over do it -- be careful. Be careful." "Just follow your imagination." "We can stir this up a little bit." "You can continue to blend it until it just goes away." "Begin laying in just some beautiful little highlights." "There's nothing worse than an angry tree." "I want this one a little bit darker." "Do you want to get crazy?" ;; Series 20, Episode 1 "I think we'll just do a happy little picture today." "We'll have a super time." "Let's make some happy little clouds in our world." "Wherever you think they should be, then that's exactly where they should be." "Wind it up, blend it together." "I am a fanatic for water." "(chuckles) Just beat the devil out of it." "This is where you take out all your frustrations and all your hostilities, and just have a good time." "All we're trying to do is teach you a technique and turn you loose on the world." "We use no patterns, and no tracings." "All we do is just sorta have an idea in our mind, and we just sorta let it happen." "You learn to take advantage of whatever happens and use it to make your painting special." "Mix it up, just like you're making a cake or something." "...two hairs and some air..." "Let's get crazy." "I don't want a lot of mountains today." "That's about all we need." "Look at your painting and make a decision." "I lived in Alaska for many, many years." "This is a very individual thing, painting is." ;; Series 21, Episode 1 "It's easy to add more color, but it's a son of a gun to take it away." "Very gently go across the entire sky." "...right on the edge of the blade..." "Everybody will see nature through different eyes" "Everybody has their own idea of what a mountain should look like." "Let it float right down the side of the mountain." "Zooooom... you've gotta make the little noises or it doesn't work right." "Painting is as individual as people are." "At some point in between, you have to reach a happy medium." "I'll bet you didn't realize you had that much power." "You can do anything that you want to do... you can move mountains!" "You can determine what your world is like." ;; Series 22, Episode 7 "A very, very small amount." "Just like it wasn't even there." "That little painter man is so cute!" "We'll put a little mountain here." "We're gonna play some games here with different planes." "I wanna be careful to not let the color go past the tape." "Just any old thing that'll stick to the canvas." "Always have that little roll of paint." "Sometimes it's fun to play little games in your mountains." "'Course I make some mistakes at home, and we call those \"abstracts\"." "Let's play some games!" "Soft as a meadow." "It's time we got strong here." "Truly the joy of painting is the friends that you make doing it." ;; Series 22, Episode 9 "Let's just have a good time." "Today's such a wonderful day, let's just make a happy little painting." "Nothing to it." "A very quiet little sky." "You know me -- I like water." "Think about form and shape -- how do you want this thing to be?" "A half a hair and some air." "Beautiful little roundy-hill-type things." "A flock of trees? I don't know... a STAND of trees. That's what you call them!" ;; Series 23, Episode 2 "Let's really have some fun." "Now things are going to start happening." "You'll be amazed at some of the effects you can achieve." "It's very hard to see your painting when you're right up against it." "We become mud-mixers." "Maybe there's a happy little tree... he lives right there." "The more that you practice, the more you're able to visualize things." "You know me, I get crazy." ;; Series 23, Episode 3 "I want to darken the edges." "Fun time! Now we wash the ol' brush!" "Let's build us a little cloud." "Don't just throw it up there and think that a cloud will appear." "That was so much fun! Let's get crazy!" "You want to be able to control these rascals." "Just make it up." "You've got to have a little sadness once in awhile to let you know when the good times come." ;; Series 24, Episode 3 "I thought today, this would be our crazy painting." "I think you'll be tickled with what you can do with something that starts out looking this bad." "Just gonna start any ol' where." "You'll be amazed at what you can do if you'll just try." "Practice visualizing things in your mind." "Don't be afraid to experiment." "You're gonna have one WILD day!" "The birds would get sort of crazy." "Stir them up a little, then blend them." "If everything was good all the time, pretty soon you'd be accepting that as normal." "You decide where all these things are." "There's too many complicated things in our life already." ;; Series 24, Episode 7 "That's the fun part of this whole technique." "Really be stingy with it." "The just do nice things for you." "You don't have to tell them you did this with a paper towel." "Enough of that." "They are very special. Take care of those!" "Quiet, quiet little bushes." "A place for all the little creatures to put their money." "We don't know exactly where this is gonna go, and we don't care at this point." "In the woods, you have all different colors of green." "Don't be afraid to have a lot of greens." ;; Series 25, Episode 3 " That's pretty already, shoot... but we're not gonna stop there." "Just let it sorta dance around in the sky." "We'll put a few little nicety things in there." "Clouds have form and shape and life and are interesting, they're not just ol' dull clouds." "When I finally got to Alaska, whew boy, I just went crazy" "The only thing I'm good at is falling down." "I look for easy ways to do things." ;; Series 25, Episode 6 "Say all that with a mouthful of rocks." "I'll show you exactly the kind of messes we get into sometimes." "I really don't know what we're gonna do except have some fun." "Painters are expected to be different." "Remember where your finger's been before you scratch your nose." "Don't be afraid to experiment." "Don't be afraid to go out on a limb once in a while." "Where are we going with this?" "Just have a good feeling... be happy, and in love with your life and your world." ;; Series 26, Episode 1 "Let's get right to it." "This is one that you can do." "That simple, that easy!" "We'll just sort of see what happens." "That'll be a challenge!" "Let's have a big cloud!" "It's a lot of fun." "Nothing to it!" "It's bad when you have to tie a bucket on the side of your painting." "Time to get crazy now!" ;; Series 26, Episode 6 "You'd better get out your big coat and put it on." "You know I'm crazy about water." "Let's have some fun!" "Make your own mind up about where your clouds should live." "Looks like there's a storm coming already." "You have to make these big decisions in your world." "You have unlimited power here." "You can do anything that you believe you can do." "Don't think there's anybody that doesn't like mountains. Well, maybe there is." "Time to get crazy." "Everybody should have a friend." "If you learn to make one tree, you can make a million trees." "It's the contrast in this painting that makes it so pretty." ;; Series 27, Episode 5 "Very, very... let me say that one more time: very." "The smallest, very little amount." "Tell you what: let's get crazy today." "You can change your mind right mid stream." "I want a very gentle, quiet little sky." "Today, I want softness in our world... tranquility, quiet, peaceful." "Whatever works is good." ;; Series 27, Episode 11 "Let's do a winter scene, what the heck." "Maybe I'll have a big mountain today." "Life's wonderful, isn't it?" "Let's make a wild mountain today." "If we make a boo-boo, it's right here -- but that's alright, because we don't make mistakes in our world." "You know what? Let's get crazy." "He's got the leanies!" ;; Series 28, Episode 3 "Let's just do a painting that's fun." "Allow the colors to blend together." "It'll just eat up all the crimson in the world." "We don't care." "He just hangs around back there and has a good time all day." "Just a nice little mountain, a little friendly guy." "It doesn't matter in our world where it goes." "I like the mountains -- they're my favorite." "You can just go on and on and on." "Absolutely no limits!" "The joy of painting really is universal." "We've got a conglomeration going on there!" "Sometimes we get crazy here." "Now a little rabbit can hide down there and look over at us!" ;; Series 28, Episode 10 "Let's just have some fun today." "Let me put a little on the other side too, we don't want it to feel left out." "Just sort of blend it around." "I want this to be very bright right in here." "I don't know exactly what they are, and I don't really care at this point." "Just let your imagination take you to anywhere you want to be." "Shh... our secret! Don't tell, just enjoy!" "Who knows? Get crazy!" ;; Series 29, Episode 1 "Please let me thank you." "Let me tell you what I've got going on up here." "Just making little X's, little criss-cross strokes." "Quickly drop in just a little warm part of the sky here." "I sorta like that." "Doesn't take too long when you're using a brush that's two inches wide." "It's a very warm blue, very nice." "Be careful, be careful." "That's really the most fun part of it." "We'll blend it all together." "That's working so well." "You create any illusion that you want." "Sometimes it's a lot of fun to put several layers." "We don't know where that goes -- it doesn't matter at this point." "Take care of it -- treasure it!" "Let's have some MORE fun!" "Be brave!" "Save your detail for the foreground." "You don't always have to have a perfect vision in your mind." "Even a tree needs a friend." ;; Series 29, Episode 5 "Let's just enjoy today." "Anything that happens here, we can live with and we can turn it into something that looks pretty good most of the time." "Fun time!" ;; Series 29, Episode 9 "That's exactly where it should be." "That's about enough right there." "Isn't life wonderful?" "Throw in some happy little things wherever you want them." "You make the big decisions where all these things live in your world." "Take your time and play with these things." "We don't know where it goes." "Let's do another one -- what the heck!" "All you do is just go back with it." "You don't have to work at it hardly at all." "Highlight a few of these rascals." "Great time!" ;; Series 30, Episode 2 "Get nervous." "You know me -- I love water." "Let's do a happy little mountain." "Just let it float." "You make the big decisions." "We're not too worried about it today." "Painting offers freedom." "Bravery test!" "Shoot, I've got to get a little crazy." ;; Series 30, Episode 3 "It's a fantastic day here!" "A winter scene that's very warm, very pretty, and will just make you feel good." "We'll just have a firecracker of a sky up here." "Let them have a good time in your world." "The cloud needs a little friend." "Just let it sort of run across here, wherever you want it to go." "Cherish it! Take care of it!" "Think about some basic shapes and forms in this -- don't just throw them on at random." "Do a cabin-ectomy." "I like big trees." ;; Series 31, Episode 3 "It's a fantastic day here, and I hope it is wherever you're at." "We'll let our imaginations take us wherever we want to go today." "Anything that happens here, you can work with it." "You can do anything you desire on this canvas." "You can do it!" "You have to make all these big decisions when you have power." "You didn't know you had so much power, did you?" "Art is an expression of self." "If you comply with that rule, how can you go wrong?" "So many things you can create." ;; Series 31, Episode 7 "Sort of an orangy-yellowish color." "OK, let's have some fun!" "Just decide basically where you wanna start, and off you go!" "The titles comes out of there, it sounds like an old car." "He's like the rest of us -- he's about half crazy." "Just go around and try them all." "That rascal's sneaky!" "You decide -- you have to make these big decisions." "Let's get crazy here." "Don't want much... don't want much..." "Everybody should paint what they see and what they feel." "A lot of things happening right here." ])
[ { "context": "helper :as h]))\n\n(def ^:private message\n {:from \"[email protected]\"\n :to \"[email protected]\"\n :subject \"hello\"\n ", "end": 199, "score": 0.9999240040779114, "start": 182, "tag": "EMAIL", "value": "[email protected]" }, { "context": "vate message\n {:from \"[email protected]\"\n :to \"[email protected]\"\n :subject \"hello\"\n :body \"world\"})\n\n(defn -m", "end": 224, "score": 0.9999237060546875, "start": 209, "tag": "EMAIL", "value": "[email protected]" } ]
dev/src/benchmark.clj
toyokumo/tarayo
34
(ns benchmark (:require [criterium.core :as criterium] [postal.core :as postal] [tarayo.core :as tarayo] [tarayo.test-helper :as h])) (def ^:private message {:from "[email protected]" :to "[email protected]" :subject "hello" :body "world"}) (defn -main [] (h/with-test-smtp-server [_ port] (println "POSTAL ----") (criterium/bench (postal/send-message {:host "localhost" :port port} message))) (println "") (h/with-test-smtp-server [_ port] (println "TARAYO ----") (criterium/bench (with-open [conn (tarayo/connect {:port port})] (tarayo/send! conn message))))) (comment (-main))
95482
(ns benchmark (:require [criterium.core :as criterium] [postal.core :as postal] [tarayo.core :as tarayo] [tarayo.test-helper :as h])) (def ^:private message {:from "<EMAIL>" :to "<EMAIL>" :subject "hello" :body "world"}) (defn -main [] (h/with-test-smtp-server [_ port] (println "POSTAL ----") (criterium/bench (postal/send-message {:host "localhost" :port port} message))) (println "") (h/with-test-smtp-server [_ port] (println "TARAYO ----") (criterium/bench (with-open [conn (tarayo/connect {:port port})] (tarayo/send! conn message))))) (comment (-main))
true
(ns benchmark (:require [criterium.core :as criterium] [postal.core :as postal] [tarayo.core :as tarayo] [tarayo.test-helper :as h])) (def ^:private message {:from "PI:EMAIL:<EMAIL>END_PI" :to "PI:EMAIL:<EMAIL>END_PI" :subject "hello" :body "world"}) (defn -main [] (h/with-test-smtp-server [_ port] (println "POSTAL ----") (criterium/bench (postal/send-message {:host "localhost" :port port} message))) (println "") (h/with-test-smtp-server [_ port] (println "TARAYO ----") (criterium/bench (with-open [conn (tarayo/connect {:port port})] (tarayo/send! conn message))))) (comment (-main))
[ { "context": "(ns ^{:author \"Leeor Engel\"}\n chapter-4.chapter-4-q5-test\n (:require [cloj", "end": 26, "score": 0.9998915791511536, "start": 15, "tag": "NAME", "value": "Leeor Engel" } ]
Clojure/test/chapter_4/chapter_4_q5_test.clj
Kiandr/crackingcodinginterview
0
(ns ^{:author "Leeor Engel"} chapter-4.chapter-4-q5-test (:require [clojure.test :refer :all] [data-structures.tree :refer :all] [chapter-4.chapter-4-q5 :refer :all])) (deftest valid-bst-test (testing "single node" (let [tree (create-tree [1])] (is (valid-bst? tree)))) (testing "two nodes" (let [tree-1 (create-tree [1 [2]]) tree-2 (create-tree [1 [0]]) tree-3 (create-tree [1 [] [2]])] (is (not (valid-bst? tree-1))) (is (valid-bst? tree-2)) (is (valid-bst? tree-3)))) (testing "balanced > 2 nodes" (let [tree-1 (create-tree [2 [1] [3]]) tree-2 (create-tree [2 [1] [4 [3]]]) tree-3 (create-tree [2 [1] [3 [4]]])] (is (valid-bst? tree-1)) (is (valid-bst? tree-2)) (is (not (valid-bst? tree-3)))))) (deftest valid-bst-alt-test (testing "single node" (let [tree (create-tree [1])] (is (alt-valid-bst? tree)))) (testing "two nodes" (let [tree-1 (create-tree [1 [2]]) tree-2 (create-tree [1 [0]]) tree-3 (create-tree [1 [] [2]])] (is (not (alt-valid-bst? tree-1))) (is (alt-valid-bst? tree-2)) (is (alt-valid-bst? tree-3)))) (testing "balanced > 2 nodes" (let [tree-1 (create-tree [2 [1] [3]]) tree-2 (create-tree [2 [1] [4 [3]]]) tree-3 (create-tree [2 [1] [3 [4]]])] (is (alt-valid-bst? tree-1)) (is (alt-valid-bst? tree-2)) (is (not (alt-valid-bst? tree-3))))))
2153
(ns ^{:author "<NAME>"} chapter-4.chapter-4-q5-test (:require [clojure.test :refer :all] [data-structures.tree :refer :all] [chapter-4.chapter-4-q5 :refer :all])) (deftest valid-bst-test (testing "single node" (let [tree (create-tree [1])] (is (valid-bst? tree)))) (testing "two nodes" (let [tree-1 (create-tree [1 [2]]) tree-2 (create-tree [1 [0]]) tree-3 (create-tree [1 [] [2]])] (is (not (valid-bst? tree-1))) (is (valid-bst? tree-2)) (is (valid-bst? tree-3)))) (testing "balanced > 2 nodes" (let [tree-1 (create-tree [2 [1] [3]]) tree-2 (create-tree [2 [1] [4 [3]]]) tree-3 (create-tree [2 [1] [3 [4]]])] (is (valid-bst? tree-1)) (is (valid-bst? tree-2)) (is (not (valid-bst? tree-3)))))) (deftest valid-bst-alt-test (testing "single node" (let [tree (create-tree [1])] (is (alt-valid-bst? tree)))) (testing "two nodes" (let [tree-1 (create-tree [1 [2]]) tree-2 (create-tree [1 [0]]) tree-3 (create-tree [1 [] [2]])] (is (not (alt-valid-bst? tree-1))) (is (alt-valid-bst? tree-2)) (is (alt-valid-bst? tree-3)))) (testing "balanced > 2 nodes" (let [tree-1 (create-tree [2 [1] [3]]) tree-2 (create-tree [2 [1] [4 [3]]]) tree-3 (create-tree [2 [1] [3 [4]]])] (is (alt-valid-bst? tree-1)) (is (alt-valid-bst? tree-2)) (is (not (alt-valid-bst? tree-3))))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} chapter-4.chapter-4-q5-test (:require [clojure.test :refer :all] [data-structures.tree :refer :all] [chapter-4.chapter-4-q5 :refer :all])) (deftest valid-bst-test (testing "single node" (let [tree (create-tree [1])] (is (valid-bst? tree)))) (testing "two nodes" (let [tree-1 (create-tree [1 [2]]) tree-2 (create-tree [1 [0]]) tree-3 (create-tree [1 [] [2]])] (is (not (valid-bst? tree-1))) (is (valid-bst? tree-2)) (is (valid-bst? tree-3)))) (testing "balanced > 2 nodes" (let [tree-1 (create-tree [2 [1] [3]]) tree-2 (create-tree [2 [1] [4 [3]]]) tree-3 (create-tree [2 [1] [3 [4]]])] (is (valid-bst? tree-1)) (is (valid-bst? tree-2)) (is (not (valid-bst? tree-3)))))) (deftest valid-bst-alt-test (testing "single node" (let [tree (create-tree [1])] (is (alt-valid-bst? tree)))) (testing "two nodes" (let [tree-1 (create-tree [1 [2]]) tree-2 (create-tree [1 [0]]) tree-3 (create-tree [1 [] [2]])] (is (not (alt-valid-bst? tree-1))) (is (alt-valid-bst? tree-2)) (is (alt-valid-bst? tree-3)))) (testing "balanced > 2 nodes" (let [tree-1 (create-tree [2 [1] [3]]) tree-2 (create-tree [2 [1] [4 [3]]]) tree-3 (create-tree [2 [1] [3 [4]]])] (is (alt-valid-bst? tree-1)) (is (alt-valid-bst? tree-2)) (is (not (alt-valid-bst? tree-3))))))
[ { "context": "\" \n :port 5432\n :user \"myapp\"\n :password \"myapppw\"\n ;; :ssl true\n ;; :sslfactory \"org.postgresq", "end": 201, "score": 0.999239444732666, "start": 194, "tag": "PASSWORD", "value": "myapppw" } ]
src/myapp/core.clj
davidneu/docker-clojure-postgresql-example
6
(ns myapp.core (:require [clojure.java.jdbc :as jdbc]) (:gen-class)) (def db {:dbtype "postgresql" :dbname "myapp" :host "db-dev" :port 5432 :user "myapp" :password "myapppw" ;; :ssl true ;; :sslfactory "org.postgresql.ssl.NonValidatingFactory" }) (defn sample-create [db n] (dotimes [_ n] (jdbc/insert! db "myapp.sample" {:x (rand)}))) (defn sample-summary [db] (jdbc/query db ["select count(*) as n, min(x) as min, avg(x) as mean, max(x) as max from myapp.sample"] {:result-set-fn first})) (defn summary-format [{:keys [n min mean max]}] (format "n=%d, min=%f, mean=%f, max=%f" n min mean max)) (defn -main [& args] (let [n 100] (jdbc/delete! db "myapp.sample" []) (println (format "I'm going to create a sample of %d random numbers ...\n" n)) (sample-create db n) (println "That was a lot of work, I'm going to take a nap ...\n") (spit "/tmp/myapp.txt" "I'm sleeping ...\n") (Thread/sleep (* 10 1000)) (println "OK, now I'm going to compute some statistics on the sample ...\n") (println (summary-format (sample-summary db)))))
60685
(ns myapp.core (:require [clojure.java.jdbc :as jdbc]) (:gen-class)) (def db {:dbtype "postgresql" :dbname "myapp" :host "db-dev" :port 5432 :user "myapp" :password "<PASSWORD>" ;; :ssl true ;; :sslfactory "org.postgresql.ssl.NonValidatingFactory" }) (defn sample-create [db n] (dotimes [_ n] (jdbc/insert! db "myapp.sample" {:x (rand)}))) (defn sample-summary [db] (jdbc/query db ["select count(*) as n, min(x) as min, avg(x) as mean, max(x) as max from myapp.sample"] {:result-set-fn first})) (defn summary-format [{:keys [n min mean max]}] (format "n=%d, min=%f, mean=%f, max=%f" n min mean max)) (defn -main [& args] (let [n 100] (jdbc/delete! db "myapp.sample" []) (println (format "I'm going to create a sample of %d random numbers ...\n" n)) (sample-create db n) (println "That was a lot of work, I'm going to take a nap ...\n") (spit "/tmp/myapp.txt" "I'm sleeping ...\n") (Thread/sleep (* 10 1000)) (println "OK, now I'm going to compute some statistics on the sample ...\n") (println (summary-format (sample-summary db)))))
true
(ns myapp.core (:require [clojure.java.jdbc :as jdbc]) (:gen-class)) (def db {:dbtype "postgresql" :dbname "myapp" :host "db-dev" :port 5432 :user "myapp" :password "PI:PASSWORD:<PASSWORD>END_PI" ;; :ssl true ;; :sslfactory "org.postgresql.ssl.NonValidatingFactory" }) (defn sample-create [db n] (dotimes [_ n] (jdbc/insert! db "myapp.sample" {:x (rand)}))) (defn sample-summary [db] (jdbc/query db ["select count(*) as n, min(x) as min, avg(x) as mean, max(x) as max from myapp.sample"] {:result-set-fn first})) (defn summary-format [{:keys [n min mean max]}] (format "n=%d, min=%f, mean=%f, max=%f" n min mean max)) (defn -main [& args] (let [n 100] (jdbc/delete! db "myapp.sample" []) (println (format "I'm going to create a sample of %d random numbers ...\n" n)) (sample-create db n) (println "That was a lot of work, I'm going to take a nap ...\n") (spit "/tmp/myapp.txt" "I'm sleeping ...\n") (Thread/sleep (* 10 1000)) (println "OK, now I'm going to compute some statistics on the sample ...\n") (println (summary-format (sample-summary db)))))
[ { "context": "normal data-structure\"\n :url \"https://github.com/AvramRobert/nemesis\"\n :license {:name \"MIT\"\n :url", "end": 177, "score": 0.9985662698745728, "start": 166, "tag": "USERNAME", "value": "AvramRobert" }, { "context": "s [\"-target\" \"1.8\" \"-source\" \"1.8\"]\n :scm {:url \"[email protected]:AvramRobert/nemesis.git\"}\n ;; use the token from", "end": 955, "score": 0.9827701449394226, "start": 941, "tag": "EMAIL", "value": "[email protected]" }, { "context": ".8\" \"-source\" \"1.8\"]\n :scm {:url \"[email protected]:AvramRobert/nemesis.git\"}\n ;; use the token from Nexus UI, n", "end": 967, "score": 0.9852262735366821, "start": 956, "tag": "USERNAME", "value": "AvramRobert" }, { "context": "[:developer\n [:name \"Robert M. Avram\"]\n [:url \"https://gi", "end": 1465, "score": 0.9998933672904968, "start": 1450, "tag": "NAME", "value": "Robert M. Avram" }, { "context": " [:url \"https://github.com/AvramRobert\"]\n [:email \"am11.rob", "end": 1535, "score": 0.9986704587936401, "start": 1524, "tag": "USERNAME", "value": "AvramRobert" }, { "context": "amRobert\"]\n [:email \"[email protected]\"]]]\n :classifiers {:javadoc {:java-source-paths ", "end": 1598, "score": 0.9999219179153442, "start": 1577, "tag": "EMAIL", "value": "[email protected]" } ]
project.clj
AvramRobert/nemesis
4
(defproject com.ravram/nemesis "0.2.1-SNAPSHOT" :description "A library for working with JSON as one would with a normal data-structure" :url "https://github.com/AvramRobert/nemesis" :license {:name "MIT" :url "https://opensource.org/licenses/MIT"} :java-source-paths ["src"] :dependencies [[io.lacuna/bifurcan "0.1.0"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/test.check "1.1.0"] [com.fasterxml.jackson.core/jackson-databind "2.10.2"] [com.typesafe.play/play-json_2.13 "2.9.2"] [com.google.code.gson/gson "2.8.6"] [criterium "0.4.6"] [cheshire "5.10.0"]] :resource-paths ["test/resources"]}} :javac-options ["-target" "1.8" "-source" "1.8"] :scm {:url "[email protected]:AvramRobert/nemesis.git"} ;; use the token from Nexus UI, not your jira credentials directly :deploy-repositories {"releases" {:url "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/" :creds :gpg} "snapshots" {:url "https://s01.oss.sonatype.org/content/repositories/snapshots/" :creds :gpg}} :pom-addition [:developers [:developer [:name "Robert M. Avram"] [:url "https://github.com/AvramRobert"] [:email "[email protected]"]]] :classifiers {:javadoc {:java-source-paths ^:replace [] :source-paths ^:replace [] :resource-paths ^:replace ["javadoc"]} :sources {:source-paths ^:replace ["src"] :resource-paths ^:replace []}})
99346
(defproject com.ravram/nemesis "0.2.1-SNAPSHOT" :description "A library for working with JSON as one would with a normal data-structure" :url "https://github.com/AvramRobert/nemesis" :license {:name "MIT" :url "https://opensource.org/licenses/MIT"} :java-source-paths ["src"] :dependencies [[io.lacuna/bifurcan "0.1.0"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/test.check "1.1.0"] [com.fasterxml.jackson.core/jackson-databind "2.10.2"] [com.typesafe.play/play-json_2.13 "2.9.2"] [com.google.code.gson/gson "2.8.6"] [criterium "0.4.6"] [cheshire "5.10.0"]] :resource-paths ["test/resources"]}} :javac-options ["-target" "1.8" "-source" "1.8"] :scm {:url "<EMAIL>:AvramRobert/nemesis.git"} ;; use the token from Nexus UI, not your jira credentials directly :deploy-repositories {"releases" {:url "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/" :creds :gpg} "snapshots" {:url "https://s01.oss.sonatype.org/content/repositories/snapshots/" :creds :gpg}} :pom-addition [:developers [:developer [:name "<NAME>"] [:url "https://github.com/AvramRobert"] [:email "<EMAIL>"]]] :classifiers {:javadoc {:java-source-paths ^:replace [] :source-paths ^:replace [] :resource-paths ^:replace ["javadoc"]} :sources {:source-paths ^:replace ["src"] :resource-paths ^:replace []}})
true
(defproject com.ravram/nemesis "0.2.1-SNAPSHOT" :description "A library for working with JSON as one would with a normal data-structure" :url "https://github.com/AvramRobert/nemesis" :license {:name "MIT" :url "https://opensource.org/licenses/MIT"} :java-source-paths ["src"] :dependencies [[io.lacuna/bifurcan "0.1.0"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.3"] [org.clojure/test.check "1.1.0"] [com.fasterxml.jackson.core/jackson-databind "2.10.2"] [com.typesafe.play/play-json_2.13 "2.9.2"] [com.google.code.gson/gson "2.8.6"] [criterium "0.4.6"] [cheshire "5.10.0"]] :resource-paths ["test/resources"]}} :javac-options ["-target" "1.8" "-source" "1.8"] :scm {:url "PI:EMAIL:<EMAIL>END_PI:AvramRobert/nemesis.git"} ;; use the token from Nexus UI, not your jira credentials directly :deploy-repositories {"releases" {:url "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/" :creds :gpg} "snapshots" {:url "https://s01.oss.sonatype.org/content/repositories/snapshots/" :creds :gpg}} :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "https://github.com/AvramRobert"] [:email "PI:EMAIL:<EMAIL>END_PI"]]] :classifiers {:javadoc {:java-source-paths ^:replace [] :source-paths ^:replace [] :resource-paths ^:replace ["javadoc"]} :sources {:source-paths ^:replace ["src"] :resource-paths ^:replace []}})
[ { "context": "ensso.timbre :as log]))\n\n(defonce login-user-key \"login-user\")\n(defonce auth-token-key \"auth-token\")\n\n(defn se", "end": 104, "score": 0.9801790714263916, "start": 94, "tag": "KEY", "value": "login-user" }, { "context": "n-user-key \"login-user\")\n(defonce auth-token-key \"auth-token\")\n\n(defn set-item!\n [key val]\n (->> val\n ", "end": 142, "score": 0.779274046421051, "start": 132, "tag": "KEY", "value": "auth-token" } ]
src/soul_talk/local_storage.cljs
neromous/Re_Frame_template_of_FamiliyCost
0
(ns soul-talk.local-storage (:require [taoensso.timbre :as log])) (defonce login-user-key "login-user") (defonce auth-token-key "auth-token") (defn set-item! [key val] (->> val (clj->js) (js/JSON.stringify) (.setItem (.-localStorage js/window) key))) (defn get-item [key] (js->clj (->> key (.getItem (.-localStorage js/window)) (.parse js/JSON)) :keywordize-keys true)) (defn remove-item! [key] (log/debug "from localstorage remove key: " key) (.removeItem (.-localStorage js/window) key))
86814
(ns soul-talk.local-storage (:require [taoensso.timbre :as log])) (defonce login-user-key "<KEY>") (defonce auth-token-key "<KEY>") (defn set-item! [key val] (->> val (clj->js) (js/JSON.stringify) (.setItem (.-localStorage js/window) key))) (defn get-item [key] (js->clj (->> key (.getItem (.-localStorage js/window)) (.parse js/JSON)) :keywordize-keys true)) (defn remove-item! [key] (log/debug "from localstorage remove key: " key) (.removeItem (.-localStorage js/window) key))
true
(ns soul-talk.local-storage (:require [taoensso.timbre :as log])) (defonce login-user-key "PI:KEY:<KEY>END_PI") (defonce auth-token-key "PI:KEY:<KEY>END_PI") (defn set-item! [key val] (->> val (clj->js) (js/JSON.stringify) (.setItem (.-localStorage js/window) key))) (defn get-item [key] (js->clj (->> key (.getItem (.-localStorage js/window)) (.parse js/JSON)) :keywordize-keys true)) (defn remove-item! [key] (log/debug "from localstorage remove key: " key) (.removeItem (.-localStorage js/window) key))
[ { "context": "operties))\n (:gen-class))\n\n(def kpow-secure-key \"KPOW_SECURE_KEY\")\n(def kpow-secure-key-location \"KPOW_SECURE_K", "end": 513, "score": 0.6568205952644348, "start": 501, "tag": "KEY", "value": "KPOW_SECURE_" } ]
src/kpow/secure.clj
operatr-io/kpow-secure
3
(ns kpow.secure (:require [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.tools.logging :as log] [kpow.secure.key :as key]) (:import (java.io StringReader) (java.nio ByteBuffer) (java.nio.charset StandardCharsets) (java.security SecureRandom) (javax.crypto SecretKey Cipher) (javax.crypto.spec IvParameterSpec) (java.util Base64 Properties)) (:gen-class)) (def kpow-secure-key "KPOW_SECURE_KEY") (def kpow-secure-key-location "KPOW_SECURE_KEY_LOCATION") (def prefix "AES:") ;; scheme version static as v1 for now and encoded into the message as first byte (def scheme-v1 (unchecked-byte 1)) (def cipher-algorithm "AES/CBC/PKCS5Padding") (defn prefixed? [input] (and input (.startsWith input prefix))) (defn random-iv "Generate a 16-byte random IvParameterSpec" [] (let [bytes (byte-array 16)] (.nextBytes (SecureRandom.) bytes) (IvParameterSpec. bytes))) (defn cipher-bytes "Produce cipher-text from key / iv / plaintext input" [^SecretKey secret-key ^IvParameterSpec iv-spec ^String plaintext] (let [cipher (Cipher/getInstance cipher-algorithm)] (.init cipher Cipher/ENCRYPT_MODE secret-key ^IvParameterSpec iv-spec) (.doFinal cipher (.getBytes plaintext (.name StandardCharsets/UTF_8))))) (defn plaintext "Produce plaintext from key / iv / cipher-bytes input" [^SecretKey secret-key ^IvParameterSpec iv-spec cipher-bytes] (let [cipher (Cipher/getInstance cipher-algorithm)] (.init cipher Cipher/DECRYPT_MODE secret-key ^IvParameterSpec iv-spec) (String. (.doFinal cipher cipher-bytes) (.name StandardCharsets/UTF_8)))) (defn encoded-payload "Produce a payload with format: * 1 byte scheme version (currently hard-coded to '1') * 1 byte initialization vector length (v1 scheme expects 16 bytes) * Initialization vector of size ^ * Cipher text" [^SecretKey secret-key ^String plaintext] (let [payload-iv (random-iv) payload-iv-bytes (.getIV ^IvParameterSpec payload-iv) payload-bytes (cipher-bytes secret-key payload-iv plaintext) payload-iv-length (count payload-iv-bytes) payload-bytes-length (count payload-bytes) buffer (ByteBuffer/allocate (+ 1 1 payload-iv-length payload-bytes-length))] (.put buffer (byte-array [scheme-v1])) (.put buffer (byte-array [(unchecked-byte payload-iv-length)])) (.put buffer ^"[B" payload-iv-bytes) (.put buffer ^"[B" payload-bytes) (String. (.encode (Base64/getEncoder) (.array buffer)) StandardCharsets/UTF_8))) (defn decoded-text "Validate the payload parts, then produce plaintext original of input cipher-text" [^SecretKey secret-key ^String encoded-payload] (let [buffer (->> (.getBytes encoded-payload StandardCharsets/UTF_8) (.decode (Base64/getDecoder)) (ByteBuffer/wrap)) message-version (unchecked-int (.get buffer)) iv-length (unchecked-int (.get buffer))] (when-not (= 1 message-version) (throw (IllegalArgumentException. (format "Invalid scheme version: %s" message-version)))) (when-not (= 16 iv-length) (throw (IllegalArgumentException. (format "Invalid initialization vector size: %s" iv-length)))) (let [iv-bytes (byte-array iv-length)] (.get buffer iv-bytes) (let [cypher-bytes (byte-array (.remaining buffer))] (.get buffer cypher-bytes) (plaintext secret-key (IvParameterSpec. iv-bytes) cypher-bytes))))) (def load-key (memoize (fn [] (when-let [key-location (System/getenv kpow-secure-key-location)] (try (slurp key-location) (catch Exception ex (log/errorf ex "Key file not found at path %s" key-location))))))) (defn lookup-key "Retrieve an encoded encryption key from the kpow-secure-key environment variable or location" [] (or (System/getenv kpow-secure-key) (load-key))) (defn encrypted ([plaintext] (encrypted (lookup-key) plaintext)) ([key-text plaintext] (when (str/blank? key-text) (throw (IllegalArgumentException. "No key provided"))) (when (nil? plaintext) (throw (IllegalArgumentException. "No plaintext provided"))) (encoded-payload (key/import-key key-text) plaintext))) (defn decrypted ([payload-text] (decrypted (lookup-key) payload-text)) ([key-text payload-text] (when (str/blank? key-text) (throw (IllegalArgumentException. "No key provided"))) (when (str/blank? payload-text) (throw (IllegalArgumentException. "No payload provided"))) (decoded-text (key/import-key key-text) payload-text))) (defn file-text [file] (when file (try (slurp file) (catch Exception ex (throw (ex-info (format "File not found: %s" file) {} ex)))))) (defn text-file [text file encrypt?] (try (spit file text) (log/infof "\n\nKpow %s:\n---------------\n\n> %s" (if encrypt? "Encrypted" "Decrypted") file) (catch Exception ex (throw (ex-info (format "Could not write to: %s" file) {} ex))))) (defn log-text [text encrypt?] (log/infof "\n\nKpow %s:\n---------------\n\n%s" (if encrypt? "Encrypted" "Decrypted") text)) (defn process [encrypt? key-text target-text out-file] (let [text (if encrypt? (encrypted key-text target-text) (decrypted key-text target-text))] (if out-file (text-file text out-file encrypt?) (log-text text encrypt?)))) (defn ->props [text] (let [props (Properties.)] (.load props (StringReader. text)) props)) (defn ->map [text] (into {} (->props text))) (def cli-options [[nil "--key TEXT" "Base64 encoded key"] [nil "--key-file FILE" "File containing base64 encoded key"] [nil "--encrypt TEXT" "Text to encrypt"] [nil "--decrypt TEXT" "Base64 encoded payload text"] [nil "--encrypt-file FILE" "File containing text to encrypt"] [nil "--decrypt-file FILE" "File containing base64 encoded payload text"] [nil "--out-file FILE" "(optional) File for encrypted/decrypted output"] ["-h" "--help"]]) (defn -main [& args] (let [{:keys [options summary errors]} (cli/parse-opts args cli-options) {:keys [key key-file encrypt decrypt encrypt-file decrypt-file out-file help]} options] (try (let [key-text (or key (file-text key-file)) target-file (or encrypt-file decrypt-file) target-text (or encrypt decrypt (file-text target-file))] (cond errors (log/error (str "\n\n" errors)) (or help (empty? options)) (log/info (str "\n\n" summary)) (str/blank? key-text) (log/info "\n\nRequired: --key, or --key-file") (str/blank? target-text) (log/info "\n\nRequired --encrypt, --decrypt, --encrypt-file, or --decrypt-file") :else (process (or encrypt encrypt-file) key-text target-text out-file))) (catch Exception ex (log/error ex)))))
56717
(ns kpow.secure (:require [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.tools.logging :as log] [kpow.secure.key :as key]) (:import (java.io StringReader) (java.nio ByteBuffer) (java.nio.charset StandardCharsets) (java.security SecureRandom) (javax.crypto SecretKey Cipher) (javax.crypto.spec IvParameterSpec) (java.util Base64 Properties)) (:gen-class)) (def kpow-secure-key "<KEY>KEY") (def kpow-secure-key-location "KPOW_SECURE_KEY_LOCATION") (def prefix "AES:") ;; scheme version static as v1 for now and encoded into the message as first byte (def scheme-v1 (unchecked-byte 1)) (def cipher-algorithm "AES/CBC/PKCS5Padding") (defn prefixed? [input] (and input (.startsWith input prefix))) (defn random-iv "Generate a 16-byte random IvParameterSpec" [] (let [bytes (byte-array 16)] (.nextBytes (SecureRandom.) bytes) (IvParameterSpec. bytes))) (defn cipher-bytes "Produce cipher-text from key / iv / plaintext input" [^SecretKey secret-key ^IvParameterSpec iv-spec ^String plaintext] (let [cipher (Cipher/getInstance cipher-algorithm)] (.init cipher Cipher/ENCRYPT_MODE secret-key ^IvParameterSpec iv-spec) (.doFinal cipher (.getBytes plaintext (.name StandardCharsets/UTF_8))))) (defn plaintext "Produce plaintext from key / iv / cipher-bytes input" [^SecretKey secret-key ^IvParameterSpec iv-spec cipher-bytes] (let [cipher (Cipher/getInstance cipher-algorithm)] (.init cipher Cipher/DECRYPT_MODE secret-key ^IvParameterSpec iv-spec) (String. (.doFinal cipher cipher-bytes) (.name StandardCharsets/UTF_8)))) (defn encoded-payload "Produce a payload with format: * 1 byte scheme version (currently hard-coded to '1') * 1 byte initialization vector length (v1 scheme expects 16 bytes) * Initialization vector of size ^ * Cipher text" [^SecretKey secret-key ^String plaintext] (let [payload-iv (random-iv) payload-iv-bytes (.getIV ^IvParameterSpec payload-iv) payload-bytes (cipher-bytes secret-key payload-iv plaintext) payload-iv-length (count payload-iv-bytes) payload-bytes-length (count payload-bytes) buffer (ByteBuffer/allocate (+ 1 1 payload-iv-length payload-bytes-length))] (.put buffer (byte-array [scheme-v1])) (.put buffer (byte-array [(unchecked-byte payload-iv-length)])) (.put buffer ^"[B" payload-iv-bytes) (.put buffer ^"[B" payload-bytes) (String. (.encode (Base64/getEncoder) (.array buffer)) StandardCharsets/UTF_8))) (defn decoded-text "Validate the payload parts, then produce plaintext original of input cipher-text" [^SecretKey secret-key ^String encoded-payload] (let [buffer (->> (.getBytes encoded-payload StandardCharsets/UTF_8) (.decode (Base64/getDecoder)) (ByteBuffer/wrap)) message-version (unchecked-int (.get buffer)) iv-length (unchecked-int (.get buffer))] (when-not (= 1 message-version) (throw (IllegalArgumentException. (format "Invalid scheme version: %s" message-version)))) (when-not (= 16 iv-length) (throw (IllegalArgumentException. (format "Invalid initialization vector size: %s" iv-length)))) (let [iv-bytes (byte-array iv-length)] (.get buffer iv-bytes) (let [cypher-bytes (byte-array (.remaining buffer))] (.get buffer cypher-bytes) (plaintext secret-key (IvParameterSpec. iv-bytes) cypher-bytes))))) (def load-key (memoize (fn [] (when-let [key-location (System/getenv kpow-secure-key-location)] (try (slurp key-location) (catch Exception ex (log/errorf ex "Key file not found at path %s" key-location))))))) (defn lookup-key "Retrieve an encoded encryption key from the kpow-secure-key environment variable or location" [] (or (System/getenv kpow-secure-key) (load-key))) (defn encrypted ([plaintext] (encrypted (lookup-key) plaintext)) ([key-text plaintext] (when (str/blank? key-text) (throw (IllegalArgumentException. "No key provided"))) (when (nil? plaintext) (throw (IllegalArgumentException. "No plaintext provided"))) (encoded-payload (key/import-key key-text) plaintext))) (defn decrypted ([payload-text] (decrypted (lookup-key) payload-text)) ([key-text payload-text] (when (str/blank? key-text) (throw (IllegalArgumentException. "No key provided"))) (when (str/blank? payload-text) (throw (IllegalArgumentException. "No payload provided"))) (decoded-text (key/import-key key-text) payload-text))) (defn file-text [file] (when file (try (slurp file) (catch Exception ex (throw (ex-info (format "File not found: %s" file) {} ex)))))) (defn text-file [text file encrypt?] (try (spit file text) (log/infof "\n\nKpow %s:\n---------------\n\n> %s" (if encrypt? "Encrypted" "Decrypted") file) (catch Exception ex (throw (ex-info (format "Could not write to: %s" file) {} ex))))) (defn log-text [text encrypt?] (log/infof "\n\nKpow %s:\n---------------\n\n%s" (if encrypt? "Encrypted" "Decrypted") text)) (defn process [encrypt? key-text target-text out-file] (let [text (if encrypt? (encrypted key-text target-text) (decrypted key-text target-text))] (if out-file (text-file text out-file encrypt?) (log-text text encrypt?)))) (defn ->props [text] (let [props (Properties.)] (.load props (StringReader. text)) props)) (defn ->map [text] (into {} (->props text))) (def cli-options [[nil "--key TEXT" "Base64 encoded key"] [nil "--key-file FILE" "File containing base64 encoded key"] [nil "--encrypt TEXT" "Text to encrypt"] [nil "--decrypt TEXT" "Base64 encoded payload text"] [nil "--encrypt-file FILE" "File containing text to encrypt"] [nil "--decrypt-file FILE" "File containing base64 encoded payload text"] [nil "--out-file FILE" "(optional) File for encrypted/decrypted output"] ["-h" "--help"]]) (defn -main [& args] (let [{:keys [options summary errors]} (cli/parse-opts args cli-options) {:keys [key key-file encrypt decrypt encrypt-file decrypt-file out-file help]} options] (try (let [key-text (or key (file-text key-file)) target-file (or encrypt-file decrypt-file) target-text (or encrypt decrypt (file-text target-file))] (cond errors (log/error (str "\n\n" errors)) (or help (empty? options)) (log/info (str "\n\n" summary)) (str/blank? key-text) (log/info "\n\nRequired: --key, or --key-file") (str/blank? target-text) (log/info "\n\nRequired --encrypt, --decrypt, --encrypt-file, or --decrypt-file") :else (process (or encrypt encrypt-file) key-text target-text out-file))) (catch Exception ex (log/error ex)))))
true
(ns kpow.secure (:require [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.tools.logging :as log] [kpow.secure.key :as key]) (:import (java.io StringReader) (java.nio ByteBuffer) (java.nio.charset StandardCharsets) (java.security SecureRandom) (javax.crypto SecretKey Cipher) (javax.crypto.spec IvParameterSpec) (java.util Base64 Properties)) (:gen-class)) (def kpow-secure-key "PI:KEY:<KEY>END_PIKEY") (def kpow-secure-key-location "KPOW_SECURE_KEY_LOCATION") (def prefix "AES:") ;; scheme version static as v1 for now and encoded into the message as first byte (def scheme-v1 (unchecked-byte 1)) (def cipher-algorithm "AES/CBC/PKCS5Padding") (defn prefixed? [input] (and input (.startsWith input prefix))) (defn random-iv "Generate a 16-byte random IvParameterSpec" [] (let [bytes (byte-array 16)] (.nextBytes (SecureRandom.) bytes) (IvParameterSpec. bytes))) (defn cipher-bytes "Produce cipher-text from key / iv / plaintext input" [^SecretKey secret-key ^IvParameterSpec iv-spec ^String plaintext] (let [cipher (Cipher/getInstance cipher-algorithm)] (.init cipher Cipher/ENCRYPT_MODE secret-key ^IvParameterSpec iv-spec) (.doFinal cipher (.getBytes plaintext (.name StandardCharsets/UTF_8))))) (defn plaintext "Produce plaintext from key / iv / cipher-bytes input" [^SecretKey secret-key ^IvParameterSpec iv-spec cipher-bytes] (let [cipher (Cipher/getInstance cipher-algorithm)] (.init cipher Cipher/DECRYPT_MODE secret-key ^IvParameterSpec iv-spec) (String. (.doFinal cipher cipher-bytes) (.name StandardCharsets/UTF_8)))) (defn encoded-payload "Produce a payload with format: * 1 byte scheme version (currently hard-coded to '1') * 1 byte initialization vector length (v1 scheme expects 16 bytes) * Initialization vector of size ^ * Cipher text" [^SecretKey secret-key ^String plaintext] (let [payload-iv (random-iv) payload-iv-bytes (.getIV ^IvParameterSpec payload-iv) payload-bytes (cipher-bytes secret-key payload-iv plaintext) payload-iv-length (count payload-iv-bytes) payload-bytes-length (count payload-bytes) buffer (ByteBuffer/allocate (+ 1 1 payload-iv-length payload-bytes-length))] (.put buffer (byte-array [scheme-v1])) (.put buffer (byte-array [(unchecked-byte payload-iv-length)])) (.put buffer ^"[B" payload-iv-bytes) (.put buffer ^"[B" payload-bytes) (String. (.encode (Base64/getEncoder) (.array buffer)) StandardCharsets/UTF_8))) (defn decoded-text "Validate the payload parts, then produce plaintext original of input cipher-text" [^SecretKey secret-key ^String encoded-payload] (let [buffer (->> (.getBytes encoded-payload StandardCharsets/UTF_8) (.decode (Base64/getDecoder)) (ByteBuffer/wrap)) message-version (unchecked-int (.get buffer)) iv-length (unchecked-int (.get buffer))] (when-not (= 1 message-version) (throw (IllegalArgumentException. (format "Invalid scheme version: %s" message-version)))) (when-not (= 16 iv-length) (throw (IllegalArgumentException. (format "Invalid initialization vector size: %s" iv-length)))) (let [iv-bytes (byte-array iv-length)] (.get buffer iv-bytes) (let [cypher-bytes (byte-array (.remaining buffer))] (.get buffer cypher-bytes) (plaintext secret-key (IvParameterSpec. iv-bytes) cypher-bytes))))) (def load-key (memoize (fn [] (when-let [key-location (System/getenv kpow-secure-key-location)] (try (slurp key-location) (catch Exception ex (log/errorf ex "Key file not found at path %s" key-location))))))) (defn lookup-key "Retrieve an encoded encryption key from the kpow-secure-key environment variable or location" [] (or (System/getenv kpow-secure-key) (load-key))) (defn encrypted ([plaintext] (encrypted (lookup-key) plaintext)) ([key-text plaintext] (when (str/blank? key-text) (throw (IllegalArgumentException. "No key provided"))) (when (nil? plaintext) (throw (IllegalArgumentException. "No plaintext provided"))) (encoded-payload (key/import-key key-text) plaintext))) (defn decrypted ([payload-text] (decrypted (lookup-key) payload-text)) ([key-text payload-text] (when (str/blank? key-text) (throw (IllegalArgumentException. "No key provided"))) (when (str/blank? payload-text) (throw (IllegalArgumentException. "No payload provided"))) (decoded-text (key/import-key key-text) payload-text))) (defn file-text [file] (when file (try (slurp file) (catch Exception ex (throw (ex-info (format "File not found: %s" file) {} ex)))))) (defn text-file [text file encrypt?] (try (spit file text) (log/infof "\n\nKpow %s:\n---------------\n\n> %s" (if encrypt? "Encrypted" "Decrypted") file) (catch Exception ex (throw (ex-info (format "Could not write to: %s" file) {} ex))))) (defn log-text [text encrypt?] (log/infof "\n\nKpow %s:\n---------------\n\n%s" (if encrypt? "Encrypted" "Decrypted") text)) (defn process [encrypt? key-text target-text out-file] (let [text (if encrypt? (encrypted key-text target-text) (decrypted key-text target-text))] (if out-file (text-file text out-file encrypt?) (log-text text encrypt?)))) (defn ->props [text] (let [props (Properties.)] (.load props (StringReader. text)) props)) (defn ->map [text] (into {} (->props text))) (def cli-options [[nil "--key TEXT" "Base64 encoded key"] [nil "--key-file FILE" "File containing base64 encoded key"] [nil "--encrypt TEXT" "Text to encrypt"] [nil "--decrypt TEXT" "Base64 encoded payload text"] [nil "--encrypt-file FILE" "File containing text to encrypt"] [nil "--decrypt-file FILE" "File containing base64 encoded payload text"] [nil "--out-file FILE" "(optional) File for encrypted/decrypted output"] ["-h" "--help"]]) (defn -main [& args] (let [{:keys [options summary errors]} (cli/parse-opts args cli-options) {:keys [key key-file encrypt decrypt encrypt-file decrypt-file out-file help]} options] (try (let [key-text (or key (file-text key-file)) target-file (or encrypt-file decrypt-file) target-text (or encrypt decrypt (file-text target-file))] (cond errors (log/error (str "\n\n" errors)) (or help (empty? options)) (log/info (str "\n\n" summary)) (str/blank? key-text) (log/info "\n\nRequired: --key, or --key-file") (str/blank? target-text) (log/info "\n\nRequired --encrypt, --decrypt, --encrypt-file, or --decrypt-file") :else (process (or encrypt encrypt-file) key-text target-text out-file))) (catch Exception ex (log/error ex)))))
[ { "context": " audio samples (wav or aif files).\"\n :author \"Jeff Rose\"}\n overtone.sc.sample\n (:use [clojure.java.io :", "end": 104, "score": 0.9998739957809448, "start": 95, "tag": "NAME", "value": "Jeff Rose" } ]
src/overtone/sc/sample.clj
namin/overtone
2
(ns ^{:doc "Making it easy to load and play audio samples (wav or aif files)." :author "Jeff Rose"} overtone.sc.sample (:use [clojure.java.io :only [file]] [overtone.helpers lib synth] [overtone.libs event deps] [overtone.sc server synth ugens buffer foundation-groups node] [overtone.sc.machinery allocator] [overtone.sc.machinery.server comms] [overtone.sc.cgens buf-io io] [overtone.studio core] [overtone.helpers.file :only [glob canonical-path resolve-tilde-path mk-path file-extension]]) (:require [overtone.sc.envelope :refer [asr]] [overtone.sc.info :refer [server-sample-rate]] [overtone.libs.counters :refer [next-id]] [overtone.osc :refer [osc-send]])) (declare sample-player) (defonce ^{:private true} __RECORDS__ (do (defrecord Sample [id size n-channels rate status path args name] to-sc-id* (to-sc-id [this] (:id this))) (defrecord-ifn PlayableSample [id size n-channels rate status path args name] sample-player to-sc-id* (to-sc-id [this] (:id this))))) (defn sample? "Returns true if s is a sample" [s] (isa? (type s) ::sample)) (defmethod print-method Sample [b ^java.io.Writer w] (.write w (format "#<buffer[%s]: %s %fs %s %d>" (name @(:status b)) (:name b) (:duration b) (cond (= 1 (:n-channels b)) "mono" (= 2 (:n-channels b)) "stereo" :else (str (:n-channels b) " channels")) (:id b)))) (defmethod print-method PlayableSample [b ^java.io.Writer w] (.write w (format "#<buffer[%s]: %s %fs %s %d>" (name @(:status b)) (:name b) (:duration b) (cond (= 1 (:n-channels b)) "mono" (= 2 (:n-channels b)) "stereo" :else (str (:n-channels b) " channels")) (:id b)))) ;; Define a default wav player synth (defonce __DEFINE-PLAYERS__ (do (defsynth mono-partial-player "Plays a mono buffer from start pos to end pos (represented as values between 0 and 1). May be looped via the loop? argument. Release time is the release phase after the looping has finished to remove clipping." [buf 0 rate 1 start 0 end 1 loop? 0 amp 1 release 0 out-bus 0] (let [n-frames (buf-frames buf) rate (* rate (buf-rate-scale buf)) start-pos (* start n-frames) end-pos (* end n-frames) phase (phasor:ar :start start-pos :end end-pos :rate rate) snd (buf-rd 1 buf phase) e-gate (+ loop? (a2k (latch:ar (line 1 0 0.0001) (bpz2 phase)))) env (env-gen (asr 0 1 release) :gate e-gate :action FREE)] (out out-bus (* amp env snd)))) (defsynth stereo-partial-player "Plays a stereo buffer from start pos to end pos (represented as values between 0 and 1). May be looped via the loop? argument. Release time is the release phase after the looping has finished to remove clipping." [buf 0 rate 1 start 0 end 1 loop? 0 amp 1 release 0 out-bus 0] (let [n-frames (buf-frames buf) rate (* rate (buf-rate-scale buf)) start-pos (* start n-frames) end-pos (* end n-frames) phase (phasor:ar :start start-pos :end end-pos :rate rate) snd (buf-rd 2 buf phase) e-gate (+ loop? (a2k (latch:ar (line 1 0 0.0001) (bpz2 phase)))) env (env-gen (asr 0 1 release) :gate e-gate :action FREE)] (out out-bus (* amp env snd)))) (defsynth mono-stream-player "Plays a single channel streaming buffer-cue. Must be freed manually when done." [buf 0 rate 1 loop? 0 amp 1 pan 0 out-bus 0] (out out-bus (* amp (pan2 (scaled-v-disk-in 1 buf rate loop?) pan)))) (defsynth stereo-stream-player "Plays a dual channel streaming buffer-cue. Must be freed manually when done." [buf 0 rate 1 loop? 0 amp 1 pan 0 out-bus 0] (let [s (scaled-v-disk-in 2 buf rate loop?)] (out out-bus (* amp (balance2 (first s) (second s) pan))))))) (defonce loaded-samples* (atom {})) (defonce cached-samples* (atom {})) (defn- load-sample* [path arg-map] (let [path (canonical-path path) f (file path)] (when-not (.exists f) (throw (Exception. (str "Unable to load sample - file does not exist: " path)))) (let [f-name (or (:name arg-map) (.getName f)) start (get arg-map :start 0) n-frames (get arg-map :size 0) buf (buffer-alloc-read path start n-frames) sample (map->Sample (assoc buf :path path :args arg-map :name f-name))] (swap! cached-samples* assoc [path arg-map] sample) (swap! loaded-samples* assoc (:id buf) sample) sample))) (defn load-sample "Synchronously load a .wav or .aiff file into a memory buffer. Returns the buffer. ; e.g. (load-sample \"~/studio/samples/kit/boom.wav\") Takes optional params :start and :size. Allocates buffer to number of channels of file and number of samples requested (:size), or fewer if sound file is smaller than requested. Reads sound file data from the given starting frame in the file (:start). If the number of frames argument is less than or equal to zero, the entire file is read. If optional param :force is set to true, any previously create cache of the sample will be removed and the sample will be forcibly reloaded." [path & args] (ensure-connected!) (let [args (apply hash-map args) force? (:force args) args (select-keys args [:start :size]) path (canonical-path path)] (if-let [sample (and (not force?) (get @cached-samples* [path args]))] sample (load-sample* path args)))) (defn- assert-audio-files [file-seq] (run! (fn [^java.io.File f] (let [ext (file-extension f)] (assert (or (= ext "aif") (= ext "aiff") (= ext "wav")) (if (.isDirectory f) (str "The file " (.getPath f) " is a directory. " "If you wish to load all the files inside the directory, " "you need to provide the path with a glob pattern (asterix).\n" "Example \"~/samples/*\" or \"~/samples/*.wav\".") (str "The file " (.getPath f) " was not a .wav or .aiff audiofile. " "If you wish to choose only audiofile from a directory, you could " "provide the glob pattern like in this:\n \"~/samples/*.wav\"."))))) file-seq)) (defn load-samples "Takes one or more directory and/or file paths, suppoerts glob or glob paths (see #'overtone.helpers.file/glob) and loads up all matching samples and returns a seq of maps representing information for each loaded sample (see load-sample). Samples should be in .aiff or .wav format." [& glob-paths] (let [paths (reduce (fn [paths-vector path-glob] (into paths-vector (let [files (glob path-glob)] (assert-audio-files files) (mapv #(.getAbsolutePath ^java.io.File %) (sort files))))) [] glob-paths)] (doall (mapv (fn [path] (load-sample path)) paths)))) (defn load-samples-async "Takes one or more directory and/or file paths, supports glob paths (see #'overtone.helpers.file/glob). Loads up all matching samples and returns a seq of maps representing information for each loaded sample (see load-sample). Samples should be in .aiff or .wav format. Returns immedietly a vector of samples, some of which could still be loading. The buffer id for the sample is available immedietly, the rest of the metadata, like n-frames, n-channels and rate are available via atom when the sample is loaded. This function is thought of as a faster but unsafer alternative to `load-samples`, which is synchronous." [& glob-paths] (let [paths (reduce (fn [paths-vector path-glob] (into paths-vector (let [files (glob path-glob)] (assert-audio-files files) (mapv #(.getAbsolutePath ^java.io.File %) (sort files))))) [] glob-paths) ;; always load the entire sample, hence same args always cache-args {:start 0 :size -1} paths-and-cache (reduce (fn [out-vec path] (conj out-vec (or (get @cached-samples* [path cache-args]) path))) [] paths)] (reduce (fn [return-samples path-or-cache] (if (sample? path-or-cache) (conj return-samples path-or-cache) (let [id (do (assert-less-than-max-buffers) (next-id :audio-buffer)) *size (atom nil) *n-channels (atom nil) *rate (atom nil) *status (atom :loading) path path-or-cache name (.getName (file path)) sample (Sample. id *size *n-channels *rate *status path cache-args name)] (future (recv "/done" (fn [{:keys [args] :as msg}] (when (and (= (first args) "/b_allocRead") (= (second args) id)) (snd "/b_query" id) (future (let [info (deref (recv "/b_info" (fn [msg] (= id (first (:args msg)))))) [_ size rate n-channels] (:args info) server-rate (server-sample-rate) rate-scale (when (> server-rate 0) (/ rate server-rate)) duration (when (> rate 0) (/ size rate))] (when (every? zero? [size rate n-channels]) (throw (Exception. (str "Unable to read file - perhaps path is not a valid audio file (only " supported-file-types " supported) : " path)))) (reset! *size size) (reset! *n-channels n-channels) (reset! *status :live) (swap! cached-samples* assoc [path cache-args] sample) (swap! loaded-samples* assoc id sample)))))) (snd "/b_allocRead" id path 0 -1)) (conj return-samples sample)))) [] paths-and-cache))) (defn- reload-all-samples [] (let [previously-loaded-samples (vals @loaded-samples* )] (reset! cached-samples* {}) (reset! loaded-samples* {}) (doseq [smpl previously-loaded-samples] (apply load-sample* (:path smpl) (:args smpl))))) (on-deps :server-ready ::load-all-samples reload-all-samples) (defn- free-loaded-sample [smpl] (let [path (:path smpl) args (:args smpl)] (if (server-connected?) (do (buffer-free smpl) (swap! cached-samples* dissoc [path args]) (swap! loaded-samples* dissoc (:id smpl)))))) (defn free-all-loaded-samples "Free all buffers associated with a loaded sample and the memory they consume. Also remove each sample from @loaded-samples once freed" [] (doseq [loaded-sample (vals @loaded-samples*)] (free-loaded-sample loaded-sample))) (defn free-sample "Free the buffer associated with smpl and the memory it consumes. Uses the cached version from @loaded-samples* in case the server has crashed or been rebooted. Also remove the sample from @loaded-samples." [smpl] (assert sample? smpl) (free-loaded-sample smpl) :sample-freed) (defn sample-player "Play the specified sample with either a mono or stereo player depending on the number of channels in the sample. Always creates a stereo signal. Accepts same args as both players, namely: {:buf 0 :rate 1.0 :start-pos 0.0 :loop? 0 :amp 1 :out-bus 0} If you wish to specify a group target vector i.e. [:head foo-g] this argument must go *after* the smpl argument: (sample-player my-samp [:head foo-g] :rate 0.5)" [smpl & pargs] {:pre [(sample? smpl)]} (let [{:keys [path args]} smpl {:keys [id n-channels]} (get @cached-samples* [path args]) [target pos pargs] (extract-target-pos-args pargs (foundation-default-group) :tail)] (cond (= n-channels 1) (apply mono-partial-player [pos target] id pargs) (= n-channels 2) (apply stereo-partial-player [pos target] id pargs)))) (defn sample "Loads a .wav or .aiff file into a memory buffer. Returns a function capable of playing that sample. Memoizes result and returns same sample on subsequent calls. ; e.g. (sample \"~/music/samples/flibble.wav\") " [path & args] (let [smpl (apply load-sample path args)] (map->PlayableSample smpl))) ;; Samples are just audio files loaded into a buffer, so buffer ;; functions work on samples too. (derive Sample ::sample) (derive PlayableSample ::playable-sample) (derive ::sample :overtone.sc.buffer/file-buffer) (derive ::playable-sample ::sample) (defmacro defsample "Define a s-name as a var in the current namespace referencing a sample with the specified path and args. Equivalent to: (def s-name (sample path args...))" [s-name path & args] `(def ~s-name (sample ~path ~@args)))
91938
(ns ^{:doc "Making it easy to load and play audio samples (wav or aif files)." :author "<NAME>"} overtone.sc.sample (:use [clojure.java.io :only [file]] [overtone.helpers lib synth] [overtone.libs event deps] [overtone.sc server synth ugens buffer foundation-groups node] [overtone.sc.machinery allocator] [overtone.sc.machinery.server comms] [overtone.sc.cgens buf-io io] [overtone.studio core] [overtone.helpers.file :only [glob canonical-path resolve-tilde-path mk-path file-extension]]) (:require [overtone.sc.envelope :refer [asr]] [overtone.sc.info :refer [server-sample-rate]] [overtone.libs.counters :refer [next-id]] [overtone.osc :refer [osc-send]])) (declare sample-player) (defonce ^{:private true} __RECORDS__ (do (defrecord Sample [id size n-channels rate status path args name] to-sc-id* (to-sc-id [this] (:id this))) (defrecord-ifn PlayableSample [id size n-channels rate status path args name] sample-player to-sc-id* (to-sc-id [this] (:id this))))) (defn sample? "Returns true if s is a sample" [s] (isa? (type s) ::sample)) (defmethod print-method Sample [b ^java.io.Writer w] (.write w (format "#<buffer[%s]: %s %fs %s %d>" (name @(:status b)) (:name b) (:duration b) (cond (= 1 (:n-channels b)) "mono" (= 2 (:n-channels b)) "stereo" :else (str (:n-channels b) " channels")) (:id b)))) (defmethod print-method PlayableSample [b ^java.io.Writer w] (.write w (format "#<buffer[%s]: %s %fs %s %d>" (name @(:status b)) (:name b) (:duration b) (cond (= 1 (:n-channels b)) "mono" (= 2 (:n-channels b)) "stereo" :else (str (:n-channels b) " channels")) (:id b)))) ;; Define a default wav player synth (defonce __DEFINE-PLAYERS__ (do (defsynth mono-partial-player "Plays a mono buffer from start pos to end pos (represented as values between 0 and 1). May be looped via the loop? argument. Release time is the release phase after the looping has finished to remove clipping." [buf 0 rate 1 start 0 end 1 loop? 0 amp 1 release 0 out-bus 0] (let [n-frames (buf-frames buf) rate (* rate (buf-rate-scale buf)) start-pos (* start n-frames) end-pos (* end n-frames) phase (phasor:ar :start start-pos :end end-pos :rate rate) snd (buf-rd 1 buf phase) e-gate (+ loop? (a2k (latch:ar (line 1 0 0.0001) (bpz2 phase)))) env (env-gen (asr 0 1 release) :gate e-gate :action FREE)] (out out-bus (* amp env snd)))) (defsynth stereo-partial-player "Plays a stereo buffer from start pos to end pos (represented as values between 0 and 1). May be looped via the loop? argument. Release time is the release phase after the looping has finished to remove clipping." [buf 0 rate 1 start 0 end 1 loop? 0 amp 1 release 0 out-bus 0] (let [n-frames (buf-frames buf) rate (* rate (buf-rate-scale buf)) start-pos (* start n-frames) end-pos (* end n-frames) phase (phasor:ar :start start-pos :end end-pos :rate rate) snd (buf-rd 2 buf phase) e-gate (+ loop? (a2k (latch:ar (line 1 0 0.0001) (bpz2 phase)))) env (env-gen (asr 0 1 release) :gate e-gate :action FREE)] (out out-bus (* amp env snd)))) (defsynth mono-stream-player "Plays a single channel streaming buffer-cue. Must be freed manually when done." [buf 0 rate 1 loop? 0 amp 1 pan 0 out-bus 0] (out out-bus (* amp (pan2 (scaled-v-disk-in 1 buf rate loop?) pan)))) (defsynth stereo-stream-player "Plays a dual channel streaming buffer-cue. Must be freed manually when done." [buf 0 rate 1 loop? 0 amp 1 pan 0 out-bus 0] (let [s (scaled-v-disk-in 2 buf rate loop?)] (out out-bus (* amp (balance2 (first s) (second s) pan))))))) (defonce loaded-samples* (atom {})) (defonce cached-samples* (atom {})) (defn- load-sample* [path arg-map] (let [path (canonical-path path) f (file path)] (when-not (.exists f) (throw (Exception. (str "Unable to load sample - file does not exist: " path)))) (let [f-name (or (:name arg-map) (.getName f)) start (get arg-map :start 0) n-frames (get arg-map :size 0) buf (buffer-alloc-read path start n-frames) sample (map->Sample (assoc buf :path path :args arg-map :name f-name))] (swap! cached-samples* assoc [path arg-map] sample) (swap! loaded-samples* assoc (:id buf) sample) sample))) (defn load-sample "Synchronously load a .wav or .aiff file into a memory buffer. Returns the buffer. ; e.g. (load-sample \"~/studio/samples/kit/boom.wav\") Takes optional params :start and :size. Allocates buffer to number of channels of file and number of samples requested (:size), or fewer if sound file is smaller than requested. Reads sound file data from the given starting frame in the file (:start). If the number of frames argument is less than or equal to zero, the entire file is read. If optional param :force is set to true, any previously create cache of the sample will be removed and the sample will be forcibly reloaded." [path & args] (ensure-connected!) (let [args (apply hash-map args) force? (:force args) args (select-keys args [:start :size]) path (canonical-path path)] (if-let [sample (and (not force?) (get @cached-samples* [path args]))] sample (load-sample* path args)))) (defn- assert-audio-files [file-seq] (run! (fn [^java.io.File f] (let [ext (file-extension f)] (assert (or (= ext "aif") (= ext "aiff") (= ext "wav")) (if (.isDirectory f) (str "The file " (.getPath f) " is a directory. " "If you wish to load all the files inside the directory, " "you need to provide the path with a glob pattern (asterix).\n" "Example \"~/samples/*\" or \"~/samples/*.wav\".") (str "The file " (.getPath f) " was not a .wav or .aiff audiofile. " "If you wish to choose only audiofile from a directory, you could " "provide the glob pattern like in this:\n \"~/samples/*.wav\"."))))) file-seq)) (defn load-samples "Takes one or more directory and/or file paths, suppoerts glob or glob paths (see #'overtone.helpers.file/glob) and loads up all matching samples and returns a seq of maps representing information for each loaded sample (see load-sample). Samples should be in .aiff or .wav format." [& glob-paths] (let [paths (reduce (fn [paths-vector path-glob] (into paths-vector (let [files (glob path-glob)] (assert-audio-files files) (mapv #(.getAbsolutePath ^java.io.File %) (sort files))))) [] glob-paths)] (doall (mapv (fn [path] (load-sample path)) paths)))) (defn load-samples-async "Takes one or more directory and/or file paths, supports glob paths (see #'overtone.helpers.file/glob). Loads up all matching samples and returns a seq of maps representing information for each loaded sample (see load-sample). Samples should be in .aiff or .wav format. Returns immedietly a vector of samples, some of which could still be loading. The buffer id for the sample is available immedietly, the rest of the metadata, like n-frames, n-channels and rate are available via atom when the sample is loaded. This function is thought of as a faster but unsafer alternative to `load-samples`, which is synchronous." [& glob-paths] (let [paths (reduce (fn [paths-vector path-glob] (into paths-vector (let [files (glob path-glob)] (assert-audio-files files) (mapv #(.getAbsolutePath ^java.io.File %) (sort files))))) [] glob-paths) ;; always load the entire sample, hence same args always cache-args {:start 0 :size -1} paths-and-cache (reduce (fn [out-vec path] (conj out-vec (or (get @cached-samples* [path cache-args]) path))) [] paths)] (reduce (fn [return-samples path-or-cache] (if (sample? path-or-cache) (conj return-samples path-or-cache) (let [id (do (assert-less-than-max-buffers) (next-id :audio-buffer)) *size (atom nil) *n-channels (atom nil) *rate (atom nil) *status (atom :loading) path path-or-cache name (.getName (file path)) sample (Sample. id *size *n-channels *rate *status path cache-args name)] (future (recv "/done" (fn [{:keys [args] :as msg}] (when (and (= (first args) "/b_allocRead") (= (second args) id)) (snd "/b_query" id) (future (let [info (deref (recv "/b_info" (fn [msg] (= id (first (:args msg)))))) [_ size rate n-channels] (:args info) server-rate (server-sample-rate) rate-scale (when (> server-rate 0) (/ rate server-rate)) duration (when (> rate 0) (/ size rate))] (when (every? zero? [size rate n-channels]) (throw (Exception. (str "Unable to read file - perhaps path is not a valid audio file (only " supported-file-types " supported) : " path)))) (reset! *size size) (reset! *n-channels n-channels) (reset! *status :live) (swap! cached-samples* assoc [path cache-args] sample) (swap! loaded-samples* assoc id sample)))))) (snd "/b_allocRead" id path 0 -1)) (conj return-samples sample)))) [] paths-and-cache))) (defn- reload-all-samples [] (let [previously-loaded-samples (vals @loaded-samples* )] (reset! cached-samples* {}) (reset! loaded-samples* {}) (doseq [smpl previously-loaded-samples] (apply load-sample* (:path smpl) (:args smpl))))) (on-deps :server-ready ::load-all-samples reload-all-samples) (defn- free-loaded-sample [smpl] (let [path (:path smpl) args (:args smpl)] (if (server-connected?) (do (buffer-free smpl) (swap! cached-samples* dissoc [path args]) (swap! loaded-samples* dissoc (:id smpl)))))) (defn free-all-loaded-samples "Free all buffers associated with a loaded sample and the memory they consume. Also remove each sample from @loaded-samples once freed" [] (doseq [loaded-sample (vals @loaded-samples*)] (free-loaded-sample loaded-sample))) (defn free-sample "Free the buffer associated with smpl and the memory it consumes. Uses the cached version from @loaded-samples* in case the server has crashed or been rebooted. Also remove the sample from @loaded-samples." [smpl] (assert sample? smpl) (free-loaded-sample smpl) :sample-freed) (defn sample-player "Play the specified sample with either a mono or stereo player depending on the number of channels in the sample. Always creates a stereo signal. Accepts same args as both players, namely: {:buf 0 :rate 1.0 :start-pos 0.0 :loop? 0 :amp 1 :out-bus 0} If you wish to specify a group target vector i.e. [:head foo-g] this argument must go *after* the smpl argument: (sample-player my-samp [:head foo-g] :rate 0.5)" [smpl & pargs] {:pre [(sample? smpl)]} (let [{:keys [path args]} smpl {:keys [id n-channels]} (get @cached-samples* [path args]) [target pos pargs] (extract-target-pos-args pargs (foundation-default-group) :tail)] (cond (= n-channels 1) (apply mono-partial-player [pos target] id pargs) (= n-channels 2) (apply stereo-partial-player [pos target] id pargs)))) (defn sample "Loads a .wav or .aiff file into a memory buffer. Returns a function capable of playing that sample. Memoizes result and returns same sample on subsequent calls. ; e.g. (sample \"~/music/samples/flibble.wav\") " [path & args] (let [smpl (apply load-sample path args)] (map->PlayableSample smpl))) ;; Samples are just audio files loaded into a buffer, so buffer ;; functions work on samples too. (derive Sample ::sample) (derive PlayableSample ::playable-sample) (derive ::sample :overtone.sc.buffer/file-buffer) (derive ::playable-sample ::sample) (defmacro defsample "Define a s-name as a var in the current namespace referencing a sample with the specified path and args. Equivalent to: (def s-name (sample path args...))" [s-name path & args] `(def ~s-name (sample ~path ~@args)))
true
(ns ^{:doc "Making it easy to load and play audio samples (wav or aif files)." :author "PI:NAME:<NAME>END_PI"} overtone.sc.sample (:use [clojure.java.io :only [file]] [overtone.helpers lib synth] [overtone.libs event deps] [overtone.sc server synth ugens buffer foundation-groups node] [overtone.sc.machinery allocator] [overtone.sc.machinery.server comms] [overtone.sc.cgens buf-io io] [overtone.studio core] [overtone.helpers.file :only [glob canonical-path resolve-tilde-path mk-path file-extension]]) (:require [overtone.sc.envelope :refer [asr]] [overtone.sc.info :refer [server-sample-rate]] [overtone.libs.counters :refer [next-id]] [overtone.osc :refer [osc-send]])) (declare sample-player) (defonce ^{:private true} __RECORDS__ (do (defrecord Sample [id size n-channels rate status path args name] to-sc-id* (to-sc-id [this] (:id this))) (defrecord-ifn PlayableSample [id size n-channels rate status path args name] sample-player to-sc-id* (to-sc-id [this] (:id this))))) (defn sample? "Returns true if s is a sample" [s] (isa? (type s) ::sample)) (defmethod print-method Sample [b ^java.io.Writer w] (.write w (format "#<buffer[%s]: %s %fs %s %d>" (name @(:status b)) (:name b) (:duration b) (cond (= 1 (:n-channels b)) "mono" (= 2 (:n-channels b)) "stereo" :else (str (:n-channels b) " channels")) (:id b)))) (defmethod print-method PlayableSample [b ^java.io.Writer w] (.write w (format "#<buffer[%s]: %s %fs %s %d>" (name @(:status b)) (:name b) (:duration b) (cond (= 1 (:n-channels b)) "mono" (= 2 (:n-channels b)) "stereo" :else (str (:n-channels b) " channels")) (:id b)))) ;; Define a default wav player synth (defonce __DEFINE-PLAYERS__ (do (defsynth mono-partial-player "Plays a mono buffer from start pos to end pos (represented as values between 0 and 1). May be looped via the loop? argument. Release time is the release phase after the looping has finished to remove clipping." [buf 0 rate 1 start 0 end 1 loop? 0 amp 1 release 0 out-bus 0] (let [n-frames (buf-frames buf) rate (* rate (buf-rate-scale buf)) start-pos (* start n-frames) end-pos (* end n-frames) phase (phasor:ar :start start-pos :end end-pos :rate rate) snd (buf-rd 1 buf phase) e-gate (+ loop? (a2k (latch:ar (line 1 0 0.0001) (bpz2 phase)))) env (env-gen (asr 0 1 release) :gate e-gate :action FREE)] (out out-bus (* amp env snd)))) (defsynth stereo-partial-player "Plays a stereo buffer from start pos to end pos (represented as values between 0 and 1). May be looped via the loop? argument. Release time is the release phase after the looping has finished to remove clipping." [buf 0 rate 1 start 0 end 1 loop? 0 amp 1 release 0 out-bus 0] (let [n-frames (buf-frames buf) rate (* rate (buf-rate-scale buf)) start-pos (* start n-frames) end-pos (* end n-frames) phase (phasor:ar :start start-pos :end end-pos :rate rate) snd (buf-rd 2 buf phase) e-gate (+ loop? (a2k (latch:ar (line 1 0 0.0001) (bpz2 phase)))) env (env-gen (asr 0 1 release) :gate e-gate :action FREE)] (out out-bus (* amp env snd)))) (defsynth mono-stream-player "Plays a single channel streaming buffer-cue. Must be freed manually when done." [buf 0 rate 1 loop? 0 amp 1 pan 0 out-bus 0] (out out-bus (* amp (pan2 (scaled-v-disk-in 1 buf rate loop?) pan)))) (defsynth stereo-stream-player "Plays a dual channel streaming buffer-cue. Must be freed manually when done." [buf 0 rate 1 loop? 0 amp 1 pan 0 out-bus 0] (let [s (scaled-v-disk-in 2 buf rate loop?)] (out out-bus (* amp (balance2 (first s) (second s) pan))))))) (defonce loaded-samples* (atom {})) (defonce cached-samples* (atom {})) (defn- load-sample* [path arg-map] (let [path (canonical-path path) f (file path)] (when-not (.exists f) (throw (Exception. (str "Unable to load sample - file does not exist: " path)))) (let [f-name (or (:name arg-map) (.getName f)) start (get arg-map :start 0) n-frames (get arg-map :size 0) buf (buffer-alloc-read path start n-frames) sample (map->Sample (assoc buf :path path :args arg-map :name f-name))] (swap! cached-samples* assoc [path arg-map] sample) (swap! loaded-samples* assoc (:id buf) sample) sample))) (defn load-sample "Synchronously load a .wav or .aiff file into a memory buffer. Returns the buffer. ; e.g. (load-sample \"~/studio/samples/kit/boom.wav\") Takes optional params :start and :size. Allocates buffer to number of channels of file and number of samples requested (:size), or fewer if sound file is smaller than requested. Reads sound file data from the given starting frame in the file (:start). If the number of frames argument is less than or equal to zero, the entire file is read. If optional param :force is set to true, any previously create cache of the sample will be removed and the sample will be forcibly reloaded." [path & args] (ensure-connected!) (let [args (apply hash-map args) force? (:force args) args (select-keys args [:start :size]) path (canonical-path path)] (if-let [sample (and (not force?) (get @cached-samples* [path args]))] sample (load-sample* path args)))) (defn- assert-audio-files [file-seq] (run! (fn [^java.io.File f] (let [ext (file-extension f)] (assert (or (= ext "aif") (= ext "aiff") (= ext "wav")) (if (.isDirectory f) (str "The file " (.getPath f) " is a directory. " "If you wish to load all the files inside the directory, " "you need to provide the path with a glob pattern (asterix).\n" "Example \"~/samples/*\" or \"~/samples/*.wav\".") (str "The file " (.getPath f) " was not a .wav or .aiff audiofile. " "If you wish to choose only audiofile from a directory, you could " "provide the glob pattern like in this:\n \"~/samples/*.wav\"."))))) file-seq)) (defn load-samples "Takes one or more directory and/or file paths, suppoerts glob or glob paths (see #'overtone.helpers.file/glob) and loads up all matching samples and returns a seq of maps representing information for each loaded sample (see load-sample). Samples should be in .aiff or .wav format." [& glob-paths] (let [paths (reduce (fn [paths-vector path-glob] (into paths-vector (let [files (glob path-glob)] (assert-audio-files files) (mapv #(.getAbsolutePath ^java.io.File %) (sort files))))) [] glob-paths)] (doall (mapv (fn [path] (load-sample path)) paths)))) (defn load-samples-async "Takes one or more directory and/or file paths, supports glob paths (see #'overtone.helpers.file/glob). Loads up all matching samples and returns a seq of maps representing information for each loaded sample (see load-sample). Samples should be in .aiff or .wav format. Returns immedietly a vector of samples, some of which could still be loading. The buffer id for the sample is available immedietly, the rest of the metadata, like n-frames, n-channels and rate are available via atom when the sample is loaded. This function is thought of as a faster but unsafer alternative to `load-samples`, which is synchronous." [& glob-paths] (let [paths (reduce (fn [paths-vector path-glob] (into paths-vector (let [files (glob path-glob)] (assert-audio-files files) (mapv #(.getAbsolutePath ^java.io.File %) (sort files))))) [] glob-paths) ;; always load the entire sample, hence same args always cache-args {:start 0 :size -1} paths-and-cache (reduce (fn [out-vec path] (conj out-vec (or (get @cached-samples* [path cache-args]) path))) [] paths)] (reduce (fn [return-samples path-or-cache] (if (sample? path-or-cache) (conj return-samples path-or-cache) (let [id (do (assert-less-than-max-buffers) (next-id :audio-buffer)) *size (atom nil) *n-channels (atom nil) *rate (atom nil) *status (atom :loading) path path-or-cache name (.getName (file path)) sample (Sample. id *size *n-channels *rate *status path cache-args name)] (future (recv "/done" (fn [{:keys [args] :as msg}] (when (and (= (first args) "/b_allocRead") (= (second args) id)) (snd "/b_query" id) (future (let [info (deref (recv "/b_info" (fn [msg] (= id (first (:args msg)))))) [_ size rate n-channels] (:args info) server-rate (server-sample-rate) rate-scale (when (> server-rate 0) (/ rate server-rate)) duration (when (> rate 0) (/ size rate))] (when (every? zero? [size rate n-channels]) (throw (Exception. (str "Unable to read file - perhaps path is not a valid audio file (only " supported-file-types " supported) : " path)))) (reset! *size size) (reset! *n-channels n-channels) (reset! *status :live) (swap! cached-samples* assoc [path cache-args] sample) (swap! loaded-samples* assoc id sample)))))) (snd "/b_allocRead" id path 0 -1)) (conj return-samples sample)))) [] paths-and-cache))) (defn- reload-all-samples [] (let [previously-loaded-samples (vals @loaded-samples* )] (reset! cached-samples* {}) (reset! loaded-samples* {}) (doseq [smpl previously-loaded-samples] (apply load-sample* (:path smpl) (:args smpl))))) (on-deps :server-ready ::load-all-samples reload-all-samples) (defn- free-loaded-sample [smpl] (let [path (:path smpl) args (:args smpl)] (if (server-connected?) (do (buffer-free smpl) (swap! cached-samples* dissoc [path args]) (swap! loaded-samples* dissoc (:id smpl)))))) (defn free-all-loaded-samples "Free all buffers associated with a loaded sample and the memory they consume. Also remove each sample from @loaded-samples once freed" [] (doseq [loaded-sample (vals @loaded-samples*)] (free-loaded-sample loaded-sample))) (defn free-sample "Free the buffer associated with smpl and the memory it consumes. Uses the cached version from @loaded-samples* in case the server has crashed or been rebooted. Also remove the sample from @loaded-samples." [smpl] (assert sample? smpl) (free-loaded-sample smpl) :sample-freed) (defn sample-player "Play the specified sample with either a mono or stereo player depending on the number of channels in the sample. Always creates a stereo signal. Accepts same args as both players, namely: {:buf 0 :rate 1.0 :start-pos 0.0 :loop? 0 :amp 1 :out-bus 0} If you wish to specify a group target vector i.e. [:head foo-g] this argument must go *after* the smpl argument: (sample-player my-samp [:head foo-g] :rate 0.5)" [smpl & pargs] {:pre [(sample? smpl)]} (let [{:keys [path args]} smpl {:keys [id n-channels]} (get @cached-samples* [path args]) [target pos pargs] (extract-target-pos-args pargs (foundation-default-group) :tail)] (cond (= n-channels 1) (apply mono-partial-player [pos target] id pargs) (= n-channels 2) (apply stereo-partial-player [pos target] id pargs)))) (defn sample "Loads a .wav or .aiff file into a memory buffer. Returns a function capable of playing that sample. Memoizes result and returns same sample on subsequent calls. ; e.g. (sample \"~/music/samples/flibble.wav\") " [path & args] (let [smpl (apply load-sample path args)] (map->PlayableSample smpl))) ;; Samples are just audio files loaded into a buffer, so buffer ;; functions work on samples too. (derive Sample ::sample) (derive PlayableSample ::playable-sample) (derive ::sample :overtone.sc.buffer/file-buffer) (derive ::playable-sample ::sample) (defmacro defsample "Define a s-name as a var in the current namespace referencing a sample with the specified path and args. Equivalent to: (def s-name (sample path args...))" [s-name path & args] `(def ~s-name (sample ~path ~@args)))
[ { "context": ";;;; Copyright 2015 Peter Stephens. All Rights Reserved.\r\n;;;;\r\n;;;; Licensed unde", "end": 36, "score": 0.9997021555900574, "start": 22, "tag": "NAME", "value": "Peter Stephens" }, { "context": "= false (contains? (get-in m [:subtitle]) 1132)) \"Phil is not subtitled\"))\r\n (testing \"Chapter with p", "end": 2135, "score": 0.7702916264533997, "start": 2131, "tag": "NAME", "value": "Phil" }, { "context": " true (contains? (get-in m [:postscript]) 1132)) \"Phil does have postscript\"))\r\n (testing \"Partition", "end": 2535, "score": 0.903212308883667, "start": 2531, "tag": "NAME", "value": "Phil" } ]
src/test/node/common/bible/iotests.cljs
pstephens/kingjames.bible
23
;;;; Copyright 2015 Peter Stephens. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.node.common.bible.iotests (:require [common.bible.io :as io] [cljs.test :refer-macros [deftest testing is]] [test.node.helpers :refer [staggs-model]])) (deftest normalized->persisted-bible (let [m (io/normalized->persisted-bible staggs-model)] (testing "Books" (is (= 66 (count (get-in m [:books]))) "Book count") (is (= 50 (get-in m [:books 0])) "Chapter count for Genesis") (is (= 150 (get-in m [:books 18])) "Chapter count for Psalms") (is (= 22 (get-in m [:books 65])) "Chapter count for Revelation")) (testing "Chapters" (is (= 1189 (count (get-in m [:chapters]))) "Chapter count") (is (= 31 (get-in m [:chapters 0])) "Verse count in Genesis 1") (is (= 26 (get-in m [:chapters 49])) "Verse count in Genesis 50") (is (= 18 (get-in m [:chapters 517])) "Verse count in Psalm 40") (is (= 176 (get-in m [:chapters 596])) "Verse count in Psalm 119") (is (= 26 (get-in m [:chapters 1132])) "Verse count in Philemon") (is (= 21 (get-in m [:chapters 1188])) "Verse count in Rev 22")) (testing "Chapters with subtitle" (is (= 115 (count (get-in m [:subtitle]))) "Subtitled chapter count") (is (= false (contains? (get-in m [:subtitle]) 0)) "Gen 1 is not subtitled") (is (= true (contains? (get-in m [:subtitle]) 517)) "Psalm 40 is subtitled") (is (= false (contains? (get-in m [:subtitle]) 1132)) "Phil is not subtitled")) (testing "Chapter with postscript" (is (= 14 (count (get-in m [:postscript]))) "Postscript chapter count") (is (= false (contains? (get-in m [:postscript]) 0)) "Gen 1 does not have postscript") (is (= false (contains? (get-in m [:postscript]) 517)) "Psalm 40 does not have postscript") (is (= true (contains? (get-in m [:postscript]) 1132)) "Phil does have postscript")) (testing "Partition size" (is (number? (get-in m [:partition-size])))))) (deftest normalized->persisted-verses (let [m (io/normalized->persisted-verses staggs-model)] (is (= (+ 31102 14 115) (count m)))))
103665
;;;; Copyright 2015 <NAME>. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.node.common.bible.iotests (:require [common.bible.io :as io] [cljs.test :refer-macros [deftest testing is]] [test.node.helpers :refer [staggs-model]])) (deftest normalized->persisted-bible (let [m (io/normalized->persisted-bible staggs-model)] (testing "Books" (is (= 66 (count (get-in m [:books]))) "Book count") (is (= 50 (get-in m [:books 0])) "Chapter count for Genesis") (is (= 150 (get-in m [:books 18])) "Chapter count for Psalms") (is (= 22 (get-in m [:books 65])) "Chapter count for Revelation")) (testing "Chapters" (is (= 1189 (count (get-in m [:chapters]))) "Chapter count") (is (= 31 (get-in m [:chapters 0])) "Verse count in Genesis 1") (is (= 26 (get-in m [:chapters 49])) "Verse count in Genesis 50") (is (= 18 (get-in m [:chapters 517])) "Verse count in Psalm 40") (is (= 176 (get-in m [:chapters 596])) "Verse count in Psalm 119") (is (= 26 (get-in m [:chapters 1132])) "Verse count in Philemon") (is (= 21 (get-in m [:chapters 1188])) "Verse count in Rev 22")) (testing "Chapters with subtitle" (is (= 115 (count (get-in m [:subtitle]))) "Subtitled chapter count") (is (= false (contains? (get-in m [:subtitle]) 0)) "Gen 1 is not subtitled") (is (= true (contains? (get-in m [:subtitle]) 517)) "Psalm 40 is subtitled") (is (= false (contains? (get-in m [:subtitle]) 1132)) "<NAME> is not subtitled")) (testing "Chapter with postscript" (is (= 14 (count (get-in m [:postscript]))) "Postscript chapter count") (is (= false (contains? (get-in m [:postscript]) 0)) "Gen 1 does not have postscript") (is (= false (contains? (get-in m [:postscript]) 517)) "Psalm 40 does not have postscript") (is (= true (contains? (get-in m [:postscript]) 1132)) "<NAME> does have postscript")) (testing "Partition size" (is (number? (get-in m [:partition-size])))))) (deftest normalized->persisted-verses (let [m (io/normalized->persisted-verses staggs-model)] (is (= (+ 31102 14 115) (count m)))))
true
;;;; Copyright 2015 PI:NAME:<NAME>END_PI. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.node.common.bible.iotests (:require [common.bible.io :as io] [cljs.test :refer-macros [deftest testing is]] [test.node.helpers :refer [staggs-model]])) (deftest normalized->persisted-bible (let [m (io/normalized->persisted-bible staggs-model)] (testing "Books" (is (= 66 (count (get-in m [:books]))) "Book count") (is (= 50 (get-in m [:books 0])) "Chapter count for Genesis") (is (= 150 (get-in m [:books 18])) "Chapter count for Psalms") (is (= 22 (get-in m [:books 65])) "Chapter count for Revelation")) (testing "Chapters" (is (= 1189 (count (get-in m [:chapters]))) "Chapter count") (is (= 31 (get-in m [:chapters 0])) "Verse count in Genesis 1") (is (= 26 (get-in m [:chapters 49])) "Verse count in Genesis 50") (is (= 18 (get-in m [:chapters 517])) "Verse count in Psalm 40") (is (= 176 (get-in m [:chapters 596])) "Verse count in Psalm 119") (is (= 26 (get-in m [:chapters 1132])) "Verse count in Philemon") (is (= 21 (get-in m [:chapters 1188])) "Verse count in Rev 22")) (testing "Chapters with subtitle" (is (= 115 (count (get-in m [:subtitle]))) "Subtitled chapter count") (is (= false (contains? (get-in m [:subtitle]) 0)) "Gen 1 is not subtitled") (is (= true (contains? (get-in m [:subtitle]) 517)) "Psalm 40 is subtitled") (is (= false (contains? (get-in m [:subtitle]) 1132)) "PI:NAME:<NAME>END_PI is not subtitled")) (testing "Chapter with postscript" (is (= 14 (count (get-in m [:postscript]))) "Postscript chapter count") (is (= false (contains? (get-in m [:postscript]) 0)) "Gen 1 does not have postscript") (is (= false (contains? (get-in m [:postscript]) 517)) "Psalm 40 does not have postscript") (is (= true (contains? (get-in m [:postscript]) 1132)) "PI:NAME:<NAME>END_PI does have postscript")) (testing "Partition size" (is (number? (get-in m [:partition-size])))))) (deftest normalized->persisted-verses (let [m (io/normalized->persisted-verses staggs-model)] (is (= (+ 31102 14 115) (count m)))))
[ { "context": " option pricing model GUI\n;;\n;; Copyright (C) 2010 Paul Legato. All rights reserved.\n;; Licensed under the New B", "end": 81, "score": 0.9998524188995361, "start": 70, "tag": "NAME", "value": "Paul Legato" } ]
src/clojure_options/gui/black_scholes_gui.clj
pjlegato/clojure_options
3
;; ;; Black-Scholes option pricing model GUI ;; ;; Copyright (C) 2010 Paul Legato. All rights reserved. ;; Licensed under the New BSD License. See the README file for details. ;; ;; Disclaimer: This code comes with NO WARRANTY, express or implied. ;; There may be any number of bugs. Use at your own risk. ;; ;; With thanks to http://kotka.de/blog/2010/05/Decoupling_Logic_and_GUI.html ;; ;; TODO: ;; ;; - Eliminate "Calculate" button and add listeners to ;; auto-recalculate whenever an input is changed. ;; - (ns clojure-options.gui.black-scholes-gui (:import [javax.swing JTable JFrame JButton JPanel JScrollPane JTextField JFormattedTextField JLabel] [javax.swing.table AbstractTableModel] [java.text NumberFormat] ) (:use [clojure.contrib.swing-utils] [clojure.contrib.miglayout :only (miglayout components)]) (:require [clojure.contrib.miglayout :as mig] [clojure-options.black-scholes :as bs])) (def *trading-days-per-year* 251) (def *spot* (atom 100)) (def *strike* (atom 75)) (def *days-till-expiry* (atom 40)) (def *riskfree* (atom 0.02)) (def *volatility* (atom 0.4)) (def *call-price* (atom 0.00)) (def *put-price* (atom 0.00)) (def *call-delta* (atom 0.00)) (def *put-delta* (atom 0.00)) (def *call-theta* (atom 0.00)) (def *put-theta* (atom 0.00)) (def *call-rho* (atom 0.00)) (def *put-rho* (atom 0.00)) (def *vega* (atom 0.0)) (def *gamma* (atom 0.0)) (defn- update-all-calculations [spot timeleft strike riskfree sigma] (swap! *call-price* (fn [_] (bs/call spot timeleft strike riskfree sigma))) (swap! *put-price* (fn [_] (bs/put spot timeleft strike riskfree sigma))) (swap! *call-delta* (fn [_] (bs/call-delta spot timeleft strike riskfree sigma))) (swap! *put-delta* (fn [_] (bs/put-delta spot timeleft strike riskfree sigma))) (swap! *call-theta* (fn [_] (bs/call-theta spot timeleft strike riskfree sigma))) (swap! *put-theta* (fn [_] (bs/put-theta spot timeleft strike riskfree sigma))) (swap! *call-rho* (fn [_] (bs/call-rho spot timeleft strike riskfree sigma))) (swap! *put-rho* (fn [_] (bs/put-rho spot timeleft strike riskfree sigma))) (swap! *vega* (fn [_] (bs/vega spot timeleft strike riskfree sigma))) (swap! *gamma* (fn [_] (bs/gamma spot timeleft strike riskfree sigma)))) (defn- update-cell "Updates the given AbstractTableModel cell and fires a change event for that cell." [model data row col] (.setValueAt model data row col) (.fireTableCellUpdated model row col)) (defn- result-table [] (let [ column-names ["" "Call" "Put"] row-names ["Price" "Delta" "Theta" "Rho" "Gamma" "Vega"] table-model (proxy [AbstractTableModel] [] (getColumnCount [] (count column-names)) (getRowCount [] (count row-names)) (isCellEditable [] false) (getColumnName [col] (nth column-names col)) (getValueAt [row col] (condp = col 0 (nth row-names row) ;; Return the row name for column zero (condp = [row col] [0 1] @*call-price* [0 2] @*put-price* [1 1] @*call-delta* [1 2] @*put-delta* [2 1] @*call-theta* [2 2] @*put-theta* [3 1] @*call-rho* [3 2] @*put-rho* [4 1] @*gamma* [4 2] "==" [5 1] @*vega* [5 2] "==" nil)))) table (doto (JTable. table-model) (.setGridColor java.awt.Color/DARK_GRAY)) ] (add-watch *call-price* ::update-call-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 1))) (add-watch *put-price* ::update-put-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 2))) (add-watch *call-delta* ::update-call-delta (fn [_ _ _ newval] (update-cell table-model newval 1 1))) (add-watch *put-delta* ::update-put-delta (fn [_ _ _ newval] (update-cell table-model newval 1 2))) (add-watch *call-theta* ::update-call-theta (fn [_ _ _ newval] (update-cell table-model newval 2 1))) (add-watch *put-theta* ::update-put-theta (fn [_ _ _ newval] (update-cell table-model newval 2 2))) (add-watch *call-rho* ::update-call-rho (fn [_ _ _ newval] (update-cell table-model newval 3 1))) (add-watch *put-rho* ::update-put-rho (fn [_ _ _ newval] (update-cell table-model newval 3 2))) (add-watch *gamma* ::update-gamma (fn [_ _ _ newval] (update-cell table-model newval 4 1))) (add-watch *vega* ::update-vega (fn [_ _ _ newval] (update-cell table-model newval 5 1))) ;; This shrinks the table's preferred viewport down to its actual size. ;; (The default is to make a huge viewport, even though the table is small.) (.setPreferredScrollableViewportSize table (.getPreferredSize table)) (JScrollPane. table) )) (defn- input-panel [quit-action] (let [ ;; Fields spot (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*spot*)) strike (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*strike*)) days-till-expiry (doto (JFormattedTextField. (NumberFormat/getIntegerInstance)) (.setColumns 6) (.setValue @*days-till-expiry*)) riskfree (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*riskfree*)) volatility (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*volatility*)) ;; Buttons calculate (JButton. "Calculate") quit (JButton. "Quit") ] (add-action-listener calculate (fn [_] (update-all-calculations (Double/parseDouble (.getText spot)) (/ (Integer/parseInt (.getText days-till-expiry)) *trading-days-per-year*) (Double/parseDouble (.getText strike)) (Double/parseDouble (.getText riskfree)) (Double/parseDouble (.getText volatility))))) (add-action-listener quit quit-action) (miglayout (JPanel.) :layout [:wrap 2 ] (JLabel. "Spot") [:align "right"] spot (JLabel. "Strike") [:align "right"] strike (JLabel. "Risk-free rate") [:align "right"] riskfree (JLabel. "Volatility") [:align "right"] volatility (JLabel. "Days till expiry") [:align "right"] days-till-expiry calculate quit))) (defn initialize-gui [] (let [frame (JFrame. "Black-Scholes Option Modeler")] (doto frame (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (-> .getContentPane (.add (miglayout (JPanel.) (input-panel (fn [_] (do-swing (doto frame (.setVisible false) (.dispose))))) (result-table) ))) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (.pack) (.setVisible true)) )) (defn main [] (do-swing* :now initialize-gui))
69864
;; ;; Black-Scholes option pricing model GUI ;; ;; Copyright (C) 2010 <NAME>. All rights reserved. ;; Licensed under the New BSD License. See the README file for details. ;; ;; Disclaimer: This code comes with NO WARRANTY, express or implied. ;; There may be any number of bugs. Use at your own risk. ;; ;; With thanks to http://kotka.de/blog/2010/05/Decoupling_Logic_and_GUI.html ;; ;; TODO: ;; ;; - Eliminate "Calculate" button and add listeners to ;; auto-recalculate whenever an input is changed. ;; - (ns clojure-options.gui.black-scholes-gui (:import [javax.swing JTable JFrame JButton JPanel JScrollPane JTextField JFormattedTextField JLabel] [javax.swing.table AbstractTableModel] [java.text NumberFormat] ) (:use [clojure.contrib.swing-utils] [clojure.contrib.miglayout :only (miglayout components)]) (:require [clojure.contrib.miglayout :as mig] [clojure-options.black-scholes :as bs])) (def *trading-days-per-year* 251) (def *spot* (atom 100)) (def *strike* (atom 75)) (def *days-till-expiry* (atom 40)) (def *riskfree* (atom 0.02)) (def *volatility* (atom 0.4)) (def *call-price* (atom 0.00)) (def *put-price* (atom 0.00)) (def *call-delta* (atom 0.00)) (def *put-delta* (atom 0.00)) (def *call-theta* (atom 0.00)) (def *put-theta* (atom 0.00)) (def *call-rho* (atom 0.00)) (def *put-rho* (atom 0.00)) (def *vega* (atom 0.0)) (def *gamma* (atom 0.0)) (defn- update-all-calculations [spot timeleft strike riskfree sigma] (swap! *call-price* (fn [_] (bs/call spot timeleft strike riskfree sigma))) (swap! *put-price* (fn [_] (bs/put spot timeleft strike riskfree sigma))) (swap! *call-delta* (fn [_] (bs/call-delta spot timeleft strike riskfree sigma))) (swap! *put-delta* (fn [_] (bs/put-delta spot timeleft strike riskfree sigma))) (swap! *call-theta* (fn [_] (bs/call-theta spot timeleft strike riskfree sigma))) (swap! *put-theta* (fn [_] (bs/put-theta spot timeleft strike riskfree sigma))) (swap! *call-rho* (fn [_] (bs/call-rho spot timeleft strike riskfree sigma))) (swap! *put-rho* (fn [_] (bs/put-rho spot timeleft strike riskfree sigma))) (swap! *vega* (fn [_] (bs/vega spot timeleft strike riskfree sigma))) (swap! *gamma* (fn [_] (bs/gamma spot timeleft strike riskfree sigma)))) (defn- update-cell "Updates the given AbstractTableModel cell and fires a change event for that cell." [model data row col] (.setValueAt model data row col) (.fireTableCellUpdated model row col)) (defn- result-table [] (let [ column-names ["" "Call" "Put"] row-names ["Price" "Delta" "Theta" "Rho" "Gamma" "Vega"] table-model (proxy [AbstractTableModel] [] (getColumnCount [] (count column-names)) (getRowCount [] (count row-names)) (isCellEditable [] false) (getColumnName [col] (nth column-names col)) (getValueAt [row col] (condp = col 0 (nth row-names row) ;; Return the row name for column zero (condp = [row col] [0 1] @*call-price* [0 2] @*put-price* [1 1] @*call-delta* [1 2] @*put-delta* [2 1] @*call-theta* [2 2] @*put-theta* [3 1] @*call-rho* [3 2] @*put-rho* [4 1] @*gamma* [4 2] "==" [5 1] @*vega* [5 2] "==" nil)))) table (doto (JTable. table-model) (.setGridColor java.awt.Color/DARK_GRAY)) ] (add-watch *call-price* ::update-call-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 1))) (add-watch *put-price* ::update-put-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 2))) (add-watch *call-delta* ::update-call-delta (fn [_ _ _ newval] (update-cell table-model newval 1 1))) (add-watch *put-delta* ::update-put-delta (fn [_ _ _ newval] (update-cell table-model newval 1 2))) (add-watch *call-theta* ::update-call-theta (fn [_ _ _ newval] (update-cell table-model newval 2 1))) (add-watch *put-theta* ::update-put-theta (fn [_ _ _ newval] (update-cell table-model newval 2 2))) (add-watch *call-rho* ::update-call-rho (fn [_ _ _ newval] (update-cell table-model newval 3 1))) (add-watch *put-rho* ::update-put-rho (fn [_ _ _ newval] (update-cell table-model newval 3 2))) (add-watch *gamma* ::update-gamma (fn [_ _ _ newval] (update-cell table-model newval 4 1))) (add-watch *vega* ::update-vega (fn [_ _ _ newval] (update-cell table-model newval 5 1))) ;; This shrinks the table's preferred viewport down to its actual size. ;; (The default is to make a huge viewport, even though the table is small.) (.setPreferredScrollableViewportSize table (.getPreferredSize table)) (JScrollPane. table) )) (defn- input-panel [quit-action] (let [ ;; Fields spot (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*spot*)) strike (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*strike*)) days-till-expiry (doto (JFormattedTextField. (NumberFormat/getIntegerInstance)) (.setColumns 6) (.setValue @*days-till-expiry*)) riskfree (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*riskfree*)) volatility (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*volatility*)) ;; Buttons calculate (JButton. "Calculate") quit (JButton. "Quit") ] (add-action-listener calculate (fn [_] (update-all-calculations (Double/parseDouble (.getText spot)) (/ (Integer/parseInt (.getText days-till-expiry)) *trading-days-per-year*) (Double/parseDouble (.getText strike)) (Double/parseDouble (.getText riskfree)) (Double/parseDouble (.getText volatility))))) (add-action-listener quit quit-action) (miglayout (JPanel.) :layout [:wrap 2 ] (JLabel. "Spot") [:align "right"] spot (JLabel. "Strike") [:align "right"] strike (JLabel. "Risk-free rate") [:align "right"] riskfree (JLabel. "Volatility") [:align "right"] volatility (JLabel. "Days till expiry") [:align "right"] days-till-expiry calculate quit))) (defn initialize-gui [] (let [frame (JFrame. "Black-Scholes Option Modeler")] (doto frame (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (-> .getContentPane (.add (miglayout (JPanel.) (input-panel (fn [_] (do-swing (doto frame (.setVisible false) (.dispose))))) (result-table) ))) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (.pack) (.setVisible true)) )) (defn main [] (do-swing* :now initialize-gui))
true
;; ;; Black-Scholes option pricing model GUI ;; ;; Copyright (C) 2010 PI:NAME:<NAME>END_PI. All rights reserved. ;; Licensed under the New BSD License. See the README file for details. ;; ;; Disclaimer: This code comes with NO WARRANTY, express or implied. ;; There may be any number of bugs. Use at your own risk. ;; ;; With thanks to http://kotka.de/blog/2010/05/Decoupling_Logic_and_GUI.html ;; ;; TODO: ;; ;; - Eliminate "Calculate" button and add listeners to ;; auto-recalculate whenever an input is changed. ;; - (ns clojure-options.gui.black-scholes-gui (:import [javax.swing JTable JFrame JButton JPanel JScrollPane JTextField JFormattedTextField JLabel] [javax.swing.table AbstractTableModel] [java.text NumberFormat] ) (:use [clojure.contrib.swing-utils] [clojure.contrib.miglayout :only (miglayout components)]) (:require [clojure.contrib.miglayout :as mig] [clojure-options.black-scholes :as bs])) (def *trading-days-per-year* 251) (def *spot* (atom 100)) (def *strike* (atom 75)) (def *days-till-expiry* (atom 40)) (def *riskfree* (atom 0.02)) (def *volatility* (atom 0.4)) (def *call-price* (atom 0.00)) (def *put-price* (atom 0.00)) (def *call-delta* (atom 0.00)) (def *put-delta* (atom 0.00)) (def *call-theta* (atom 0.00)) (def *put-theta* (atom 0.00)) (def *call-rho* (atom 0.00)) (def *put-rho* (atom 0.00)) (def *vega* (atom 0.0)) (def *gamma* (atom 0.0)) (defn- update-all-calculations [spot timeleft strike riskfree sigma] (swap! *call-price* (fn [_] (bs/call spot timeleft strike riskfree sigma))) (swap! *put-price* (fn [_] (bs/put spot timeleft strike riskfree sigma))) (swap! *call-delta* (fn [_] (bs/call-delta spot timeleft strike riskfree sigma))) (swap! *put-delta* (fn [_] (bs/put-delta spot timeleft strike riskfree sigma))) (swap! *call-theta* (fn [_] (bs/call-theta spot timeleft strike riskfree sigma))) (swap! *put-theta* (fn [_] (bs/put-theta spot timeleft strike riskfree sigma))) (swap! *call-rho* (fn [_] (bs/call-rho spot timeleft strike riskfree sigma))) (swap! *put-rho* (fn [_] (bs/put-rho spot timeleft strike riskfree sigma))) (swap! *vega* (fn [_] (bs/vega spot timeleft strike riskfree sigma))) (swap! *gamma* (fn [_] (bs/gamma spot timeleft strike riskfree sigma)))) (defn- update-cell "Updates the given AbstractTableModel cell and fires a change event for that cell." [model data row col] (.setValueAt model data row col) (.fireTableCellUpdated model row col)) (defn- result-table [] (let [ column-names ["" "Call" "Put"] row-names ["Price" "Delta" "Theta" "Rho" "Gamma" "Vega"] table-model (proxy [AbstractTableModel] [] (getColumnCount [] (count column-names)) (getRowCount [] (count row-names)) (isCellEditable [] false) (getColumnName [col] (nth column-names col)) (getValueAt [row col] (condp = col 0 (nth row-names row) ;; Return the row name for column zero (condp = [row col] [0 1] @*call-price* [0 2] @*put-price* [1 1] @*call-delta* [1 2] @*put-delta* [2 1] @*call-theta* [2 2] @*put-theta* [3 1] @*call-rho* [3 2] @*put-rho* [4 1] @*gamma* [4 2] "==" [5 1] @*vega* [5 2] "==" nil)))) table (doto (JTable. table-model) (.setGridColor java.awt.Color/DARK_GRAY)) ] (add-watch *call-price* ::update-call-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 1))) (add-watch *put-price* ::update-put-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 2))) (add-watch *call-delta* ::update-call-delta (fn [_ _ _ newval] (update-cell table-model newval 1 1))) (add-watch *put-delta* ::update-put-delta (fn [_ _ _ newval] (update-cell table-model newval 1 2))) (add-watch *call-theta* ::update-call-theta (fn [_ _ _ newval] (update-cell table-model newval 2 1))) (add-watch *put-theta* ::update-put-theta (fn [_ _ _ newval] (update-cell table-model newval 2 2))) (add-watch *call-rho* ::update-call-rho (fn [_ _ _ newval] (update-cell table-model newval 3 1))) (add-watch *put-rho* ::update-put-rho (fn [_ _ _ newval] (update-cell table-model newval 3 2))) (add-watch *gamma* ::update-gamma (fn [_ _ _ newval] (update-cell table-model newval 4 1))) (add-watch *vega* ::update-vega (fn [_ _ _ newval] (update-cell table-model newval 5 1))) ;; This shrinks the table's preferred viewport down to its actual size. ;; (The default is to make a huge viewport, even though the table is small.) (.setPreferredScrollableViewportSize table (.getPreferredSize table)) (JScrollPane. table) )) (defn- input-panel [quit-action] (let [ ;; Fields spot (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*spot*)) strike (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*strike*)) days-till-expiry (doto (JFormattedTextField. (NumberFormat/getIntegerInstance)) (.setColumns 6) (.setValue @*days-till-expiry*)) riskfree (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*riskfree*)) volatility (doto (JFormattedTextField. (NumberFormat/getNumberInstance)) (.setColumns 6) (.setValue @*volatility*)) ;; Buttons calculate (JButton. "Calculate") quit (JButton. "Quit") ] (add-action-listener calculate (fn [_] (update-all-calculations (Double/parseDouble (.getText spot)) (/ (Integer/parseInt (.getText days-till-expiry)) *trading-days-per-year*) (Double/parseDouble (.getText strike)) (Double/parseDouble (.getText riskfree)) (Double/parseDouble (.getText volatility))))) (add-action-listener quit quit-action) (miglayout (JPanel.) :layout [:wrap 2 ] (JLabel. "Spot") [:align "right"] spot (JLabel. "Strike") [:align "right"] strike (JLabel. "Risk-free rate") [:align "right"] riskfree (JLabel. "Volatility") [:align "right"] volatility (JLabel. "Days till expiry") [:align "right"] days-till-expiry calculate quit))) (defn initialize-gui [] (let [frame (JFrame. "Black-Scholes Option Modeler")] (doto frame (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (-> .getContentPane (.add (miglayout (JPanel.) (input-panel (fn [_] (do-swing (doto frame (.setVisible false) (.dispose))))) (result-table) ))) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (.pack) (.setVisible true)) )) (defn main [] (do-swing* :now initialize-gui))
[ { "context": "just hand code a few\n {:items [(make-person 1 \"Tony\")\n (make-thing 2 \"Toaster\")\n ", "end": 4734, "score": 0.9971314668655396, "start": 4730, "tag": "NAME", "value": "Tony" }, { "context": "-place 3 \"New York\")\n (make-person 4 \"Sally\")\n (make-thing 5 \"Pillow\")\n ", "end": 4848, "score": 0.9981151819229126, "start": 4843, "tag": "NAME", "value": "Sally" } ]
src/demos/recipes/defrouter_for_type_selection.cljs
weirp/fulcrodev
0
(ns recipes.defrouter-for-type-selection (:require [om.dom :as dom] [fulcro.client.routing :as r :refer [defrouter]] [om.next :as om :refer [defui]] [fulcro.client.core :as fc] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.elements :as ele])) (defn item-ident "Generate an ident from a person, place, or thing." [props] [(:kind props) (:db/id props)]) (defn item-key "Generate a distinct react key for a person, place, or thing" [props] (str (:kind props) "-" (:db/id props))) (defn make-person [id n] {:db/id id :kind :person :person/name n}) (defn make-place [id n] {:db/id id :kind :place :place/name n}) (defn make-thing [id n] {:db/id id :kind :thing :thing/label n}) (defui ^:once PersonDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :person/name]) ; defrouter expects there to be an initial state for each possible target. We'll cause this to be a "no selection" ; state so that the detail screen that starts out will show "Nothing selected". We initialize all three in case ; we later re-order them in the defrouter. static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :person}) Object (render [this] (let [{:keys [db/id person/name]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about person " name)))))) (defui ^:once PlaceDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :place/name]) static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :place}) Object (render [this] (let [{:keys [db/id place/name]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about place " name)))))) (defui ^:once ThingDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :thing/label]) static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :thing}) Object (render [this] (let [{:keys [db/id thing/label]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about thing " label)))))) (defui ^:once PersonListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :person/name]) Object (render [this] (let [{:keys [db/id person/name] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Person " id " " name)))))) (def ui-person (om/factory PersonListItem {:keyfn item-key})) (defui ^:once PlaceListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :place/name]) Object (render [this] (let [{:keys [db/id place/name] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Place " id " : " name)))))) (def ui-place (om/factory PlaceListItem {:keyfn item-key})) (defui ^:once ThingListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :thing/label]) Object (render [this] (let [{:keys [db/id thing/label] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Thing " id " : " label)))))) (def ui-thing (om/factory ThingListItem item-key)) (defrouter ItemDetail :detail-router (ident [this props] (item-ident props)) :person PersonDetail :place PlaceDetail :thing ThingDetail) (def ui-item-detail (om/factory ItemDetail)) (defui ^:once ItemUnion static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] {:person (om/get-query PersonListItem) :place (om/get-query PlaceListItem) :thing (om/get-query ThingListItem)}) Object (render [this] (let [{:keys [kind] :as props} (om/props this)] (case kind :person (ui-person props) :place (ui-place props) :thing (ui-thing props))))) (def ui-item-union (om/factory ItemUnion {:keyfn item-key})) (defui ^:once ItemList static fc/InitialAppState (initial-state [c p] ; These would normally be loaded...but for demo purposes we just hand code a few {:items [(make-person 1 "Tony") (make-thing 2 "Toaster") (make-place 3 "New York") (make-person 4 "Sally") (make-thing 5 "Pillow") (make-place 6 "Canada")]}) static om/Ident (ident [this props] [:lists/by-id :singleton]) static om/IQuery (query [this] [{:items (om/get-query ItemUnion)}]) Object (render [this] (let [{:keys [items]} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/ul nil (map (fn [i] (ui-item-union (om/computed i {:onSelect onSelect}))) items))))) (def ui-item-list (om/factory ItemList)) (defui ^:once DemoRoot static om/IQuery (query [this] [{:item-list (om/get-query ItemList)} {:item-detail (om/get-query ItemDetail)}]) static fc/InitialAppState (initial-state [c p] (merge (r/routing-tree (r/make-route :detail [(r/router-instruction :detail-router [:param/kind :param/id])])) {:item-list (fc/get-initial-state ItemList nil) :item-detail (fc/get-initial-state ItemDetail nil)})) Object (render [this] (let [{:keys [item-list item-detail]} (om/props this) ; This is the only thing to do: Route the to the detail screen with the given route params! showDetail (fn [[kind id]] (om/transact! this `[(r/route-to {:handler :detail :route-params {:kind ~kind :id ~id}})]))] ; devcards, embed in iframe so we can use bootstrap css easily (ele/ui-iframe {:frameBorder 0 :height "300px" :width "100%"} (dom/div #js {:key "example-frame-key"} (dom/style nil ".boxed {border: 1px solid black}") (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (b/container-fluid {} (b/row {} (b/col {:xs 6} "Items") (b/col {:xs 6} "Detail")) (b/row {} (b/col {:xs 6} (ui-item-list (om/computed item-list {:onSelect showDetail}))) (b/col {:xs 6} (ui-item-detail item-detail)))))))))
14529
(ns recipes.defrouter-for-type-selection (:require [om.dom :as dom] [fulcro.client.routing :as r :refer [defrouter]] [om.next :as om :refer [defui]] [fulcro.client.core :as fc] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.elements :as ele])) (defn item-ident "Generate an ident from a person, place, or thing." [props] [(:kind props) (:db/id props)]) (defn item-key "Generate a distinct react key for a person, place, or thing" [props] (str (:kind props) "-" (:db/id props))) (defn make-person [id n] {:db/id id :kind :person :person/name n}) (defn make-place [id n] {:db/id id :kind :place :place/name n}) (defn make-thing [id n] {:db/id id :kind :thing :thing/label n}) (defui ^:once PersonDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :person/name]) ; defrouter expects there to be an initial state for each possible target. We'll cause this to be a "no selection" ; state so that the detail screen that starts out will show "Nothing selected". We initialize all three in case ; we later re-order them in the defrouter. static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :person}) Object (render [this] (let [{:keys [db/id person/name]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about person " name)))))) (defui ^:once PlaceDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :place/name]) static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :place}) Object (render [this] (let [{:keys [db/id place/name]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about place " name)))))) (defui ^:once ThingDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :thing/label]) static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :thing}) Object (render [this] (let [{:keys [db/id thing/label]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about thing " label)))))) (defui ^:once PersonListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :person/name]) Object (render [this] (let [{:keys [db/id person/name] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Person " id " " name)))))) (def ui-person (om/factory PersonListItem {:keyfn item-key})) (defui ^:once PlaceListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :place/name]) Object (render [this] (let [{:keys [db/id place/name] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Place " id " : " name)))))) (def ui-place (om/factory PlaceListItem {:keyfn item-key})) (defui ^:once ThingListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :thing/label]) Object (render [this] (let [{:keys [db/id thing/label] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Thing " id " : " label)))))) (def ui-thing (om/factory ThingListItem item-key)) (defrouter ItemDetail :detail-router (ident [this props] (item-ident props)) :person PersonDetail :place PlaceDetail :thing ThingDetail) (def ui-item-detail (om/factory ItemDetail)) (defui ^:once ItemUnion static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] {:person (om/get-query PersonListItem) :place (om/get-query PlaceListItem) :thing (om/get-query ThingListItem)}) Object (render [this] (let [{:keys [kind] :as props} (om/props this)] (case kind :person (ui-person props) :place (ui-place props) :thing (ui-thing props))))) (def ui-item-union (om/factory ItemUnion {:keyfn item-key})) (defui ^:once ItemList static fc/InitialAppState (initial-state [c p] ; These would normally be loaded...but for demo purposes we just hand code a few {:items [(make-person 1 "<NAME>") (make-thing 2 "Toaster") (make-place 3 "New York") (make-person 4 "<NAME>") (make-thing 5 "Pillow") (make-place 6 "Canada")]}) static om/Ident (ident [this props] [:lists/by-id :singleton]) static om/IQuery (query [this] [{:items (om/get-query ItemUnion)}]) Object (render [this] (let [{:keys [items]} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/ul nil (map (fn [i] (ui-item-union (om/computed i {:onSelect onSelect}))) items))))) (def ui-item-list (om/factory ItemList)) (defui ^:once DemoRoot static om/IQuery (query [this] [{:item-list (om/get-query ItemList)} {:item-detail (om/get-query ItemDetail)}]) static fc/InitialAppState (initial-state [c p] (merge (r/routing-tree (r/make-route :detail [(r/router-instruction :detail-router [:param/kind :param/id])])) {:item-list (fc/get-initial-state ItemList nil) :item-detail (fc/get-initial-state ItemDetail nil)})) Object (render [this] (let [{:keys [item-list item-detail]} (om/props this) ; This is the only thing to do: Route the to the detail screen with the given route params! showDetail (fn [[kind id]] (om/transact! this `[(r/route-to {:handler :detail :route-params {:kind ~kind :id ~id}})]))] ; devcards, embed in iframe so we can use bootstrap css easily (ele/ui-iframe {:frameBorder 0 :height "300px" :width "100%"} (dom/div #js {:key "example-frame-key"} (dom/style nil ".boxed {border: 1px solid black}") (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (b/container-fluid {} (b/row {} (b/col {:xs 6} "Items") (b/col {:xs 6} "Detail")) (b/row {} (b/col {:xs 6} (ui-item-list (om/computed item-list {:onSelect showDetail}))) (b/col {:xs 6} (ui-item-detail item-detail)))))))))
true
(ns recipes.defrouter-for-type-selection (:require [om.dom :as dom] [fulcro.client.routing :as r :refer [defrouter]] [om.next :as om :refer [defui]] [fulcro.client.core :as fc] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.elements :as ele])) (defn item-ident "Generate an ident from a person, place, or thing." [props] [(:kind props) (:db/id props)]) (defn item-key "Generate a distinct react key for a person, place, or thing" [props] (str (:kind props) "-" (:db/id props))) (defn make-person [id n] {:db/id id :kind :person :person/name n}) (defn make-place [id n] {:db/id id :kind :place :place/name n}) (defn make-thing [id n] {:db/id id :kind :thing :thing/label n}) (defui ^:once PersonDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :person/name]) ; defrouter expects there to be an initial state for each possible target. We'll cause this to be a "no selection" ; state so that the detail screen that starts out will show "Nothing selected". We initialize all three in case ; we later re-order them in the defrouter. static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :person}) Object (render [this] (let [{:keys [db/id person/name]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about person " name)))))) (defui ^:once PlaceDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :place/name]) static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :place}) Object (render [this] (let [{:keys [db/id place/name]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about place " name)))))) (defui ^:once ThingDetail static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :thing/label]) static fc/InitialAppState (initial-state [c p] {:db/id :no-selection :kind :thing}) Object (render [this] (let [{:keys [db/id thing/label]} (om/props this)] (dom/div nil (if (= id :no-selection) "Nothing selected" (str "Details about thing " label)))))) (defui ^:once PersonListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :person/name]) Object (render [this] (let [{:keys [db/id person/name] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Person " id " " name)))))) (def ui-person (om/factory PersonListItem {:keyfn item-key})) (defui ^:once PlaceListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :place/name]) Object (render [this] (let [{:keys [db/id place/name] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Place " id " : " name)))))) (def ui-place (om/factory PlaceListItem {:keyfn item-key})) (defui ^:once ThingListItem static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] [:kind :db/id :thing/label]) Object (render [this] (let [{:keys [db/id thing/label] :as props} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/li #js {:onClick #(onSelect (item-ident props))} (dom/a #js {:href "javascript:void(0)"} (str "Thing " id " : " label)))))) (def ui-thing (om/factory ThingListItem item-key)) (defrouter ItemDetail :detail-router (ident [this props] (item-ident props)) :person PersonDetail :place PlaceDetail :thing ThingDetail) (def ui-item-detail (om/factory ItemDetail)) (defui ^:once ItemUnion static om/Ident (ident [this props] (item-ident props)) static om/IQuery (query [this] {:person (om/get-query PersonListItem) :place (om/get-query PlaceListItem) :thing (om/get-query ThingListItem)}) Object (render [this] (let [{:keys [kind] :as props} (om/props this)] (case kind :person (ui-person props) :place (ui-place props) :thing (ui-thing props))))) (def ui-item-union (om/factory ItemUnion {:keyfn item-key})) (defui ^:once ItemList static fc/InitialAppState (initial-state [c p] ; These would normally be loaded...but for demo purposes we just hand code a few {:items [(make-person 1 "PI:NAME:<NAME>END_PI") (make-thing 2 "Toaster") (make-place 3 "New York") (make-person 4 "PI:NAME:<NAME>END_PI") (make-thing 5 "Pillow") (make-place 6 "Canada")]}) static om/Ident (ident [this props] [:lists/by-id :singleton]) static om/IQuery (query [this] [{:items (om/get-query ItemUnion)}]) Object (render [this] (let [{:keys [items]} (om/props this) onSelect (om/get-computed this :onSelect)] (dom/ul nil (map (fn [i] (ui-item-union (om/computed i {:onSelect onSelect}))) items))))) (def ui-item-list (om/factory ItemList)) (defui ^:once DemoRoot static om/IQuery (query [this] [{:item-list (om/get-query ItemList)} {:item-detail (om/get-query ItemDetail)}]) static fc/InitialAppState (initial-state [c p] (merge (r/routing-tree (r/make-route :detail [(r/router-instruction :detail-router [:param/kind :param/id])])) {:item-list (fc/get-initial-state ItemList nil) :item-detail (fc/get-initial-state ItemDetail nil)})) Object (render [this] (let [{:keys [item-list item-detail]} (om/props this) ; This is the only thing to do: Route the to the detail screen with the given route params! showDetail (fn [[kind id]] (om/transact! this `[(r/route-to {:handler :detail :route-params {:kind ~kind :id ~id}})]))] ; devcards, embed in iframe so we can use bootstrap css easily (ele/ui-iframe {:frameBorder 0 :height "300px" :width "100%"} (dom/div #js {:key "example-frame-key"} (dom/style nil ".boxed {border: 1px solid black}") (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (b/container-fluid {} (b/row {} (b/col {:xs 6} "Items") (b/col {:xs 6} "Detail")) (b/row {} (b/col {:xs 6} (ui-item-list (om/computed item-list {:onSelect showDetail}))) (b/col {:xs 6} (ui-item-detail item-detail)))))))))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-04-16\"\n ", "end": 96, "score": 0.6977638006210327, "start": 87, "tag": "EMAIL", "value": "wahpenayo" }, { "context": "-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-04-16\"\n :doc \n \"Tes", "end": 113, "score": 0.6356860995292664, "start": 100, "tag": "EMAIL", "value": "gmail dot com" } ]
src/test/clojure/zana/test/optimization/math3/lp.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :date "2018-04-16" :doc "Tests for [[zana.optimization.math3.lp]]." } zana.test.optimization.math3.lp (:require [clojure.test :as test] [zana.api :as z]) (:import [clojure.lang IFn IFn$OD] [org.apache.commons.math3.optim.linear NoFeasibleSolutionException])) ;; mvn -Dtest=zana.test.optimization.math3.lp clojure:test ;;---------------------------------------------------------------- ;; Tests borrowed from ;; org.apache.commons.math3.optim.linear.SimplexSolverTest ;;---------------------------------------------------------------- ;; assume constraint is [function relationship] pair ;; function must be double valued ;; assume relationship is specified with one of <= == >= ;; implied constraint is on function value relative to zero (defn- approximatelySatisfies [^double delta [^IFn$OD f ^IFn r] ^doubles x] (let [y (.invokePrim f x)] (cond (= r <=) (<= y delta) (= r ==) (<= (Math/abs y) delta) (= r >=) (>= y (- delta)) :else (throw (IllegalArgumentException. (print-str "not a valid relationship function:" r)))))) ;;---------------------------------------------------------------- (test/deftest math-842-cycle-affine (let [objective (z/affine-functional [10.0 -57.0 -9.0 -24.0] 0.0) constraints [[(z/affine-functional [0.5 -5.5 -2.5 9.0] 0.0) <=] [(z/affine-functional [0.5 -1.5 -0.5 1.0] 0.0) <=] [(z/affine-functional [1.0 0.0 0.0 0.0] -1.0) <=]] options {:minimize? false :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-842-cycle-linear (let [objective (z/linear-functional [10.0 -57.0 -9.0 -24.0]) constraints [[(z/linear-functional [0.5 -5.5 -2.5 9.0]) <=] [(z/linear-functional [0.5 -1.5 -0.5 1.0]) <=] [(z/affine-functional [1.0 0.0 0.0 0.0] -1.0) <=]] options {:minimize? false :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-828 (let [objective (z/linear-functional [1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]) constraints [[(z/affine-functional [ 0.0 39.0 23.0 96.0 15.0 48.0 9.0 21.0 48.0 36.0 76.0 19.0 88.0 17.0 16.0 36.0] -15.0) >=] [(z/affine-functional [ 0.0 59.0 93.0 12.0 29.0 78.0 73.0 87.0 32.0 70.0 68.0 24.0 11.0 26.0 65.0 25.0] -29.0) >=] [(z/affine-functional [ 0.0 74.0 5.0 82.0 6.0 97.0 55.0 44.0 52.0 54.0 5.0 93.0 91.0 8.0 20.0 97.0] -6.0) >=] [(z/linear-functional [ 8.0 -3.0 -28.0 -72.0 -8.0 -31.0 -31.0 -74.0 -47.0 -59.0 -24.0 -57.0 -56.0 -16.0 -92.0 -59.0]) >=] [(z/linear-functional [ 25.0 -7.0 -99.0 -78.0 -25.0 -14.0 -16.0 -89.0 -39.0 -56.0 -53.0 -9.0 -18.0 -26.0 -11.0 -61.0]) >=] [(z/linear-functional [ 33.0 -95.0 -15.0 -4.0 -33.0 -3.0 -20.0 -96.0 -27.0 -13.0 -80.0 -24.0 -3.0 -13.0 -57.0 -76.0]) >=] [(z/linear-functional [ 7.0 -95.0 -39.0 -93.0 -7.0 -94.0 -94.0 -62.0 -76.0 -26.0 -53.0 -57.0 -31.0 -76.0 -53.0 -52.0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-828-cycle (let [objective (z/linear-functional [1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]) constraints [[(z/affine-functional [0.0 16.0 14.0 69.0 1.0 85.0 52.0 43.0 64.0 97.0 14.0 74.0 89.0 28.0 94.0 58.0 13.0 22.0 21.0 17.0 30.0 25.0 1.0 59.0 91.0 78.0 12.0 74.0 56.0 3.0 88.0] -91.0) >=] [(z/affine-functional [0.0 60.0 40.0 81.0 71.0 72.0 46.0 45.0 38.0 48.0 40.0 17.0 33.0 85.0 64.0 32.0 84.0 3.0 54.0 44.0 71.0 67.0 90.0 95.0 54.0 99.0 99.0 29.0 52.0 98.0 9.0] -54.0) >=] [(z/affine-functional [0.0 41.0 12.0 86.0 90.0 61.0 31.0 41.0 23.0 89.0 17.0 74.0 44.0 27.0 16.0 47.0 80.0 32.0 11.0 56.0 68.0 82.0 11.0 62.0 62.0 53.0 39.0 16.0 48.0 1.0 63.0] -62.0) >=] [(z/linear-functional [83.0 -76.0 -94.0 -19.0 -15.0 -70.0 -72.0 -57.0 -63.0 -65.0 -22.0 -94.0 -22.0 -88.0 -86.0 -89.0 -72.0 -16.0 -80.0 -49.0 -70.0 -93.0 -95.0 -17.0 -83.0 -97.0 -31.0 -47.0 -31.0 -13.0 -23.0]) >=]; [(z/linear-functional [41.0 -96.0 -41.0 -48.0 -70.0 -43.0 -43.0 -43.0 -97.0 -37.0 -85.0 -70.0 -45.0 -67.0 -87.0 -69.0 -94.0 -54.0 -54.0 -92.0 -79.0 -10.0 -35.0 -20.0 -41.0 -41.0 -65.0 -25.0 -12.0 -8.0 -46.0]) >=] [(z/linear-functional [27.0 -42.0 -65.0 -49.0 -53.0 -42.0 -17.0 -2.0 -61.0 -31.0 -76.0 -47.0 -8.0 -93.0 -86.0 -62.0 -65.0 -63.0 -22.0 -43.0 -27.0 -23.0 -32.0 -74.0 -27.0 -63.0 -47.0 -78.0 -29.0 -95.0 -73.0]) >=] [(z/linear-functional [15.0 -46.0 -41.0 -83.0 -98.0 -99.0 -21.0 -35.0 -7.0 -14.0 -80.0 -63.0 -18.0 -42.0 -5.0 -34.0 -56.0 -70.0 -16.0 -18.0 -74.0 -61.0 -47.0 -41.0 -15.0 -79.0 -18.0 -47.0 -88.0 -68.0 -55.0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-781 (let [objective (z/linear-functional [2.0 6.0 7.0]) constraints [[(z/affine-functional [1 2 1] -2) <=] [(z/affine-functional [-1 1 1] 1) <=] [(z/affine-functional [2 -3 1] 1) <=]] options {:max-iterations 100 :minimize? false :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== (* 2 ulps) 2.0 y)) (test/is (z/approximately<= ulps 1.0909090909090913 (aget x 0))) (test/is (z/approximately<= ulps 0.8181818181818182 (aget x 1))) (test/is (z/approximately>= ulps -0.7272727272727272 (aget x 2))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-713-negative-variable (let [objective (z/linear-functional [1.0 1.0]) constraints [[(z/affine-functional [1 0] -1) ==]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (test/is (z/approximately<= ulps 0.0 (aget x 0))) (test/is (z/approximately<= ulps 0.0 (aget x 1))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-434-negative-variable (let [objective (z/linear-functional [0 0 1]) constraints [[(z/affine-functional [1 1 0] -5) ==] [(z/affine-functional [0 0 1] 10) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps -10.0 y)) (test/is (z/approximately== ulps 5.0 (+ (aget x 0) (aget x 1)))) (test/is (z/approximately== ulps -10.0 (aget x 2))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-434-unfeasible-solution (let [ulps (double 1.0e-6) objective (z/linear-functional [1 0]) constraints [[(z/linear-functional [(/ ulps 2.0) 0.5]) ==] [(z/affine-functional [1.0e-3 0.1] -10) ==]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints}] (test/is (thrown? NoFeasibleSolutionException (z/optimize-lp options))))) ;;---------------------------------------------------------------- (test/deftest math-434-pivot-row-selection (let [ulps (double 1.0) objective (z/linear-functional [1]) constraints [[(z/affine-functional [200] -1) >=] [(z/affine-functional [100] -0.499900001) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately== ulps 0.0050 y)) (test/is (z/approximately<= ulps 1.0 (* 200 (aget x 0)))))) ;;---------------------------------------------------------------- (test/deftest math-434-pivot-row-selection-2 (let [ulps (double 1.0) objective (z/linear-functional [0 1 1 0 0 0 0]) constraints [[(z/affine-functional [1 -0.1 0 0 0 0 0] 0.1) ==] [(z/affine-functional [1 0 0 0 0 0 0] 1.0e-18) >=] [(z/linear-functional [0 1 0 0 0 0 0]) >=] [(z/linear-functional [0 0 0 1 0 -0.0128588 1.0e-5]) ==] [(z/affine-functional [0 0 0 0 1 1.0e-5 -0.0128586] 1.0e-10) ==] [(z/linear-functional [0 0 1 -1 0 0 0]) >=] [(z/linear-functional [0 0 1 1 0 0 0]) >=] [(z/linear-functional [0 0 1 0 -1 0 0]) >=] [(z/linear-functional [0 0 1 0 1 0 0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately>= ulps -1.0e-18 (aget x 0))) (test/is (z/approximately== ulps 1.0 (aget x 1))) (test/is (z/approximately== ulps 0.0 (aget x 2))) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-272 (let [ulps (double 1.0) objective (z/linear-functional [2 2 1]) constraints [[(z/affine-functional [1 1 0] -1) >=] [(z/affine-functional [1 0 1] -1) >=] [(z/affine-functional [0 1 0] -1) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately>= ulps 0.0 (aget x 0))) (test/is (z/approximately== ulps 1.0 (aget x 1))) (test/is (z/approximately== ulps 1.0 (aget x 2))) (test/is (z/approximately== ulps 3.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- ; @Test ; public void testMath272() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(0.0, solution.getPoint()[0], .0000001); ; Assert.assertEquals(1.0, solution.getPoint()[1], .0000001); ; Assert.assertEquals(1.0, solution.getPoint()[2], .0000001); ; Assert.assertEquals(3.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath286() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(25.8, solution.getValue(), .0000001); ; Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001); ; Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001); ; Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001); ; Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001); ; Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001); ; } ; ; @Test ; public void testDegeneracy() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(13.6, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath288() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(10.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath290GEQ() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0)); ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0, solution.getValue(), .0000001); ; Assert.assertEquals(0, solution.getPoint()[0], .0000001); ; Assert.assertEquals(0, solution.getPoint()[1], .0000001); ; } ; ; @Test(expected=NoFeasibleSolutionException.class) ; public void testMath290LEQ() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0)); ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; } ; ; @Test ; public void testMath293() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution1 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[1], .0001); ; Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[3], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[4], .0001); ; Assert.assertEquals(30.0, solution1.getPoint()[5], .0001); ; Assert.assertEquals(40.57143, solution1.getValue(), .0001); ; ; double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1]; ; double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3]; ; double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5]; ; ; f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); ; constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC)); ; ; PointValuePair solution2 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(40.57143, solution2.getValue(), .0001); ; } ; ; @Test ; public void testMath930() { ; Collection<LinearConstraint> constraints = createMath930Constraints(); ; ; double[] objFunctionCoeff = new double[33]; ; objFunctionCoeff[3] = 1; ; LinearObjectiveFunction f = new LinearObjectiveFunction(objFunctionCoeff, 0); ; SimplexSolver solver = new SimplexSolver(1e-4, 10, 1e-6); ; ; PointValuePair solution = solver.optimize(new MaxIter(1000), f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0.3752298, solution.getValue(), 1e-4); ; } ; ; private List<LinearConstraint> createMath930Constraints() { ; List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] {1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.628803}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.676993}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.136677}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.444434}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.302218}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.653981}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.690437}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.423786}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.486717}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304747}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.205625}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.621944}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.764385}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.432572}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.480762}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.055983}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11378}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.407308}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.452749}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.269677}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.321806}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.06902}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.028754}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.484254}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.524607}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.385492}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.430134}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.34983}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.375781}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.281308}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304995}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.345347}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.288899}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.332212}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.14351}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17057}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.157435}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.141071}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.232574}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.091644}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.203531}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -0.028754}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Relationship.EQ, 1.0)); ; return constraints; ; } ; ; @Test ; public void testSimplexSolver() { ; LinearObjectiveFunction f = ; new LinearObjectiveFunction(new double[] { 15, 10 }, 7); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(57.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testSingleVariableAndConstraint() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(10.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(30.0, solution.getValue(), 0.0); ; } ; ; /** ; * With no artificial variables needed (no equals and no greater than ; * constraints) we can go straight to Phase 2. ; */ ; @Test ; public void testModelWithNoArtificialVars() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(50.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testMinimization() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); ; constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(4.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(0.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(-13.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testSolutionWithNegativeDecisionVariable() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); ; constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(8.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(12.0, solution.getValue(), 0.0); ; } ; ; @Test(expected = NoFeasibleSolutionException.class) ; public void testInfeasibleSolution() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); ; ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; } ; ; @Test(expected = UnboundedSolutionException.class) ; public void testUnboundedSolution() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); ; ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; } ; ; @Test ; public void testRestrictVariablesToNonNegative() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); ; constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); ; constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); ; constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); ; constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); ; Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[2], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[3], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[4], .0000001); ; Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001); ; } ; ; @Test ; public void testEpsilon() { ; LinearObjectiveFunction f = ; new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); ; constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); ; constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(1.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(1.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(0.0, solution.getPoint()[2], 0.0); ; Assert.assertEquals(15.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testTrivialModel() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testLargeModel() { ; double[] objective = new double[] { ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1}; ; ; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); ; constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); ; constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); ; constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); ; constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); ; constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); ; constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); ; constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); ; constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); ; constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); ; constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); ; constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); ; constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); ; constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); ; constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); ; constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); ; constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); ; constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); ; constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); ; constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); ; constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); ; constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); ; constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); ; constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); ; constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); ; constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); ; constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); ; constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); ; constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); ; constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); ; constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); ; constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); ; constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); ; constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); ; constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); ; constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); ; constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); ; constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); ; constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); ; constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); ; constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); ; constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); ; constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); ; constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); ; constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); ; constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); ; constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); ; constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); ; constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); ; constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); ; constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); ; constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); ; constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); ; constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); ; constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); ; constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); ; constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); ; constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); ; constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); ; constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); ; constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); ; constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); ; constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); ; constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); ; constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); ; constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); ; constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); ; constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); ; constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); ; constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); ; constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); ; constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); ; constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); ; constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); ; constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); ; constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); ; constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); ; constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); ; constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); ; constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); ; constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); ; constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); ; constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); ; constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); ; constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); ; constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); ; constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); ; constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); ; constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); ; constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); ; constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); ; constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); ; constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(7518.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testSolutionCallback() { ; // re-use the problem from testcase for MATH-288 ; // it normally requires 5 iterations ; ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); ; ; List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); ; ; final SimplexSolver solver = new SimplexSolver(); ; final SolutionCallback callback = new SolutionCallback(); ; ; Assert.assertNull(callback.getSolution()); ; Assert.assertFalse(callback.isSolutionOptimal()); ; ; try { ; solver.optimize(new MaxIter(3), f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback); ; Assert.fail("expected TooManyIterationsException"); ; } catch (TooManyIterationsException ex) { ; // expected ; } ; ; final PointValuePair solution = callback.getSolution(); ; Assert.assertNotNull(solution); ; Assert.assertTrue(validSolution(solution, constraints, 1e-4)); ; Assert.assertFalse(callback.isSolutionOptimal()); ; // the solution is clearly not optimal: optimal = 10.0 ; Assert.assertEquals(7.0, solution.getValue(), 1e-4); ; } ;
28207
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL> at <EMAIL>" :date "2018-04-16" :doc "Tests for [[zana.optimization.math3.lp]]." } zana.test.optimization.math3.lp (:require [clojure.test :as test] [zana.api :as z]) (:import [clojure.lang IFn IFn$OD] [org.apache.commons.math3.optim.linear NoFeasibleSolutionException])) ;; mvn -Dtest=zana.test.optimization.math3.lp clojure:test ;;---------------------------------------------------------------- ;; Tests borrowed from ;; org.apache.commons.math3.optim.linear.SimplexSolverTest ;;---------------------------------------------------------------- ;; assume constraint is [function relationship] pair ;; function must be double valued ;; assume relationship is specified with one of <= == >= ;; implied constraint is on function value relative to zero (defn- approximatelySatisfies [^double delta [^IFn$OD f ^IFn r] ^doubles x] (let [y (.invokePrim f x)] (cond (= r <=) (<= y delta) (= r ==) (<= (Math/abs y) delta) (= r >=) (>= y (- delta)) :else (throw (IllegalArgumentException. (print-str "not a valid relationship function:" r)))))) ;;---------------------------------------------------------------- (test/deftest math-842-cycle-affine (let [objective (z/affine-functional [10.0 -57.0 -9.0 -24.0] 0.0) constraints [[(z/affine-functional [0.5 -5.5 -2.5 9.0] 0.0) <=] [(z/affine-functional [0.5 -1.5 -0.5 1.0] 0.0) <=] [(z/affine-functional [1.0 0.0 0.0 0.0] -1.0) <=]] options {:minimize? false :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-842-cycle-linear (let [objective (z/linear-functional [10.0 -57.0 -9.0 -24.0]) constraints [[(z/linear-functional [0.5 -5.5 -2.5 9.0]) <=] [(z/linear-functional [0.5 -1.5 -0.5 1.0]) <=] [(z/affine-functional [1.0 0.0 0.0 0.0] -1.0) <=]] options {:minimize? false :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-828 (let [objective (z/linear-functional [1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]) constraints [[(z/affine-functional [ 0.0 39.0 23.0 96.0 15.0 48.0 9.0 21.0 48.0 36.0 76.0 19.0 88.0 17.0 16.0 36.0] -15.0) >=] [(z/affine-functional [ 0.0 59.0 93.0 12.0 29.0 78.0 73.0 87.0 32.0 70.0 68.0 24.0 11.0 26.0 65.0 25.0] -29.0) >=] [(z/affine-functional [ 0.0 74.0 5.0 82.0 6.0 97.0 55.0 44.0 52.0 54.0 5.0 93.0 91.0 8.0 20.0 97.0] -6.0) >=] [(z/linear-functional [ 8.0 -3.0 -28.0 -72.0 -8.0 -31.0 -31.0 -74.0 -47.0 -59.0 -24.0 -57.0 -56.0 -16.0 -92.0 -59.0]) >=] [(z/linear-functional [ 25.0 -7.0 -99.0 -78.0 -25.0 -14.0 -16.0 -89.0 -39.0 -56.0 -53.0 -9.0 -18.0 -26.0 -11.0 -61.0]) >=] [(z/linear-functional [ 33.0 -95.0 -15.0 -4.0 -33.0 -3.0 -20.0 -96.0 -27.0 -13.0 -80.0 -24.0 -3.0 -13.0 -57.0 -76.0]) >=] [(z/linear-functional [ 7.0 -95.0 -39.0 -93.0 -7.0 -94.0 -94.0 -62.0 -76.0 -26.0 -53.0 -57.0 -31.0 -76.0 -53.0 -52.0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-828-cycle (let [objective (z/linear-functional [1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]) constraints [[(z/affine-functional [0.0 16.0 14.0 69.0 1.0 85.0 52.0 43.0 64.0 97.0 14.0 74.0 89.0 28.0 94.0 58.0 13.0 22.0 21.0 17.0 30.0 25.0 1.0 59.0 91.0 78.0 12.0 74.0 56.0 3.0 88.0] -91.0) >=] [(z/affine-functional [0.0 60.0 40.0 81.0 71.0 72.0 46.0 45.0 38.0 48.0 40.0 17.0 33.0 85.0 64.0 32.0 84.0 3.0 54.0 44.0 71.0 67.0 90.0 95.0 54.0 99.0 99.0 29.0 52.0 98.0 9.0] -54.0) >=] [(z/affine-functional [0.0 41.0 12.0 86.0 90.0 61.0 31.0 41.0 23.0 89.0 17.0 74.0 44.0 27.0 16.0 47.0 80.0 32.0 11.0 56.0 68.0 82.0 11.0 62.0 62.0 53.0 39.0 16.0 48.0 1.0 63.0] -62.0) >=] [(z/linear-functional [83.0 -76.0 -94.0 -19.0 -15.0 -70.0 -72.0 -57.0 -63.0 -65.0 -22.0 -94.0 -22.0 -88.0 -86.0 -89.0 -72.0 -16.0 -80.0 -49.0 -70.0 -93.0 -95.0 -17.0 -83.0 -97.0 -31.0 -47.0 -31.0 -13.0 -23.0]) >=]; [(z/linear-functional [41.0 -96.0 -41.0 -48.0 -70.0 -43.0 -43.0 -43.0 -97.0 -37.0 -85.0 -70.0 -45.0 -67.0 -87.0 -69.0 -94.0 -54.0 -54.0 -92.0 -79.0 -10.0 -35.0 -20.0 -41.0 -41.0 -65.0 -25.0 -12.0 -8.0 -46.0]) >=] [(z/linear-functional [27.0 -42.0 -65.0 -49.0 -53.0 -42.0 -17.0 -2.0 -61.0 -31.0 -76.0 -47.0 -8.0 -93.0 -86.0 -62.0 -65.0 -63.0 -22.0 -43.0 -27.0 -23.0 -32.0 -74.0 -27.0 -63.0 -47.0 -78.0 -29.0 -95.0 -73.0]) >=] [(z/linear-functional [15.0 -46.0 -41.0 -83.0 -98.0 -99.0 -21.0 -35.0 -7.0 -14.0 -80.0 -63.0 -18.0 -42.0 -5.0 -34.0 -56.0 -70.0 -16.0 -18.0 -74.0 -61.0 -47.0 -41.0 -15.0 -79.0 -18.0 -47.0 -88.0 -68.0 -55.0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-781 (let [objective (z/linear-functional [2.0 6.0 7.0]) constraints [[(z/affine-functional [1 2 1] -2) <=] [(z/affine-functional [-1 1 1] 1) <=] [(z/affine-functional [2 -3 1] 1) <=]] options {:max-iterations 100 :minimize? false :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== (* 2 ulps) 2.0 y)) (test/is (z/approximately<= ulps 1.0909090909090913 (aget x 0))) (test/is (z/approximately<= ulps 0.8181818181818182 (aget x 1))) (test/is (z/approximately>= ulps -0.7272727272727272 (aget x 2))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-713-negative-variable (let [objective (z/linear-functional [1.0 1.0]) constraints [[(z/affine-functional [1 0] -1) ==]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (test/is (z/approximately<= ulps 0.0 (aget x 0))) (test/is (z/approximately<= ulps 0.0 (aget x 1))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-434-negative-variable (let [objective (z/linear-functional [0 0 1]) constraints [[(z/affine-functional [1 1 0] -5) ==] [(z/affine-functional [0 0 1] 10) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps -10.0 y)) (test/is (z/approximately== ulps 5.0 (+ (aget x 0) (aget x 1)))) (test/is (z/approximately== ulps -10.0 (aget x 2))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-434-unfeasible-solution (let [ulps (double 1.0e-6) objective (z/linear-functional [1 0]) constraints [[(z/linear-functional [(/ ulps 2.0) 0.5]) ==] [(z/affine-functional [1.0e-3 0.1] -10) ==]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints}] (test/is (thrown? NoFeasibleSolutionException (z/optimize-lp options))))) ;;---------------------------------------------------------------- (test/deftest math-434-pivot-row-selection (let [ulps (double 1.0) objective (z/linear-functional [1]) constraints [[(z/affine-functional [200] -1) >=] [(z/affine-functional [100] -0.499900001) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately== ulps 0.0050 y)) (test/is (z/approximately<= ulps 1.0 (* 200 (aget x 0)))))) ;;---------------------------------------------------------------- (test/deftest math-434-pivot-row-selection-2 (let [ulps (double 1.0) objective (z/linear-functional [0 1 1 0 0 0 0]) constraints [[(z/affine-functional [1 -0.1 0 0 0 0 0] 0.1) ==] [(z/affine-functional [1 0 0 0 0 0 0] 1.0e-18) >=] [(z/linear-functional [0 1 0 0 0 0 0]) >=] [(z/linear-functional [0 0 0 1 0 -0.0128588 1.0e-5]) ==] [(z/affine-functional [0 0 0 0 1 1.0e-5 -0.0128586] 1.0e-10) ==] [(z/linear-functional [0 0 1 -1 0 0 0]) >=] [(z/linear-functional [0 0 1 1 0 0 0]) >=] [(z/linear-functional [0 0 1 0 -1 0 0]) >=] [(z/linear-functional [0 0 1 0 1 0 0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately>= ulps -1.0e-18 (aget x 0))) (test/is (z/approximately== ulps 1.0 (aget x 1))) (test/is (z/approximately== ulps 0.0 (aget x 2))) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-272 (let [ulps (double 1.0) objective (z/linear-functional [2 2 1]) constraints [[(z/affine-functional [1 1 0] -1) >=] [(z/affine-functional [1 0 1] -1) >=] [(z/affine-functional [0 1 0] -1) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately>= ulps 0.0 (aget x 0))) (test/is (z/approximately== ulps 1.0 (aget x 1))) (test/is (z/approximately== ulps 1.0 (aget x 2))) (test/is (z/approximately== ulps 3.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- ; @Test ; public void testMath272() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(0.0, solution.getPoint()[0], .0000001); ; Assert.assertEquals(1.0, solution.getPoint()[1], .0000001); ; Assert.assertEquals(1.0, solution.getPoint()[2], .0000001); ; Assert.assertEquals(3.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath286() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(25.8, solution.getValue(), .0000001); ; Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001); ; Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001); ; Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001); ; Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001); ; Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001); ; } ; ; @Test ; public void testDegeneracy() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(13.6, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath288() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(10.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath290GEQ() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0)); ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0, solution.getValue(), .0000001); ; Assert.assertEquals(0, solution.getPoint()[0], .0000001); ; Assert.assertEquals(0, solution.getPoint()[1], .0000001); ; } ; ; @Test(expected=NoFeasibleSolutionException.class) ; public void testMath290LEQ() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0)); ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; } ; ; @Test ; public void testMath293() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution1 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[1], .0001); ; Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[3], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[4], .0001); ; Assert.assertEquals(30.0, solution1.getPoint()[5], .0001); ; Assert.assertEquals(40.57143, solution1.getValue(), .0001); ; ; double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1]; ; double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3]; ; double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5]; ; ; f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); ; constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC)); ; ; PointValuePair solution2 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(40.57143, solution2.getValue(), .0001); ; } ; ; @Test ; public void testMath930() { ; Collection<LinearConstraint> constraints = createMath930Constraints(); ; ; double[] objFunctionCoeff = new double[33]; ; objFunctionCoeff[3] = 1; ; LinearObjectiveFunction f = new LinearObjectiveFunction(objFunctionCoeff, 0); ; SimplexSolver solver = new SimplexSolver(1e-4, 10, 1e-6); ; ; PointValuePair solution = solver.optimize(new MaxIter(1000), f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0.3752298, solution.getValue(), 1e-4); ; } ; ; private List<LinearConstraint> createMath930Constraints() { ; List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] {1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.628803}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.676993}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.136677}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.444434}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.302218}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.653981}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.690437}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.423786}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.486717}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304747}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.205625}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.621944}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.764385}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.432572}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.480762}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.055983}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11378}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.407308}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.452749}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.269677}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.321806}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.06902}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.028754}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.484254}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.524607}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.385492}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.430134}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.34983}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.375781}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.281308}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304995}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.345347}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.288899}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.332212}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.14351}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17057}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.157435}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.141071}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.232574}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.091644}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.203531}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -0.028754}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Relationship.EQ, 1.0)); ; return constraints; ; } ; ; @Test ; public void testSimplexSolver() { ; LinearObjectiveFunction f = ; new LinearObjectiveFunction(new double[] { 15, 10 }, 7); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(57.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testSingleVariableAndConstraint() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(10.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(30.0, solution.getValue(), 0.0); ; } ; ; /** ; * With no artificial variables needed (no equals and no greater than ; * constraints) we can go straight to Phase 2. ; */ ; @Test ; public void testModelWithNoArtificialVars() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(50.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testMinimization() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); ; constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(4.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(0.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(-13.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testSolutionWithNegativeDecisionVariable() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); ; constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(8.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(12.0, solution.getValue(), 0.0); ; } ; ; @Test(expected = NoFeasibleSolutionException.class) ; public void testInfeasibleSolution() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); ; ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; } ; ; @Test(expected = UnboundedSolutionException.class) ; public void testUnboundedSolution() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); ; ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; } ; ; @Test ; public void testRestrictVariablesToNonNegative() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); ; constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); ; constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); ; constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); ; constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); ; Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[2], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[3], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[4], .0000001); ; Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001); ; } ; ; @Test ; public void testEpsilon() { ; LinearObjectiveFunction f = ; new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); ; constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); ; constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(1.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(1.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(0.0, solution.getPoint()[2], 0.0); ; Assert.assertEquals(15.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testTrivialModel() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testLargeModel() { ; double[] objective = new double[] { ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1}; ; ; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); ; constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); ; constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); ; constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); ; constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); ; constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); ; constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); ; constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); ; constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); ; constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); ; constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); ; constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); ; constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); ; constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); ; constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); ; constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); ; constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); ; constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); ; constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); ; constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); ; constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); ; constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); ; constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); ; constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); ; constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); ; constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); ; constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); ; constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); ; constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); ; constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); ; constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); ; constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); ; constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); ; constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); ; constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); ; constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); ; constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); ; constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); ; constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); ; constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); ; constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); ; constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); ; constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); ; constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); ; constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); ; constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); ; constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); ; constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); ; constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); ; constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); ; constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); ; constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); ; constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); ; constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); ; constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); ; constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); ; constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); ; constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); ; constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); ; constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); ; constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); ; constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); ; constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); ; constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); ; constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); ; constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); ; constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); ; constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); ; constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); ; constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); ; constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); ; constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); ; constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); ; constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); ; constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); ; constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); ; constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); ; constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); ; constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); ; constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); ; constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); ; constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); ; constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); ; constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); ; constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); ; constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); ; constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); ; constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); ; constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); ; constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); ; constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); ; constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); ; constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(7518.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testSolutionCallback() { ; // re-use the problem from testcase for MATH-288 ; // it normally requires 5 iterations ; ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); ; ; List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); ; ; final SimplexSolver solver = new SimplexSolver(); ; final SolutionCallback callback = new SolutionCallback(); ; ; Assert.assertNull(callback.getSolution()); ; Assert.assertFalse(callback.isSolutionOptimal()); ; ; try { ; solver.optimize(new MaxIter(3), f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback); ; Assert.fail("expected TooManyIterationsException"); ; } catch (TooManyIterationsException ex) { ; // expected ; } ; ; final PointValuePair solution = callback.getSolution(); ; Assert.assertNotNull(solution); ; Assert.assertTrue(validSolution(solution, constraints, 1e-4)); ; Assert.assertFalse(callback.isSolutionOptimal()); ; // the solution is clearly not optimal: optimal = 10.0 ; Assert.assertEquals(7.0, solution.getValue(), 1e-4); ; } ;
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI" :date "2018-04-16" :doc "Tests for [[zana.optimization.math3.lp]]." } zana.test.optimization.math3.lp (:require [clojure.test :as test] [zana.api :as z]) (:import [clojure.lang IFn IFn$OD] [org.apache.commons.math3.optim.linear NoFeasibleSolutionException])) ;; mvn -Dtest=zana.test.optimization.math3.lp clojure:test ;;---------------------------------------------------------------- ;; Tests borrowed from ;; org.apache.commons.math3.optim.linear.SimplexSolverTest ;;---------------------------------------------------------------- ;; assume constraint is [function relationship] pair ;; function must be double valued ;; assume relationship is specified with one of <= == >= ;; implied constraint is on function value relative to zero (defn- approximatelySatisfies [^double delta [^IFn$OD f ^IFn r] ^doubles x] (let [y (.invokePrim f x)] (cond (= r <=) (<= y delta) (= r ==) (<= (Math/abs y) delta) (= r >=) (>= y (- delta)) :else (throw (IllegalArgumentException. (print-str "not a valid relationship function:" r)))))) ;;---------------------------------------------------------------- (test/deftest math-842-cycle-affine (let [objective (z/affine-functional [10.0 -57.0 -9.0 -24.0] 0.0) constraints [[(z/affine-functional [0.5 -5.5 -2.5 9.0] 0.0) <=] [(z/affine-functional [0.5 -1.5 -0.5 1.0] 0.0) <=] [(z/affine-functional [1.0 0.0 0.0 0.0] -1.0) <=]] options {:minimize? false :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-842-cycle-linear (let [objective (z/linear-functional [10.0 -57.0 -9.0 -24.0]) constraints [[(z/linear-functional [0.5 -5.5 -2.5 9.0]) <=] [(z/linear-functional [0.5 -1.5 -0.5 1.0]) <=] [(z/affine-functional [1.0 0.0 0.0 0.0] -1.0) <=]] options {:minimize? false :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-828 (let [objective (z/linear-functional [1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]) constraints [[(z/affine-functional [ 0.0 39.0 23.0 96.0 15.0 48.0 9.0 21.0 48.0 36.0 76.0 19.0 88.0 17.0 16.0 36.0] -15.0) >=] [(z/affine-functional [ 0.0 59.0 93.0 12.0 29.0 78.0 73.0 87.0 32.0 70.0 68.0 24.0 11.0 26.0 65.0 25.0] -29.0) >=] [(z/affine-functional [ 0.0 74.0 5.0 82.0 6.0 97.0 55.0 44.0 52.0 54.0 5.0 93.0 91.0 8.0 20.0 97.0] -6.0) >=] [(z/linear-functional [ 8.0 -3.0 -28.0 -72.0 -8.0 -31.0 -31.0 -74.0 -47.0 -59.0 -24.0 -57.0 -56.0 -16.0 -92.0 -59.0]) >=] [(z/linear-functional [ 25.0 -7.0 -99.0 -78.0 -25.0 -14.0 -16.0 -89.0 -39.0 -56.0 -53.0 -9.0 -18.0 -26.0 -11.0 -61.0]) >=] [(z/linear-functional [ 33.0 -95.0 -15.0 -4.0 -33.0 -3.0 -20.0 -96.0 -27.0 -13.0 -80.0 -24.0 -3.0 -13.0 -57.0 -76.0]) >=] [(z/linear-functional [ 7.0 -95.0 -39.0 -93.0 -7.0 -94.0 -94.0 -62.0 -76.0 -26.0 -53.0 -57.0 -31.0 -76.0 -53.0 -52.0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-828-cycle (let [objective (z/linear-functional [1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]) constraints [[(z/affine-functional [0.0 16.0 14.0 69.0 1.0 85.0 52.0 43.0 64.0 97.0 14.0 74.0 89.0 28.0 94.0 58.0 13.0 22.0 21.0 17.0 30.0 25.0 1.0 59.0 91.0 78.0 12.0 74.0 56.0 3.0 88.0] -91.0) >=] [(z/affine-functional [0.0 60.0 40.0 81.0 71.0 72.0 46.0 45.0 38.0 48.0 40.0 17.0 33.0 85.0 64.0 32.0 84.0 3.0 54.0 44.0 71.0 67.0 90.0 95.0 54.0 99.0 99.0 29.0 52.0 98.0 9.0] -54.0) >=] [(z/affine-functional [0.0 41.0 12.0 86.0 90.0 61.0 31.0 41.0 23.0 89.0 17.0 74.0 44.0 27.0 16.0 47.0 80.0 32.0 11.0 56.0 68.0 82.0 11.0 62.0 62.0 53.0 39.0 16.0 48.0 1.0 63.0] -62.0) >=] [(z/linear-functional [83.0 -76.0 -94.0 -19.0 -15.0 -70.0 -72.0 -57.0 -63.0 -65.0 -22.0 -94.0 -22.0 -88.0 -86.0 -89.0 -72.0 -16.0 -80.0 -49.0 -70.0 -93.0 -95.0 -17.0 -83.0 -97.0 -31.0 -47.0 -31.0 -13.0 -23.0]) >=]; [(z/linear-functional [41.0 -96.0 -41.0 -48.0 -70.0 -43.0 -43.0 -43.0 -97.0 -37.0 -85.0 -70.0 -45.0 -67.0 -87.0 -69.0 -94.0 -54.0 -54.0 -92.0 -79.0 -10.0 -35.0 -20.0 -41.0 -41.0 -65.0 -25.0 -12.0 -8.0 -46.0]) >=] [(z/linear-functional [27.0 -42.0 -65.0 -49.0 -53.0 -42.0 -17.0 -2.0 -61.0 -31.0 -76.0 -47.0 -8.0 -93.0 -86.0 -62.0 -65.0 -63.0 -22.0 -43.0 -27.0 -23.0 -32.0 -74.0 -27.0 -63.0 -47.0 -78.0 -29.0 -95.0 -73.0]) >=] [(z/linear-functional [15.0 -46.0 -41.0 -83.0 -98.0 -99.0 -21.0 -35.0 -7.0 -14.0 -80.0 -63.0 -18.0 -42.0 -5.0 -34.0 -56.0 -70.0 -16.0 -18.0 -74.0 -61.0 -47.0 -41.0 -15.0 -79.0 -18.0 -47.0 -88.0 -68.0 -55.0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :pivot-selection-rule :bland :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-781 (let [objective (z/linear-functional [2.0 6.0 7.0]) constraints [[(z/affine-functional [1 2 1] -2) <=] [(z/affine-functional [-1 1 1] 1) <=] [(z/affine-functional [2 -3 1] 1) <=]] options {:max-iterations 100 :minimize? false :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== (* 2 ulps) 2.0 y)) (test/is (z/approximately<= ulps 1.0909090909090913 (aget x 0))) (test/is (z/approximately<= ulps 0.8181818181818182 (aget x 1))) (test/is (z/approximately>= ulps -0.7272727272727272 (aget x 2))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-713-negative-variable (let [objective (z/linear-functional [1.0 1.0]) constraints [[(z/affine-functional [1 0] -1) ==]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps 1.0 y)) (test/is (z/approximately<= ulps 0.0 (aget x 0))) (test/is (z/approximately<= ulps 0.0 (aget x 1))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-434-negative-variable (let [objective (z/linear-functional [0 0 1]) constraints [[(z/affine-functional [1 1 0] -5) ==] [(z/affine-functional [0 0 1] 10) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options) ulps (double 1.0)] (println (into [] x) y) (test/is (z/approximately== ulps -10.0 y)) (test/is (z/approximately== ulps 5.0 (+ (aget x 0) (aget x 1)))) (test/is (z/approximately== ulps -10.0 (aget x 2))) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-434-unfeasible-solution (let [ulps (double 1.0e-6) objective (z/linear-functional [1 0]) constraints [[(z/linear-functional [(/ ulps 2.0) 0.5]) ==] [(z/affine-functional [1.0e-3 0.1] -10) ==]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints}] (test/is (thrown? NoFeasibleSolutionException (z/optimize-lp options))))) ;;---------------------------------------------------------------- (test/deftest math-434-pivot-row-selection (let [ulps (double 1.0) objective (z/linear-functional [1]) constraints [[(z/affine-functional [200] -1) >=] [(z/affine-functional [100] -0.499900001) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately== ulps 0.0050 y)) (test/is (z/approximately<= ulps 1.0 (* 200 (aget x 0)))))) ;;---------------------------------------------------------------- (test/deftest math-434-pivot-row-selection-2 (let [ulps (double 1.0) objective (z/linear-functional [0 1 1 0 0 0 0]) constraints [[(z/affine-functional [1 -0.1 0 0 0 0 0] 0.1) ==] [(z/affine-functional [1 0 0 0 0 0 0] 1.0e-18) >=] [(z/linear-functional [0 1 0 0 0 0 0]) >=] [(z/linear-functional [0 0 0 1 0 -0.0128588 1.0e-5]) ==] [(z/affine-functional [0 0 0 0 1 1.0e-5 -0.0128586] 1.0e-10) ==] [(z/linear-functional [0 0 1 -1 0 0 0]) >=] [(z/linear-functional [0 0 1 1 0 0 0]) >=] [(z/linear-functional [0 0 1 0 -1 0 0]) >=] [(z/linear-functional [0 0 1 0 1 0 0]) >=]] options {:max-iterations 100 :minimize? true :nonnegative? false :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately>= ulps -1.0e-18 (aget x 0))) (test/is (z/approximately== ulps 1.0 (aget x 1))) (test/is (z/approximately== ulps 0.0 (aget x 2))) (test/is (z/approximately== ulps 1.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- (test/deftest math-272 (let [ulps (double 1.0) objective (z/linear-functional [2 2 1]) constraints [[(z/affine-functional [1 1 0] -1) >=] [(z/affine-functional [1 0 1] -1) >=] [(z/affine-functional [0 1 0] -1) >=]] options {:max-iterations 100 :minimize? true :nonnegative? true :objective objective :constraints constraints} [^doubles x ^double y] (z/optimize-lp options)] (println (into [] x) y) (test/is (z/approximately>= ulps 0.0 (aget x 0))) (test/is (z/approximately== ulps 1.0 (aget x 1))) (test/is (z/approximately== ulps 1.0 (aget x 2))) (test/is (z/approximately== ulps 3.0 y)) (doseq [constraint constraints] (test/is (approximatelySatisfies ulps constraint x))))) ;;---------------------------------------------------------------- ; @Test ; public void testMath272() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(0.0, solution.getPoint()[0], .0000001); ; Assert.assertEquals(1.0, solution.getPoint()[1], .0000001); ; Assert.assertEquals(1.0, solution.getPoint()[2], .0000001); ; Assert.assertEquals(3.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath286() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(25.8, solution.getValue(), .0000001); ; Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001); ; Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001); ; Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001); ; Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001); ; Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001); ; } ; ; @Test ; public void testDegeneracy() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(13.6, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath288() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(10.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testMath290GEQ() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0)); ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0, solution.getValue(), .0000001); ; Assert.assertEquals(0, solution.getPoint()[0], .0000001); ; Assert.assertEquals(0, solution.getPoint()[1], .0000001); ; } ; ; @Test(expected=NoFeasibleSolutionException.class) ; public void testMath290LEQ() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0)); ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; } ; ; @Test ; public void testMath293() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution1 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; ; Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[1], .0001); ; Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[3], .0001); ; Assert.assertEquals(0.0, solution1.getPoint()[4], .0001); ; Assert.assertEquals(30.0, solution1.getPoint()[5], .0001); ; Assert.assertEquals(40.57143, solution1.getValue(), .0001); ; ; double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1]; ; double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3]; ; double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5]; ; ; f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); ; constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); ; constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB)); ; constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC)); ; ; PointValuePair solution2 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(40.57143, solution2.getValue(), .0001); ; } ; ; @Test ; public void testMath930() { ; Collection<LinearConstraint> constraints = createMath930Constraints(); ; ; double[] objFunctionCoeff = new double[33]; ; objFunctionCoeff[3] = 1; ; LinearObjectiveFunction f = new LinearObjectiveFunction(objFunctionCoeff, 0); ; SimplexSolver solver = new SimplexSolver(1e-4, 10, 1e-6); ; ; PointValuePair solution = solver.optimize(new MaxIter(1000), f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0.3752298, solution.getValue(), 1e-4); ; } ; ; private List<LinearConstraint> createMath930Constraints() { ; List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] {1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.628803}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.676993}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.136677}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.444434}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.302218}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.653981}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.690437}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.423786}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.486717}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304747}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.205625}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.621944}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.764385}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.432572}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.480762}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.055983}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11378}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.407308}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.452749}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.269677}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.321806}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.06902}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.028754}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.484254}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.524607}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.385492}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.430134}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.34983}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.375781}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.281308}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304995}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.345347}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.288899}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.332212}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.14351}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17057}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.157435}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.141071}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.232574}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.091644}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.203531}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -0.028754}, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Relationship.EQ, 1.0)); ; return constraints; ; } ; ; @Test ; public void testSimplexSolver() { ; LinearObjectiveFunction f = ; new LinearObjectiveFunction(new double[] { 15, 10 }, 7); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(57.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testSingleVariableAndConstraint() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(10.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(30.0, solution.getValue(), 0.0); ; } ; ; /** ; * With no artificial variables needed (no equals and no greater than ; * constraints) we can go straight to Phase 2. ; */ ; @Test ; public void testModelWithNoArtificialVars() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(50.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testMinimization() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); ; constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); ; constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(4.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(0.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(-13.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testSolutionWithNegativeDecisionVariable() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); ; constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(8.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(12.0, solution.getValue(), 0.0); ; } ; ; @Test(expected = NoFeasibleSolutionException.class) ; public void testInfeasibleSolution() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); ; constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); ; ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; } ; ; @Test(expected = UnboundedSolutionException.class) ; public void testUnboundedSolution() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); ; ; SimplexSolver solver = new SimplexSolver(); ; solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; } ; ; @Test ; public void testRestrictVariablesToNonNegative() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); ; constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); ; constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); ; constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); ; constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); ; Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[2], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[3], .0000001); ; Assert.assertEquals(0.0, solution.getPoint()[4], .0000001); ; Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001); ; } ; ; @Test ; public void testEpsilon() { ; LinearObjectiveFunction f = ; new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); ; constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); ; constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(false)); ; Assert.assertEquals(1.0, solution.getPoint()[0], 0.0); ; Assert.assertEquals(1.0, solution.getPoint()[1], 0.0); ; Assert.assertEquals(0.0, solution.getPoint()[2], 0.0); ; Assert.assertEquals(15.0, solution.getValue(), 0.0); ; } ; ; @Test ; public void testTrivialModel() { ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testLargeModel() { ; double[] objective = new double[] { ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ; 1, 1, 1, 1, 1, 1}; ; ; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); ; Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); ; constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); ; constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); ; constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); ; constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); ; constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); ; constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); ; constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); ; constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); ; constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); ; constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); ; constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); ; constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); ; constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); ; constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); ; constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); ; constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); ; constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); ; constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); ; constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); ; constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); ; constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); ; constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); ; constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); ; constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); ; constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); ; constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); ; constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); ; constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); ; constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); ; constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); ; constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); ; constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); ; constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); ; constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); ; constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); ; constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); ; constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); ; constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); ; constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); ; constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); ; constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); ; constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); ; constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); ; constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); ; constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); ; constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); ; constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); ; constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); ; constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); ; constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); ; constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); ; constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); ; constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); ; constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); ; constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); ; constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); ; constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); ; constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); ; constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); ; constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); ; constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); ; constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); ; constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); ; constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); ; constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); ; constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); ; constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); ; constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); ; constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); ; constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); ; constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); ; constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); ; constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); ; constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); ; constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); ; constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); ; constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); ; constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); ; constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); ; constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); ; constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); ; constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); ; constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); ; constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); ; constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); ; constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); ; constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); ; constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); ; constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); ; constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); ; constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); ; constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); ; ; SimplexSolver solver = new SimplexSolver(); ; PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), ; GoalType.MINIMIZE, new NonNegativeConstraint(true)); ; Assert.assertEquals(7518.0, solution.getValue(), .0000001); ; } ; ; @Test ; public void testSolutionCallback() { ; // re-use the problem from testcase for MATH-288 ; // it normally requires 5 iterations ; ; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); ; ; List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); ; constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); ; constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); ; constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); ; ; final SimplexSolver solver = new SimplexSolver(); ; final SolutionCallback callback = new SolutionCallback(); ; ; Assert.assertNull(callback.getSolution()); ; Assert.assertFalse(callback.isSolutionOptimal()); ; ; try { ; solver.optimize(new MaxIter(3), f, new LinearConstraintSet(constraints), ; GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback); ; Assert.fail("expected TooManyIterationsException"); ; } catch (TooManyIterationsException ex) { ; // expected ; } ; ; final PointValuePair solution = callback.getSolution(); ; Assert.assertNotNull(solution); ; Assert.assertTrue(validSolution(solution, constraints, 1e-4)); ; Assert.assertFalse(callback.isSolutionOptimal()); ; // the solution is clearly not optimal: optimal = 10.0 ; Assert.assertEquals(7.0, solution.getValue(), 1e-4); ; } ;
[ { "context": "ide Effects\n(defn wisdom\n [words]\n (str words \", Daniel-san\"))\n\n(wisdom \"Always bathe on Fridays\")\n\n;; Not a ", "end": 138, "score": 0.998742401599884, "start": 128, "tag": "NAME", "value": "Daniel-san" } ]
language-learning/clojure/functions/functional.clj
imteekay/programming-language-research
627
;; A pure function: use only the passed parameter ;; Pure Functions Have No Side Effects (defn wisdom [words] (str words ", Daniel-san")) (wisdom "Always bathe on Fridays") ;; Not a pure function because it uses an external global object (def PI 3.14) (defn calculate-area [radius] (* radius radius PI)) (calculate-area 10) ;; returns 314.0 ;; pure function because it uses only parameters passed as arguments (def PI 3.14) (defn calculate-area [radius, PI] (* radius radius PI)) (calculate-area 10 PI) ;; returns 314.0 ;; Not pure: it uses the global variable and modify the variable (def counter 1) (defn increase-counter [value] (def counter (inc value))) (increase-counter counter) ;; pure function: returns the value increased by 1 (def counter 1) (defn increase-counter [value] (inc value)) (increase-counter counter) ;; 2 counter ;; 1 ;; impure function: reads an external file (defn characters-counter [text] (str "Character count: " (count text))) (defn analyze-file [filename] (characters-counter (slurp filename))) (analyze-file "test.txt") ;; using a referentially transparent function, you never have to consider what ;; possible external conditions could affect the return value of the function. ;; immutability
31666
;; A pure function: use only the passed parameter ;; Pure Functions Have No Side Effects (defn wisdom [words] (str words ", <NAME>")) (wisdom "Always bathe on Fridays") ;; Not a pure function because it uses an external global object (def PI 3.14) (defn calculate-area [radius] (* radius radius PI)) (calculate-area 10) ;; returns 314.0 ;; pure function because it uses only parameters passed as arguments (def PI 3.14) (defn calculate-area [radius, PI] (* radius radius PI)) (calculate-area 10 PI) ;; returns 314.0 ;; Not pure: it uses the global variable and modify the variable (def counter 1) (defn increase-counter [value] (def counter (inc value))) (increase-counter counter) ;; pure function: returns the value increased by 1 (def counter 1) (defn increase-counter [value] (inc value)) (increase-counter counter) ;; 2 counter ;; 1 ;; impure function: reads an external file (defn characters-counter [text] (str "Character count: " (count text))) (defn analyze-file [filename] (characters-counter (slurp filename))) (analyze-file "test.txt") ;; using a referentially transparent function, you never have to consider what ;; possible external conditions could affect the return value of the function. ;; immutability
true
;; A pure function: use only the passed parameter ;; Pure Functions Have No Side Effects (defn wisdom [words] (str words ", PI:NAME:<NAME>END_PI")) (wisdom "Always bathe on Fridays") ;; Not a pure function because it uses an external global object (def PI 3.14) (defn calculate-area [radius] (* radius radius PI)) (calculate-area 10) ;; returns 314.0 ;; pure function because it uses only parameters passed as arguments (def PI 3.14) (defn calculate-area [radius, PI] (* radius radius PI)) (calculate-area 10 PI) ;; returns 314.0 ;; Not pure: it uses the global variable and modify the variable (def counter 1) (defn increase-counter [value] (def counter (inc value))) (increase-counter counter) ;; pure function: returns the value increased by 1 (def counter 1) (defn increase-counter [value] (inc value)) (increase-counter counter) ;; 2 counter ;; 1 ;; impure function: reads an external file (defn characters-counter [text] (str "Character count: " (count text))) (defn analyze-file [filename] (characters-counter (slurp filename))) (analyze-file "test.txt") ;; using a referentially transparent function, you never have to consider what ;; possible external conditions could affect the return value of the function. ;; immutability
[ { "context": "-reply tr \\\"/count\\\" [step] 42))\"\n contributor \"Sam Aaron\"))\n", "end": 1201, "score": 0.999756395816803, "start": 1192, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/sc/examples/trig.clj
ABaldwinHunter/overtone
3,870
(ns overtone.sc.examples.trig (:use [overtone.sc.machinery defexample] [overtone.sc ugens])) (defexamples send-reply (:count "Send back an OSC message containing a rolling count" "Here our example consists of three parts. Firstly we create a trigger called tr which will fire trigger signal every 'rate' times per second. This is used to drive both the stepper and the send-reply. The stepper simply counts from 0 to 12 inclusive repeating back to 0 - each tick of the count is driven by tr. Similarly tr drives the emission of a new OSC message created by send-reply. This specifies an OSC path = /count in this case as well as a list of args (here we just send the step val back) as well as a unique id which allows us to identify this particular reply in a sea of other similar replies. In order to view the responses, you need to add an event handler such as the following: (on-event \"/count\" (fn [msg] (println msg)) ::foo)" rate :kr [rate {:default 3 :doc "Rate of count in times per second. Increase to up the count rate"}] " (let [tr (impulse rate) step (stepper tr 0 0 12)] (send-reply tr \"/count\" [step] 42))" contributor "Sam Aaron"))
72707
(ns overtone.sc.examples.trig (:use [overtone.sc.machinery defexample] [overtone.sc ugens])) (defexamples send-reply (:count "Send back an OSC message containing a rolling count" "Here our example consists of three parts. Firstly we create a trigger called tr which will fire trigger signal every 'rate' times per second. This is used to drive both the stepper and the send-reply. The stepper simply counts from 0 to 12 inclusive repeating back to 0 - each tick of the count is driven by tr. Similarly tr drives the emission of a new OSC message created by send-reply. This specifies an OSC path = /count in this case as well as a list of args (here we just send the step val back) as well as a unique id which allows us to identify this particular reply in a sea of other similar replies. In order to view the responses, you need to add an event handler such as the following: (on-event \"/count\" (fn [msg] (println msg)) ::foo)" rate :kr [rate {:default 3 :doc "Rate of count in times per second. Increase to up the count rate"}] " (let [tr (impulse rate) step (stepper tr 0 0 12)] (send-reply tr \"/count\" [step] 42))" contributor "<NAME>"))
true
(ns overtone.sc.examples.trig (:use [overtone.sc.machinery defexample] [overtone.sc ugens])) (defexamples send-reply (:count "Send back an OSC message containing a rolling count" "Here our example consists of three parts. Firstly we create a trigger called tr which will fire trigger signal every 'rate' times per second. This is used to drive both the stepper and the send-reply. The stepper simply counts from 0 to 12 inclusive repeating back to 0 - each tick of the count is driven by tr. Similarly tr drives the emission of a new OSC message created by send-reply. This specifies an OSC path = /count in this case as well as a list of args (here we just send the step val back) as well as a unique id which allows us to identify this particular reply in a sea of other similar replies. In order to view the responses, you need to add an event handler such as the following: (on-event \"/count\" (fn [msg] (println msg)) ::foo)" rate :kr [rate {:default 3 :doc "Rate of count in times per second. Increase to up the count rate"}] " (let [tr (impulse rate) step (stepper tr 0 0 12)] (send-reply tr \"/count\" [step] 42))" contributor "PI:NAME:<NAME>END_PI"))
[ { "context": ";; Copyright (c) Andrew A. Raines\n;;\n;; Permission is hereby granted, free of charg", "end": 33, "score": 0.9998774528503418, "start": 17, "tag": "NAME", "value": "Andrew A. Raines" }, { "context": "\"}\n {:from \"[email protected]\"\n :to \"bar", "end": 1741, "score": 0.9999212026596069, "start": 1726, "tag": "EMAIL", "value": "[email protected]" }, { "context": "com\"\n :to \"[email protected]\"}))))\n (is (= :smtp (:which\n ", "end": 1803, "score": 0.9999208450317383, "start": 1788, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\"}\n {:from \"[email protected]\"\n :to \"bar", "end": 2007, "score": 0.9999217987060547, "start": 1992, "tag": "EMAIL", "value": "[email protected]" }, { "context": "com\"\n :to \"[email protected]\"}))))\n (is (= :sendmail (:which\n ", "end": 2069, "score": 0.9999220967292786, "start": 2054, "tag": "EMAIL", "value": "[email protected]" }, { "context": " (postal/send-message {:from \"[email protected]\"\n :to ", "end": 2171, "score": 0.9999225735664368, "start": 2156, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\n :to \"[email protected]\"}))))))\n", "end": 2237, "score": 0.9999211430549622, "start": 2222, "tag": "EMAIL", "value": "[email protected]" } ]
test/postal/test/core.clj
poenneby/postal
371
;; Copyright (c) Andrew A. Raines ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.test.core (:require [postal.core :as postal] [postal.sendmail :as local] [postal.smtp :as smtp]) (:use [clojure.test])) (defn sendmail-send [msg] (merge {:which :sendmail} msg (meta msg))) (defn smtp-send [server msg] (merge {:which :smtp} server msg (meta msg))) (deftest integration (with-redefs [local/sendmail-send sendmail-send smtp/smtp-send smtp-send] (is (= :smtp (:which (postal/send-message ^{:host "localhost" :port "25"} {:from "[email protected]" :to "[email protected]"})))) (is (= :smtp (:which (postal/send-message {:host "localhost" :port "25"} {:from "[email protected]" :to "[email protected]"})))) (is (= :sendmail (:which (postal/send-message {:from "[email protected]" :to "[email protected]"}))))))
8754
;; Copyright (c) <NAME> ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.test.core (:require [postal.core :as postal] [postal.sendmail :as local] [postal.smtp :as smtp]) (:use [clojure.test])) (defn sendmail-send [msg] (merge {:which :sendmail} msg (meta msg))) (defn smtp-send [server msg] (merge {:which :smtp} server msg (meta msg))) (deftest integration (with-redefs [local/sendmail-send sendmail-send smtp/smtp-send smtp-send] (is (= :smtp (:which (postal/send-message ^{:host "localhost" :port "25"} {:from "<EMAIL>" :to "<EMAIL>"})))) (is (= :smtp (:which (postal/send-message {:host "localhost" :port "25"} {:from "<EMAIL>" :to "<EMAIL>"})))) (is (= :sendmail (:which (postal/send-message {:from "<EMAIL>" :to "<EMAIL>"}))))))
true
;; Copyright (c) PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.test.core (:require [postal.core :as postal] [postal.sendmail :as local] [postal.smtp :as smtp]) (:use [clojure.test])) (defn sendmail-send [msg] (merge {:which :sendmail} msg (meta msg))) (defn smtp-send [server msg] (merge {:which :smtp} server msg (meta msg))) (deftest integration (with-redefs [local/sendmail-send sendmail-send smtp/smtp-send smtp-send] (is (= :smtp (:which (postal/send-message ^{:host "localhost" :port "25"} {:from "PI:EMAIL:<EMAIL>END_PI" :to "PI:EMAIL:<EMAIL>END_PI"})))) (is (= :smtp (:which (postal/send-message {:host "localhost" :port "25"} {:from "PI:EMAIL:<EMAIL>END_PI" :to "PI:EMAIL:<EMAIL>END_PI"})))) (is (= :sendmail (:which (postal/send-message {:from "PI:EMAIL:<EMAIL>END_PI" :to "PI:EMAIL:<EMAIL>END_PI"}))))))
[ { "context": ";; Copyright (c) 2013, Damien JEGOU\n;; All rights reserved.\n\n;; Redistribution and us", "end": 35, "score": 0.9998703598976135, "start": 23, "tag": "NAME", "value": "Damien JEGOU" } ]
src/renkobricks/core.clj
LoupSolitaire/renkobricks
1
;; Copyright (c) 2013, Damien JEGOU ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;; HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ;; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS ;; OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED ;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY ;; WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;; POSSIBILITY OF SUCH DAMAGE. (ns renkobricks.core (:require [taoensso.carmine :as car] [clojure.stacktrace :as st]) (:import (java.util Date) (java.text SimpleDateFormat)) (:gen-class)) ;; redis (def pool (car/make-conn-pool)) (def spec-server1 (car/make-conn-spec)) (defmacro wcar [& body] `(car/with-conn pool spec-server1 ~@body)) (def bricksize (ref 100)) (def lastbrick (ref nil)) ;; utility functions (defn abs [x] (if (< x 0) (- x) x)) (defn log [& args] (spit "traderbot.log" (str (.format (new SimpleDateFormat "yyyy/MM/dd HH:mm:ss") (new Date)) ; prepend date " " (apply format args) "\n") :append true)) (defn makebrick [rawmsg] (try (let [msg (apply hash-map (read-string (last rawmsg))) bid (:valuationBidPrice msg) ask (:valuationAskPrice msg) avg (/ (+ bid ask) 2)] (log "%s %s %s" @lastbrick avg (if @lastbrick (abs (- @lastbrick avg)) "nil")) (if (not @lastbrick) (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) (wcar (car/publish "Bricks1" (str @lastbrick))) (log "test1") (log "First brick %s" (str @lastbrick))) (if (> (abs (- @lastbrick avg)) 100) (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) (wcar (car/publish "Bricks1" (str @lastbrick))) (log "test2") (log "New brick %s" (str @lastbrick)))))) (catch Exception e (log "exception %s" e)))) (defn -main [& args] (let [listen-orders (car/with-new-pubsub-listener spec-server1 {"OrderBookEvent" makebrick} (car/subscribe "OrderBookEvent"))] (log "Start making bricks...") ;; useful ? (while true (Thread/sleep 500)))) ;; (let [listener (car/with-new-pubsub-listener ;; spec-server1 {"OrderBookEvent" (fn [rawmsg] ;; ;(try (if (= (first rawmsg) "message"))) ;; (let [msg (apply hash-map (read-string (last rawmsg))) ;; bid (:valuationBidPrice msg) ;; ask (:valuationAskPrice msg) ;; avg (/ (+ bid ask) 2)] ;; ;(log "bid : %s, ask : %s, avg : %s" bid ask avg) ;; (if (not @lastbrick) ;; (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) ;; (wcar (car/publish "Bricks1" @lastbrick)) ;; (log "First brick")) ;; (if (> (abs (- @lastbrick avg)) 100) ;; (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) ;; (wcar (car/publish "Bricks1" @lastbrick)) ;; (log "New brick"))))))} ;; ; (catch Exception e (log "%s" e)) ;; (car/subscribe "OrderBookEvent"))] ;; (while true (Thread/sleep 500)))
84273
;; Copyright (c) 2013, <NAME> ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;; HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ;; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS ;; OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED ;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY ;; WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;; POSSIBILITY OF SUCH DAMAGE. (ns renkobricks.core (:require [taoensso.carmine :as car] [clojure.stacktrace :as st]) (:import (java.util Date) (java.text SimpleDateFormat)) (:gen-class)) ;; redis (def pool (car/make-conn-pool)) (def spec-server1 (car/make-conn-spec)) (defmacro wcar [& body] `(car/with-conn pool spec-server1 ~@body)) (def bricksize (ref 100)) (def lastbrick (ref nil)) ;; utility functions (defn abs [x] (if (< x 0) (- x) x)) (defn log [& args] (spit "traderbot.log" (str (.format (new SimpleDateFormat "yyyy/MM/dd HH:mm:ss") (new Date)) ; prepend date " " (apply format args) "\n") :append true)) (defn makebrick [rawmsg] (try (let [msg (apply hash-map (read-string (last rawmsg))) bid (:valuationBidPrice msg) ask (:valuationAskPrice msg) avg (/ (+ bid ask) 2)] (log "%s %s %s" @lastbrick avg (if @lastbrick (abs (- @lastbrick avg)) "nil")) (if (not @lastbrick) (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) (wcar (car/publish "Bricks1" (str @lastbrick))) (log "test1") (log "First brick %s" (str @lastbrick))) (if (> (abs (- @lastbrick avg)) 100) (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) (wcar (car/publish "Bricks1" (str @lastbrick))) (log "test2") (log "New brick %s" (str @lastbrick)))))) (catch Exception e (log "exception %s" e)))) (defn -main [& args] (let [listen-orders (car/with-new-pubsub-listener spec-server1 {"OrderBookEvent" makebrick} (car/subscribe "OrderBookEvent"))] (log "Start making bricks...") ;; useful ? (while true (Thread/sleep 500)))) ;; (let [listener (car/with-new-pubsub-listener ;; spec-server1 {"OrderBookEvent" (fn [rawmsg] ;; ;(try (if (= (first rawmsg) "message"))) ;; (let [msg (apply hash-map (read-string (last rawmsg))) ;; bid (:valuationBidPrice msg) ;; ask (:valuationAskPrice msg) ;; avg (/ (+ bid ask) 2)] ;; ;(log "bid : %s, ask : %s, avg : %s" bid ask avg) ;; (if (not @lastbrick) ;; (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) ;; (wcar (car/publish "Bricks1" @lastbrick)) ;; (log "First brick")) ;; (if (> (abs (- @lastbrick avg)) 100) ;; (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) ;; (wcar (car/publish "Bricks1" @lastbrick)) ;; (log "New brick"))))))} ;; ; (catch Exception e (log "%s" e)) ;; (car/subscribe "OrderBookEvent"))] ;; (while true (Thread/sleep 500)))
true
;; Copyright (c) 2013, PI:NAME:<NAME>END_PI ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;; HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ;; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS ;; OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED ;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY ;; WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;; POSSIBILITY OF SUCH DAMAGE. (ns renkobricks.core (:require [taoensso.carmine :as car] [clojure.stacktrace :as st]) (:import (java.util Date) (java.text SimpleDateFormat)) (:gen-class)) ;; redis (def pool (car/make-conn-pool)) (def spec-server1 (car/make-conn-spec)) (defmacro wcar [& body] `(car/with-conn pool spec-server1 ~@body)) (def bricksize (ref 100)) (def lastbrick (ref nil)) ;; utility functions (defn abs [x] (if (< x 0) (- x) x)) (defn log [& args] (spit "traderbot.log" (str (.format (new SimpleDateFormat "yyyy/MM/dd HH:mm:ss") (new Date)) ; prepend date " " (apply format args) "\n") :append true)) (defn makebrick [rawmsg] (try (let [msg (apply hash-map (read-string (last rawmsg))) bid (:valuationBidPrice msg) ask (:valuationAskPrice msg) avg (/ (+ bid ask) 2)] (log "%s %s %s" @lastbrick avg (if @lastbrick (abs (- @lastbrick avg)) "nil")) (if (not @lastbrick) (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) (wcar (car/publish "Bricks1" (str @lastbrick))) (log "test1") (log "First brick %s" (str @lastbrick))) (if (> (abs (- @lastbrick avg)) 100) (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) (wcar (car/publish "Bricks1" (str @lastbrick))) (log "test2") (log "New brick %s" (str @lastbrick)))))) (catch Exception e (log "exception %s" e)))) (defn -main [& args] (let [listen-orders (car/with-new-pubsub-listener spec-server1 {"OrderBookEvent" makebrick} (car/subscribe "OrderBookEvent"))] (log "Start making bricks...") ;; useful ? (while true (Thread/sleep 500)))) ;; (let [listener (car/with-new-pubsub-listener ;; spec-server1 {"OrderBookEvent" (fn [rawmsg] ;; ;(try (if (= (first rawmsg) "message"))) ;; (let [msg (apply hash-map (read-string (last rawmsg))) ;; bid (:valuationBidPrice msg) ;; ask (:valuationAskPrice msg) ;; avg (/ (+ bid ask) 2)] ;; ;(log "bid : %s, ask : %s, avg : %s" bid ask avg) ;; (if (not @lastbrick) ;; (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) ;; (wcar (car/publish "Bricks1" @lastbrick)) ;; (log "First brick")) ;; (if (> (abs (- @lastbrick avg)) 100) ;; (do (dosync (ref-set lastbrick (* (quot avg 100) 100))) ;; (wcar (car/publish "Bricks1" @lastbrick)) ;; (log "New brick"))))))} ;; ; (catch Exception e (log "%s" e)) ;; (car/subscribe "OrderBookEvent"))] ;; (while true (Thread/sleep 500)))
[ { "context": " :distro \"alpine\"}})\n\n(def maintainers\n \"Paul Lam <[email protected]> & Wes Morgan <wesmorgan@iclo", "end": 1854, "score": 0.9998741149902344, "start": 1846, "tag": "NAME", "value": "Paul Lam" }, { "context": "o \"alpine\"}})\n\n(def maintainers\n \"Paul Lam <[email protected]> & Wes Morgan <[email protected]>\")\n\n(defn def", "end": 1874, "score": 0.9999324679374695, "start": 1856, "tag": "EMAIL", "value": "[email protected]" }, { "context": "def maintainers\n \"Paul Lam <[email protected]> & Wes Morgan <[email protected]>\")\n\n(defn default-distro [j", "end": 1888, "score": 0.9998664259910583, "start": 1878, "tag": "NAME", "value": "Wes Morgan" }, { "context": "rs\n \"Paul Lam <[email protected]> & Wes Morgan <[email protected]>\")\n\n(defn default-distro [jdk-version]\n (get def", "end": 1910, "score": 0.9999337196350098, "start": 1890, "tag": "EMAIL", "value": "[email protected]" } ]
src/docker_clojure/core.clj
pelerkejepit/Quantisan
0
(ns docker-clojure.core (:require [clojure.java.shell :refer [sh with-sh-dir]] [clojure.math.combinatorics :as combo] [clojure.spec.alpha :as s] [clojure.string :as str] [docker-clojure.dockerfile :as df])) (s/def ::non-blank-string (s/and string? #(not (str/blank? %)))) (s/def ::jdk-version (s/and pos-int? #(<= 8 %))) (s/def ::jdk-versions (s/coll-of ::jdk-version :distinct true :into #{})) (s/def ::base-image ::non-blank-string) (s/def ::base-images (s/coll-of ::base-image :distinct true :into #{})) (s/def ::distro ::non-blank-string) (s/def ::distros (s/coll-of ::distro :distinct true :into #{})) (s/def ::build-tool (s/or ::specific-tool ::non-blank-string ::all-tools #(= ::all %))) (s/def ::build-tool-version (s/nilable (s/and ::non-blank-string #(re-matches #"[\d\.]+" %)))) (s/def ::build-tools (s/map-of ::build-tool ::build-tool-version)) (s/def ::exclusions (s/keys :opt-un [::jdk-version ::distro ::build-tool ::build-tool-version])) (s/def ::maintainers (s/coll-of ::non-blank-string :distinct true :into #{})) (def base-image "openjdk") (def jdk-versions #{8 11 15 16 17}) ;; The default JDK version to use for tags that don't specify one; usually the latest LTS release (def default-jdk-version 11) (def distros #{"buster" "slim-buster" "alpine"}) ;; The default distro to use for tags that don't specify one, keyed by jdk-version. (def default-distros {:default "slim-buster"}) (def build-tools {"lein" "2.9.5" "boot" "2.8.3" "tools-deps" "1.10.3.822"}) (def exclusions ; don't build these for whatever reason(s) #{{:jdk-version 8 :distro "alpine"} {:jdk-version 11 :distro "alpine"} {:jdk-version 15 :distro "alpine"} {:jdk-version 16 :distro "alpine"}}) (def maintainers "Paul Lam <[email protected]> & Wes Morgan <[email protected]>") (defn default-distro [jdk-version] (get default-distros jdk-version (:default default-distros))) (defn contains-every-key-value? "Returns true if the map `haystack` contains every key-value pair in the map `needles`. `haystack` may contain additional keys that are not in `needles`. Returns false if any of the keys in `needles` are missing from `haystack` or have different values." [haystack needles] (every? (fn [[k v]] (= v (get haystack k))) needles)) (defn base-image-name [jdk-version distro] (str base-image ":" jdk-version "-" distro)) (defn exclude? "Returns true if `variant` matches one of `exclusions` elements (meaning `(contains-every-key-value? variant exclusion)` returns true)." [exclusions variant] (some (partial contains-every-key-value? variant) exclusions)) (defn docker-tag [{:keys [jdk-version distro build-tool build-tool-version]}] (if (= ::all build-tool) "latest" (let [jdk-label (if (= default-jdk-version jdk-version) nil (str base-image "-" jdk-version)) dd (default-distro jdk-version) distro-label (if (= dd distro) nil distro)] (str/join "-" (remove nil? [jdk-label build-tool build-tool-version distro-label]))))) (s/def ::variant (s/keys :req-un [::jdk-version ::base-image ::distro ::build-tool ::build-tool-version ::maintainer ::docker-tag] :opt-un [::build-tool-versions])) (defn assoc-if [m pred k v] (if (pred) (assoc m k v) m)) (defn variant-map [[jdk-version distro [build-tool build-tool-version]]] (let [base {:jdk-version jdk-version :base-image (base-image-name jdk-version distro) :distro distro :build-tool build-tool :build-tool-version build-tool-version :maintainer maintainers}] (-> base (assoc :docker-tag (docker-tag base)) (assoc-if #(nil? (:build-tool-version base)) :build-tool-versions build-tools)))) (defn pull-image [image] (sh "docker" "pull" image)) (defn build-image [{:keys [docker-tag dockerfile build-dir base-image] :as variant}] (let [image-tag (str "clojure:" docker-tag) build-cmd ["docker" "build" "--no-cache" "-t" image-tag "-f" dockerfile "."]] (println "Pulling base image" base-image) (pull-image base-image) (df/write-file build-dir dockerfile variant) (apply println "Running" build-cmd) (let [{:keys [out err exit]} (with-sh-dir build-dir (apply sh build-cmd))] (if (zero? exit) (println "Succeeded") (do (println "ERROR:" err) (print out))))) (println)) (def latest-variant "The latest variant is special because we include all 3 build tools via the [::all] value on the end." (list default-jdk-version (default-distro default-jdk-version) [::all])) (defn image-variants [jdk-versions distros build-tools] (->> (combo/cartesian-product jdk-versions distros build-tools) (cons latest-variant) (map variant-map) (remove #(= ::s/invalid (s/conform ::variant %))) set)) (defn build-images [variants] (println "Building images") (doseq [variant variants] (when-not (exclude? exclusions variant) (build-image variant)))) (defn generate-dockerfile! [variant] (let [build-dir (df/build-dir variant) filename "Dockerfile"] (println "Generating" (str build-dir "/" filename)) (df/write-file build-dir filename variant) (assoc variant :build-dir build-dir :dockerfile filename))) (defn generate-dockerfiles! [] (for [variant (image-variants jdk-versions distros build-tools) :when (not (exclude? exclusions variant))] (generate-dockerfile! variant))) (defn -main [& args] (case (first args) "clean" (df/clean-all) "dockerfiles" (dorun (generate-dockerfiles!)) (build-images (generate-dockerfiles!))) (System/exit 0))
68134
(ns docker-clojure.core (:require [clojure.java.shell :refer [sh with-sh-dir]] [clojure.math.combinatorics :as combo] [clojure.spec.alpha :as s] [clojure.string :as str] [docker-clojure.dockerfile :as df])) (s/def ::non-blank-string (s/and string? #(not (str/blank? %)))) (s/def ::jdk-version (s/and pos-int? #(<= 8 %))) (s/def ::jdk-versions (s/coll-of ::jdk-version :distinct true :into #{})) (s/def ::base-image ::non-blank-string) (s/def ::base-images (s/coll-of ::base-image :distinct true :into #{})) (s/def ::distro ::non-blank-string) (s/def ::distros (s/coll-of ::distro :distinct true :into #{})) (s/def ::build-tool (s/or ::specific-tool ::non-blank-string ::all-tools #(= ::all %))) (s/def ::build-tool-version (s/nilable (s/and ::non-blank-string #(re-matches #"[\d\.]+" %)))) (s/def ::build-tools (s/map-of ::build-tool ::build-tool-version)) (s/def ::exclusions (s/keys :opt-un [::jdk-version ::distro ::build-tool ::build-tool-version])) (s/def ::maintainers (s/coll-of ::non-blank-string :distinct true :into #{})) (def base-image "openjdk") (def jdk-versions #{8 11 15 16 17}) ;; The default JDK version to use for tags that don't specify one; usually the latest LTS release (def default-jdk-version 11) (def distros #{"buster" "slim-buster" "alpine"}) ;; The default distro to use for tags that don't specify one, keyed by jdk-version. (def default-distros {:default "slim-buster"}) (def build-tools {"lein" "2.9.5" "boot" "2.8.3" "tools-deps" "1.10.3.822"}) (def exclusions ; don't build these for whatever reason(s) #{{:jdk-version 8 :distro "alpine"} {:jdk-version 11 :distro "alpine"} {:jdk-version 15 :distro "alpine"} {:jdk-version 16 :distro "alpine"}}) (def maintainers "<NAME> <<EMAIL>> & <NAME> <<EMAIL>>") (defn default-distro [jdk-version] (get default-distros jdk-version (:default default-distros))) (defn contains-every-key-value? "Returns true if the map `haystack` contains every key-value pair in the map `needles`. `haystack` may contain additional keys that are not in `needles`. Returns false if any of the keys in `needles` are missing from `haystack` or have different values." [haystack needles] (every? (fn [[k v]] (= v (get haystack k))) needles)) (defn base-image-name [jdk-version distro] (str base-image ":" jdk-version "-" distro)) (defn exclude? "Returns true if `variant` matches one of `exclusions` elements (meaning `(contains-every-key-value? variant exclusion)` returns true)." [exclusions variant] (some (partial contains-every-key-value? variant) exclusions)) (defn docker-tag [{:keys [jdk-version distro build-tool build-tool-version]}] (if (= ::all build-tool) "latest" (let [jdk-label (if (= default-jdk-version jdk-version) nil (str base-image "-" jdk-version)) dd (default-distro jdk-version) distro-label (if (= dd distro) nil distro)] (str/join "-" (remove nil? [jdk-label build-tool build-tool-version distro-label]))))) (s/def ::variant (s/keys :req-un [::jdk-version ::base-image ::distro ::build-tool ::build-tool-version ::maintainer ::docker-tag] :opt-un [::build-tool-versions])) (defn assoc-if [m pred k v] (if (pred) (assoc m k v) m)) (defn variant-map [[jdk-version distro [build-tool build-tool-version]]] (let [base {:jdk-version jdk-version :base-image (base-image-name jdk-version distro) :distro distro :build-tool build-tool :build-tool-version build-tool-version :maintainer maintainers}] (-> base (assoc :docker-tag (docker-tag base)) (assoc-if #(nil? (:build-tool-version base)) :build-tool-versions build-tools)))) (defn pull-image [image] (sh "docker" "pull" image)) (defn build-image [{:keys [docker-tag dockerfile build-dir base-image] :as variant}] (let [image-tag (str "clojure:" docker-tag) build-cmd ["docker" "build" "--no-cache" "-t" image-tag "-f" dockerfile "."]] (println "Pulling base image" base-image) (pull-image base-image) (df/write-file build-dir dockerfile variant) (apply println "Running" build-cmd) (let [{:keys [out err exit]} (with-sh-dir build-dir (apply sh build-cmd))] (if (zero? exit) (println "Succeeded") (do (println "ERROR:" err) (print out))))) (println)) (def latest-variant "The latest variant is special because we include all 3 build tools via the [::all] value on the end." (list default-jdk-version (default-distro default-jdk-version) [::all])) (defn image-variants [jdk-versions distros build-tools] (->> (combo/cartesian-product jdk-versions distros build-tools) (cons latest-variant) (map variant-map) (remove #(= ::s/invalid (s/conform ::variant %))) set)) (defn build-images [variants] (println "Building images") (doseq [variant variants] (when-not (exclude? exclusions variant) (build-image variant)))) (defn generate-dockerfile! [variant] (let [build-dir (df/build-dir variant) filename "Dockerfile"] (println "Generating" (str build-dir "/" filename)) (df/write-file build-dir filename variant) (assoc variant :build-dir build-dir :dockerfile filename))) (defn generate-dockerfiles! [] (for [variant (image-variants jdk-versions distros build-tools) :when (not (exclude? exclusions variant))] (generate-dockerfile! variant))) (defn -main [& args] (case (first args) "clean" (df/clean-all) "dockerfiles" (dorun (generate-dockerfiles!)) (build-images (generate-dockerfiles!))) (System/exit 0))
true
(ns docker-clojure.core (:require [clojure.java.shell :refer [sh with-sh-dir]] [clojure.math.combinatorics :as combo] [clojure.spec.alpha :as s] [clojure.string :as str] [docker-clojure.dockerfile :as df])) (s/def ::non-blank-string (s/and string? #(not (str/blank? %)))) (s/def ::jdk-version (s/and pos-int? #(<= 8 %))) (s/def ::jdk-versions (s/coll-of ::jdk-version :distinct true :into #{})) (s/def ::base-image ::non-blank-string) (s/def ::base-images (s/coll-of ::base-image :distinct true :into #{})) (s/def ::distro ::non-blank-string) (s/def ::distros (s/coll-of ::distro :distinct true :into #{})) (s/def ::build-tool (s/or ::specific-tool ::non-blank-string ::all-tools #(= ::all %))) (s/def ::build-tool-version (s/nilable (s/and ::non-blank-string #(re-matches #"[\d\.]+" %)))) (s/def ::build-tools (s/map-of ::build-tool ::build-tool-version)) (s/def ::exclusions (s/keys :opt-un [::jdk-version ::distro ::build-tool ::build-tool-version])) (s/def ::maintainers (s/coll-of ::non-blank-string :distinct true :into #{})) (def base-image "openjdk") (def jdk-versions #{8 11 15 16 17}) ;; The default JDK version to use for tags that don't specify one; usually the latest LTS release (def default-jdk-version 11) (def distros #{"buster" "slim-buster" "alpine"}) ;; The default distro to use for tags that don't specify one, keyed by jdk-version. (def default-distros {:default "slim-buster"}) (def build-tools {"lein" "2.9.5" "boot" "2.8.3" "tools-deps" "1.10.3.822"}) (def exclusions ; don't build these for whatever reason(s) #{{:jdk-version 8 :distro "alpine"} {:jdk-version 11 :distro "alpine"} {:jdk-version 15 :distro "alpine"} {:jdk-version 16 :distro "alpine"}}) (def maintainers "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> & PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>") (defn default-distro [jdk-version] (get default-distros jdk-version (:default default-distros))) (defn contains-every-key-value? "Returns true if the map `haystack` contains every key-value pair in the map `needles`. `haystack` may contain additional keys that are not in `needles`. Returns false if any of the keys in `needles` are missing from `haystack` or have different values." [haystack needles] (every? (fn [[k v]] (= v (get haystack k))) needles)) (defn base-image-name [jdk-version distro] (str base-image ":" jdk-version "-" distro)) (defn exclude? "Returns true if `variant` matches one of `exclusions` elements (meaning `(contains-every-key-value? variant exclusion)` returns true)." [exclusions variant] (some (partial contains-every-key-value? variant) exclusions)) (defn docker-tag [{:keys [jdk-version distro build-tool build-tool-version]}] (if (= ::all build-tool) "latest" (let [jdk-label (if (= default-jdk-version jdk-version) nil (str base-image "-" jdk-version)) dd (default-distro jdk-version) distro-label (if (= dd distro) nil distro)] (str/join "-" (remove nil? [jdk-label build-tool build-tool-version distro-label]))))) (s/def ::variant (s/keys :req-un [::jdk-version ::base-image ::distro ::build-tool ::build-tool-version ::maintainer ::docker-tag] :opt-un [::build-tool-versions])) (defn assoc-if [m pred k v] (if (pred) (assoc m k v) m)) (defn variant-map [[jdk-version distro [build-tool build-tool-version]]] (let [base {:jdk-version jdk-version :base-image (base-image-name jdk-version distro) :distro distro :build-tool build-tool :build-tool-version build-tool-version :maintainer maintainers}] (-> base (assoc :docker-tag (docker-tag base)) (assoc-if #(nil? (:build-tool-version base)) :build-tool-versions build-tools)))) (defn pull-image [image] (sh "docker" "pull" image)) (defn build-image [{:keys [docker-tag dockerfile build-dir base-image] :as variant}] (let [image-tag (str "clojure:" docker-tag) build-cmd ["docker" "build" "--no-cache" "-t" image-tag "-f" dockerfile "."]] (println "Pulling base image" base-image) (pull-image base-image) (df/write-file build-dir dockerfile variant) (apply println "Running" build-cmd) (let [{:keys [out err exit]} (with-sh-dir build-dir (apply sh build-cmd))] (if (zero? exit) (println "Succeeded") (do (println "ERROR:" err) (print out))))) (println)) (def latest-variant "The latest variant is special because we include all 3 build tools via the [::all] value on the end." (list default-jdk-version (default-distro default-jdk-version) [::all])) (defn image-variants [jdk-versions distros build-tools] (->> (combo/cartesian-product jdk-versions distros build-tools) (cons latest-variant) (map variant-map) (remove #(= ::s/invalid (s/conform ::variant %))) set)) (defn build-images [variants] (println "Building images") (doseq [variant variants] (when-not (exclude? exclusions variant) (build-image variant)))) (defn generate-dockerfile! [variant] (let [build-dir (df/build-dir variant) filename "Dockerfile"] (println "Generating" (str build-dir "/" filename)) (df/write-file build-dir filename variant) (assoc variant :build-dir build-dir :dockerfile filename))) (defn generate-dockerfiles! [] (for [variant (image-variants jdk-versions distros build-tools) :when (not (exclude? exclusions variant))] (generate-dockerfile! variant))) (defn -main [& args] (case (first args) "clean" (df/clean-all) "dockerfiles" (dorun (generate-dockerfiles!)) (build-images (generate-dockerfiles!))) (System/exit 0))
[ { "context": ";\n; Copyright 2015 Peter Monks\n; SPDX-License-Identifier: Apache-2.0\n;\n; License", "end": 30, "score": 0.9998100399971008, "start": 19, "tag": "NAME", "value": "Peter Monks" }, { "context": "d game.\"\n :url \"https://github.com/pmonks/clj-chain-reaction\"\n :license {:spdx-li", "end": 813, "score": 0.5943574905395508, "start": 808, "tag": "USERNAME", "value": "monks" } ]
project.clj
pmonks/clj-chain-reaction
1
; ; Copyright 2015 Peter Monks ; SPDX-License-Identifier: Apache-2.0 ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (defproject org.clojars.pmonks/clj-chain-reaction "0.1.0-SNAPSHOT" :description "Clojure/Script implementation of Chain Reaction board game." :url "https://github.com/pmonks/clj-chain-reaction" :license {:spdx-license-identifier "Apache-2.0" :name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.9.0" :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/clojurescript "1.10.520"]] :cljsbuild {:builds {} :test-commands {"unit-tests" ["lein" "with-profile" "test" "doo" "node" "once"]}} :doo {:build "test"} :profiles {:dev {:plugins [[lein-cljsbuild "1.1.7"] [lein-doo "0.1.11"]]} :test {:cljsbuild {:builds {:test {:source-paths ["src" "test"] :compiler {:output-to "unit-tests.js" :target :nodejs :main chain-reaction.doo-runner} :optimizations :whitespace :pretty-print true}}}}})
11040
; ; Copyright 2015 <NAME> ; SPDX-License-Identifier: Apache-2.0 ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (defproject org.clojars.pmonks/clj-chain-reaction "0.1.0-SNAPSHOT" :description "Clojure/Script implementation of Chain Reaction board game." :url "https://github.com/pmonks/clj-chain-reaction" :license {:spdx-license-identifier "Apache-2.0" :name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.9.0" :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/clojurescript "1.10.520"]] :cljsbuild {:builds {} :test-commands {"unit-tests" ["lein" "with-profile" "test" "doo" "node" "once"]}} :doo {:build "test"} :profiles {:dev {:plugins [[lein-cljsbuild "1.1.7"] [lein-doo "0.1.11"]]} :test {:cljsbuild {:builds {:test {:source-paths ["src" "test"] :compiler {:output-to "unit-tests.js" :target :nodejs :main chain-reaction.doo-runner} :optimizations :whitespace :pretty-print true}}}}})
true
; ; Copyright 2015 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: Apache-2.0 ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (defproject org.clojars.pmonks/clj-chain-reaction "0.1.0-SNAPSHOT" :description "Clojure/Script implementation of Chain Reaction board game." :url "https://github.com/pmonks/clj-chain-reaction" :license {:spdx-license-identifier "Apache-2.0" :name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.9.0" :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/clojurescript "1.10.520"]] :cljsbuild {:builds {} :test-commands {"unit-tests" ["lein" "with-profile" "test" "doo" "node" "once"]}} :doo {:build "test"} :profiles {:dev {:plugins [[lein-cljsbuild "1.1.7"] [lein-doo "0.1.11"]]} :test {:cljsbuild {:builds {:test {:source-paths ["src" "test"] :compiler {:output-to "unit-tests.js" :target :nodejs :main chain-reaction.doo-runner} :optimizations :whitespace :pretty-print true}}}}})
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.flux.core\n\n \"A ", "end": 597, "score": 0.9998504519462585, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/flux/core.clj
llnek/fluxion
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.flux.core "A minimal worflow framework." (:require [clojure.java.io :as io] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.proc :as p] [czlab.basal.meta :as m] [czlab.basal.util :as u] [czlab.basal.core :as c :refer [n#]]) (:import [java.util.concurrent.atomic AtomicInteger] [java.util.concurrent TimeoutException] [java.util TimerTask])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol WorkFlow (exec [_ job] "Apply this workflow to the job.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Job (wkflow [_] "Return the workflow object.") (runner [_] "Return the executor.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Step "A step in the workflow." (g-job [_] "Get the job.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Symbol "A workflow symbol." (step-init [_ step] "Initialize the Step.") (step-reify [_ next] "Instantiate this Symbol.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defwflow "Define a workflow." {:arglists '([name & tasks])} [name & tasks] `(def ~name (czlab.flux.core/workflow<> [ ~@tasks ]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- csymb?? "Cast to a Symbol?" {:arglists '([a])} [a] `(let [x# ~a] (if (c/sas? Symbol x#) x#))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- cstep?? "Cast to a Step?" {:arglists '([a])} [a] `(let [x# ~a] (if (c/sas? Step x#) x#))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- is-null-join? [s] `(= (c/typeid ~s) ::null-join)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- err! [c e] `(array-map :step ~c :error ~e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare step-run-after step-run proto-step<>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- rinit! "Reset a step." [step] (if step (step-init (c/parent step) step))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Script [] Symbol (step-init [me step] (let [{:keys [work-func]} me [s _] (m/count-arity work-func)] (c/init step {:work work-func :arity s}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next work arity]} (c/get-conf cur) a (cond (c/in? arity 2) (work cur job) (c/in? arity 1) (work job) :else (u/throw-BadArg "Expected %s: on %s" "arity 2 or 1" (class work)))] (rinit! cur) (if-some [a' (csymb?? a)] (step-reify a' next) next)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (c/stror (:script me) (name (c/typeid me))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro script<> "Create a *scriptable symbol*." {:arglists '([workFunc] [workFunc script-name])} ([workFunc] `(script<> ~workFunc nil)) ([workFunc script-name] `(czlab.basal.core/object<> czlab.flux.core.Script :work-func ~workFunc :script ~script-name :typeid :czlab.flux.core/script))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn wrap-symb?? "If x is a function, wrapped it inside a script symbol*." {:arglists '([x])} [x] (cond (c/sas? Symbol x) x (fn? x) (script<> x) :else (u/throw-BadArg "bad param type: " (if (nil? x) "null" (class x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wrapc "Create a step from this Symbol" [x nxt] (-> x wrap-symb?? (step-reify nxt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fanout "Fork off tasks." [job nx defs] (let [cpu (runner job)] (c/debug "fanout: forking [%d] sub-tasks." (c/n# defs)) (doseq [t defs] (p/run cpu (wrapc t nx))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- sa! "Set alarm." [step job wsecs] (when (c/spos? wsecs) (p/alarm (runner job) (* 1000 wsecs) step job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- proto-step<> "Create a generic step object. We need to know the type of step to instantiate, and the step to call after this step is run." [proto n args] (let [_id (str "step#" (u/seqint2)) impl (atom (assoc args :next n))] (reify Step (g-job [_] (let [{:keys [job next]} @impl] (or job (g-job next)))) Runnable (run [_] (step-run _ (:action @impl))) c/Configurable (get-conf [_ k] (get @impl k)) (get-conf [_] @impl) (set-conf [_ x] _) (set-conf [_ k v] (swap! impl assoc k v) _) c/Idable (id [_] _id) c/Hierarchical (parent [_] proto) c/Initable (init [me m] (c/if-fn [f (:init-fn @impl)] (f me m) (swap! impl merge m)) me) c/Interruptable (interrupt [me job] (c/if-fn [f (:timer @impl)] (f me job)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Terminal [] Symbol (step-init [_ s] s) (step-reify [me nx] (u/throw-UOE "Cannot reify a terminal.")) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- terminal<> "*terminal*" [] (c/object<> Terminal :typeid ::terminal)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- terminal-step<> [job] {:pre [(some? job)]} (let [t (terminal<>)] (step-init t (proto-step<> t nil {:job job})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- step-run-after [orig arg] (let [par' (c/parent orig) job (g-job orig) cpu (runner job) step (if (csymb?? arg) (wrapc arg (terminal-step<> job)) arg)] (when (cstep?? step) (cond (= ::terminal (-> step c/parent c/typeid)) (c/debug "%s :-> terminal" (c/id par')) (c/is-valid? cpu) (do (c/debug "%s :-> %s" (c/id par') (c/id (c/parent step))) (p/run cpu step)) :else (c/debug "no-cpu, %s skipping %s" (c/id par') (c/id (c/parent step))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- step-run [step action] (let [job (g-job step) ws (wkflow job)] (step-run-after step (try (action step job) (catch Throwable e# (if-not (c/sas? c/Catchable ws) (c/do->nil (c/exception e#)) (u/try!!! (c/exception e#) (c/catche ws (err! step e#))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- join-timer [step job] (c/warn "%s: timer expired." (c/id (c/parent step))) (let [_ (->> (u/mono-flop<> true) (c/set-conf step :error)) e (csymb?? (c/get-conf step :expiry)) ws (wkflow job) n (when (and (nil? e) (c/sas? c/Catchable ws)) (->> (TimeoutException.) (err! step) (c/catche ws)))] (some->> (some-> (or e n) (wrapc (terminal-step<> job))) (p/run (runner job))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Postpone [] Symbol (step-init [me step] (c/init step {:delay (:delay-secs me)})) (step-reify [me nx] (->> {:action (fn [cur job] (c/do->nil (let [cpu (runner job) {:keys [next delay]} (c/get-conf cur)] (->> (c/num?? delay 0) (* 1000) (p/postpone cpu next)) (rinit! cur))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro postpone<> "Create a *delay symbol*." {:arglists '([delay-secs])} [delay-secs] `(czlab.basal.core/object<> czlab.flux.core.Postpone :delay-secs ~delay-secs :typeid :czlab.flux.core/delay)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Switch [] Symbol (step-init [_ step] (let [{:keys [choices cexpr default]} _ {:keys [next]} (c/get-conf step)] (c/init step {:dft (some-> default wrap-symb?? (wrapc next)) :cexpr cexpr :choices (c/preduce<vec> #(let [[k v] %2] (-> (conj! %1 k) (conj! (wrapc v next)))) (partition 2 choices))}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [cexpr dft choices]} (c/get-conf cur) m (cexpr job)] (rinit! cur) (or (if m (some #(if (= m (c/_1 %1)) (c/_E %1)) (partition 2 choices))) dft)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro choice<> "Create a *choice symbol*." {:arglists '([cexpr & choices])} [cexpr & choices] (let [[a b] (take-last 2 choices) [dft args] (if (and b (= a :default)) [b (drop-last 2 choices)] [nil choices])] `(czlab.basal.core/object<> czlab.flux.core.Switch :choices [~@args] :default ~dft :cexpr ~cexpr :typeid :czlab.flux.core/switch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Decision [] Symbol (step-init [me step] (c/init step (select-keys me [:bexpr :then :else]))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [bexpr next then else]} (c/get-conf cur)] (rinit! cur) (if (bexpr job) (wrapc then next) (wrapc else next))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decision<> "Create a *decision symbol*." {:arglists '([bexpr then] [bexpr then else])} ([bexpr then] `(decision<> ~bexpr ~then nil)) ([bexpr then else] `(czlab.basal.core/object<> czlab.flux.core.Decision :bexpr ~bexpr :then ~then :else ~else :typeid :czlab.flux.core/decision))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WhileLoop [] Symbol (step-init [_ step] (let [{:keys [body bexpr]} _] (assert (fn? bexpr)) (c/init step {:bexpr bexpr :body (wrapc body step)}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next bexpr body]} (c/get-conf cur)] (if-not (bexpr job) (do (rinit! cur) next) (c/do->nil (p/run (runner job) body)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro while<> "Create a *while-loop symbol*." {:arglists '([bexpr body])} [bexpr body] `(czlab.basal.core/object<> WhileLoop :bexpr ~bexpr :body ~body :typeid :czlab.flux.core/while)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord SplitJoin [] Symbol (step-init [me step] (let [{:keys [impl wait-secs forks expiry]} me] (c/init step (->> (if-not (is-null-join? me) {:expiry expiry :impl impl :error nil :wait wait-secs :counter (AtomicInteger. 0)}) (merge {:forks (map #(wrap-symb?? %) forks)}))))) (step-reify [me nx] ;-we need a timer so that we don't wait forever ;in case some subtasks don't return. ;-this step is re-entrant. ;-we start off by forking off the set of subtasks, ;then wait for them to return. ;if time out occurs, this step ;is flagged as in error and may proceed differently ;depending on the error handling logic. ;-each subtask returning will up' the counter, ;and-join: wait for all to return, ;or-join: only one returning will proceed to next. (->> (if (is-null-join? me) {:action (fn [cur job] (fanout job (terminal-step<> job) (c/get-conf cur :forks)) (c/get-conf cur :next))} {:timer join-timer :action (fn [cur job] (let [{:keys [error wait impl forks]} (c/get-conf cur)] (cond (some? error) (c/do->nil (c/debug "too late.")) (number? forks) (impl cur) (empty? forks) (c/get-conf cur :next) (not-empty forks) (c/do->nil (fanout job cur forks) (c/set-conf cur :forks (n# forks)) (c/set-conf cur :alarm (sa! cur job wait))))))}) (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- nulljoin "Create a do-nothing *join task*." [branches] (c/object<> SplitJoin :typeid ::null-join :forks branches)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- andjoin "Create a *join(and) task*." [branches waitSecs expiry] (c/object<> SplitJoin :typeid ::and-join :forks branches :expiry expiry :wait-secs waitSecs :impl #(let [{:keys [counter forks alarm next]} (c/get-conf %) n (-> ^AtomicInteger counter .incrementAndGet)] (c/debug "andjoin: sub-task[%d] returned." n) (when (== n forks) (c/debug "andjoin: sub-tasks completed.") (some-> ^TimerTask alarm .cancel) (c/set-conf % :alarm nil) (rinit! %) next)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- orjoin "Create a *or join symbol*." [branches waitSecs expiry] (c/object<> SplitJoin :wait-secs waitSecs :typeid ::or-join :forks branches :expiry expiry :impl #(let [{:keys [counter next alarm]} (c/get-conf %) n (-> ^AtomicInteger counter .incrementAndGet)] (c/debug "orjoin: sub-task[%d] returned." n) (some-> ^TimerTask alarm .cancel) (c/set-conf % :alarm nil) (when (== n 1) (rinit! %) next)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Split [] Symbol (step-init [_ step] (let [{:keys [expiry forks options]} _ {:keys [type wait-secs]} options] (c/init step {:expiry (some-> expiry wrap-symb??) :wait (c/num?? wait-secs 0) :join-style type :forks (map #(wrap-symb?? %) forks)}))) (step-reify [me nx] (->> {:action (fn [cur _] (let [{:keys [join-style wait expiry next forks]} (c/get-conf cur)] (wrapc (cond (= :and join-style) (andjoin forks wait expiry) (= :or join-style) (orjoin forks wait expiry) :else (nulljoin forks)) next)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro split-join<> "Create a split-join." {:arglists '([bindings & forks])} [bindings & forks] (let [{:keys [type wait-secs] :as M} (apply array-map bindings) [a b] (take-last 2 forks) [exp args] (if (= a :expiry) [b (drop-last 2 forks)] [nil forks])] (assert (contains? #{:and :or} type)) (if wait-secs (assert (number? wait-secs))) (if (= a :expiry) (assert (some? exp))) (assert (not-empty args)) `(czlab.basal.core/object<> czlab.flux.core.Split :expiry ~exp :forks [~@args] :options ~M :typeid :czlab.flux.core/split))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro split<> "Create a split." {:arglists '([f1 & more])} [f1 & more] (let [forks (cons f1 more)] `(czlab.basal.core/object<> czlab.flux.core.Split :forks [~@forks] :typeid :czlab.flux.core/split))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Group [] Symbol (step-init [me step] (c/init step {:alist (map #(wrap-symb?? %) (:symbols me))})) (step-reify [me nx] ;iterate through the group, treating it like a ;queue, poping off one at a time. Each symbol ;pop'ed off will be run and will return back here ;for the next iteration to occur. We can do this ;by passing this group-step as the next step to ;be performed after the item is done. (->> {:action (fn [cur job] (let [[a & more] (c/get-conf cur :alist)] (if-some [s (some-> a (wrapc cur))] (do (c/set-conf cur :alist more) s) (do (rinit! cur) (c/get-conf cur :next)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro group<> "Create a group." {:arglists '([a & more])} [a & more] `(czlab.basal.core/object<> czlab.flux.core.Group :symbols [~a ~@more] :typeid :czlab.flux.core/group)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- range-expr [lower upper] (let [loopy (atom lower)] (c/fn_1 (let [job ____1 v @loopy] (if (< v upper) (swap! loopy #(do (c/setv job :$range-index v) (+ 1 %)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ForLoop [] Symbol (step-init [me step] (let [job (g-job step) {:keys [lower upper body]} me low (cond (number? lower) lower (fn? lower) (lower job)) high (cond (number? upper) upper (fn? upper) (upper job))] (assert (and (number? low) (number? high) (<= low high)) "for<>: Bad lower/upper bound.") (c/init step {:body (wrapc body step) :bexpr (range-expr low high)}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next bexpr body]} (c/get-conf cur)] (if-not (bexpr job) (do (rinit! cur) next) (c/do->nil (p/run (runner job) body)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro for<> "Create a for." {:arglists '([lower upper body])} [lower upper body] `(czlab.basal.core/object<> czlab.flux.core.ForLoop :lower ~lower :upper ~upper :body ~body :typeid :czlab.flux.core/for)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn job<> "Create a job context." {:arglists '([sch] [sch initObj] [sch initObj originObj])} ([_sch initObj] (job<> _sch initObj nil)) ([_sch] (job<> _sch nil nil)) ([_sch initObj originObj] (let [impl (atom {:last-result nil}) data (atom (or initObj {})) _id (str "job#" (u/seqint2))] (reify Job (runner [_] _sch) (wkflow [_] (:wflow @impl)) c/Configurable (set-conf [_ k v] _) (set-conf [me _] me) (get-conf [_] nil) (get-conf [_ k] (get @impl k)) c/Hierarchical ;where this job came from? (parent [_] originObj) c/Idable (id [_] _id) ;for app data c/Settable (unsetv [_ k] (swap! data dissoc k)) (setv [_ k v] (swap! data assoc k v)) c/Gettable (getv [_ k] (get @data k)) (has? [_ k] (contains? @data k)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wsexec "Apply workflow to this job." [ws job] (c/set-conf job :wflow ws) (p/run (runner job) (wrapc (:head ws) (terminal-step<> job)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WorkFlowExObj [] c/Catchable (catche [me e] ((:efn me) e)) WorkFlow (exec [me job] (wsexec me job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WorkFlowObj [] WorkFlow (exec [me job] (wsexec me job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn workflow<> "Creare workflow from a list of symbols." {:arglists '([symbols])} [symbols] {:pre [(sequential? symbols)]} ;;first we look for error handling which, ;;if defined, must be at the end of the args. (let [[a b] (take-last 2 symbols) [err syms] (if (and (fn? b) (= :catch a)) [b (drop-last 2 symbols)] [nil symbols]) head (c/object<> Group :symbols syms :typeid :group)] (if-not (fn? err) (c/object<> WorkFlowObj :head head) (c/object<> WorkFlowExObj :head head :efn err)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn workflow* "Create a work flow with the follwing syntax: (workflow<> symbol [symbol...] [:catch func])" {:arglists '([symbol0 & args])} [symbol0 & args] {:pre [(some? symbol0)]} (workflow<> (cons symbol0 args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
55498
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.flux.core "A minimal worflow framework." (:require [clojure.java.io :as io] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.proc :as p] [czlab.basal.meta :as m] [czlab.basal.util :as u] [czlab.basal.core :as c :refer [n#]]) (:import [java.util.concurrent.atomic AtomicInteger] [java.util.concurrent TimeoutException] [java.util TimerTask])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol WorkFlow (exec [_ job] "Apply this workflow to the job.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Job (wkflow [_] "Return the workflow object.") (runner [_] "Return the executor.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Step "A step in the workflow." (g-job [_] "Get the job.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Symbol "A workflow symbol." (step-init [_ step] "Initialize the Step.") (step-reify [_ next] "Instantiate this Symbol.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defwflow "Define a workflow." {:arglists '([name & tasks])} [name & tasks] `(def ~name (czlab.flux.core/workflow<> [ ~@tasks ]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- csymb?? "Cast to a Symbol?" {:arglists '([a])} [a] `(let [x# ~a] (if (c/sas? Symbol x#) x#))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- cstep?? "Cast to a Step?" {:arglists '([a])} [a] `(let [x# ~a] (if (c/sas? Step x#) x#))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- is-null-join? [s] `(= (c/typeid ~s) ::null-join)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- err! [c e] `(array-map :step ~c :error ~e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare step-run-after step-run proto-step<>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- rinit! "Reset a step." [step] (if step (step-init (c/parent step) step))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Script [] Symbol (step-init [me step] (let [{:keys [work-func]} me [s _] (m/count-arity work-func)] (c/init step {:work work-func :arity s}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next work arity]} (c/get-conf cur) a (cond (c/in? arity 2) (work cur job) (c/in? arity 1) (work job) :else (u/throw-BadArg "Expected %s: on %s" "arity 2 or 1" (class work)))] (rinit! cur) (if-some [a' (csymb?? a)] (step-reify a' next) next)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (c/stror (:script me) (name (c/typeid me))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro script<> "Create a *scriptable symbol*." {:arglists '([workFunc] [workFunc script-name])} ([workFunc] `(script<> ~workFunc nil)) ([workFunc script-name] `(czlab.basal.core/object<> czlab.flux.core.Script :work-func ~workFunc :script ~script-name :typeid :czlab.flux.core/script))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn wrap-symb?? "If x is a function, wrapped it inside a script symbol*." {:arglists '([x])} [x] (cond (c/sas? Symbol x) x (fn? x) (script<> x) :else (u/throw-BadArg "bad param type: " (if (nil? x) "null" (class x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wrapc "Create a step from this Symbol" [x nxt] (-> x wrap-symb?? (step-reify nxt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fanout "Fork off tasks." [job nx defs] (let [cpu (runner job)] (c/debug "fanout: forking [%d] sub-tasks." (c/n# defs)) (doseq [t defs] (p/run cpu (wrapc t nx))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- sa! "Set alarm." [step job wsecs] (when (c/spos? wsecs) (p/alarm (runner job) (* 1000 wsecs) step job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- proto-step<> "Create a generic step object. We need to know the type of step to instantiate, and the step to call after this step is run." [proto n args] (let [_id (str "step#" (u/seqint2)) impl (atom (assoc args :next n))] (reify Step (g-job [_] (let [{:keys [job next]} @impl] (or job (g-job next)))) Runnable (run [_] (step-run _ (:action @impl))) c/Configurable (get-conf [_ k] (get @impl k)) (get-conf [_] @impl) (set-conf [_ x] _) (set-conf [_ k v] (swap! impl assoc k v) _) c/Idable (id [_] _id) c/Hierarchical (parent [_] proto) c/Initable (init [me m] (c/if-fn [f (:init-fn @impl)] (f me m) (swap! impl merge m)) me) c/Interruptable (interrupt [me job] (c/if-fn [f (:timer @impl)] (f me job)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Terminal [] Symbol (step-init [_ s] s) (step-reify [me nx] (u/throw-UOE "Cannot reify a terminal.")) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- terminal<> "*terminal*" [] (c/object<> Terminal :typeid ::terminal)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- terminal-step<> [job] {:pre [(some? job)]} (let [t (terminal<>)] (step-init t (proto-step<> t nil {:job job})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- step-run-after [orig arg] (let [par' (c/parent orig) job (g-job orig) cpu (runner job) step (if (csymb?? arg) (wrapc arg (terminal-step<> job)) arg)] (when (cstep?? step) (cond (= ::terminal (-> step c/parent c/typeid)) (c/debug "%s :-> terminal" (c/id par')) (c/is-valid? cpu) (do (c/debug "%s :-> %s" (c/id par') (c/id (c/parent step))) (p/run cpu step)) :else (c/debug "no-cpu, %s skipping %s" (c/id par') (c/id (c/parent step))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- step-run [step action] (let [job (g-job step) ws (wkflow job)] (step-run-after step (try (action step job) (catch Throwable e# (if-not (c/sas? c/Catchable ws) (c/do->nil (c/exception e#)) (u/try!!! (c/exception e#) (c/catche ws (err! step e#))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- join-timer [step job] (c/warn "%s: timer expired." (c/id (c/parent step))) (let [_ (->> (u/mono-flop<> true) (c/set-conf step :error)) e (csymb?? (c/get-conf step :expiry)) ws (wkflow job) n (when (and (nil? e) (c/sas? c/Catchable ws)) (->> (TimeoutException.) (err! step) (c/catche ws)))] (some->> (some-> (or e n) (wrapc (terminal-step<> job))) (p/run (runner job))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Postpone [] Symbol (step-init [me step] (c/init step {:delay (:delay-secs me)})) (step-reify [me nx] (->> {:action (fn [cur job] (c/do->nil (let [cpu (runner job) {:keys [next delay]} (c/get-conf cur)] (->> (c/num?? delay 0) (* 1000) (p/postpone cpu next)) (rinit! cur))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro postpone<> "Create a *delay symbol*." {:arglists '([delay-secs])} [delay-secs] `(czlab.basal.core/object<> czlab.flux.core.Postpone :delay-secs ~delay-secs :typeid :czlab.flux.core/delay)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Switch [] Symbol (step-init [_ step] (let [{:keys [choices cexpr default]} _ {:keys [next]} (c/get-conf step)] (c/init step {:dft (some-> default wrap-symb?? (wrapc next)) :cexpr cexpr :choices (c/preduce<vec> #(let [[k v] %2] (-> (conj! %1 k) (conj! (wrapc v next)))) (partition 2 choices))}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [cexpr dft choices]} (c/get-conf cur) m (cexpr job)] (rinit! cur) (or (if m (some #(if (= m (c/_1 %1)) (c/_E %1)) (partition 2 choices))) dft)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro choice<> "Create a *choice symbol*." {:arglists '([cexpr & choices])} [cexpr & choices] (let [[a b] (take-last 2 choices) [dft args] (if (and b (= a :default)) [b (drop-last 2 choices)] [nil choices])] `(czlab.basal.core/object<> czlab.flux.core.Switch :choices [~@args] :default ~dft :cexpr ~cexpr :typeid :czlab.flux.core/switch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Decision [] Symbol (step-init [me step] (c/init step (select-keys me [:bexpr :then :else]))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [bexpr next then else]} (c/get-conf cur)] (rinit! cur) (if (bexpr job) (wrapc then next) (wrapc else next))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decision<> "Create a *decision symbol*." {:arglists '([bexpr then] [bexpr then else])} ([bexpr then] `(decision<> ~bexpr ~then nil)) ([bexpr then else] `(czlab.basal.core/object<> czlab.flux.core.Decision :bexpr ~bexpr :then ~then :else ~else :typeid :czlab.flux.core/decision))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WhileLoop [] Symbol (step-init [_ step] (let [{:keys [body bexpr]} _] (assert (fn? bexpr)) (c/init step {:bexpr bexpr :body (wrapc body step)}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next bexpr body]} (c/get-conf cur)] (if-not (bexpr job) (do (rinit! cur) next) (c/do->nil (p/run (runner job) body)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro while<> "Create a *while-loop symbol*." {:arglists '([bexpr body])} [bexpr body] `(czlab.basal.core/object<> WhileLoop :bexpr ~bexpr :body ~body :typeid :czlab.flux.core/while)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord SplitJoin [] Symbol (step-init [me step] (let [{:keys [impl wait-secs forks expiry]} me] (c/init step (->> (if-not (is-null-join? me) {:expiry expiry :impl impl :error nil :wait wait-secs :counter (AtomicInteger. 0)}) (merge {:forks (map #(wrap-symb?? %) forks)}))))) (step-reify [me nx] ;-we need a timer so that we don't wait forever ;in case some subtasks don't return. ;-this step is re-entrant. ;-we start off by forking off the set of subtasks, ;then wait for them to return. ;if time out occurs, this step ;is flagged as in error and may proceed differently ;depending on the error handling logic. ;-each subtask returning will up' the counter, ;and-join: wait for all to return, ;or-join: only one returning will proceed to next. (->> (if (is-null-join? me) {:action (fn [cur job] (fanout job (terminal-step<> job) (c/get-conf cur :forks)) (c/get-conf cur :next))} {:timer join-timer :action (fn [cur job] (let [{:keys [error wait impl forks]} (c/get-conf cur)] (cond (some? error) (c/do->nil (c/debug "too late.")) (number? forks) (impl cur) (empty? forks) (c/get-conf cur :next) (not-empty forks) (c/do->nil (fanout job cur forks) (c/set-conf cur :forks (n# forks)) (c/set-conf cur :alarm (sa! cur job wait))))))}) (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- nulljoin "Create a do-nothing *join task*." [branches] (c/object<> SplitJoin :typeid ::null-join :forks branches)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- andjoin "Create a *join(and) task*." [branches waitSecs expiry] (c/object<> SplitJoin :typeid ::and-join :forks branches :expiry expiry :wait-secs waitSecs :impl #(let [{:keys [counter forks alarm next]} (c/get-conf %) n (-> ^AtomicInteger counter .incrementAndGet)] (c/debug "andjoin: sub-task[%d] returned." n) (when (== n forks) (c/debug "andjoin: sub-tasks completed.") (some-> ^TimerTask alarm .cancel) (c/set-conf % :alarm nil) (rinit! %) next)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- orjoin "Create a *or join symbol*." [branches waitSecs expiry] (c/object<> SplitJoin :wait-secs waitSecs :typeid ::or-join :forks branches :expiry expiry :impl #(let [{:keys [counter next alarm]} (c/get-conf %) n (-> ^AtomicInteger counter .incrementAndGet)] (c/debug "orjoin: sub-task[%d] returned." n) (some-> ^TimerTask alarm .cancel) (c/set-conf % :alarm nil) (when (== n 1) (rinit! %) next)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Split [] Symbol (step-init [_ step] (let [{:keys [expiry forks options]} _ {:keys [type wait-secs]} options] (c/init step {:expiry (some-> expiry wrap-symb??) :wait (c/num?? wait-secs 0) :join-style type :forks (map #(wrap-symb?? %) forks)}))) (step-reify [me nx] (->> {:action (fn [cur _] (let [{:keys [join-style wait expiry next forks]} (c/get-conf cur)] (wrapc (cond (= :and join-style) (andjoin forks wait expiry) (= :or join-style) (orjoin forks wait expiry) :else (nulljoin forks)) next)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro split-join<> "Create a split-join." {:arglists '([bindings & forks])} [bindings & forks] (let [{:keys [type wait-secs] :as M} (apply array-map bindings) [a b] (take-last 2 forks) [exp args] (if (= a :expiry) [b (drop-last 2 forks)] [nil forks])] (assert (contains? #{:and :or} type)) (if wait-secs (assert (number? wait-secs))) (if (= a :expiry) (assert (some? exp))) (assert (not-empty args)) `(czlab.basal.core/object<> czlab.flux.core.Split :expiry ~exp :forks [~@args] :options ~M :typeid :czlab.flux.core/split))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro split<> "Create a split." {:arglists '([f1 & more])} [f1 & more] (let [forks (cons f1 more)] `(czlab.basal.core/object<> czlab.flux.core.Split :forks [~@forks] :typeid :czlab.flux.core/split))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Group [] Symbol (step-init [me step] (c/init step {:alist (map #(wrap-symb?? %) (:symbols me))})) (step-reify [me nx] ;iterate through the group, treating it like a ;queue, poping off one at a time. Each symbol ;pop'ed off will be run and will return back here ;for the next iteration to occur. We can do this ;by passing this group-step as the next step to ;be performed after the item is done. (->> {:action (fn [cur job] (let [[a & more] (c/get-conf cur :alist)] (if-some [s (some-> a (wrapc cur))] (do (c/set-conf cur :alist more) s) (do (rinit! cur) (c/get-conf cur :next)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro group<> "Create a group." {:arglists '([a & more])} [a & more] `(czlab.basal.core/object<> czlab.flux.core.Group :symbols [~a ~@more] :typeid :czlab.flux.core/group)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- range-expr [lower upper] (let [loopy (atom lower)] (c/fn_1 (let [job ____1 v @loopy] (if (< v upper) (swap! loopy #(do (c/setv job :$range-index v) (+ 1 %)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ForLoop [] Symbol (step-init [me step] (let [job (g-job step) {:keys [lower upper body]} me low (cond (number? lower) lower (fn? lower) (lower job)) high (cond (number? upper) upper (fn? upper) (upper job))] (assert (and (number? low) (number? high) (<= low high)) "for<>: Bad lower/upper bound.") (c/init step {:body (wrapc body step) :bexpr (range-expr low high)}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next bexpr body]} (c/get-conf cur)] (if-not (bexpr job) (do (rinit! cur) next) (c/do->nil (p/run (runner job) body)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro for<> "Create a for." {:arglists '([lower upper body])} [lower upper body] `(czlab.basal.core/object<> czlab.flux.core.ForLoop :lower ~lower :upper ~upper :body ~body :typeid :czlab.flux.core/for)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn job<> "Create a job context." {:arglists '([sch] [sch initObj] [sch initObj originObj])} ([_sch initObj] (job<> _sch initObj nil)) ([_sch] (job<> _sch nil nil)) ([_sch initObj originObj] (let [impl (atom {:last-result nil}) data (atom (or initObj {})) _id (str "job#" (u/seqint2))] (reify Job (runner [_] _sch) (wkflow [_] (:wflow @impl)) c/Configurable (set-conf [_ k v] _) (set-conf [me _] me) (get-conf [_] nil) (get-conf [_ k] (get @impl k)) c/Hierarchical ;where this job came from? (parent [_] originObj) c/Idable (id [_] _id) ;for app data c/Settable (unsetv [_ k] (swap! data dissoc k)) (setv [_ k v] (swap! data assoc k v)) c/Gettable (getv [_ k] (get @data k)) (has? [_ k] (contains? @data k)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wsexec "Apply workflow to this job." [ws job] (c/set-conf job :wflow ws) (p/run (runner job) (wrapc (:head ws) (terminal-step<> job)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WorkFlowExObj [] c/Catchable (catche [me e] ((:efn me) e)) WorkFlow (exec [me job] (wsexec me job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WorkFlowObj [] WorkFlow (exec [me job] (wsexec me job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn workflow<> "Creare workflow from a list of symbols." {:arglists '([symbols])} [symbols] {:pre [(sequential? symbols)]} ;;first we look for error handling which, ;;if defined, must be at the end of the args. (let [[a b] (take-last 2 symbols) [err syms] (if (and (fn? b) (= :catch a)) [b (drop-last 2 symbols)] [nil symbols]) head (c/object<> Group :symbols syms :typeid :group)] (if-not (fn? err) (c/object<> WorkFlowObj :head head) (c/object<> WorkFlowExObj :head head :efn err)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn workflow* "Create a work flow with the follwing syntax: (workflow<> symbol [symbol...] [:catch func])" {:arglists '([symbol0 & args])} [symbol0 & args] {:pre [(some? symbol0)]} (workflow<> (cons symbol0 args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.flux.core "A minimal worflow framework." (:require [clojure.java.io :as io] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.proc :as p] [czlab.basal.meta :as m] [czlab.basal.util :as u] [czlab.basal.core :as c :refer [n#]]) (:import [java.util.concurrent.atomic AtomicInteger] [java.util.concurrent TimeoutException] [java.util TimerTask])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol WorkFlow (exec [_ job] "Apply this workflow to the job.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Job (wkflow [_] "Return the workflow object.") (runner [_] "Return the executor.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Step "A step in the workflow." (g-job [_] "Get the job.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Symbol "A workflow symbol." (step-init [_ step] "Initialize the Step.") (step-reify [_ next] "Instantiate this Symbol.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defwflow "Define a workflow." {:arglists '([name & tasks])} [name & tasks] `(def ~name (czlab.flux.core/workflow<> [ ~@tasks ]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- csymb?? "Cast to a Symbol?" {:arglists '([a])} [a] `(let [x# ~a] (if (c/sas? Symbol x#) x#))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- cstep?? "Cast to a Step?" {:arglists '([a])} [a] `(let [x# ~a] (if (c/sas? Step x#) x#))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- is-null-join? [s] `(= (c/typeid ~s) ::null-join)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- err! [c e] `(array-map :step ~c :error ~e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare step-run-after step-run proto-step<>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- rinit! "Reset a step." [step] (if step (step-init (c/parent step) step))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Script [] Symbol (step-init [me step] (let [{:keys [work-func]} me [s _] (m/count-arity work-func)] (c/init step {:work work-func :arity s}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next work arity]} (c/get-conf cur) a (cond (c/in? arity 2) (work cur job) (c/in? arity 1) (work job) :else (u/throw-BadArg "Expected %s: on %s" "arity 2 or 1" (class work)))] (rinit! cur) (if-some [a' (csymb?? a)] (step-reify a' next) next)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (c/stror (:script me) (name (c/typeid me))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro script<> "Create a *scriptable symbol*." {:arglists '([workFunc] [workFunc script-name])} ([workFunc] `(script<> ~workFunc nil)) ([workFunc script-name] `(czlab.basal.core/object<> czlab.flux.core.Script :work-func ~workFunc :script ~script-name :typeid :czlab.flux.core/script))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn wrap-symb?? "If x is a function, wrapped it inside a script symbol*." {:arglists '([x])} [x] (cond (c/sas? Symbol x) x (fn? x) (script<> x) :else (u/throw-BadArg "bad param type: " (if (nil? x) "null" (class x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wrapc "Create a step from this Symbol" [x nxt] (-> x wrap-symb?? (step-reify nxt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fanout "Fork off tasks." [job nx defs] (let [cpu (runner job)] (c/debug "fanout: forking [%d] sub-tasks." (c/n# defs)) (doseq [t defs] (p/run cpu (wrapc t nx))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- sa! "Set alarm." [step job wsecs] (when (c/spos? wsecs) (p/alarm (runner job) (* 1000 wsecs) step job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- proto-step<> "Create a generic step object. We need to know the type of step to instantiate, and the step to call after this step is run." [proto n args] (let [_id (str "step#" (u/seqint2)) impl (atom (assoc args :next n))] (reify Step (g-job [_] (let [{:keys [job next]} @impl] (or job (g-job next)))) Runnable (run [_] (step-run _ (:action @impl))) c/Configurable (get-conf [_ k] (get @impl k)) (get-conf [_] @impl) (set-conf [_ x] _) (set-conf [_ k v] (swap! impl assoc k v) _) c/Idable (id [_] _id) c/Hierarchical (parent [_] proto) c/Initable (init [me m] (c/if-fn [f (:init-fn @impl)] (f me m) (swap! impl merge m)) me) c/Interruptable (interrupt [me job] (c/if-fn [f (:timer @impl)] (f me job)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Terminal [] Symbol (step-init [_ s] s) (step-reify [me nx] (u/throw-UOE "Cannot reify a terminal.")) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- terminal<> "*terminal*" [] (c/object<> Terminal :typeid ::terminal)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- terminal-step<> [job] {:pre [(some? job)]} (let [t (terminal<>)] (step-init t (proto-step<> t nil {:job job})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- step-run-after [orig arg] (let [par' (c/parent orig) job (g-job orig) cpu (runner job) step (if (csymb?? arg) (wrapc arg (terminal-step<> job)) arg)] (when (cstep?? step) (cond (= ::terminal (-> step c/parent c/typeid)) (c/debug "%s :-> terminal" (c/id par')) (c/is-valid? cpu) (do (c/debug "%s :-> %s" (c/id par') (c/id (c/parent step))) (p/run cpu step)) :else (c/debug "no-cpu, %s skipping %s" (c/id par') (c/id (c/parent step))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- step-run [step action] (let [job (g-job step) ws (wkflow job)] (step-run-after step (try (action step job) (catch Throwable e# (if-not (c/sas? c/Catchable ws) (c/do->nil (c/exception e#)) (u/try!!! (c/exception e#) (c/catche ws (err! step e#))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- join-timer [step job] (c/warn "%s: timer expired." (c/id (c/parent step))) (let [_ (->> (u/mono-flop<> true) (c/set-conf step :error)) e (csymb?? (c/get-conf step :expiry)) ws (wkflow job) n (when (and (nil? e) (c/sas? c/Catchable ws)) (->> (TimeoutException.) (err! step) (c/catche ws)))] (some->> (some-> (or e n) (wrapc (terminal-step<> job))) (p/run (runner job))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Postpone [] Symbol (step-init [me step] (c/init step {:delay (:delay-secs me)})) (step-reify [me nx] (->> {:action (fn [cur job] (c/do->nil (let [cpu (runner job) {:keys [next delay]} (c/get-conf cur)] (->> (c/num?? delay 0) (* 1000) (p/postpone cpu next)) (rinit! cur))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro postpone<> "Create a *delay symbol*." {:arglists '([delay-secs])} [delay-secs] `(czlab.basal.core/object<> czlab.flux.core.Postpone :delay-secs ~delay-secs :typeid :czlab.flux.core/delay)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Switch [] Symbol (step-init [_ step] (let [{:keys [choices cexpr default]} _ {:keys [next]} (c/get-conf step)] (c/init step {:dft (some-> default wrap-symb?? (wrapc next)) :cexpr cexpr :choices (c/preduce<vec> #(let [[k v] %2] (-> (conj! %1 k) (conj! (wrapc v next)))) (partition 2 choices))}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [cexpr dft choices]} (c/get-conf cur) m (cexpr job)] (rinit! cur) (or (if m (some #(if (= m (c/_1 %1)) (c/_E %1)) (partition 2 choices))) dft)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro choice<> "Create a *choice symbol*." {:arglists '([cexpr & choices])} [cexpr & choices] (let [[a b] (take-last 2 choices) [dft args] (if (and b (= a :default)) [b (drop-last 2 choices)] [nil choices])] `(czlab.basal.core/object<> czlab.flux.core.Switch :choices [~@args] :default ~dft :cexpr ~cexpr :typeid :czlab.flux.core/switch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Decision [] Symbol (step-init [me step] (c/init step (select-keys me [:bexpr :then :else]))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [bexpr next then else]} (c/get-conf cur)] (rinit! cur) (if (bexpr job) (wrapc then next) (wrapc else next))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro decision<> "Create a *decision symbol*." {:arglists '([bexpr then] [bexpr then else])} ([bexpr then] `(decision<> ~bexpr ~then nil)) ([bexpr then else] `(czlab.basal.core/object<> czlab.flux.core.Decision :bexpr ~bexpr :then ~then :else ~else :typeid :czlab.flux.core/decision))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WhileLoop [] Symbol (step-init [_ step] (let [{:keys [body bexpr]} _] (assert (fn? bexpr)) (c/init step {:bexpr bexpr :body (wrapc body step)}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next bexpr body]} (c/get-conf cur)] (if-not (bexpr job) (do (rinit! cur) next) (c/do->nil (p/run (runner job) body)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro while<> "Create a *while-loop symbol*." {:arglists '([bexpr body])} [bexpr body] `(czlab.basal.core/object<> WhileLoop :bexpr ~bexpr :body ~body :typeid :czlab.flux.core/while)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord SplitJoin [] Symbol (step-init [me step] (let [{:keys [impl wait-secs forks expiry]} me] (c/init step (->> (if-not (is-null-join? me) {:expiry expiry :impl impl :error nil :wait wait-secs :counter (AtomicInteger. 0)}) (merge {:forks (map #(wrap-symb?? %) forks)}))))) (step-reify [me nx] ;-we need a timer so that we don't wait forever ;in case some subtasks don't return. ;-this step is re-entrant. ;-we start off by forking off the set of subtasks, ;then wait for them to return. ;if time out occurs, this step ;is flagged as in error and may proceed differently ;depending on the error handling logic. ;-each subtask returning will up' the counter, ;and-join: wait for all to return, ;or-join: only one returning will proceed to next. (->> (if (is-null-join? me) {:action (fn [cur job] (fanout job (terminal-step<> job) (c/get-conf cur :forks)) (c/get-conf cur :next))} {:timer join-timer :action (fn [cur job] (let [{:keys [error wait impl forks]} (c/get-conf cur)] (cond (some? error) (c/do->nil (c/debug "too late.")) (number? forks) (impl cur) (empty? forks) (c/get-conf cur :next) (not-empty forks) (c/do->nil (fanout job cur forks) (c/set-conf cur :forks (n# forks)) (c/set-conf cur :alarm (sa! cur job wait))))))}) (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- nulljoin "Create a do-nothing *join task*." [branches] (c/object<> SplitJoin :typeid ::null-join :forks branches)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- andjoin "Create a *join(and) task*." [branches waitSecs expiry] (c/object<> SplitJoin :typeid ::and-join :forks branches :expiry expiry :wait-secs waitSecs :impl #(let [{:keys [counter forks alarm next]} (c/get-conf %) n (-> ^AtomicInteger counter .incrementAndGet)] (c/debug "andjoin: sub-task[%d] returned." n) (when (== n forks) (c/debug "andjoin: sub-tasks completed.") (some-> ^TimerTask alarm .cancel) (c/set-conf % :alarm nil) (rinit! %) next)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- orjoin "Create a *or join symbol*." [branches waitSecs expiry] (c/object<> SplitJoin :wait-secs waitSecs :typeid ::or-join :forks branches :expiry expiry :impl #(let [{:keys [counter next alarm]} (c/get-conf %) n (-> ^AtomicInteger counter .incrementAndGet)] (c/debug "orjoin: sub-task[%d] returned." n) (some-> ^TimerTask alarm .cancel) (c/set-conf % :alarm nil) (when (== n 1) (rinit! %) next)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Split [] Symbol (step-init [_ step] (let [{:keys [expiry forks options]} _ {:keys [type wait-secs]} options] (c/init step {:expiry (some-> expiry wrap-symb??) :wait (c/num?? wait-secs 0) :join-style type :forks (map #(wrap-symb?? %) forks)}))) (step-reify [me nx] (->> {:action (fn [cur _] (let [{:keys [join-style wait expiry next forks]} (c/get-conf cur)] (wrapc (cond (= :and join-style) (andjoin forks wait expiry) (= :or join-style) (orjoin forks wait expiry) :else (nulljoin forks)) next)))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro split-join<> "Create a split-join." {:arglists '([bindings & forks])} [bindings & forks] (let [{:keys [type wait-secs] :as M} (apply array-map bindings) [a b] (take-last 2 forks) [exp args] (if (= a :expiry) [b (drop-last 2 forks)] [nil forks])] (assert (contains? #{:and :or} type)) (if wait-secs (assert (number? wait-secs))) (if (= a :expiry) (assert (some? exp))) (assert (not-empty args)) `(czlab.basal.core/object<> czlab.flux.core.Split :expiry ~exp :forks [~@args] :options ~M :typeid :czlab.flux.core/split))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro split<> "Create a split." {:arglists '([f1 & more])} [f1 & more] (let [forks (cons f1 more)] `(czlab.basal.core/object<> czlab.flux.core.Split :forks [~@forks] :typeid :czlab.flux.core/split))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord Group [] Symbol (step-init [me step] (c/init step {:alist (map #(wrap-symb?? %) (:symbols me))})) (step-reify [me nx] ;iterate through the group, treating it like a ;queue, poping off one at a time. Each symbol ;pop'ed off will be run and will return back here ;for the next iteration to occur. We can do this ;by passing this group-step as the next step to ;be performed after the item is done. (->> {:action (fn [cur job] (let [[a & more] (c/get-conf cur :alist)] (if-some [s (some-> a (wrapc cur))] (do (c/set-conf cur :alist more) s) (do (rinit! cur) (c/get-conf cur :next)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro group<> "Create a group." {:arglists '([a & more])} [a & more] `(czlab.basal.core/object<> czlab.flux.core.Group :symbols [~a ~@more] :typeid :czlab.flux.core/group)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- range-expr [lower upper] (let [loopy (atom lower)] (c/fn_1 (let [job ____1 v @loopy] (if (< v upper) (swap! loopy #(do (c/setv job :$range-index v) (+ 1 %)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ForLoop [] Symbol (step-init [me step] (let [job (g-job step) {:keys [lower upper body]} me low (cond (number? lower) lower (fn? lower) (lower job)) high (cond (number? upper) upper (fn? upper) (upper job))] (assert (and (number? low) (number? high) (<= low high)) "for<>: Bad lower/upper bound.") (c/init step {:body (wrapc body step) :bexpr (range-expr low high)}))) (step-reify [me nx] (->> {:action (fn [cur job] (let [{:keys [next bexpr body]} (c/get-conf cur)] (if-not (bexpr job) (do (rinit! cur) next) (c/do->nil (p/run (runner job) body)))))} (proto-step<> me nx) (step-init me))) c/Typeable (typeid [_] (:typeid _)) c/Idable (id [me] (name (c/typeid me)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro for<> "Create a for." {:arglists '([lower upper body])} [lower upper body] `(czlab.basal.core/object<> czlab.flux.core.ForLoop :lower ~lower :upper ~upper :body ~body :typeid :czlab.flux.core/for)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn job<> "Create a job context." {:arglists '([sch] [sch initObj] [sch initObj originObj])} ([_sch initObj] (job<> _sch initObj nil)) ([_sch] (job<> _sch nil nil)) ([_sch initObj originObj] (let [impl (atom {:last-result nil}) data (atom (or initObj {})) _id (str "job#" (u/seqint2))] (reify Job (runner [_] _sch) (wkflow [_] (:wflow @impl)) c/Configurable (set-conf [_ k v] _) (set-conf [me _] me) (get-conf [_] nil) (get-conf [_ k] (get @impl k)) c/Hierarchical ;where this job came from? (parent [_] originObj) c/Idable (id [_] _id) ;for app data c/Settable (unsetv [_ k] (swap! data dissoc k)) (setv [_ k v] (swap! data assoc k v)) c/Gettable (getv [_ k] (get @data k)) (has? [_ k] (contains? @data k)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wsexec "Apply workflow to this job." [ws job] (c/set-conf job :wflow ws) (p/run (runner job) (wrapc (:head ws) (terminal-step<> job)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WorkFlowExObj [] c/Catchable (catche [me e] ((:efn me) e)) WorkFlow (exec [me job] (wsexec me job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord WorkFlowObj [] WorkFlow (exec [me job] (wsexec me job))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn workflow<> "Creare workflow from a list of symbols." {:arglists '([symbols])} [symbols] {:pre [(sequential? symbols)]} ;;first we look for error handling which, ;;if defined, must be at the end of the args. (let [[a b] (take-last 2 symbols) [err syms] (if (and (fn? b) (= :catch a)) [b (drop-last 2 symbols)] [nil symbols]) head (c/object<> Group :symbols syms :typeid :group)] (if-not (fn? err) (c/object<> WorkFlowObj :head head) (c/object<> WorkFlowExObj :head head :efn err)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn workflow* "Create a work flow with the follwing syntax: (workflow<> symbol [symbol...] [:catch func])" {:arglists '([symbol0 & args])} [symbol0 & args] {:pre [(some? symbol0)]} (workflow<> (cons symbol0 args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": " Test methods\n(let [private-patient {:id 1 :name \"Victor\" :document \"123456\"}\n plan-patient {:id 2 :n", "end": 1052, "score": 0.9992690086364746, "start": 1046, "tag": "NAME", "value": "Victor" }, { "context": "cument \"123456\"}\n plan-patient {:id 2 :name \"Fred\" :document \"987654\" :plan [:x-ray :ultrasound]}]\n", "end": 1111, "score": 0.9994351863861084, "start": 1107, "tag": "NAME", "value": "Fred" } ]
hospital_patient/src/hospital_patient/class5.clj
vgeorgo/courses-alura-clojure
0
(ns hospital-patient.class5 (:use clojure.pprint)) ; Returns anything that will be used to identify what method should be used. ; Using :keys to defined what method it will use. (defn type-of-authorization [request] (let [patient (:patient request) situation (:situation request)] (cond (= :urgent situation) :authorized (contains? patient :plan) :heath-insurance :else :private))) ; Defines a method that will have multiple implementations depending the result of the function ; 'type-of-authorization' (defmulti sign-authorization? type-of-authorization) ; Defining the methods based on the possible returns of 'type-of-authorization' (defmethod sign-authorization? :authorized [_] false) (defmethod sign-authorization? :private [request] (>= (:value request 0) 50)) (defmethod sign-authorization? :heath-insurance [request] (let [plan (:plan (:patient request)) procedure (:procedure request)] (not (some #(= % procedure) plan)))) ; Test methods (let [private-patient {:id 1 :name "Victor" :document "123456"} plan-patient {:id 2 :name "Fred" :document "987654" :plan [:x-ray :ultrasound]}] (println "Private patient normal sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :normal})) (println "Private patient normal sign 40? " (sign-authorization? {:patient private-patient, :value 40, :procedure :blood-sample})) (println "Private patient urgent sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :urgent})) (println "Plan patient normal sign x-ray? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :x-ray :situation :normal})) (println "Plan patient normal sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :normal})) (println "Plan patient urgent sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :urgent})))
91690
(ns hospital-patient.class5 (:use clojure.pprint)) ; Returns anything that will be used to identify what method should be used. ; Using :keys to defined what method it will use. (defn type-of-authorization [request] (let [patient (:patient request) situation (:situation request)] (cond (= :urgent situation) :authorized (contains? patient :plan) :heath-insurance :else :private))) ; Defines a method that will have multiple implementations depending the result of the function ; 'type-of-authorization' (defmulti sign-authorization? type-of-authorization) ; Defining the methods based on the possible returns of 'type-of-authorization' (defmethod sign-authorization? :authorized [_] false) (defmethod sign-authorization? :private [request] (>= (:value request 0) 50)) (defmethod sign-authorization? :heath-insurance [request] (let [plan (:plan (:patient request)) procedure (:procedure request)] (not (some #(= % procedure) plan)))) ; Test methods (let [private-patient {:id 1 :name "<NAME>" :document "123456"} plan-patient {:id 2 :name "<NAME>" :document "987654" :plan [:x-ray :ultrasound]}] (println "Private patient normal sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :normal})) (println "Private patient normal sign 40? " (sign-authorization? {:patient private-patient, :value 40, :procedure :blood-sample})) (println "Private patient urgent sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :urgent})) (println "Plan patient normal sign x-ray? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :x-ray :situation :normal})) (println "Plan patient normal sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :normal})) (println "Plan patient urgent sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :urgent})))
true
(ns hospital-patient.class5 (:use clojure.pprint)) ; Returns anything that will be used to identify what method should be used. ; Using :keys to defined what method it will use. (defn type-of-authorization [request] (let [patient (:patient request) situation (:situation request)] (cond (= :urgent situation) :authorized (contains? patient :plan) :heath-insurance :else :private))) ; Defines a method that will have multiple implementations depending the result of the function ; 'type-of-authorization' (defmulti sign-authorization? type-of-authorization) ; Defining the methods based on the possible returns of 'type-of-authorization' (defmethod sign-authorization? :authorized [_] false) (defmethod sign-authorization? :private [request] (>= (:value request 0) 50)) (defmethod sign-authorization? :heath-insurance [request] (let [plan (:plan (:patient request)) procedure (:procedure request)] (not (some #(= % procedure) plan)))) ; Test methods (let [private-patient {:id 1 :name "PI:NAME:<NAME>END_PI" :document "123456"} plan-patient {:id 2 :name "PI:NAME:<NAME>END_PI" :document "987654" :plan [:x-ray :ultrasound]}] (println "Private patient normal sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :normal})) (println "Private patient normal sign 40? " (sign-authorization? {:patient private-patient, :value 40, :procedure :blood-sample})) (println "Private patient urgent sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :urgent})) (println "Plan patient normal sign x-ray? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :x-ray :situation :normal})) (println "Plan patient normal sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :normal})) (println "Plan patient urgent sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :urgent})))
[ { "context": " :style {:-fx-font-size 24}\n :text (str bot-username)}\n {:fx/type :label\n :text \"Option", "end": 3971, "score": 0.9994063973426819, "start": 3959, "tag": "USERNAME", "value": "bot-username" }, { "context": "ption-change\n :bot-username bot-username\n :server-key server-key}\n ", "end": 4251, "score": 0.999646008014679, "start": 4239, "tag": "USERNAME", "value": "bot-username" }, { "context": "ailable-options\n :bot-username bot-username\n :channel-name channel-name\n ", "end": 4758, "score": 0.9996369481086731, "start": 4746, "tag": "USERNAME", "value": "bot-username" }, { "context": "/sub-val context get-in [:report-user server-key :username])\n message (fx/sub-val context get-in [:re", "end": 5369, "score": 0.9781003594398499, "start": 5361, "tag": "USERNAME", "value": "username" }, { "context": " :message message\n :username username}}\n {:fx/type :pane\n :h-box/hgr", "end": 7121, "score": 0.9829871654510498, "start": 7113, "tag": "USERNAME", "value": "username" }, { "context": "yers-table-impl\n [{:fx/keys [context]\n :keys [mod-name players server-key]}]\n (let [am-host (fx/sub-ctx", "end": 7424, "score": 0.892319917678833, "start": 7416, "tag": "KEY", "value": "mod-name" }, { "context": "er-key\n :username username}}])\n [{:fx/type :menu-item\n ", "end": 11806, "score": 0.9783987402915955, "start": 11798, "tag": "USERNAME", "value": "username" }, { "context": "nel-name\n :username username}}]\n (when (and host-username\n ", "end": 12113, "score": 0.6203016042709351, "start": 12105, "tag": "USERNAME", "value": "username" }, { "context": "name\n (= host-username username)\n (-> user :client-st", "end": 12214, "score": 0.8558166027069092, "start": 12206, "tag": "USERNAME", "value": "username" }, { "context": "er-key\n :username username}}\n {:fx/type :menu-item\n ", "end": 15585, "score": 0.9866589307785034, "start": 15577, "tag": "USERNAME", "value": "username" }, { "context": "er-key\n :username username}})]\n (when (contains? (:compflag", "end": 15848, "score": 0.9901999235153198, "start": 15840, "tag": "USERNAME", "value": "username" }, { "context": "er-key\n :username username}}]))}})))}\n :columns\n (concat\n ", "end": 16246, "score": 0.963452160358429, "start": 16238, "tag": "USERNAME", "value": "username" }, { "context": " (select-keys id [:bot-name :username]))\n :graphic\n ", "end": 18706, "score": 0.6478949785232544, "start": 18698, "tag": "USERNAME", "value": "username" }, { "context": "version\n :bot-username bot-name\n :server-key server-k", "end": 19193, "score": 0.8978509306907654, "start": 19185, "tag": "USERNAME", "value": "bot-name" }, { "context": "ser)\n am-host (= username host-username)]\n {:text \"\"\n ", "end": 21857, "score": 0.701470673084259, "start": 21844, "tag": "USERNAME", "value": "host-username" }, { "context": " [{:fx/type :table-column\n :text \"Ally\"\n :resizable false\n :pref", "end": 25349, "score": 0.9685791730880737, "start": 25345, "tag": "NAME", "value": "Ally" }, { "context": "reate-on-key-changed\n :key [(u/nickname i) increment-ids]\n :desc\n ", "end": 26171, "score": 0.6952655911445618, "start": 26161, "tag": "KEY", "value": "u/nickname" }, { "context": " :is-me (= (:username i) username)\n :is-bo", "end": 26576, "score": 0.6701622605323792, "start": 26568, "tag": "USERNAME", "value": "username" }, { "context": " :is-me (= (:username i) username)\n :is-", "end": 28598, "score": 0.5512122511863708, "start": 28590, "tag": "USERNAME", "value": "username" }, { "context": " (= (:username i) username)\n ", "end": 29134, "score": 0.5685157179832458, "start": 29133, "tag": "USERNAME", "value": "i" }, { "context": " (= (:username i) username)\n (", "end": 29144, "score": 0.8829057216644287, "start": 29136, "tag": "USERNAME", "value": "username" }, { "context": " (= (:username i) username)\n (", "end": 32445, "score": 0.6364859342575073, "start": 32437, "tag": "USERNAME", "value": "username" }, { "context": " :is-me (= (:username i) username)\n :is-", "end": 33856, "score": 0.8895124793052673, "start": 33848, "tag": "USERNAME", "value": "username" }, { "context": " (= (:username i) username)\n (", "end": 34343, "score": 0.8040288686752319, "start": 34335, "tag": "USERNAME", "value": "username" }, { "context": "create-on-key-changed\n :key (u/nickname i)\n :desc\n ", "end": 36539, "score": 0.9326908588409424, "start": 36527, "tag": "KEY", "value": "u/nickname i" } ]
src/clj/skylobby/fx/players_table.clj
badosu/skylobby
7
(ns skylobby.fx.players-table (:require [cljfx.api :as fx] [clojure.string :as string] java-time [skylobby.color :as color] skylobby.fx [skylobby.fx.color :as fx.color] [skylobby.fx.ext :refer [ext-recreate-on-key-changed ext-table-column-auto-size]] [skylobby.fx.flag-icon :as flag-icon] [skylobby.fx.font-icon :as font-icon] [skylobby.fx.spring-options :as fx.spring-options] [skylobby.fx.sub :as sub] [skylobby.fx.tooltip-nofocus :as tooltip-nofocus] [skylobby.util :as u] [spring-lobby.spring :as spring] [taoensso.timbre :as log] [taoensso.tufte :as tufte]) (:import (javafx.scene.input Clipboard ClipboardContent) (javafx.scene.paint Color))) (set! *warn-on-reflection* true) (def allyteam-colors (->> color/ffa-colors-web (map u/hex-color-to-css) (map-indexed vector) (into {}))) (def allyteam-javafx-colors (->> color/ffa-colors-web (map #(Color/web %)) (map-indexed vector) (into {}))) (def sort-playing (comp u/to-number not u/to-bool :mode :battle-status)) (def sort-bot (comp u/to-number :bot :client-status :user)) (def sort-ally (comp u/to-number :ally :battle-status)) (def sort-skill (comp (fnil - 0) u/parse-skill :skill)) (def sort-id (comp u/to-number :id :battle-status)) (def sort-side (comp u/to-number :side :battle-status)) (def sort-rank (comp (fnil - 0) u/to-number :rank :client-status :user)) (defn ai-options-window [{:fx/keys [context]}] (let [ show (boolean (fx/sub-val context :show-ai-options-window)) server-key (fx/sub-val context get-in [:ai-options :server-key]) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) channel-name (fx/sub-ctx context skylobby.fx/battle-channel-sub server-key) am-host (fx/sub-ctx context sub/am-host server-key) bot-name (fx/sub-val context get-in [:ai-options :bot-name]) bot-version (fx/sub-val context get-in [:ai-options :bot-version]) bot-username (fx/sub-val context get-in [:ai-options :bot-username]) current-options (fx/sub-val context get-in [:by-server server-key :battle :scripttags "game" "bots" bot-username "options"]) spring-root (fx/sub-ctx context sub/spring-root server-key) battle-id (fx/sub-val context get-in [:by-server server-key :battle :battle-id]) engine-version (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-version]) engine-details (fx/sub-ctx context sub/indexed-engine spring-root engine-version) engine-bots (:engine-bots engine-details) mod-name (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-modname]) indexed-mod (fx/sub-ctx context sub/indexed-mod spring-root mod-name) battle-mod-details (fx/sub-ctx context skylobby.fx/mod-details-sub indexed-mod) bots (concat engine-bots (->> battle-mod-details :luaai (map second) (map (fn [ai] {:bot-name (:name ai) :bot-version "<game>"})))) bot-options-map (->> bots (map (juxt (juxt :bot-name :bot-version) :bot-options)) (into {})) available-options (get bot-options-map [bot-name bot-version])] {:fx/type :stage :showing show :title (str u/app-name " AI Options") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-ai-options-window} :height 480 :width 600 :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root {:fx/type :v-box :style {:-fx-font-size 16} :children [ {:fx/type :label :style {:-fx-font-size 24} :text (str bot-username)} {:fx/type :label :text "Options:"} {:fx/type :v-box :children [ {:fx/type fx.spring-options/modoptions-view :event-data {:event/type :spring-lobby/aioption-change :bot-username bot-username :server-key server-key} :modoptions available-options :current-options current-options :server-key server-key :singleplayer (= server-key :local)}]} {:fx/type :button :style {:-fx-font-size 24} :text "Save" :on-action {:event/type :spring-lobby/save-aioptions :am-host am-host :available-options available-options :bot-username bot-username :channel-name channel-name :client-data client-data :current-options current-options}}]}}})) (defn report-user-window [{:fx/keys [context]}] (let [ show (boolean (fx/sub-val context :show-report-user-window)) server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) battle-id (fx/sub-val context get-in [:report-user server-key :battle-id]) username (fx/sub-val context get-in [:report-user server-key :username]) message (fx/sub-val context get-in [:report-user server-key :message])] {:fx/type :stage :showing show :title (str u/app-name " Report User") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-report-user-window} :height 480 :width 600 :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root {:fx/type :v-box :style {:-fx-font-size 20} :children [ {:fx/type :h-box :alignment :center :children [ {:fx/type :label :style {:-fx-font-size 24} :text " Report user: "} {:fx/type :label :style {:-fx-font-size 28} :text (str username)}]} {:fx/type :h-box :alignment :center :children [ {:fx/type :label :text (str " As " server-key)}]} {:fx/type :h-box :alignment :center :children [ {:fx/type :label :text (str " In battle id " battle-id)}]} {:fx/type :label :text " Reason:"} {:fx/type :text-area :v-box/vgrow :always :text (str message) :on-text-changed {:event/type :spring-lobby/assoc-in :path [:report-user server-key :message]}} {:fx/type :h-box :children [{:fx/type :button :text "Report" :on-action {:event/type :spring-lobby/send-user-report :battle-id battle-id :client-data client-data :message message :username username}} {:fx/type :pane :h-box/hgrow :always} {:fx/type :button :text "Cancel" :on-action {:event/type :spring-lobby/dissoc :key :show-report-user-window}}]}]}}})) (defn players-table-impl [{:fx/keys [context] :keys [mod-name players server-key]}] (let [am-host (fx/sub-ctx context sub/am-host server-key) am-spec (fx/sub-ctx context sub/am-spec server-key) battle-players-color-type (fx/sub-val context :battle-players-color-type) channel-name (fx/sub-ctx context skylobby.fx/battle-channel-sub server-key) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) host-ingame (fx/sub-ctx context sub/host-ingame server-key) host-username (fx/sub-ctx context sub/host-username server-key) ignore-users (fx/sub-val context :ignore-users) increment-ids (fx/sub-val context :increment-ids) players-table-columns (fx/sub-val context :players-table-columns) ready-on-unspec (fx/sub-val context :ready-on-unspec) scripttags (fx/sub-val context get-in [:by-server server-key :battle :scripttags]) battle-id (fx/sub-val context get-in [:by-server server-key :battle :battle-id]) mod-name (or mod-name (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-modname])) spring-root (fx/sub-ctx context sub/spring-root server-key) indexed-mod (fx/sub-ctx context sub/indexed-mod spring-root mod-name) battle-mod-details (fx/sub-ctx context skylobby.fx/mod-details-sub indexed-mod) sides (spring/mod-sides battle-mod-details) side-items (->> sides seq (sort-by first) (map second)) singleplayer (or (not server-key) (= :local server-key)) username (fx/sub-val context get-in [:by-server server-key :username]) players-with-skill (map (fn [{:keys [skill skilluncertainty username] :as player}] (let [username-lc (when username (string/lower-case username)) tags (get-in scripttags ["game" "players" username-lc]) uncertainty (or (try (u/to-number skilluncertainty) (catch Exception e (log/debug e "Error parsing skill uncertainty"))) (try (u/to-number (get tags "skilluncertainty")) (catch Exception e (log/debug e "Error parsing skill uncertainty"))) 3)] (assoc player :skill (or skill (get tags "skill")) :skilluncertainty uncertainty))) players) incrementing-cell (fn [id] {:text (if increment-ids (when-let [n (u/to-number id)] (str (inc n))) (str id))}) now (or (fx/sub-val context :now) (u/curr-millis)) sorm (if singleplayer "singleplayer" "multiplayer")] {:fx/type ext-recreate-on-key-changed :key players-table-columns :desc {:fx/type ext-table-column-auto-size :items (sort-by (juxt sort-playing sort-bot sort-ally sort-skill sort-id) players-with-skill) :desc {:fx/type :table-view :style-class ["table-view" "skylobby-players-" sorm] :column-resize-policy :unconstrained :style {:-fx-min-height 200} :row-factory {:fx/cell-type :table-row :describe (fn [{:keys [owner team-color username user]}] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :row { :context-menu {:fx/type :context-menu :style {:-fx-font-size 16} :items (concat [] (when (not owner) [ {:fx/type :menu-item :text "Message" :on-action {:event/type :spring-lobby/join-direct-message :server-key server-key :username username}}]) [{:fx/type :menu-item :text "Ring" :on-action {:event/type :spring-lobby/ring :client-data client-data :channel-name channel-name :username username}}] (when (and host-username (= host-username username) (-> user :client-status :bot)) (concat [{:fx/type :menu-item :text "!help" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!help" :server-key server-key}} {:fx/type :menu-item :text "!status battle" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!status battle" :server-key server-key}}] (if host-ingame [{:fx/type :menu-item :text "!status game" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!status game" :server-key server-key}}] [{:fx/type :menu-item :text "!stats" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!stats" :server-key server-key}}]))) (when (->> players (filter (comp #{host-username} :username)) first :user :client-status :bot) [{:fx/type :menu-item :text "!whois" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message (str "!whois " username) :server-key server-key}}]) [ {:fx/type :menu-item :text (str "User ID: " (-> user :user-id))} {:fx/type :menu-item :text (str "Copy color") :on-action (fn [_event] (let [clipboard (Clipboard/getSystemClipboard) content (ClipboardContent.) color (fx.color/spring-color-to-javafx team-color)] (.putString content (str color)) (.setContent clipboard content)))} (if (-> ignore-users (get server-key) (get username)) {:fx/type :menu-item :text "Unignore" :on-action {:event/type :spring-lobby/unignore-user :server-key server-key :username username}} {:fx/type :menu-item :text "Ignore" :on-action {:event/type :spring-lobby/ignore-user :server-key server-key :username username}})] (when (contains? (:compflags client-data) "teiserver") [{:fx/type :menu-item :text "Report" :on-action {:event/type :spring-lobby/show-report-user :battle-id battle-id :server-key server-key :username username}}]))}})))} :columns (concat [{:fx/type :table-column :text "Nickname" :resizable true :min-width 200 :cell-value-factory (juxt (comp (fnil string/lower-case "") u/nickname) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_nickname-lc nickname {:keys [ai-name ai-version bot-name owner] :as id}]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :nickname (let [not-spec (-> id :battle-status :mode u/to-bool) text-color-javafx (or (when not-spec (case battle-players-color-type "team" (get allyteam-javafx-colors (-> id :battle-status :ally)) "player" (-> id :team-color fx.color/spring-color-to-javafx) ; else nil)) Color/WHITE) text-color-css (-> text-color-javafx str u/hex-color-to-css)] {:text "" :tooltip {:fx/type tooltip-nofocus/lifecycle :show-delay skylobby.fx/tooltip-show-delay :style {:-fx-font-size 18} :text nickname} :graphic {:fx/type :h-box :alignment :center :children (concat (when (and username (not= username (:username id)) (or am-host (= owner username))) [ {:fx/type :button :on-action (merge {:event/type :spring-lobby/kick-battle :client-data client-data :singleplayer singleplayer} (select-keys id [:bot-name :username])) :graphic {:fx/type font-icon/lifecycle :icon-literal "mdi-account-remove:16:white"}} {:fx/type :button :on-action {:event/type :spring-lobby/show-ai-options-window :bot-name ai-name :bot-version ai-version :bot-username bot-name :server-key server-key} :graphic {:fx/type font-icon/lifecycle :icon-literal "mdi-settings:16:white"}}]) [{:fx/type :pane :style {:-fx-pref-width 8}} (merge {:fx/type :text :style-class ["text" (str "skylobby-players-" sorm "-nickname")] :effect {:fx/type :drop-shadow :color (if (color/dark? text-color-javafx) "#d5d5d5" "black") :radius 2 :spread 1} :text nickname :fill text-color-css :style (merge {:-fx-font-smoothing-type :gray} (when not-spec {:-fx-font-weight "bold"}))})])}}))))}}] (when (:skill players-table-columns) [{:fx/type :table-column :text "Skill" :resizable false :pref-width 80 :cell-value-factory (juxt sort-skill :skilluncertainty :skill) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ skilluncertainty skill]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :skill {:alignment :center-left :text (str skill " " (when (number? skilluncertainty) (apply str (repeat skilluncertainty "?"))))})))}}]) (when (:status players-table-columns) [{:fx/type :table-column :text "Status" :resizable false :pref-width 82 :cell-value-factory (juxt sort-playing (comp :ingame :client-status :user) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ {:keys [battle-status user username]}]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :status (let [client-status (:client-status user) am-host (= username host-username)] {:text "" :tooltip {:fx/type tooltip-nofocus/lifecycle :show-delay skylobby.fx/tooltip-show-delay :style {:-fx-font-size 16} :text (str (case (int (or (:sync battle-status) 0)) 1 "Synced" 2 "Unsynced" "Unknown sync") "\n" (if (u/to-bool (:mode battle-status)) "Playing" "Spectating") (when (u/to-bool (:mode battle-status)) (str "\n" (if (:ready battle-status) "Ready" "Unready"))) (when (:ingame client-status) "\nIn game") (when-let [away-start-time (:away-start-time user)] (when (and (:away client-status) away-start-time) (str "\nAway: " (let [diff (- now away-start-time)] (if (< diff 30000) " just now" (str " " (u/format-duration (java-time/duration (- now away-start-time) :millis)))))))))} :graphic {:fx/type :h-box :alignment :center-left :children (concat (when-not singleplayer [ {:fx/type font-icon/lifecycle :icon-literal (let [sync-status (int (or (:sync battle-status) 0))] (case sync-status 1 "mdi-sync:16:green" 2 "mdi-sync-off:16:red" ; else "mdi-sync-alert:16:yellow"))}]) [(cond (:bot client-status) {:fx/type font-icon/lifecycle :icon-literal "mdi-robot:16:grey"} (not (u/to-bool (:mode battle-status))) {:fx/type font-icon/lifecycle :icon-literal "mdi-magnify:16:white"} (:ready battle-status) {:fx/type font-icon/lifecycle :icon-literal "mdi-account-check:16:green"} am-host {:fx/type font-icon/lifecycle :icon-literal "mdi-account-key:16:orange"} :else {:fx/type font-icon/lifecycle :icon-literal "mdi-account:16:white"})] (when (:ingame client-status) [{:fx/type font-icon/lifecycle :icon-literal "mdi-sword:16:red"}]) (when (:away client-status) [{:fx/type font-icon/lifecycle :icon-literal "mdi-sleep:16:grey"}]))}}))))}}]) (when (:ally players-table-columns) [{:fx/type :table-column :text "Ally" :resizable false :pref-width 86 :cell-value-factory (juxt sort-playing sort-ally sort-skill sort-id u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_status _ally _skill _team _username i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :ally {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key [(u/nickname i) increment-ids] :desc {:fx/type :combo-box :value (-> i :battle-status :ally str) :on-value-changed {:event/type :spring-lobby/battle-ally-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :items (map str (take 16 (iterate inc 0))) :button-cell incrementing-cell :cell-factory {:fx/cell-type :list-cell :describe incrementing-cell} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}})))}}]) (when (:team players-table-columns) [{:fx/type :table-column :text "Team" :resizable false :pref-width 86 :cell-value-factory (juxt sort-playing sort-id sort-skill u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_play id _skill _username i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :team (let [items (map str (take 16 (iterate inc 0))) value (str id)] {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key [(u/nickname i) increment-ids] :desc {:fx/type :combo-box :value value :on-value-changed {:event/type :spring-lobby/battle-team-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :items items :button-cell incrementing-cell :cell-factory {:fx/cell-type :list-cell :describe incrementing-cell} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}}))))}}]) (when (:color players-table-columns) [{:fx/type :table-column :text "Color" :resizable false :pref-width 130 :cell-value-factory (juxt :team-color u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[team-color nickname i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :color {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key nickname :desc {:fx/type :color-picker :value (fx.color/spring-color-to-javafx team-color) :on-action {:event/type :spring-lobby/battle-color-action :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}})))}}]) (when (:spectator players-table-columns) [{:fx/type :table-column :text "Spectator" :resizable false :pref-width 80 :cell-value-factory (juxt sort-playing sort-skill u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :spectator (let [is-spec (-> i :battle-status :mode u/to-bool not boolean)] {:text "" :alignment :center :graphic {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :check-box :selected (boolean is-spec) :on-selected-changed {:event/type :spring-lobby/battle-spectate-change :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i :ready-on-unspec ready-on-unspec} :disable (or (not username) (not (or (and am-host (not is-spec)) (= (:username i) username) (= (:owner i) username))))}}}))))}}]) (when (:faction players-table-columns) [{:fx/type :table-column :text "Faction" :resizable false :pref-width 120 :cell-value-factory (juxt sort-playing sort-side sort-skill :username identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :faction {:text "" :graphic (if (seq side-items) {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :combo-box :value (->> i :battle-status :side (get sides) str) :on-value-changed {:event/type :spring-lobby/battle-side-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i :indexed-mod indexed-mod :sides sides} :items side-items :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}} {:fx/type :label :text "loading..."})})))}}]) (when (:rank players-table-columns) [{:fx/type :table-column :editable false :text "Rank" :pref-width 48 :resizable false :cell-value-factory (juxt sort-rank (comp u/to-number :rank :client-status :user)) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ rank]] {:text (str rank)})}}]) (when (:country players-table-columns) [{:fx/type :table-column :text "Country" :resizable false :pref-width 64 :cell-value-factory (comp :country :user) :cell-factory {:fx/cell-type :table-cell :describe (fn [country] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :flag {:text "" :graphic {:fx/type flag-icon/flag-icon :country-code country}})))}}]) (when (:bonus players-table-columns) [{:fx/type :table-column :text "Bonus" :resizable true :min-width 64 :pref-width 64 :cell-value-factory (juxt (comp str :handicap :battle-status) (comp :handicap :battle-status) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ bonus _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :bonus {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :text-field :disable (boolean am-spec) :text-formatter {:fx/type :text-formatter :value-converter :integer :value (int (or bonus 0)) :on-value-changed {:event/type :spring-lobby/battle-handicap-change :client-data (when-not singleplayer client-data) :is-bot (-> i :user :client-status :bot) :id i}}}}})))}}]))}}})) (defn players-table [state] (tufte/profile {:dynamic? true :id :skylobby/ui} (tufte/p :players-table (players-table-impl state))))
6331
(ns skylobby.fx.players-table (:require [cljfx.api :as fx] [clojure.string :as string] java-time [skylobby.color :as color] skylobby.fx [skylobby.fx.color :as fx.color] [skylobby.fx.ext :refer [ext-recreate-on-key-changed ext-table-column-auto-size]] [skylobby.fx.flag-icon :as flag-icon] [skylobby.fx.font-icon :as font-icon] [skylobby.fx.spring-options :as fx.spring-options] [skylobby.fx.sub :as sub] [skylobby.fx.tooltip-nofocus :as tooltip-nofocus] [skylobby.util :as u] [spring-lobby.spring :as spring] [taoensso.timbre :as log] [taoensso.tufte :as tufte]) (:import (javafx.scene.input Clipboard ClipboardContent) (javafx.scene.paint Color))) (set! *warn-on-reflection* true) (def allyteam-colors (->> color/ffa-colors-web (map u/hex-color-to-css) (map-indexed vector) (into {}))) (def allyteam-javafx-colors (->> color/ffa-colors-web (map #(Color/web %)) (map-indexed vector) (into {}))) (def sort-playing (comp u/to-number not u/to-bool :mode :battle-status)) (def sort-bot (comp u/to-number :bot :client-status :user)) (def sort-ally (comp u/to-number :ally :battle-status)) (def sort-skill (comp (fnil - 0) u/parse-skill :skill)) (def sort-id (comp u/to-number :id :battle-status)) (def sort-side (comp u/to-number :side :battle-status)) (def sort-rank (comp (fnil - 0) u/to-number :rank :client-status :user)) (defn ai-options-window [{:fx/keys [context]}] (let [ show (boolean (fx/sub-val context :show-ai-options-window)) server-key (fx/sub-val context get-in [:ai-options :server-key]) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) channel-name (fx/sub-ctx context skylobby.fx/battle-channel-sub server-key) am-host (fx/sub-ctx context sub/am-host server-key) bot-name (fx/sub-val context get-in [:ai-options :bot-name]) bot-version (fx/sub-val context get-in [:ai-options :bot-version]) bot-username (fx/sub-val context get-in [:ai-options :bot-username]) current-options (fx/sub-val context get-in [:by-server server-key :battle :scripttags "game" "bots" bot-username "options"]) spring-root (fx/sub-ctx context sub/spring-root server-key) battle-id (fx/sub-val context get-in [:by-server server-key :battle :battle-id]) engine-version (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-version]) engine-details (fx/sub-ctx context sub/indexed-engine spring-root engine-version) engine-bots (:engine-bots engine-details) mod-name (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-modname]) indexed-mod (fx/sub-ctx context sub/indexed-mod spring-root mod-name) battle-mod-details (fx/sub-ctx context skylobby.fx/mod-details-sub indexed-mod) bots (concat engine-bots (->> battle-mod-details :luaai (map second) (map (fn [ai] {:bot-name (:name ai) :bot-version "<game>"})))) bot-options-map (->> bots (map (juxt (juxt :bot-name :bot-version) :bot-options)) (into {})) available-options (get bot-options-map [bot-name bot-version])] {:fx/type :stage :showing show :title (str u/app-name " AI Options") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-ai-options-window} :height 480 :width 600 :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root {:fx/type :v-box :style {:-fx-font-size 16} :children [ {:fx/type :label :style {:-fx-font-size 24} :text (str bot-username)} {:fx/type :label :text "Options:"} {:fx/type :v-box :children [ {:fx/type fx.spring-options/modoptions-view :event-data {:event/type :spring-lobby/aioption-change :bot-username bot-username :server-key server-key} :modoptions available-options :current-options current-options :server-key server-key :singleplayer (= server-key :local)}]} {:fx/type :button :style {:-fx-font-size 24} :text "Save" :on-action {:event/type :spring-lobby/save-aioptions :am-host am-host :available-options available-options :bot-username bot-username :channel-name channel-name :client-data client-data :current-options current-options}}]}}})) (defn report-user-window [{:fx/keys [context]}] (let [ show (boolean (fx/sub-val context :show-report-user-window)) server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) battle-id (fx/sub-val context get-in [:report-user server-key :battle-id]) username (fx/sub-val context get-in [:report-user server-key :username]) message (fx/sub-val context get-in [:report-user server-key :message])] {:fx/type :stage :showing show :title (str u/app-name " Report User") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-report-user-window} :height 480 :width 600 :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root {:fx/type :v-box :style {:-fx-font-size 20} :children [ {:fx/type :h-box :alignment :center :children [ {:fx/type :label :style {:-fx-font-size 24} :text " Report user: "} {:fx/type :label :style {:-fx-font-size 28} :text (str username)}]} {:fx/type :h-box :alignment :center :children [ {:fx/type :label :text (str " As " server-key)}]} {:fx/type :h-box :alignment :center :children [ {:fx/type :label :text (str " In battle id " battle-id)}]} {:fx/type :label :text " Reason:"} {:fx/type :text-area :v-box/vgrow :always :text (str message) :on-text-changed {:event/type :spring-lobby/assoc-in :path [:report-user server-key :message]}} {:fx/type :h-box :children [{:fx/type :button :text "Report" :on-action {:event/type :spring-lobby/send-user-report :battle-id battle-id :client-data client-data :message message :username username}} {:fx/type :pane :h-box/hgrow :always} {:fx/type :button :text "Cancel" :on-action {:event/type :spring-lobby/dissoc :key :show-report-user-window}}]}]}}})) (defn players-table-impl [{:fx/keys [context] :keys [<KEY> players server-key]}] (let [am-host (fx/sub-ctx context sub/am-host server-key) am-spec (fx/sub-ctx context sub/am-spec server-key) battle-players-color-type (fx/sub-val context :battle-players-color-type) channel-name (fx/sub-ctx context skylobby.fx/battle-channel-sub server-key) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) host-ingame (fx/sub-ctx context sub/host-ingame server-key) host-username (fx/sub-ctx context sub/host-username server-key) ignore-users (fx/sub-val context :ignore-users) increment-ids (fx/sub-val context :increment-ids) players-table-columns (fx/sub-val context :players-table-columns) ready-on-unspec (fx/sub-val context :ready-on-unspec) scripttags (fx/sub-val context get-in [:by-server server-key :battle :scripttags]) battle-id (fx/sub-val context get-in [:by-server server-key :battle :battle-id]) mod-name (or mod-name (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-modname])) spring-root (fx/sub-ctx context sub/spring-root server-key) indexed-mod (fx/sub-ctx context sub/indexed-mod spring-root mod-name) battle-mod-details (fx/sub-ctx context skylobby.fx/mod-details-sub indexed-mod) sides (spring/mod-sides battle-mod-details) side-items (->> sides seq (sort-by first) (map second)) singleplayer (or (not server-key) (= :local server-key)) username (fx/sub-val context get-in [:by-server server-key :username]) players-with-skill (map (fn [{:keys [skill skilluncertainty username] :as player}] (let [username-lc (when username (string/lower-case username)) tags (get-in scripttags ["game" "players" username-lc]) uncertainty (or (try (u/to-number skilluncertainty) (catch Exception e (log/debug e "Error parsing skill uncertainty"))) (try (u/to-number (get tags "skilluncertainty")) (catch Exception e (log/debug e "Error parsing skill uncertainty"))) 3)] (assoc player :skill (or skill (get tags "skill")) :skilluncertainty uncertainty))) players) incrementing-cell (fn [id] {:text (if increment-ids (when-let [n (u/to-number id)] (str (inc n))) (str id))}) now (or (fx/sub-val context :now) (u/curr-millis)) sorm (if singleplayer "singleplayer" "multiplayer")] {:fx/type ext-recreate-on-key-changed :key players-table-columns :desc {:fx/type ext-table-column-auto-size :items (sort-by (juxt sort-playing sort-bot sort-ally sort-skill sort-id) players-with-skill) :desc {:fx/type :table-view :style-class ["table-view" "skylobby-players-" sorm] :column-resize-policy :unconstrained :style {:-fx-min-height 200} :row-factory {:fx/cell-type :table-row :describe (fn [{:keys [owner team-color username user]}] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :row { :context-menu {:fx/type :context-menu :style {:-fx-font-size 16} :items (concat [] (when (not owner) [ {:fx/type :menu-item :text "Message" :on-action {:event/type :spring-lobby/join-direct-message :server-key server-key :username username}}]) [{:fx/type :menu-item :text "Ring" :on-action {:event/type :spring-lobby/ring :client-data client-data :channel-name channel-name :username username}}] (when (and host-username (= host-username username) (-> user :client-status :bot)) (concat [{:fx/type :menu-item :text "!help" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!help" :server-key server-key}} {:fx/type :menu-item :text "!status battle" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!status battle" :server-key server-key}}] (if host-ingame [{:fx/type :menu-item :text "!status game" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!status game" :server-key server-key}}] [{:fx/type :menu-item :text "!stats" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!stats" :server-key server-key}}]))) (when (->> players (filter (comp #{host-username} :username)) first :user :client-status :bot) [{:fx/type :menu-item :text "!whois" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message (str "!whois " username) :server-key server-key}}]) [ {:fx/type :menu-item :text (str "User ID: " (-> user :user-id))} {:fx/type :menu-item :text (str "Copy color") :on-action (fn [_event] (let [clipboard (Clipboard/getSystemClipboard) content (ClipboardContent.) color (fx.color/spring-color-to-javafx team-color)] (.putString content (str color)) (.setContent clipboard content)))} (if (-> ignore-users (get server-key) (get username)) {:fx/type :menu-item :text "Unignore" :on-action {:event/type :spring-lobby/unignore-user :server-key server-key :username username}} {:fx/type :menu-item :text "Ignore" :on-action {:event/type :spring-lobby/ignore-user :server-key server-key :username username}})] (when (contains? (:compflags client-data) "teiserver") [{:fx/type :menu-item :text "Report" :on-action {:event/type :spring-lobby/show-report-user :battle-id battle-id :server-key server-key :username username}}]))}})))} :columns (concat [{:fx/type :table-column :text "Nickname" :resizable true :min-width 200 :cell-value-factory (juxt (comp (fnil string/lower-case "") u/nickname) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_nickname-lc nickname {:keys [ai-name ai-version bot-name owner] :as id}]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :nickname (let [not-spec (-> id :battle-status :mode u/to-bool) text-color-javafx (or (when not-spec (case battle-players-color-type "team" (get allyteam-javafx-colors (-> id :battle-status :ally)) "player" (-> id :team-color fx.color/spring-color-to-javafx) ; else nil)) Color/WHITE) text-color-css (-> text-color-javafx str u/hex-color-to-css)] {:text "" :tooltip {:fx/type tooltip-nofocus/lifecycle :show-delay skylobby.fx/tooltip-show-delay :style {:-fx-font-size 18} :text nickname} :graphic {:fx/type :h-box :alignment :center :children (concat (when (and username (not= username (:username id)) (or am-host (= owner username))) [ {:fx/type :button :on-action (merge {:event/type :spring-lobby/kick-battle :client-data client-data :singleplayer singleplayer} (select-keys id [:bot-name :username])) :graphic {:fx/type font-icon/lifecycle :icon-literal "mdi-account-remove:16:white"}} {:fx/type :button :on-action {:event/type :spring-lobby/show-ai-options-window :bot-name ai-name :bot-version ai-version :bot-username bot-name :server-key server-key} :graphic {:fx/type font-icon/lifecycle :icon-literal "mdi-settings:16:white"}}]) [{:fx/type :pane :style {:-fx-pref-width 8}} (merge {:fx/type :text :style-class ["text" (str "skylobby-players-" sorm "-nickname")] :effect {:fx/type :drop-shadow :color (if (color/dark? text-color-javafx) "#d5d5d5" "black") :radius 2 :spread 1} :text nickname :fill text-color-css :style (merge {:-fx-font-smoothing-type :gray} (when not-spec {:-fx-font-weight "bold"}))})])}}))))}}] (when (:skill players-table-columns) [{:fx/type :table-column :text "Skill" :resizable false :pref-width 80 :cell-value-factory (juxt sort-skill :skilluncertainty :skill) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ skilluncertainty skill]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :skill {:alignment :center-left :text (str skill " " (when (number? skilluncertainty) (apply str (repeat skilluncertainty "?"))))})))}}]) (when (:status players-table-columns) [{:fx/type :table-column :text "Status" :resizable false :pref-width 82 :cell-value-factory (juxt sort-playing (comp :ingame :client-status :user) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ {:keys [battle-status user username]}]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :status (let [client-status (:client-status user) am-host (= username host-username)] {:text "" :tooltip {:fx/type tooltip-nofocus/lifecycle :show-delay skylobby.fx/tooltip-show-delay :style {:-fx-font-size 16} :text (str (case (int (or (:sync battle-status) 0)) 1 "Synced" 2 "Unsynced" "Unknown sync") "\n" (if (u/to-bool (:mode battle-status)) "Playing" "Spectating") (when (u/to-bool (:mode battle-status)) (str "\n" (if (:ready battle-status) "Ready" "Unready"))) (when (:ingame client-status) "\nIn game") (when-let [away-start-time (:away-start-time user)] (when (and (:away client-status) away-start-time) (str "\nAway: " (let [diff (- now away-start-time)] (if (< diff 30000) " just now" (str " " (u/format-duration (java-time/duration (- now away-start-time) :millis)))))))))} :graphic {:fx/type :h-box :alignment :center-left :children (concat (when-not singleplayer [ {:fx/type font-icon/lifecycle :icon-literal (let [sync-status (int (or (:sync battle-status) 0))] (case sync-status 1 "mdi-sync:16:green" 2 "mdi-sync-off:16:red" ; else "mdi-sync-alert:16:yellow"))}]) [(cond (:bot client-status) {:fx/type font-icon/lifecycle :icon-literal "mdi-robot:16:grey"} (not (u/to-bool (:mode battle-status))) {:fx/type font-icon/lifecycle :icon-literal "mdi-magnify:16:white"} (:ready battle-status) {:fx/type font-icon/lifecycle :icon-literal "mdi-account-check:16:green"} am-host {:fx/type font-icon/lifecycle :icon-literal "mdi-account-key:16:orange"} :else {:fx/type font-icon/lifecycle :icon-literal "mdi-account:16:white"})] (when (:ingame client-status) [{:fx/type font-icon/lifecycle :icon-literal "mdi-sword:16:red"}]) (when (:away client-status) [{:fx/type font-icon/lifecycle :icon-literal "mdi-sleep:16:grey"}]))}}))))}}]) (when (:ally players-table-columns) [{:fx/type :table-column :text "<NAME>" :resizable false :pref-width 86 :cell-value-factory (juxt sort-playing sort-ally sort-skill sort-id u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_status _ally _skill _team _username i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :ally {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key [(<KEY> i) increment-ids] :desc {:fx/type :combo-box :value (-> i :battle-status :ally str) :on-value-changed {:event/type :spring-lobby/battle-ally-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :items (map str (take 16 (iterate inc 0))) :button-cell incrementing-cell :cell-factory {:fx/cell-type :list-cell :describe incrementing-cell} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}})))}}]) (when (:team players-table-columns) [{:fx/type :table-column :text "Team" :resizable false :pref-width 86 :cell-value-factory (juxt sort-playing sort-id sort-skill u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_play id _skill _username i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :team (let [items (map str (take 16 (iterate inc 0))) value (str id)] {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key [(u/nickname i) increment-ids] :desc {:fx/type :combo-box :value value :on-value-changed {:event/type :spring-lobby/battle-team-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :items items :button-cell incrementing-cell :cell-factory {:fx/cell-type :list-cell :describe incrementing-cell} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}}))))}}]) (when (:color players-table-columns) [{:fx/type :table-column :text "Color" :resizable false :pref-width 130 :cell-value-factory (juxt :team-color u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[team-color nickname i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :color {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key nickname :desc {:fx/type :color-picker :value (fx.color/spring-color-to-javafx team-color) :on-action {:event/type :spring-lobby/battle-color-action :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}})))}}]) (when (:spectator players-table-columns) [{:fx/type :table-column :text "Spectator" :resizable false :pref-width 80 :cell-value-factory (juxt sort-playing sort-skill u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :spectator (let [is-spec (-> i :battle-status :mode u/to-bool not boolean)] {:text "" :alignment :center :graphic {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :check-box :selected (boolean is-spec) :on-selected-changed {:event/type :spring-lobby/battle-spectate-change :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i :ready-on-unspec ready-on-unspec} :disable (or (not username) (not (or (and am-host (not is-spec)) (= (:username i) username) (= (:owner i) username))))}}}))))}}]) (when (:faction players-table-columns) [{:fx/type :table-column :text "Faction" :resizable false :pref-width 120 :cell-value-factory (juxt sort-playing sort-side sort-skill :username identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :faction {:text "" :graphic (if (seq side-items) {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :combo-box :value (->> i :battle-status :side (get sides) str) :on-value-changed {:event/type :spring-lobby/battle-side-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i :indexed-mod indexed-mod :sides sides} :items side-items :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}} {:fx/type :label :text "loading..."})})))}}]) (when (:rank players-table-columns) [{:fx/type :table-column :editable false :text "Rank" :pref-width 48 :resizable false :cell-value-factory (juxt sort-rank (comp u/to-number :rank :client-status :user)) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ rank]] {:text (str rank)})}}]) (when (:country players-table-columns) [{:fx/type :table-column :text "Country" :resizable false :pref-width 64 :cell-value-factory (comp :country :user) :cell-factory {:fx/cell-type :table-cell :describe (fn [country] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :flag {:text "" :graphic {:fx/type flag-icon/flag-icon :country-code country}})))}}]) (when (:bonus players-table-columns) [{:fx/type :table-column :text "Bonus" :resizable true :min-width 64 :pref-width 64 :cell-value-factory (juxt (comp str :handicap :battle-status) (comp :handicap :battle-status) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ bonus _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :bonus {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key (<KEY>) :desc {:fx/type :text-field :disable (boolean am-spec) :text-formatter {:fx/type :text-formatter :value-converter :integer :value (int (or bonus 0)) :on-value-changed {:event/type :spring-lobby/battle-handicap-change :client-data (when-not singleplayer client-data) :is-bot (-> i :user :client-status :bot) :id i}}}}})))}}]))}}})) (defn players-table [state] (tufte/profile {:dynamic? true :id :skylobby/ui} (tufte/p :players-table (players-table-impl state))))
true
(ns skylobby.fx.players-table (:require [cljfx.api :as fx] [clojure.string :as string] java-time [skylobby.color :as color] skylobby.fx [skylobby.fx.color :as fx.color] [skylobby.fx.ext :refer [ext-recreate-on-key-changed ext-table-column-auto-size]] [skylobby.fx.flag-icon :as flag-icon] [skylobby.fx.font-icon :as font-icon] [skylobby.fx.spring-options :as fx.spring-options] [skylobby.fx.sub :as sub] [skylobby.fx.tooltip-nofocus :as tooltip-nofocus] [skylobby.util :as u] [spring-lobby.spring :as spring] [taoensso.timbre :as log] [taoensso.tufte :as tufte]) (:import (javafx.scene.input Clipboard ClipboardContent) (javafx.scene.paint Color))) (set! *warn-on-reflection* true) (def allyteam-colors (->> color/ffa-colors-web (map u/hex-color-to-css) (map-indexed vector) (into {}))) (def allyteam-javafx-colors (->> color/ffa-colors-web (map #(Color/web %)) (map-indexed vector) (into {}))) (def sort-playing (comp u/to-number not u/to-bool :mode :battle-status)) (def sort-bot (comp u/to-number :bot :client-status :user)) (def sort-ally (comp u/to-number :ally :battle-status)) (def sort-skill (comp (fnil - 0) u/parse-skill :skill)) (def sort-id (comp u/to-number :id :battle-status)) (def sort-side (comp u/to-number :side :battle-status)) (def sort-rank (comp (fnil - 0) u/to-number :rank :client-status :user)) (defn ai-options-window [{:fx/keys [context]}] (let [ show (boolean (fx/sub-val context :show-ai-options-window)) server-key (fx/sub-val context get-in [:ai-options :server-key]) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) channel-name (fx/sub-ctx context skylobby.fx/battle-channel-sub server-key) am-host (fx/sub-ctx context sub/am-host server-key) bot-name (fx/sub-val context get-in [:ai-options :bot-name]) bot-version (fx/sub-val context get-in [:ai-options :bot-version]) bot-username (fx/sub-val context get-in [:ai-options :bot-username]) current-options (fx/sub-val context get-in [:by-server server-key :battle :scripttags "game" "bots" bot-username "options"]) spring-root (fx/sub-ctx context sub/spring-root server-key) battle-id (fx/sub-val context get-in [:by-server server-key :battle :battle-id]) engine-version (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-version]) engine-details (fx/sub-ctx context sub/indexed-engine spring-root engine-version) engine-bots (:engine-bots engine-details) mod-name (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-modname]) indexed-mod (fx/sub-ctx context sub/indexed-mod spring-root mod-name) battle-mod-details (fx/sub-ctx context skylobby.fx/mod-details-sub indexed-mod) bots (concat engine-bots (->> battle-mod-details :luaai (map second) (map (fn [ai] {:bot-name (:name ai) :bot-version "<game>"})))) bot-options-map (->> bots (map (juxt (juxt :bot-name :bot-version) :bot-options)) (into {})) available-options (get bot-options-map [bot-name bot-version])] {:fx/type :stage :showing show :title (str u/app-name " AI Options") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-ai-options-window} :height 480 :width 600 :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root {:fx/type :v-box :style {:-fx-font-size 16} :children [ {:fx/type :label :style {:-fx-font-size 24} :text (str bot-username)} {:fx/type :label :text "Options:"} {:fx/type :v-box :children [ {:fx/type fx.spring-options/modoptions-view :event-data {:event/type :spring-lobby/aioption-change :bot-username bot-username :server-key server-key} :modoptions available-options :current-options current-options :server-key server-key :singleplayer (= server-key :local)}]} {:fx/type :button :style {:-fx-font-size 24} :text "Save" :on-action {:event/type :spring-lobby/save-aioptions :am-host am-host :available-options available-options :bot-username bot-username :channel-name channel-name :client-data client-data :current-options current-options}}]}}})) (defn report-user-window [{:fx/keys [context]}] (let [ show (boolean (fx/sub-val context :show-report-user-window)) server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) battle-id (fx/sub-val context get-in [:report-user server-key :battle-id]) username (fx/sub-val context get-in [:report-user server-key :username]) message (fx/sub-val context get-in [:report-user server-key :message])] {:fx/type :stage :showing show :title (str u/app-name " Report User") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-report-user-window} :height 480 :width 600 :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root {:fx/type :v-box :style {:-fx-font-size 20} :children [ {:fx/type :h-box :alignment :center :children [ {:fx/type :label :style {:-fx-font-size 24} :text " Report user: "} {:fx/type :label :style {:-fx-font-size 28} :text (str username)}]} {:fx/type :h-box :alignment :center :children [ {:fx/type :label :text (str " As " server-key)}]} {:fx/type :h-box :alignment :center :children [ {:fx/type :label :text (str " In battle id " battle-id)}]} {:fx/type :label :text " Reason:"} {:fx/type :text-area :v-box/vgrow :always :text (str message) :on-text-changed {:event/type :spring-lobby/assoc-in :path [:report-user server-key :message]}} {:fx/type :h-box :children [{:fx/type :button :text "Report" :on-action {:event/type :spring-lobby/send-user-report :battle-id battle-id :client-data client-data :message message :username username}} {:fx/type :pane :h-box/hgrow :always} {:fx/type :button :text "Cancel" :on-action {:event/type :spring-lobby/dissoc :key :show-report-user-window}}]}]}}})) (defn players-table-impl [{:fx/keys [context] :keys [PI:KEY:<KEY>END_PI players server-key]}] (let [am-host (fx/sub-ctx context sub/am-host server-key) am-spec (fx/sub-ctx context sub/am-spec server-key) battle-players-color-type (fx/sub-val context :battle-players-color-type) channel-name (fx/sub-ctx context skylobby.fx/battle-channel-sub server-key) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) host-ingame (fx/sub-ctx context sub/host-ingame server-key) host-username (fx/sub-ctx context sub/host-username server-key) ignore-users (fx/sub-val context :ignore-users) increment-ids (fx/sub-val context :increment-ids) players-table-columns (fx/sub-val context :players-table-columns) ready-on-unspec (fx/sub-val context :ready-on-unspec) scripttags (fx/sub-val context get-in [:by-server server-key :battle :scripttags]) battle-id (fx/sub-val context get-in [:by-server server-key :battle :battle-id]) mod-name (or mod-name (fx/sub-val context get-in [:by-server server-key :battles battle-id :battle-modname])) spring-root (fx/sub-ctx context sub/spring-root server-key) indexed-mod (fx/sub-ctx context sub/indexed-mod spring-root mod-name) battle-mod-details (fx/sub-ctx context skylobby.fx/mod-details-sub indexed-mod) sides (spring/mod-sides battle-mod-details) side-items (->> sides seq (sort-by first) (map second)) singleplayer (or (not server-key) (= :local server-key)) username (fx/sub-val context get-in [:by-server server-key :username]) players-with-skill (map (fn [{:keys [skill skilluncertainty username] :as player}] (let [username-lc (when username (string/lower-case username)) tags (get-in scripttags ["game" "players" username-lc]) uncertainty (or (try (u/to-number skilluncertainty) (catch Exception e (log/debug e "Error parsing skill uncertainty"))) (try (u/to-number (get tags "skilluncertainty")) (catch Exception e (log/debug e "Error parsing skill uncertainty"))) 3)] (assoc player :skill (or skill (get tags "skill")) :skilluncertainty uncertainty))) players) incrementing-cell (fn [id] {:text (if increment-ids (when-let [n (u/to-number id)] (str (inc n))) (str id))}) now (or (fx/sub-val context :now) (u/curr-millis)) sorm (if singleplayer "singleplayer" "multiplayer")] {:fx/type ext-recreate-on-key-changed :key players-table-columns :desc {:fx/type ext-table-column-auto-size :items (sort-by (juxt sort-playing sort-bot sort-ally sort-skill sort-id) players-with-skill) :desc {:fx/type :table-view :style-class ["table-view" "skylobby-players-" sorm] :column-resize-policy :unconstrained :style {:-fx-min-height 200} :row-factory {:fx/cell-type :table-row :describe (fn [{:keys [owner team-color username user]}] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :row { :context-menu {:fx/type :context-menu :style {:-fx-font-size 16} :items (concat [] (when (not owner) [ {:fx/type :menu-item :text "Message" :on-action {:event/type :spring-lobby/join-direct-message :server-key server-key :username username}}]) [{:fx/type :menu-item :text "Ring" :on-action {:event/type :spring-lobby/ring :client-data client-data :channel-name channel-name :username username}}] (when (and host-username (= host-username username) (-> user :client-status :bot)) (concat [{:fx/type :menu-item :text "!help" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!help" :server-key server-key}} {:fx/type :menu-item :text "!status battle" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!status battle" :server-key server-key}}] (if host-ingame [{:fx/type :menu-item :text "!status game" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!status game" :server-key server-key}}] [{:fx/type :menu-item :text "!stats" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message "!stats" :server-key server-key}}]))) (when (->> players (filter (comp #{host-username} :username)) first :user :client-status :bot) [{:fx/type :menu-item :text "!whois" :on-action {:event/type :spring-lobby/send-message :client-data client-data :channel-name (u/user-channel-name host-username) :message (str "!whois " username) :server-key server-key}}]) [ {:fx/type :menu-item :text (str "User ID: " (-> user :user-id))} {:fx/type :menu-item :text (str "Copy color") :on-action (fn [_event] (let [clipboard (Clipboard/getSystemClipboard) content (ClipboardContent.) color (fx.color/spring-color-to-javafx team-color)] (.putString content (str color)) (.setContent clipboard content)))} (if (-> ignore-users (get server-key) (get username)) {:fx/type :menu-item :text "Unignore" :on-action {:event/type :spring-lobby/unignore-user :server-key server-key :username username}} {:fx/type :menu-item :text "Ignore" :on-action {:event/type :spring-lobby/ignore-user :server-key server-key :username username}})] (when (contains? (:compflags client-data) "teiserver") [{:fx/type :menu-item :text "Report" :on-action {:event/type :spring-lobby/show-report-user :battle-id battle-id :server-key server-key :username username}}]))}})))} :columns (concat [{:fx/type :table-column :text "Nickname" :resizable true :min-width 200 :cell-value-factory (juxt (comp (fnil string/lower-case "") u/nickname) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_nickname-lc nickname {:keys [ai-name ai-version bot-name owner] :as id}]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :nickname (let [not-spec (-> id :battle-status :mode u/to-bool) text-color-javafx (or (when not-spec (case battle-players-color-type "team" (get allyteam-javafx-colors (-> id :battle-status :ally)) "player" (-> id :team-color fx.color/spring-color-to-javafx) ; else nil)) Color/WHITE) text-color-css (-> text-color-javafx str u/hex-color-to-css)] {:text "" :tooltip {:fx/type tooltip-nofocus/lifecycle :show-delay skylobby.fx/tooltip-show-delay :style {:-fx-font-size 18} :text nickname} :graphic {:fx/type :h-box :alignment :center :children (concat (when (and username (not= username (:username id)) (or am-host (= owner username))) [ {:fx/type :button :on-action (merge {:event/type :spring-lobby/kick-battle :client-data client-data :singleplayer singleplayer} (select-keys id [:bot-name :username])) :graphic {:fx/type font-icon/lifecycle :icon-literal "mdi-account-remove:16:white"}} {:fx/type :button :on-action {:event/type :spring-lobby/show-ai-options-window :bot-name ai-name :bot-version ai-version :bot-username bot-name :server-key server-key} :graphic {:fx/type font-icon/lifecycle :icon-literal "mdi-settings:16:white"}}]) [{:fx/type :pane :style {:-fx-pref-width 8}} (merge {:fx/type :text :style-class ["text" (str "skylobby-players-" sorm "-nickname")] :effect {:fx/type :drop-shadow :color (if (color/dark? text-color-javafx) "#d5d5d5" "black") :radius 2 :spread 1} :text nickname :fill text-color-css :style (merge {:-fx-font-smoothing-type :gray} (when not-spec {:-fx-font-weight "bold"}))})])}}))))}}] (when (:skill players-table-columns) [{:fx/type :table-column :text "Skill" :resizable false :pref-width 80 :cell-value-factory (juxt sort-skill :skilluncertainty :skill) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ skilluncertainty skill]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :skill {:alignment :center-left :text (str skill " " (when (number? skilluncertainty) (apply str (repeat skilluncertainty "?"))))})))}}]) (when (:status players-table-columns) [{:fx/type :table-column :text "Status" :resizable false :pref-width 82 :cell-value-factory (juxt sort-playing (comp :ingame :client-status :user) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ {:keys [battle-status user username]}]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :status (let [client-status (:client-status user) am-host (= username host-username)] {:text "" :tooltip {:fx/type tooltip-nofocus/lifecycle :show-delay skylobby.fx/tooltip-show-delay :style {:-fx-font-size 16} :text (str (case (int (or (:sync battle-status) 0)) 1 "Synced" 2 "Unsynced" "Unknown sync") "\n" (if (u/to-bool (:mode battle-status)) "Playing" "Spectating") (when (u/to-bool (:mode battle-status)) (str "\n" (if (:ready battle-status) "Ready" "Unready"))) (when (:ingame client-status) "\nIn game") (when-let [away-start-time (:away-start-time user)] (when (and (:away client-status) away-start-time) (str "\nAway: " (let [diff (- now away-start-time)] (if (< diff 30000) " just now" (str " " (u/format-duration (java-time/duration (- now away-start-time) :millis)))))))))} :graphic {:fx/type :h-box :alignment :center-left :children (concat (when-not singleplayer [ {:fx/type font-icon/lifecycle :icon-literal (let [sync-status (int (or (:sync battle-status) 0))] (case sync-status 1 "mdi-sync:16:green" 2 "mdi-sync-off:16:red" ; else "mdi-sync-alert:16:yellow"))}]) [(cond (:bot client-status) {:fx/type font-icon/lifecycle :icon-literal "mdi-robot:16:grey"} (not (u/to-bool (:mode battle-status))) {:fx/type font-icon/lifecycle :icon-literal "mdi-magnify:16:white"} (:ready battle-status) {:fx/type font-icon/lifecycle :icon-literal "mdi-account-check:16:green"} am-host {:fx/type font-icon/lifecycle :icon-literal "mdi-account-key:16:orange"} :else {:fx/type font-icon/lifecycle :icon-literal "mdi-account:16:white"})] (when (:ingame client-status) [{:fx/type font-icon/lifecycle :icon-literal "mdi-sword:16:red"}]) (when (:away client-status) [{:fx/type font-icon/lifecycle :icon-literal "mdi-sleep:16:grey"}]))}}))))}}]) (when (:ally players-table-columns) [{:fx/type :table-column :text "PI:NAME:<NAME>END_PI" :resizable false :pref-width 86 :cell-value-factory (juxt sort-playing sort-ally sort-skill sort-id u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_status _ally _skill _team _username i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :ally {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key [(PI:KEY:<KEY>END_PI i) increment-ids] :desc {:fx/type :combo-box :value (-> i :battle-status :ally str) :on-value-changed {:event/type :spring-lobby/battle-ally-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :items (map str (take 16 (iterate inc 0))) :button-cell incrementing-cell :cell-factory {:fx/cell-type :list-cell :describe incrementing-cell} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}})))}}]) (when (:team players-table-columns) [{:fx/type :table-column :text "Team" :resizable false :pref-width 86 :cell-value-factory (juxt sort-playing sort-id sort-skill u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_play id _skill _username i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :team (let [items (map str (take 16 (iterate inc 0))) value (str id)] {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key [(u/nickname i) increment-ids] :desc {:fx/type :combo-box :value value :on-value-changed {:event/type :spring-lobby/battle-team-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :items items :button-cell incrementing-cell :cell-factory {:fx/cell-type :list-cell :describe incrementing-cell} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}}))))}}]) (when (:color players-table-columns) [{:fx/type :table-column :text "Color" :resizable false :pref-width 130 :cell-value-factory (juxt :team-color u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[team-color nickname i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :color {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key nickname :desc {:fx/type :color-picker :value (fx.color/spring-color-to-javafx team-color) :on-action {:event/type :spring-lobby/battle-color-action :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i} :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}}})))}}]) (when (:spectator players-table-columns) [{:fx/type :table-column :text "Spectator" :resizable false :pref-width 80 :cell-value-factory (juxt sort-playing sort-skill u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :spectator (let [is-spec (-> i :battle-status :mode u/to-bool not boolean)] {:text "" :alignment :center :graphic {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :check-box :selected (boolean is-spec) :on-selected-changed {:event/type :spring-lobby/battle-spectate-change :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i :ready-on-unspec ready-on-unspec} :disable (or (not username) (not (or (and am-host (not is-spec)) (= (:username i) username) (= (:owner i) username))))}}}))))}}]) (when (:faction players-table-columns) [{:fx/type :table-column :text "Faction" :resizable false :pref-width 120 :cell-value-factory (juxt sort-playing sort-side sort-skill :username identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ _ _ _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :faction {:text "" :graphic (if (seq side-items) {:fx/type ext-recreate-on-key-changed :key (u/nickname i) :desc {:fx/type :combo-box :value (->> i :battle-status :side (get sides) str) :on-value-changed {:event/type :spring-lobby/battle-side-changed :client-data (when-not singleplayer client-data) :is-me (= (:username i) username) :is-bot (-> i :user :client-status :bot) :id i :indexed-mod indexed-mod :sides sides} :items side-items :disable (or (not username) (not (or am-host (= (:username i) username) (= (:owner i) username))))}} {:fx/type :label :text "loading..."})})))}}]) (when (:rank players-table-columns) [{:fx/type :table-column :editable false :text "Rank" :pref-width 48 :resizable false :cell-value-factory (juxt sort-rank (comp u/to-number :rank :client-status :user)) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ rank]] {:text (str rank)})}}]) (when (:country players-table-columns) [{:fx/type :table-column :text "Country" :resizable false :pref-width 64 :cell-value-factory (comp :country :user) :cell-factory {:fx/cell-type :table-cell :describe (fn [country] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :flag {:text "" :graphic {:fx/type flag-icon/flag-icon :country-code country}})))}}]) (when (:bonus players-table-columns) [{:fx/type :table-column :text "Bonus" :resizable true :min-width 64 :pref-width 64 :cell-value-factory (juxt (comp str :handicap :battle-status) (comp :handicap :battle-status) u/nickname identity) :cell-factory {:fx/cell-type :table-cell :describe (fn [[_ bonus _ i]] (tufte/profile {:dynamic? true :id :skylobby/player-table} (tufte/p :bonus {:text "" :graphic {:fx/type ext-recreate-on-key-changed :key (PI:KEY:<KEY>END_PI) :desc {:fx/type :text-field :disable (boolean am-spec) :text-formatter {:fx/type :text-formatter :value-converter :integer :value (int (or bonus 0)) :on-value-changed {:event/type :spring-lobby/battle-handicap-change :client-data (when-not singleplayer client-data) :is-bot (-> i :user :client-status :bot) :id i}}}}})))}}]))}}})) (defn players-table [state] (tufte/profile {:dynamic? true :id :skylobby/ui} (tufte/p :players-table (players-table-impl state))))
[ { "context": "ap! persons-atom assoc\n email {:first-name first-name\n :last-name last-name\n ", "end": 188, "score": 0.9396047592163086, "start": 183, "tag": "NAME", "value": "first" }, { "context": "first-name first-name\n :last-name last-name\n :city city\n :", "end": 227, "score": 0.938193678855896, "start": 223, "tag": "NAME", "value": "last" }, { "context": "name first-name\n :last-name last-name\n :city city\n :stree", "end": 232, "score": 0.505570650100708, "start": 228, "tag": "NAME", "value": "name" }, { "context": " ))\n\n(defn first-name\n [email]\n (:first-name (@persons-atom email)))\n\n(defn last-name\n [email]\n (:last", "end": 437, "score": 0.5686737895011902, "start": 428, "tag": "USERNAME", "value": "(@persons" }, { "context": " email)))\n\n(defn last-name\n [email]\n (:last-name (@persons-atom email)))\n\n(defn address\n [email]\n (str (:c", "end": 502, "score": 0.5986555814743042, "start": 493, "tag": "USERNAME", "value": "(@persons" } ]
fp/src/fp/db.clj
Skrzetuski/functional-programming
0
(ns fp.db) (defonce persons-atom (atom {})) (defn add-person! [email first-name last-name city street nr-street post-code] (swap! persons-atom assoc email {:first-name first-name :last-name last-name :city city :street street :nr-street nr-street :post-code post-code} )) (defn first-name [email] (:first-name (@persons-atom email))) (defn last-name [email] (:last-name (@persons-atom email))) (defn address [email] (str (:city (@persons-atom email)) ", ul. " (:street (@persons-atom email)) " " (:nr-street (@persons-atom email)) " " (:post-code (@persons-atom email))))
72825
(ns fp.db) (defonce persons-atom (atom {})) (defn add-person! [email first-name last-name city street nr-street post-code] (swap! persons-atom assoc email {:first-name <NAME>-name :last-name <NAME>-<NAME> :city city :street street :nr-street nr-street :post-code post-code} )) (defn first-name [email] (:first-name (@persons-atom email))) (defn last-name [email] (:last-name (@persons-atom email))) (defn address [email] (str (:city (@persons-atom email)) ", ul. " (:street (@persons-atom email)) " " (:nr-street (@persons-atom email)) " " (:post-code (@persons-atom email))))
true
(ns fp.db) (defonce persons-atom (atom {})) (defn add-person! [email first-name last-name city street nr-street post-code] (swap! persons-atom assoc email {:first-name PI:NAME:<NAME>END_PI-name :last-name PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI :city city :street street :nr-street nr-street :post-code post-code} )) (defn first-name [email] (:first-name (@persons-atom email))) (defn last-name [email] (:last-name (@persons-atom email))) (defn address [email] (str (:city (@persons-atom email)) ", ul. " (:street (@persons-atom email)) " " (:nr-street (@persons-atom email)) " " (:post-code (@persons-atom email))))
[ { "context": "/set\n :zeno/path [:zeno/crdt \"Alice\"]}\n {:zeno/arg 8\n ", "end": 8875, "score": 0.999101996421814, "start": 8870, "tag": "NAME", "value": "Alice" }, { "context": "/set\n :zeno/path [:zeno/crdt \"Bob\"]}\n {:zeno/arg 12\n ", "end": 9000, "score": 0.9993571639060974, "start": 8997, "tag": "NAME", "value": "Bob" }, { "context": "/set\n :zeno/path [:zeno/crdt \"Bob\"]}]\n :root :zeno/crdt\n :s", "end": 9126, "score": 0.9988739490509033, "start": 9123, "tag": "NAME", "value": "Bob" }, { "context": "s->crdt crdt-ops schema)\n expected-value {\"Alice\" 31 \"Bob\" 12}]\n (is (= expected-value\n ", "end": 9360, "score": 0.9986363053321838, "start": 9355, "tag": "NAME", "value": "Alice" }, { "context": "t-ops schema)\n expected-value {\"Alice\" 31 \"Bob\" 12}]\n (is (= expected-value\n (->val", "end": 9369, "score": 0.9985498785972595, "start": 9366, "tag": "NAME", "value": "Bob" }, { "context": "r-schema)\n arg {:cmds [{:zeno/arg [{:name \"Bill\"\n :specialties {:", "end": 11307, "score": 0.9998669624328613, "start": 11303, "tag": "NAME", "value": "Bill" }, { "context": " crdt-ops schema)\n expected-value [{:name \"Bill\" :specialties {:aggression true}}]]\n (is (= ex", "end": 11873, "score": 0.9998475909233093, "start": 11869, "tag": "NAME", "value": "Bill" }, { "context": "ath [:zeno/crdt]}\n {:zeno/arg \"Bob\"\n :zeno/op :zeno/set\n ", "end": 14417, "score": 0.9925389289855957, "start": 14414, "tag": "NAME", "value": "Bob" }, { "context": "dt crdt-ops schema)\n expected-value [\"Hi\" \"Bob\"]]\n (is (= expected-value\n (->value ", "end": 14740, "score": 0.9997778534889221, "start": 14737, "tag": "NAME", "value": "Bob" }, { "context": "ath [:zeno/crdt]}\n {:zeno/arg \"Bob\"\n :zeno/op :zeno/set\n ", "end": 15201, "score": 0.9997939467430115, "start": 15198, "tag": "NAME", "value": "Bob" }, { "context": "s->crdt crdt-ops schema)\n expected-value [\"Bob\" \"there\"]]\n (is (= expected-value\n (", "end": 15520, "score": 0.9998039603233337, "start": 15517, "tag": "NAME", "value": "Bob" }, { "context": "ath [:zeno/crdt]}\n {:zeno/arg \"Bob\"\n :zeno/op :zeno/set\n ", "end": 15969, "score": 0.9998082518577576, "start": 15966, "tag": "NAME", "value": "Bob" }, { "context": "ath [:zeno/crdt]}\n {:zeno/arg \"Bob\"\n :zeno/op :zeno/set\n ", "end": 16684, "score": 0.9996272325515747, "start": 16681, "tag": "NAME", "value": "Bob" }, { "context": "h [:zeno/crdt 0]}\n {:zeno/arg \"Bob\"\n :zeno/op :zeno/insert-after", "end": 21277, "score": 0.9367557764053345, "start": 21274, "tag": "NAME", "value": "Bob" }, { "context": "ner-schema\n arg {:cmds [{:zeno/arg {:name \"Bill\"\n :pets [{:name \"P", "end": 27363, "score": 0.9993147850036621, "start": 27359, "tag": "NAME", "value": "Bill" }, { "context": "l\"\n :pets [{:name \"Pinky\"\n :species", "end": 27417, "score": 0.9975330829620361, "start": 27412, "tag": "NAME", "value": "Pinky" }, { "context": "\"}\n {:name \"Fishy\"\n :species", "end": 27535, "score": 0.9975462555885315, "start": 27530, "tag": "NAME", "value": "Fishy" }, { "context": "t crdt-ops schema)\n expected-value {:name \"Bill\"\n :pets [{:name \"Pinky\"\n ", "end": 28032, "score": 0.9996909499168396, "start": 28028, "tag": "NAME", "value": "Bill" }, { "context": "ame \"Bill\"\n :pets [{:name \"Pinky\"\n :species \"Felis ", "end": 28078, "score": 0.9987340569496155, "start": 28073, "tag": "NAME", "value": "Pinky" }, { "context": "is catus\"}\n {:name \"Goldy\"\n :species \"Carass", "end": 28180, "score": 0.998650312423706, "start": 28175, "tag": "NAME", "value": "Goldy" }, { "context": " (->value acrdt [] schema)))\n (is (= {:name \"Pinky\"\n :species \"Felis catus\"}\n (", "end": 28372, "score": 0.998979389667511, "start": 28367, "tag": "NAME", "value": "Pinky" }, { "context": "ner-schema\n arg {:cmds [{:zeno/arg {:name \"Bill\"\n :pets [{:name \"P", "end": 28645, "score": 0.9997636079788208, "start": 28641, "tag": "NAME", "value": "Bill" }, { "context": "l\"\n :pets [{:name \"Pinky\"\n :species", "end": 28699, "score": 0.9985926747322083, "start": 28694, "tag": "NAME", "value": "Pinky" }, { "context": "\"}\n {:name \"Fishy\"\n :species", "end": 28817, "score": 0.9985261559486389, "start": 28812, "tag": "NAME", "value": "Fishy" }, { "context": "t crdt-ops schema)\n expected-value {:name \"Bill\"\n :pets [{:name \"Fishy\"\n ", "end": 29366, "score": 0.9997789263725281, "start": 29362, "tag": "NAME", "value": "Bill" }, { "context": "ame \"Bill\"\n :pets [{:name \"Fishy\"\n :species \"Carass", "end": 29412, "score": 0.9984831213951111, "start": 29407, "tag": "NAME", "value": "Fishy" }, { "context": "er-schema\n arg1 {:cmds [{:zeno/arg {:name \"Bill\"\n :pets [{:name \"", "end": 29689, "score": 0.9994891881942749, "start": 29685, "tag": "NAME", "value": "Bill" }, { "context": "\"\n :pets [{:name \"Pinky\"\n :specie", "end": 29744, "score": 0.9962911605834961, "start": 29739, "tag": "NAME", "value": "Pinky" }, { "context": "}\n {:name \"Fishy\"\n :specie", "end": 29864, "score": 0.9956890344619751, "start": 29859, "tag": "NAME", "value": "Fishy" }, { "context": "crdt2-ops) schema)\n expected-value {:name \"Bill\"\n :pets [{:name \"Fishy\"\n ", "end": 30518, "score": 0.9995286464691162, "start": 30514, "tag": "NAME", "value": "Bill" }, { "context": "ame \"Bill\"\n :pets [{:name \"Fishy\"\n :species \"Carass", "end": 30564, "score": 0.9940062761306763, "start": 30559, "tag": "NAME", "value": "Fishy" }, { "context": "-conflict\n (let [arg0 {:cmds [{:zeno/arg {:name \"Bill\"\n :pets [{:name \"", "end": 30880, "score": 0.9994872808456421, "start": 30876, "tag": "NAME", "value": "Bill" }, { "context": "\"\n :pets [{:name \"Pinky\"\n :specie", "end": 30935, "score": 0.9948042035102844, "start": 30930, "tag": "NAME", "value": "Pinky" }, { "context": "}\n {:name \"Fishy\"\n :specie", "end": 31055, "score": 0.995704174041748, "start": 31050, "tag": "NAME", "value": "Fishy" }, { "context": "mds arg0)\n arg1 {:cmds [{:zeno/arg {:name \"Chris\"\n :species \"Canis", "end": 31415, "score": 0.9773833155632019, "start": 31410, "tag": "NAME", "value": "Chris" }, { "context": "r-schema}\n arg2 {:cmds [{:zeno/arg {:name \"Pat\"\n :species \"Canis", "end": 31726, "score": 0.999832272529602, "start": 31723, "tag": "NAME", "value": "Pat" }, { "context": "et-owner-schema})\n expected-value [{:name \"Chris\"\n :species \"Canis familia", "end": 32434, "score": 0.9973965883255005, "start": 32429, "tag": "NAME", "value": "Chris" }, { "context": "anis familiaris\"}\n {:name \"Pinky\"\n :species \"Felis catus\"}", "end": 32527, "score": 0.9986729025840759, "start": 32522, "tag": "NAME", "value": "Pinky" }, { "context": "es \"Felis catus\"}\n {:name \"Fishy\"\n :species \"Carassius aur", "end": 32615, "score": 0.9992619752883911, "start": 32610, "tag": "NAME", "value": "Fishy" }, { "context": "rassius auratus\"}\n {:name \"Pat\"\n :species \"Canis familia", "end": 32707, "score": 0.999840259552002, "start": 32704, "tag": "NAME", "value": "Pat" }, { "context": "r \"I\" n))\n arg0 {:cmds [{:zeno/arg {:name \"Bill\"\n :pets [{:name \"", "end": 33157, "score": 0.9998500347137451, "start": 33153, "tag": "NAME", "value": "Bill" }, { "context": "\"\n :pets [{:name \"Pinky\"\n :specie", "end": 33212, "score": 0.9981266856193542, "start": 33207, "tag": "NAME", "value": "Pinky" }, { "context": "}\n {:name \"Fishy\"\n :specie", "end": 33332, "score": 0.9991618394851685, "start": 33327, "tag": "NAME", "value": "Fishy" }, { "context": "mds arg0)\n arg1 {:cmds [{:zeno/arg {:name \"Chris\"\n :species \"Canis", "end": 33685, "score": 0.9992109537124634, "start": 33680, "tag": "NAME", "value": "Chris" }, { "context": " make-id}\n arg2 {:cmds [{:zeno/arg {:name \"Pat\"\n :species \"Canis", "end": 34034, "score": 0.9998735785484314, "start": 34031, "tag": "NAME", "value": "Pat" }, { "context": "t-owner-schema}))\n expected-value [{:name \"Chris\"\n :species \"Canis familia", "end": 34745, "score": 0.9978806972503662, "start": 34740, "tag": "NAME", "value": "Chris" }, { "context": "anis familiaris\"}\n {:name \"Pat\"\n :species \"Canis familia", "end": 34836, "score": 0.9998713135719299, "start": 34833, "tag": "NAME", "value": "Pat" }, { "context": "anis familiaris\"}\n {:name \"Pinky\"\n :species \"Felis catus\"}", "end": 34929, "score": 0.9995824694633484, "start": 34924, "tag": "NAME", "value": "Pinky" }, { "context": "es \"Felis catus\"}\n {:name \"Fishy\"\n :species \"Carassius aur", "end": 35017, "score": 0.9997248649597168, "start": 35012, "tag": "NAME", "value": "Fishy" }, { "context": "-conflict\n (let [arg0 {:cmds [{:zeno/arg {:name \"Bill\"\n :pets [{:name \"", "end": 42712, "score": 0.9989319443702698, "start": 42708, "tag": "NAME", "value": "Bill" }, { "context": "\"\n :pets [{:name \"Pinky\"\n :specie", "end": 42767, "score": 0.9923755526542664, "start": 42762, "tag": "NAME", "value": "Pinky" }, { "context": "}\n {:name \"Fishy\"\n :specie", "end": 42887, "score": 0.9692986011505127, "start": 42882, "tag": "NAME", "value": "Fishy" }, { "context": "ocess-cmds arg0)\n arg1 {:cmds [{:zeno/arg \"Goldy\"\n :zeno/op :zeno/set\n ", "end": 43202, "score": 0.9996836185455322, "start": 43197, "tag": "NAME", "value": "Goldy" }, { "context": "1640205282000\")}\n arg2 {:cmds [{:zeno/arg \"Herman\"\n :zeno/op :zeno/set\n ", "end": 43508, "score": 0.9996711015701294, "start": 43502, "tag": "NAME", "value": "Herman" }, { "context": " :schema pet-owner-schema}))]\n ;; We expect \"Herman\" because its sys-time-ms is later\n (is (= \"Her", "end": 44173, "score": 0.9996143579483032, "start": 44167, "tag": "NAME", "value": "Herman" }, { "context": "man\" because its sys-time-ms is later\n (is (= \"Herman\" (crdt/get-value {:crdt merged-crdt\n ", "end": 44226, "score": 0.9995821714401245, "start": 44220, "tag": "NAME", "value": "Herman" } ]
test/unit/crdt_commands_test.cljc
Oncurrent/zeno
0
(ns unit.crdt-commands-test (:require [clojure.set :as set] [clojure.test :as t :refer [deftest is]] [deercreeklabs.lancaster :as l] [com.oncurrent.zeno.state-providers.crdt.apply-ops :as apply-ops] [com.oncurrent.zeno.state-providers.crdt.commands :as commands] [com.oncurrent.zeno.state-providers.crdt.common :as crdt] [com.oncurrent.zeno.state-providers.crdt.repair :as repair] [com.oncurrent.zeno.utils :as u] #?(:clj [kaocha.repl]) [taoensso.timbre :as log]) #?(:clj (:import (clojure.lang ExceptionInfo)))) (comment (kaocha.repl/run *ns* {:capture-output? false})) #?(:clj (defn krun ([sym] (krun sym nil)) ([sym opts] (kaocha.repl/run sym (merge {:color? false :capture-output? false} opts))))) (l/def-record-schema pet-schema [:name l/string-schema] [:species l/string-schema]) (l/def-record-schema pet-owner-schema [:name l/string-schema] [:pets (l/array-schema pet-schema)]) (l/def-record-schema specialties-schema [:aggression l/boolean-schema] [:barking l/boolean-schema]) (l/def-record-schema pet-trainer-schema [:name l/string-schema] [:specialties specialties-schema]) (l/def-map-schema pet-owners-schema pet-owner-schema) (l/def-record-schema pet-school-schema [:pet-owners (l/map-schema pet-owner-schema)]) (l/def-record-schema tree-schema [:value l/int-schema] [:right-child ::tree] [:left-child ::tree]) (defn ops->crdt [crdt-ops schema] (-> (apply-ops/apply-ops (u/sym-map crdt-ops schema)) (:crdt))) (defn ->value [crdt path schema] (crdt/get-value (u/sym-map crdt path schema))) (comment (krun #'test-empty-map-of-records)) (deftest test-empty-map-of-records (is (= nil (->value {} [] pet-owners-schema))) (is (= nil (->value {} ["a"] pet-owners-schema))) (is (= nil (->value {} [nil] pet-owners-schema)))) (comment (krun #'test-set-empty-map-of-records)) (deftest test-set-empty-map-of-records (let [schema pet-owners-schema arg {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= {} (->value crdt [] schema) (->value acrdt [] schema))) (is (= nil (->value crdt ["a"] schema) (->value acrdt ["a"] schema))) (is (= nil (->value crdt [nil] schema) (->value acrdt [nil] schema))))) (comment (krun #'test-empty-record-with-map-of-records)) (deftest test-empty-record-with-map-of-records (is (= nil (->value {} [:pet-owners] pet-school-schema))) (is (= nil (->value {} [:pet-owners "a"] pet-school-schema))) (is (= nil (->value {} [:pet-owners nil] pet-school-schema)))) (comment (krun #'test-set-empty-record-with-map-of-records)) (deftest test-set-empty-record-with-map-of-records (let [schema pet-school-schema arg {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= nil (->value crdt [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-then-reset-empty-record-with-empty-map-of-records)) (deftest test-set-then-reset-empty-record-with-empty-map-of-records (let [schema pet-school-schema arg1 {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 (assoc arg1 :cmds [{:zeno/arg {:pet-owners {}} :zeno/op :zeno/set :zeno/path []}] :crdt crdt1) {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) acrdt (ops->crdt (set/union crdt1-ops crdt2-ops) schema)] (is (= {} (->value crdt2 [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt2 [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt2 [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-empty-record-then-path-set-with-empty-map-of-records)) (deftest test-set-empty-record-then-path-set-with-empty-map-of-records (let [schema pet-school-schema arg1 {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 (assoc arg1 :cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path [:pet-owners]}] :crdt crdt1) {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) all-ops (set/union crdt1-ops crdt2-ops) acrdt (ops->crdt all-ops schema)] (is (= {} (->value crdt2 [:pet-owners] schema))) (is (= {} (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt2 [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt2 [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-record-with-empty-map-of-records)) (deftest test-set-record-with-empty-map-of-records (let [schema pet-school-schema arg {:cmds [{:zeno/arg {:pet-owners {}} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= {} (->value crdt [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-crdt-set)) (deftest test-crdt-set (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hi" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "Hi"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-set-and-remove)) (deftest test-crdt-set-and-remove (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hello" :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value nil] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-set-and-reset)) (deftest test-crdt-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hello" :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Goodbye" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "Goodbye"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-map-set-and-reset)) (deftest test-crdt-map-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema (l/map-schema l/int-schema) arg {:cmds [{:zeno/arg 31 :zeno/op :zeno/set :zeno/path [:zeno/crdt "Alice"]} {:zeno/arg 8 :zeno/op :zeno/set :zeno/path [:zeno/crdt "Bob"]} {:zeno/arg 12 :zeno/op :zeno/set :zeno/path [:zeno/crdt "Bob"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"Alice" 31 "Bob" 12}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-record-set-and-reset)) (deftest test-crdt-record-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema pet-schema arg {:cmds [{:zeno/arg "Lamby" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]} {:zeno/arg "Ovis aries" :zeno/op :zeno/set :zeno/path [:zeno/crdt :species]} {:zeno/arg "Sheepy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Sheepy" :species "Ovis aries"}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-record-set-optional)) (deftest test-crdt-record-set-optional (let [sys-time-ms (u/str->long "1643061294782") schema pet-schema arg {:cmds [{:zeno/arg "Sheepy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Sheepy"}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-record-set-and-remove)) (deftest test-crdt-nested-record-set-and-remove (let [sys-time-ms (u/str->long "1643061294782") schema (l/array-schema pet-trainer-schema) arg {:cmds [{:zeno/arg [{:name "Bill" :specialties {:aggression true :barking false}}] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0 :specialties :barking]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [{:name "Bill" :specialties {:aggression true}}]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-union-set-and-reset)) (deftest test-crdt-union-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema (l/union-schema [l/string-schema l/float-schema]) arg {:cmds [{:zeno/arg 3.14 :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "pi" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "pi"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set)) (deftest test-crdt-array-set (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hi" "There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-empty)) (deftest test-crdt-array-set-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg [] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value []] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-pos)) (deftest test-crdt-array-set-index-pos (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Bob" :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hi" "Bob"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-neg)) (deftest test-crdt-array-set-index-neg (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Bob" :zeno/op :zeno/set :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Bob" "there"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-out-of-bounds-pos)) (deftest test-crdt-array-set-index-out-of-bounds-pos (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Bob" :zeno/op :zeno/set :zeno/path [:zeno/crdt 2]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-crdt-array-set-index-out-of-bounds-neg)) (deftest test-crdt-array-set-index-out-of-bounds-neg (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Bob" :zeno/op :zeno/set :zeno/path [:zeno/crdt -3]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-crdt-array-set-index-into-empty)) (deftest test-crdt-array-set-index-into-empty (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg "Hi" :zeno/op :zeno/set :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (deftest test-crdt-array-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-maps-set-and-remove)) (deftest test-crdt-nested-maps-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/map-schema (l/map-schema l/int-schema)) arg {:cmds [{:zeno/arg {"j" {"a" 1 "b" 2} "k" {"y" 10 "z" 20} "l" {"c" 3}} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt "k" "y"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"j" {"a" 1 "b" 2} "k" {"z" 20} "l" {"c" 3}}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-of-maps-set-and-remove)) (deftest test-crdt-array-of-maps-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema (l/map-schema l/int-schema)) arg {:cmds [{:zeno/arg [{"a" 1 "b" 2} {"y" 10 "z" 20} {"c" 3}] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 1 "y"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [{"a" 1 "b" 2} {"z" 20} {"c" 3}]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-set-and-reset (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Go" :zeno/op :zeno/set :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Go" "There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-simple-inserts (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Hello!" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Bob" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hello!" "Hi" "There" "Bob"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-before-into-empty (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg "Hello!" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hello!"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-after-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg "Hello!" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) _ (is (= {:norm-path [0] :value "Hello!" :exists? true} (crdt/get-value-info {:crdt crdt :path [-1] :schema schema}) (crdt/get-value-info {:crdt acrdt :path [-1] :schema schema}))) expected-value ["Hello!"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-insert-range-after-into-empty)) (deftest test-crdt-array-insert-range-after-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-before-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-insert-range-before-into-front)) (deftest test-crdt-array-insert-range-before-into-front (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["4" "5"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3" "4" "5"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-after-end (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["4" "5"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["4" "5" "1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-before-into-middle (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["A" "B"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "A" "B" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-after-into-middle (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["A" "B"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "A" "B" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-nested-set (let [schema pet-owner-schema arg {:cmds [{:zeno/arg {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Goldy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Goldy" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))) (is (= {:name "Pinky" :species "Felis catus"} (->value crdt [:pets -2] schema) (->value acrdt [:pets -2] schema))))) (deftest test-nested-set-and-remove (let [*next-id-num (atom 0) schema pet-owner-schema arg {:cmds [{:zeno/arg {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :schema schema :make-id #(let [n (swap! *next-id-num inc)] (str "I" n))} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Bill" :pets [{:name "Fishy" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-subsequent-txns (let [schema pet-owner-schema arg1 {:cmds [{:zeno/arg {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 {:cmds [{:zeno/op :zeno/remove :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt crdt1 :schema schema} {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) acrdt (ops->crdt (set/union crdt1-ops crdt2-ops) schema) expected-value {:name "Bill" :pets [{:name "Fishy" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt2 [] schema) (->value acrdt [] schema))))) (comment (krun #'test-nested-merge-array-no-conflict)) (deftest test-nested-merge-array-no-conflict (let [arg0 {:cmds [{:zeno/arg {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema} {crdt0 :crdt crdt0-ops :crdt-ops} (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg {:name "Chris" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt crdt0 :schema pet-owner-schema} arg2 {:cmds [{:zeno/arg {:name "Pat" :species "Canis familiaris"} :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :pets -1]}] :root :zeno/crdt :crdt crdt0 :schema pet-owner-schema} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) {merged-crdt :crdt rc-ops :repair-crdt-ops} (apply-ops/apply-ops {:crdt crdt0 :crdt-ops new-crdt-ops :schema pet-owner-schema}) expected-value [{:name "Chris" :species "Canis familiaris"} {:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"} {:name "Pat" :species "Canis familiaris"}]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [:pets] :schema pet-owner-schema}))))) (deftest test-nested-merge-array-conflict (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) arg0 {:cmds [{:zeno/arg {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg {:name "Chris" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :make-id make-id} arg2 {:cmds [{:zeno/arg {:name "Pat" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema pet-owner-schema})) expected-value [{:name "Chris" :species "Canis familiaris"} {:name "Pat" :species "Canis familiaris"} {:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [:pets] :schema pet-owner-schema}))))) (deftest test-merge-3-way-array-conflict (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "2" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "3" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) ;; Order of the first three items is determined by their add-ids. ;; Any ordering would be fine, as long as it is deterministic. ;; The important part is that all three appear before the original ;; sequence (["A" "B"]). expected-value ["2" "3" "1" "A" "B"] v (crdt/get-value {:crdt merged-crdt :path [] :schema schema})] (is (= expected-value v)))) (deftest test-merge-3-way-array-conflict-multiple-peer-cmds (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "X1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "X2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "Y1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Y2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "Z1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Z2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) ;; Order of the first three pairs of items is determined by their ;; add-ids. Any ordering would be fine, as long as it is deterministic. ;; The important part is that all three appear before the original ;; sequence (["A" "B"]) and that the Xs, Ys, and Zs are not interleaved. expected-value ["Y1" "Y2" "Z1" "Z2" "X1" "X2" "A" "B"]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [] :schema schema}))))) (deftest test-merge-multiple-conflicts (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B" "C"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "XF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "XL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "YF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "YL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "ZF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "ZL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) expected-value ["XF" "YF" "ZF" "A" "B" "C" "XL" "YL" "ZL"]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :make-id make-id :path [] :schema schema}))))) (deftest test-nested-merge-conflict (let [arg0 {:cmds [{:zeno/arg {:name "Bill" :pets [{:name "Pinky" :species "Felis catus"} {:name "Fishy" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "Goldy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :sys-time-ms (u/str->long "1640205282000")} arg2 {:cmds [{:zeno/arg "Herman" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :sys-time-ms (u/str->long "1640205282999")} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) all-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops all-ops :schema pet-owner-schema}))] ;; We expect "Herman" because its sys-time-ms is later (is (= "Herman" (crdt/get-value {:crdt merged-crdt :path [:pets -1 :name] :schema pet-owner-schema}))))) (deftest test-set-into-empty-array (let [arg {:cmds [{:zeno/arg "1" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema (l/array-schema l/string-schema)}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"arg is not sequential" (commands/process-cmds arg))))) (comment (krun #'test-set-map-of-two-arrays)) (deftest test-set-map-of-two-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" [1] "b" [2]} schema (l/map-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-set-nested-map-of-two-arrays)) (deftest test-set-nested-map-of-two-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" {"aa" [1]} "b" {"bb" [2]}} schema (l/map-schema (l/map-schema (l/array-schema l/int-schema))) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set {:capture-output? true})) (deftest test-crdt-nested-arrays-set (let [sys-time-ms (u/str->long "1643061294782") value [[[[[1 2]]]] [[[[3]] [[4]]]] [[[[5]]] [[[6 7]]]]] schema (-> l/int-schema l/array-schema l/array-schema l/array-schema l/array-schema l/array-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set-index)) (deftest test-crdt-nested-arrays-set-index (let [sys-time-ms (u/str->long "1643061294782") schema (l/array-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg [[1 2] [2]] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg [3] :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} expected-value [[1 2] [3]] {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set-index-out-of-bounds)) (deftest test-crdt-nested-arrays-set-index-out-of-bounds (let [sys-time-ms (u/str->long "1643061294782") arg {:cmds [{:zeno/arg [[1 2]] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg [3] :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema (l/array-schema (l/array-schema l/int-schema)) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-set-nested-map-of-two-nested-arrays)) (deftest test-set-nested-map-of-two-nested-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" {"aa" [[1 2] [3]]} "b" {"bb" [[4 5] [6]]}} schema (-> l/int-schema l/array-schema l/array-schema l/map-schema l/map-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-set-remove-nested-arrays)) (deftest test-set-remove-nested-arrays (let [sys-time-ms (u/str->long "1643061294782") value [[1 2] [3]] schema (l/array-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0 1]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [[1]]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array)) (deftest test-empty-array (let [value [] schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array-as-value)) (deftest test-empty-array-as-value (let [value {"a" []} schema (l/map-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array-in-record)) (deftest test-empty-array-in-record (let [value [] schema (l/record-schema :r1 [[:a (l/array-schema l/string-schema)]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt :a]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [:a] schema) (->value acrdt [:a] schema))))) (comment (krun #'test-empty-array-in-map)) (deftest test-empty-array-in-map (let [value [] schema (l/map-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt "a"]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt ["a"] schema) (->value acrdt ["a"] schema))))) (comment (krun #'test-record-nested-negative-insert-after)) (deftest test-record-nested-negative-insert-after (let [value "id" schema (l/record-schema :r1 [[:a (l/array-schema l/string-schema)]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :a -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:a [value]}] (is (= value (->value crdt [:a -1] schema) (->value acrdt [:a -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-array-insert-after)) (deftest test-array-insert-after (let [value "id" schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [value]] (is (= value (->value crdt [-1] schema) (->value acrdt [-1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-array-nested-insert-after)) (deftest test-array-nested-insert-after (let [value "id" schema (l/array-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0 -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [[value]]] (is (= value (->value crdt [0 -1] schema) (->value acrdt [0 -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-nested-negative-insert-after (let [value 42 schema (l/map-schema (l/map-schema (l/array-schema l/int-schema))) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt "a" "b" 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"a" {"b" [value]}}] (is (= value (->value crdt ["a" "b" 0] schema) (->value acrdt ["a" "b" 0] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-deep-nested-negative-insert-after)) (deftest test-deep-nested-negative-insert-after (let [value "id" schema (l/record-schema :r1 [[:a (l/map-schema (l/array-schema (l/map-schema (l/record-schema :r2 [[:d (l/array-schema (l/array-schema l/string-schema))]]))))]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :a "b" 0 "c" :d 0 -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:a {"b" [{"c" {:d [[value]]}}]}}] (is (= value (->value crdt [:a "b" 0 "c" :d 0 -1] schema) (->value acrdt [:a "b" 0 "c" :d 0 -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-recursive-schema (let [data {:value 42 :right-child {:value 3 :right-child {:value 8 :right-child {:value 21} :left-child {:value 43}} :left-child {:value 8 :right-child {:value 21} :left-child {:value 43}}} :left-child {:value 3 :right-child {:value 8 :right-child {:value 21} :left-child {:value 43}} :left-child {:value 8 :right-child {:value 21} :left-child {:value 43}}}} schema tree-schema arg {:cmds [{:zeno/arg data :zeno/op :zeno/set :zeno/path []}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= data (->value crdt [] schema) (->value acrdt [] schema)))))
42733
(ns unit.crdt-commands-test (:require [clojure.set :as set] [clojure.test :as t :refer [deftest is]] [deercreeklabs.lancaster :as l] [com.oncurrent.zeno.state-providers.crdt.apply-ops :as apply-ops] [com.oncurrent.zeno.state-providers.crdt.commands :as commands] [com.oncurrent.zeno.state-providers.crdt.common :as crdt] [com.oncurrent.zeno.state-providers.crdt.repair :as repair] [com.oncurrent.zeno.utils :as u] #?(:clj [kaocha.repl]) [taoensso.timbre :as log]) #?(:clj (:import (clojure.lang ExceptionInfo)))) (comment (kaocha.repl/run *ns* {:capture-output? false})) #?(:clj (defn krun ([sym] (krun sym nil)) ([sym opts] (kaocha.repl/run sym (merge {:color? false :capture-output? false} opts))))) (l/def-record-schema pet-schema [:name l/string-schema] [:species l/string-schema]) (l/def-record-schema pet-owner-schema [:name l/string-schema] [:pets (l/array-schema pet-schema)]) (l/def-record-schema specialties-schema [:aggression l/boolean-schema] [:barking l/boolean-schema]) (l/def-record-schema pet-trainer-schema [:name l/string-schema] [:specialties specialties-schema]) (l/def-map-schema pet-owners-schema pet-owner-schema) (l/def-record-schema pet-school-schema [:pet-owners (l/map-schema pet-owner-schema)]) (l/def-record-schema tree-schema [:value l/int-schema] [:right-child ::tree] [:left-child ::tree]) (defn ops->crdt [crdt-ops schema] (-> (apply-ops/apply-ops (u/sym-map crdt-ops schema)) (:crdt))) (defn ->value [crdt path schema] (crdt/get-value (u/sym-map crdt path schema))) (comment (krun #'test-empty-map-of-records)) (deftest test-empty-map-of-records (is (= nil (->value {} [] pet-owners-schema))) (is (= nil (->value {} ["a"] pet-owners-schema))) (is (= nil (->value {} [nil] pet-owners-schema)))) (comment (krun #'test-set-empty-map-of-records)) (deftest test-set-empty-map-of-records (let [schema pet-owners-schema arg {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= {} (->value crdt [] schema) (->value acrdt [] schema))) (is (= nil (->value crdt ["a"] schema) (->value acrdt ["a"] schema))) (is (= nil (->value crdt [nil] schema) (->value acrdt [nil] schema))))) (comment (krun #'test-empty-record-with-map-of-records)) (deftest test-empty-record-with-map-of-records (is (= nil (->value {} [:pet-owners] pet-school-schema))) (is (= nil (->value {} [:pet-owners "a"] pet-school-schema))) (is (= nil (->value {} [:pet-owners nil] pet-school-schema)))) (comment (krun #'test-set-empty-record-with-map-of-records)) (deftest test-set-empty-record-with-map-of-records (let [schema pet-school-schema arg {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= nil (->value crdt [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-then-reset-empty-record-with-empty-map-of-records)) (deftest test-set-then-reset-empty-record-with-empty-map-of-records (let [schema pet-school-schema arg1 {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 (assoc arg1 :cmds [{:zeno/arg {:pet-owners {}} :zeno/op :zeno/set :zeno/path []}] :crdt crdt1) {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) acrdt (ops->crdt (set/union crdt1-ops crdt2-ops) schema)] (is (= {} (->value crdt2 [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt2 [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt2 [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-empty-record-then-path-set-with-empty-map-of-records)) (deftest test-set-empty-record-then-path-set-with-empty-map-of-records (let [schema pet-school-schema arg1 {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 (assoc arg1 :cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path [:pet-owners]}] :crdt crdt1) {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) all-ops (set/union crdt1-ops crdt2-ops) acrdt (ops->crdt all-ops schema)] (is (= {} (->value crdt2 [:pet-owners] schema))) (is (= {} (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt2 [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt2 [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-record-with-empty-map-of-records)) (deftest test-set-record-with-empty-map-of-records (let [schema pet-school-schema arg {:cmds [{:zeno/arg {:pet-owners {}} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= {} (->value crdt [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-crdt-set)) (deftest test-crdt-set (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hi" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "Hi"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-set-and-remove)) (deftest test-crdt-set-and-remove (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hello" :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value nil] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-set-and-reset)) (deftest test-crdt-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hello" :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Goodbye" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "Goodbye"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-map-set-and-reset)) (deftest test-crdt-map-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema (l/map-schema l/int-schema) arg {:cmds [{:zeno/arg 31 :zeno/op :zeno/set :zeno/path [:zeno/crdt "<NAME>"]} {:zeno/arg 8 :zeno/op :zeno/set :zeno/path [:zeno/crdt "<NAME>"]} {:zeno/arg 12 :zeno/op :zeno/set :zeno/path [:zeno/crdt "<NAME>"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"<NAME>" 31 "<NAME>" 12}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-record-set-and-reset)) (deftest test-crdt-record-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema pet-schema arg {:cmds [{:zeno/arg "Lamby" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]} {:zeno/arg "Ovis aries" :zeno/op :zeno/set :zeno/path [:zeno/crdt :species]} {:zeno/arg "Sheepy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Sheepy" :species "Ovis aries"}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-record-set-optional)) (deftest test-crdt-record-set-optional (let [sys-time-ms (u/str->long "1643061294782") schema pet-schema arg {:cmds [{:zeno/arg "Sheepy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Sheepy"}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-record-set-and-remove)) (deftest test-crdt-nested-record-set-and-remove (let [sys-time-ms (u/str->long "1643061294782") schema (l/array-schema pet-trainer-schema) arg {:cmds [{:zeno/arg [{:name "<NAME>" :specialties {:aggression true :barking false}}] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0 :specialties :barking]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [{:name "<NAME>" :specialties {:aggression true}}]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-union-set-and-reset)) (deftest test-crdt-union-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema (l/union-schema [l/string-schema l/float-schema]) arg {:cmds [{:zeno/arg 3.14 :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "pi" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "pi"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set)) (deftest test-crdt-array-set (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hi" "There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-empty)) (deftest test-crdt-array-set-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg [] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value []] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-pos)) (deftest test-crdt-array-set-index-pos (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "<NAME>" :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hi" "<NAME>"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-neg)) (deftest test-crdt-array-set-index-neg (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "<NAME>" :zeno/op :zeno/set :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["<NAME>" "there"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-out-of-bounds-pos)) (deftest test-crdt-array-set-index-out-of-bounds-pos (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "<NAME>" :zeno/op :zeno/set :zeno/path [:zeno/crdt 2]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-crdt-array-set-index-out-of-bounds-neg)) (deftest test-crdt-array-set-index-out-of-bounds-neg (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "<NAME>" :zeno/op :zeno/set :zeno/path [:zeno/crdt -3]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-crdt-array-set-index-into-empty)) (deftest test-crdt-array-set-index-into-empty (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg "Hi" :zeno/op :zeno/set :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (deftest test-crdt-array-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-maps-set-and-remove)) (deftest test-crdt-nested-maps-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/map-schema (l/map-schema l/int-schema)) arg {:cmds [{:zeno/arg {"j" {"a" 1 "b" 2} "k" {"y" 10 "z" 20} "l" {"c" 3}} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt "k" "y"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"j" {"a" 1 "b" 2} "k" {"z" 20} "l" {"c" 3}}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-of-maps-set-and-remove)) (deftest test-crdt-array-of-maps-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema (l/map-schema l/int-schema)) arg {:cmds [{:zeno/arg [{"a" 1 "b" 2} {"y" 10 "z" 20} {"c" 3}] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 1 "y"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [{"a" 1 "b" 2} {"z" 20} {"c" 3}]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-set-and-reset (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Go" :zeno/op :zeno/set :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Go" "There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-simple-inserts (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Hello!" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "<NAME>" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hello!" "Hi" "There" "Bob"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-before-into-empty (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg "Hello!" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hello!"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-after-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg "Hello!" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) _ (is (= {:norm-path [0] :value "Hello!" :exists? true} (crdt/get-value-info {:crdt crdt :path [-1] :schema schema}) (crdt/get-value-info {:crdt acrdt :path [-1] :schema schema}))) expected-value ["Hello!"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-insert-range-after-into-empty)) (deftest test-crdt-array-insert-range-after-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-before-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-insert-range-before-into-front)) (deftest test-crdt-array-insert-range-before-into-front (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["4" "5"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3" "4" "5"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-after-end (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["4" "5"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["4" "5" "1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-before-into-middle (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["A" "B"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "A" "B" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-after-into-middle (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["A" "B"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "A" "B" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-nested-set (let [schema pet-owner-schema arg {:cmds [{:zeno/arg {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Goldy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))) (is (= {:name "<NAME>" :species "Felis catus"} (->value crdt [:pets -2] schema) (->value acrdt [:pets -2] schema))))) (deftest test-nested-set-and-remove (let [*next-id-num (atom 0) schema pet-owner-schema arg {:cmds [{:zeno/arg {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :schema schema :make-id #(let [n (swap! *next-id-num inc)] (str "I" n))} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "<NAME>" :pets [{:name "<NAME>" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-subsequent-txns (let [schema pet-owner-schema arg1 {:cmds [{:zeno/arg {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 {:cmds [{:zeno/op :zeno/remove :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt crdt1 :schema schema} {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) acrdt (ops->crdt (set/union crdt1-ops crdt2-ops) schema) expected-value {:name "<NAME>" :pets [{:name "<NAME>" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt2 [] schema) (->value acrdt [] schema))))) (comment (krun #'test-nested-merge-array-no-conflict)) (deftest test-nested-merge-array-no-conflict (let [arg0 {:cmds [{:zeno/arg {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema} {crdt0 :crdt crdt0-ops :crdt-ops} (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg {:name "<NAME>" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt crdt0 :schema pet-owner-schema} arg2 {:cmds [{:zeno/arg {:name "<NAME>" :species "Canis familiaris"} :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :pets -1]}] :root :zeno/crdt :crdt crdt0 :schema pet-owner-schema} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) {merged-crdt :crdt rc-ops :repair-crdt-ops} (apply-ops/apply-ops {:crdt crdt0 :crdt-ops new-crdt-ops :schema pet-owner-schema}) expected-value [{:name "<NAME>" :species "Canis familiaris"} {:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"} {:name "<NAME>" :species "Canis familiaris"}]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [:pets] :schema pet-owner-schema}))))) (deftest test-nested-merge-array-conflict (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) arg0 {:cmds [{:zeno/arg {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg {:name "<NAME>" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :make-id make-id} arg2 {:cmds [{:zeno/arg {:name "<NAME>" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema pet-owner-schema})) expected-value [{:name "<NAME>" :species "Canis familiaris"} {:name "<NAME>" :species "Canis familiaris"} {:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [:pets] :schema pet-owner-schema}))))) (deftest test-merge-3-way-array-conflict (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "2" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "3" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) ;; Order of the first three items is determined by their add-ids. ;; Any ordering would be fine, as long as it is deterministic. ;; The important part is that all three appear before the original ;; sequence (["A" "B"]). expected-value ["2" "3" "1" "A" "B"] v (crdt/get-value {:crdt merged-crdt :path [] :schema schema})] (is (= expected-value v)))) (deftest test-merge-3-way-array-conflict-multiple-peer-cmds (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "X1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "X2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "Y1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Y2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "Z1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Z2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) ;; Order of the first three pairs of items is determined by their ;; add-ids. Any ordering would be fine, as long as it is deterministic. ;; The important part is that all three appear before the original ;; sequence (["A" "B"]) and that the Xs, Ys, and Zs are not interleaved. expected-value ["Y1" "Y2" "Z1" "Z2" "X1" "X2" "A" "B"]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [] :schema schema}))))) (deftest test-merge-multiple-conflicts (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B" "C"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "XF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "XL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "YF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "YL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "ZF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "ZL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) expected-value ["XF" "YF" "ZF" "A" "B" "C" "XL" "YL" "ZL"]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :make-id make-id :path [] :schema schema}))))) (deftest test-nested-merge-conflict (let [arg0 {:cmds [{:zeno/arg {:name "<NAME>" :pets [{:name "<NAME>" :species "Felis catus"} {:name "<NAME>" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "<NAME>" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :sys-time-ms (u/str->long "1640205282000")} arg2 {:cmds [{:zeno/arg "<NAME>" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :sys-time-ms (u/str->long "1640205282999")} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) all-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops all-ops :schema pet-owner-schema}))] ;; We expect "<NAME>" because its sys-time-ms is later (is (= "<NAME>" (crdt/get-value {:crdt merged-crdt :path [:pets -1 :name] :schema pet-owner-schema}))))) (deftest test-set-into-empty-array (let [arg {:cmds [{:zeno/arg "1" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema (l/array-schema l/string-schema)}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"arg is not sequential" (commands/process-cmds arg))))) (comment (krun #'test-set-map-of-two-arrays)) (deftest test-set-map-of-two-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" [1] "b" [2]} schema (l/map-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-set-nested-map-of-two-arrays)) (deftest test-set-nested-map-of-two-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" {"aa" [1]} "b" {"bb" [2]}} schema (l/map-schema (l/map-schema (l/array-schema l/int-schema))) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set {:capture-output? true})) (deftest test-crdt-nested-arrays-set (let [sys-time-ms (u/str->long "1643061294782") value [[[[[1 2]]]] [[[[3]] [[4]]]] [[[[5]]] [[[6 7]]]]] schema (-> l/int-schema l/array-schema l/array-schema l/array-schema l/array-schema l/array-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set-index)) (deftest test-crdt-nested-arrays-set-index (let [sys-time-ms (u/str->long "1643061294782") schema (l/array-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg [[1 2] [2]] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg [3] :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} expected-value [[1 2] [3]] {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set-index-out-of-bounds)) (deftest test-crdt-nested-arrays-set-index-out-of-bounds (let [sys-time-ms (u/str->long "1643061294782") arg {:cmds [{:zeno/arg [[1 2]] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg [3] :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema (l/array-schema (l/array-schema l/int-schema)) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-set-nested-map-of-two-nested-arrays)) (deftest test-set-nested-map-of-two-nested-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" {"aa" [[1 2] [3]]} "b" {"bb" [[4 5] [6]]}} schema (-> l/int-schema l/array-schema l/array-schema l/map-schema l/map-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-set-remove-nested-arrays)) (deftest test-set-remove-nested-arrays (let [sys-time-ms (u/str->long "1643061294782") value [[1 2] [3]] schema (l/array-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0 1]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [[1]]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array)) (deftest test-empty-array (let [value [] schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array-as-value)) (deftest test-empty-array-as-value (let [value {"a" []} schema (l/map-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array-in-record)) (deftest test-empty-array-in-record (let [value [] schema (l/record-schema :r1 [[:a (l/array-schema l/string-schema)]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt :a]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [:a] schema) (->value acrdt [:a] schema))))) (comment (krun #'test-empty-array-in-map)) (deftest test-empty-array-in-map (let [value [] schema (l/map-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt "a"]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt ["a"] schema) (->value acrdt ["a"] schema))))) (comment (krun #'test-record-nested-negative-insert-after)) (deftest test-record-nested-negative-insert-after (let [value "id" schema (l/record-schema :r1 [[:a (l/array-schema l/string-schema)]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :a -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:a [value]}] (is (= value (->value crdt [:a -1] schema) (->value acrdt [:a -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-array-insert-after)) (deftest test-array-insert-after (let [value "id" schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [value]] (is (= value (->value crdt [-1] schema) (->value acrdt [-1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-array-nested-insert-after)) (deftest test-array-nested-insert-after (let [value "id" schema (l/array-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0 -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [[value]]] (is (= value (->value crdt [0 -1] schema) (->value acrdt [0 -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-nested-negative-insert-after (let [value 42 schema (l/map-schema (l/map-schema (l/array-schema l/int-schema))) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt "a" "b" 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"a" {"b" [value]}}] (is (= value (->value crdt ["a" "b" 0] schema) (->value acrdt ["a" "b" 0] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-deep-nested-negative-insert-after)) (deftest test-deep-nested-negative-insert-after (let [value "id" schema (l/record-schema :r1 [[:a (l/map-schema (l/array-schema (l/map-schema (l/record-schema :r2 [[:d (l/array-schema (l/array-schema l/string-schema))]]))))]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :a "b" 0 "c" :d 0 -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:a {"b" [{"c" {:d [[value]]}}]}}] (is (= value (->value crdt [:a "b" 0 "c" :d 0 -1] schema) (->value acrdt [:a "b" 0 "c" :d 0 -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-recursive-schema (let [data {:value 42 :right-child {:value 3 :right-child {:value 8 :right-child {:value 21} :left-child {:value 43}} :left-child {:value 8 :right-child {:value 21} :left-child {:value 43}}} :left-child {:value 3 :right-child {:value 8 :right-child {:value 21} :left-child {:value 43}} :left-child {:value 8 :right-child {:value 21} :left-child {:value 43}}}} schema tree-schema arg {:cmds [{:zeno/arg data :zeno/op :zeno/set :zeno/path []}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= data (->value crdt [] schema) (->value acrdt [] schema)))))
true
(ns unit.crdt-commands-test (:require [clojure.set :as set] [clojure.test :as t :refer [deftest is]] [deercreeklabs.lancaster :as l] [com.oncurrent.zeno.state-providers.crdt.apply-ops :as apply-ops] [com.oncurrent.zeno.state-providers.crdt.commands :as commands] [com.oncurrent.zeno.state-providers.crdt.common :as crdt] [com.oncurrent.zeno.state-providers.crdt.repair :as repair] [com.oncurrent.zeno.utils :as u] #?(:clj [kaocha.repl]) [taoensso.timbre :as log]) #?(:clj (:import (clojure.lang ExceptionInfo)))) (comment (kaocha.repl/run *ns* {:capture-output? false})) #?(:clj (defn krun ([sym] (krun sym nil)) ([sym opts] (kaocha.repl/run sym (merge {:color? false :capture-output? false} opts))))) (l/def-record-schema pet-schema [:name l/string-schema] [:species l/string-schema]) (l/def-record-schema pet-owner-schema [:name l/string-schema] [:pets (l/array-schema pet-schema)]) (l/def-record-schema specialties-schema [:aggression l/boolean-schema] [:barking l/boolean-schema]) (l/def-record-schema pet-trainer-schema [:name l/string-schema] [:specialties specialties-schema]) (l/def-map-schema pet-owners-schema pet-owner-schema) (l/def-record-schema pet-school-schema [:pet-owners (l/map-schema pet-owner-schema)]) (l/def-record-schema tree-schema [:value l/int-schema] [:right-child ::tree] [:left-child ::tree]) (defn ops->crdt [crdt-ops schema] (-> (apply-ops/apply-ops (u/sym-map crdt-ops schema)) (:crdt))) (defn ->value [crdt path schema] (crdt/get-value (u/sym-map crdt path schema))) (comment (krun #'test-empty-map-of-records)) (deftest test-empty-map-of-records (is (= nil (->value {} [] pet-owners-schema))) (is (= nil (->value {} ["a"] pet-owners-schema))) (is (= nil (->value {} [nil] pet-owners-schema)))) (comment (krun #'test-set-empty-map-of-records)) (deftest test-set-empty-map-of-records (let [schema pet-owners-schema arg {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= {} (->value crdt [] schema) (->value acrdt [] schema))) (is (= nil (->value crdt ["a"] schema) (->value acrdt ["a"] schema))) (is (= nil (->value crdt [nil] schema) (->value acrdt [nil] schema))))) (comment (krun #'test-empty-record-with-map-of-records)) (deftest test-empty-record-with-map-of-records (is (= nil (->value {} [:pet-owners] pet-school-schema))) (is (= nil (->value {} [:pet-owners "a"] pet-school-schema))) (is (= nil (->value {} [:pet-owners nil] pet-school-schema)))) (comment (krun #'test-set-empty-record-with-map-of-records)) (deftest test-set-empty-record-with-map-of-records (let [schema pet-school-schema arg {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= nil (->value crdt [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-then-reset-empty-record-with-empty-map-of-records)) (deftest test-set-then-reset-empty-record-with-empty-map-of-records (let [schema pet-school-schema arg1 {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 (assoc arg1 :cmds [{:zeno/arg {:pet-owners {}} :zeno/op :zeno/set :zeno/path []}] :crdt crdt1) {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) acrdt (ops->crdt (set/union crdt1-ops crdt2-ops) schema)] (is (= {} (->value crdt2 [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt2 [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt2 [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-empty-record-then-path-set-with-empty-map-of-records)) (deftest test-set-empty-record-then-path-set-with-empty-map-of-records (let [schema pet-school-schema arg1 {:cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path []}] :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 (assoc arg1 :cmds [{:zeno/arg {} :zeno/op :zeno/set :zeno/path [:pet-owners]}] :crdt crdt1) {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) all-ops (set/union crdt1-ops crdt2-ops) acrdt (ops->crdt all-ops schema)] (is (= {} (->value crdt2 [:pet-owners] schema))) (is (= {} (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt2 [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt2 [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-set-record-with-empty-map-of-records)) (deftest test-set-record-with-empty-map-of-records (let [schema pet-school-schema arg {:cmds [{:zeno/arg {:pet-owners {}} :zeno/op :zeno/set :zeno/path []}] :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= {} (->value crdt [:pet-owners] schema) (->value acrdt [:pet-owners] schema))) (is (= nil (->value crdt [:pet-owners "a"] schema) (->value acrdt [:pet-owners "a"] schema))) (is (= nil (->value crdt [:pet-owners nil] schema) (->value acrdt [:pet-owners nil] schema))))) (comment (krun #'test-crdt-set)) (deftest test-crdt-set (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hi" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "Hi"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-set-and-remove)) (deftest test-crdt-set-and-remove (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hello" :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value nil] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-set-and-reset)) (deftest test-crdt-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema l/string-schema arg {:cmds [{:zeno/arg "Hello" :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Goodbye" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "Goodbye"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-map-set-and-reset)) (deftest test-crdt-map-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema (l/map-schema l/int-schema) arg {:cmds [{:zeno/arg 31 :zeno/op :zeno/set :zeno/path [:zeno/crdt "PI:NAME:<NAME>END_PI"]} {:zeno/arg 8 :zeno/op :zeno/set :zeno/path [:zeno/crdt "PI:NAME:<NAME>END_PI"]} {:zeno/arg 12 :zeno/op :zeno/set :zeno/path [:zeno/crdt "PI:NAME:<NAME>END_PI"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"PI:NAME:<NAME>END_PI" 31 "PI:NAME:<NAME>END_PI" 12}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-record-set-and-reset)) (deftest test-crdt-record-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema pet-schema arg {:cmds [{:zeno/arg "Lamby" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]} {:zeno/arg "Ovis aries" :zeno/op :zeno/set :zeno/path [:zeno/crdt :species]} {:zeno/arg "Sheepy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Sheepy" :species "Ovis aries"}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-record-set-optional)) (deftest test-crdt-record-set-optional (let [sys-time-ms (u/str->long "1643061294782") schema pet-schema arg {:cmds [{:zeno/arg "Sheepy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :name]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "Sheepy"}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-record-set-and-remove)) (deftest test-crdt-nested-record-set-and-remove (let [sys-time-ms (u/str->long "1643061294782") schema (l/array-schema pet-trainer-schema) arg {:cmds [{:zeno/arg [{:name "PI:NAME:<NAME>END_PI" :specialties {:aggression true :barking false}}] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0 :specialties :barking]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [{:name "PI:NAME:<NAME>END_PI" :specialties {:aggression true}}]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-union-set-and-reset)) (deftest test-crdt-union-set-and-reset (let [sys-time-ms (u/str->long "1643061294782") schema (l/union-schema [l/string-schema l/float-schema]) arg {:cmds [{:zeno/arg 3.14 :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "pi" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value "pi"] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set)) (deftest test-crdt-array-set (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hi" "There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-empty)) (deftest test-crdt-array-set-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg [] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value []] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-pos)) (deftest test-crdt-array-set-index-pos (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hi" "PI:NAME:<NAME>END_PI"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-neg)) (deftest test-crdt-array-set-index-neg (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/set :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["PI:NAME:<NAME>END_PI" "there"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-set-index-out-of-bounds-pos)) (deftest test-crdt-array-set-index-out-of-bounds-pos (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/set :zeno/path [:zeno/crdt 2]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-crdt-array-set-index-out-of-bounds-neg)) (deftest test-crdt-array-set-index-out-of-bounds-neg (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg ["Hi" "there"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/set :zeno/path [:zeno/crdt -3]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-crdt-array-set-index-into-empty)) (deftest test-crdt-array-set-index-into-empty (let [sys-time-ms (u/str->long "1643061294999") arg {:cmds [{:zeno/arg "Hi" :zeno/op :zeno/set :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema (l/array-schema l/string-schema) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (deftest test-crdt-array-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-maps-set-and-remove)) (deftest test-crdt-nested-maps-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/map-schema (l/map-schema l/int-schema)) arg {:cmds [{:zeno/arg {"j" {"a" 1 "b" 2} "k" {"y" 10 "z" 20} "l" {"c" 3}} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt "k" "y"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"j" {"a" 1 "b" 2} "k" {"z" 20} "l" {"c" 3}}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-of-maps-set-and-remove)) (deftest test-crdt-array-of-maps-set-and-remove (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema (l/map-schema l/int-schema)) arg {:cmds [{:zeno/arg [{"a" 1 "b" 2} {"y" 10 "z" 20} {"c" 3}] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 1 "y"]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [{"a" 1 "b" 2} {"z" 20} {"c" 3}]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-set-and-reset (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Go" :zeno/op :zeno/set :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Go" "There"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-simple-inserts (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["Hi" "There"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Hello!" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hello!" "Hi" "There" "Bob"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-before-into-empty (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg "Hello!" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["Hello!"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-after-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg "Hello!" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) _ (is (= {:norm-path [0] :value "Hello!" :exists? true} (crdt/get-value-info {:crdt crdt :path [-1] :schema schema}) (crdt/get-value-info {:crdt acrdt :path [-1] :schema schema}))) expected-value ["Hello!"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-insert-range-after-into-empty)) (deftest test-crdt-array-insert-range-after-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-before-into-empty (let [sys-time-ms (u/str->long "1643061294999") schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-array-insert-range-before-into-front)) (deftest test-crdt-array-insert-range-before-into-front (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["4" "5"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "3" "4" "5"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-after-end (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["4" "5"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["1" "2" "3"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["4" "5" "1" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-before-into-middle (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["A" "B"] :zeno/op :zeno/insert-range-before :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "A" "B" "2" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-crdt-array-insert-range-after-into-middle (let [schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg ["1" "2" "3"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg ["A" "B"] :zeno/op :zeno/insert-range-after :zeno/path [:zeno/crdt -2]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value ["1" "2" "A" "B" "3"]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-nested-set (let [schema pet-owner-schema arg {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg "Goldy" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))) (is (= {:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} (->value crdt [:pets -2] schema) (->value acrdt [:pets -2] schema))))) (deftest test-nested-set-and-remove (let [*next-id-num (atom 0) schema pet-owner-schema arg {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :schema schema :make-id #(let [n (swap! *next-id-num inc)] (str "I" n))} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-subsequent-txns (let [schema pet-owner-schema arg1 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {crdt1 :crdt crdt1-ops :crdt-ops} (commands/process-cmds arg1) arg2 {:cmds [{:zeno/op :zeno/remove :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt crdt1 :schema schema} {crdt2 :crdt crdt2-ops :crdt-ops} (commands/process-cmds arg2) acrdt (ops->crdt (set/union crdt1-ops crdt2-ops) schema) expected-value {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]}] (is (= expected-value (->value crdt2 [] schema) (->value acrdt [] schema))))) (comment (krun #'test-nested-merge-array-no-conflict)) (deftest test-nested-merge-array-no-conflict (let [arg0 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema} {crdt0 :crdt crdt0-ops :crdt-ops} (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt crdt0 :schema pet-owner-schema} arg2 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :pets -1]}] :root :zeno/crdt :crdt crdt0 :schema pet-owner-schema} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) {merged-crdt :crdt rc-ops :repair-crdt-ops} (apply-ops/apply-ops {:crdt crdt0 :crdt-ops new-crdt-ops :schema pet-owner-schema}) expected-value [{:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} {:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"} {:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"}]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [:pets] :schema pet-owner-schema}))))) (deftest test-nested-merge-array-conflict (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) arg0 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :make-id make-id} arg2 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt :pets 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema pet-owner-schema})) expected-value [{:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} {:name "PI:NAME:<NAME>END_PI" :species "Canis familiaris"} {:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [:pets] :schema pet-owner-schema}))))) (deftest test-merge-3-way-array-conflict (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "2" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "3" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) ;; Order of the first three items is determined by their add-ids. ;; Any ordering would be fine, as long as it is deterministic. ;; The important part is that all three appear before the original ;; sequence (["A" "B"]). expected-value ["2" "3" "1" "A" "B"] v (crdt/get-value {:crdt merged-crdt :path [] :schema schema})] (is (= expected-value v)))) (deftest test-merge-3-way-array-conflict-multiple-peer-cmds (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "X1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "X2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "Y1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Y2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "Z1" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "Z2" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) ;; Order of the first three pairs of items is determined by their ;; add-ids. Any ordering would be fine, as long as it is deterministic. ;; The important part is that all three appear before the original ;; sequence (["A" "B"]) and that the Xs, Ys, and Zs are not interleaved. expected-value ["Y1" "Y2" "Z1" "Z2" "X1" "X2" "A" "B"]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :path [] :schema schema}))))) (deftest test-merge-multiple-conflicts (let [*next-id-num (atom 0) make-id #(let [n (swap! *next-id-num inc)] (str "I" n)) schema (l/array-schema l/string-schema) arg0 {:cmds [{:zeno/arg ["A" "B" "C"] :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :make-id make-id} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "XF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "XL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg2 {:cmds [{:zeno/arg "YF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "YL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} arg3 {:cmds [{:zeno/arg "ZF" :zeno/op :zeno/insert-before :zeno/path [:zeno/crdt 0]} {:zeno/arg "ZL" :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :crdt (:crdt ret0) :schema schema :make-id make-id} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) ret3 (commands/process-cmds arg3) new-crdt-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2) (:crdt-ops ret3)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops new-crdt-ops :schema schema})) expected-value ["XF" "YF" "ZF" "A" "B" "C" "XL" "YL" "ZL"]] (is (= expected-value (crdt/get-value {:crdt merged-crdt :make-id make-id :path [] :schema schema}))))) (deftest test-nested-merge-conflict (let [arg0 {:cmds [{:zeno/arg {:name "PI:NAME:<NAME>END_PI" :pets [{:name "PI:NAME:<NAME>END_PI" :species "Felis catus"} {:name "PI:NAME:<NAME>END_PI" :species "Carassius auratus"}]} :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema pet-owner-schema} ret0 (commands/process-cmds arg0) arg1 {:cmds [{:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :sys-time-ms (u/str->long "1640205282000")} arg2 {:cmds [{:zeno/arg "PI:NAME:<NAME>END_PI" :zeno/op :zeno/set :zeno/path [:zeno/crdt :pets -1 :name]}] :root :zeno/crdt :crdt (:crdt ret0) :schema pet-owner-schema :sys-time-ms (u/str->long "1640205282999")} ret1 (commands/process-cmds arg1) ret2 (commands/process-cmds arg2) all-ops (set/union (:crdt-ops ret1) (:crdt-ops ret2)) merged-crdt (:crdt (apply-ops/apply-ops {:crdt (:crdt ret0) :crdt-ops all-ops :schema pet-owner-schema}))] ;; We expect "PI:NAME:<NAME>END_PI" because its sys-time-ms is later (is (= "PI:NAME:<NAME>END_PI" (crdt/get-value {:crdt merged-crdt :path [:pets -1 :name] :schema pet-owner-schema}))))) (deftest test-set-into-empty-array (let [arg {:cmds [{:zeno/arg "1" :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema (l/array-schema l/string-schema)}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"arg is not sequential" (commands/process-cmds arg))))) (comment (krun #'test-set-map-of-two-arrays)) (deftest test-set-map-of-two-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" [1] "b" [2]} schema (l/map-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-set-nested-map-of-two-arrays)) (deftest test-set-nested-map-of-two-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" {"aa" [1]} "b" {"bb" [2]}} schema (l/map-schema (l/map-schema (l/array-schema l/int-schema))) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set {:capture-output? true})) (deftest test-crdt-nested-arrays-set (let [sys-time-ms (u/str->long "1643061294782") value [[[[[1 2]]]] [[[[3]] [[4]]]] [[[[5]]] [[[6 7]]]]] schema (-> l/int-schema l/array-schema l/array-schema l/array-schema l/array-schema l/array-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set-index)) (deftest test-crdt-nested-arrays-set-index (let [sys-time-ms (u/str->long "1643061294782") schema (l/array-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg [[1 2] [2]] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg [3] :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} expected-value [[1 2] [3]] {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-crdt-nested-arrays-set-index-out-of-bounds)) (deftest test-crdt-nested-arrays-set-index-out-of-bounds (let [sys-time-ms (u/str->long "1643061294782") arg {:cmds [{:zeno/arg [[1 2]] :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/arg [3] :zeno/op :zeno/set :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema (l/array-schema (l/array-schema l/int-schema)) :sys-time-ms sys-time-ms}] (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Index .* into array .* is out of bounds" (commands/process-cmds arg))))) (comment (krun #'test-set-nested-map-of-two-nested-arrays)) (deftest test-set-nested-map-of-two-nested-arrays (let [sys-time-ms (u/str->long "1643061294782") value {"a" {"aa" [[1 2] [3]]} "b" {"bb" [[4 5] [6]]}} schema (-> l/int-schema l/array-schema l/array-schema l/map-schema l/map-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-set-remove-nested-arrays)) (deftest test-set-remove-nested-arrays (let [sys-time-ms (u/str->long "1643061294782") value [[1 2] [3]] schema (l/array-schema (l/array-schema l/int-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 0 1]} {:zeno/op :zeno/remove :zeno/path [:zeno/crdt 1]}] :root :zeno/crdt :schema schema :sys-time-ms sys-time-ms} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [[1]]] (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array)) (deftest test-empty-array (let [value [] schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array-as-value)) (deftest test-empty-array-as-value (let [value {"a" []} schema (l/map-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-empty-array-in-record)) (deftest test-empty-array-in-record (let [value [] schema (l/record-schema :r1 [[:a (l/array-schema l/string-schema)]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt :a]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt [:a] schema) (->value acrdt [:a] schema))))) (comment (krun #'test-empty-array-in-map)) (deftest test-empty-array-in-map (let [value [] schema (l/map-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/set :zeno/path [:zeno/crdt "a"]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= value (->value crdt ["a"] schema) (->value acrdt ["a"] schema))))) (comment (krun #'test-record-nested-negative-insert-after)) (deftest test-record-nested-negative-insert-after (let [value "id" schema (l/record-schema :r1 [[:a (l/array-schema l/string-schema)]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :a -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:a [value]}] (is (= value (->value crdt [:a -1] schema) (->value acrdt [:a -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-array-insert-after)) (deftest test-array-insert-after (let [value "id" schema (l/array-schema l/string-schema) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [value]] (is (= value (->value crdt [-1] schema) (->value acrdt [-1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-array-nested-insert-after)) (deftest test-array-nested-insert-after (let [value "id" schema (l/array-schema (l/array-schema l/string-schema)) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt 0 -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value [[value]]] (is (= value (->value crdt [0 -1] schema) (->value acrdt [0 -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-nested-negative-insert-after (let [value 42 schema (l/map-schema (l/map-schema (l/array-schema l/int-schema))) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt "a" "b" 0]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {"a" {"b" [value]}}] (is (= value (->value crdt ["a" "b" 0] schema) (->value acrdt ["a" "b" 0] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (comment (krun #'test-deep-nested-negative-insert-after)) (deftest test-deep-nested-negative-insert-after (let [value "id" schema (l/record-schema :r1 [[:a (l/map-schema (l/array-schema (l/map-schema (l/record-schema :r2 [[:d (l/array-schema (l/array-schema l/string-schema))]]))))]]) arg {:cmds [{:zeno/arg value :zeno/op :zeno/insert-after :zeno/path [:zeno/crdt :a "b" 0 "c" :d 0 -1]}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema) expected-value {:a {"b" [{"c" {:d [[value]]}}]}}] (is (= value (->value crdt [:a "b" 0 "c" :d 0 -1] schema) (->value acrdt [:a "b" 0 "c" :d 0 -1] schema))) (is (= expected-value (->value crdt [] schema) (->value acrdt [] schema))))) (deftest test-recursive-schema (let [data {:value 42 :right-child {:value 3 :right-child {:value 8 :right-child {:value 21} :left-child {:value 43}} :left-child {:value 8 :right-child {:value 21} :left-child {:value 43}}} :left-child {:value 3 :right-child {:value 8 :right-child {:value 21} :left-child {:value 43}} :left-child {:value 8 :right-child {:value 21} :left-child {:value 43}}}} schema tree-schema arg {:cmds [{:zeno/arg data :zeno/op :zeno/set :zeno/path []}] :root :zeno/crdt :schema schema} {:keys [crdt crdt-ops]} (commands/process-cmds arg) acrdt (ops->crdt crdt-ops schema)] (is (= data (->value crdt [] schema) (->value acrdt [] schema)))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998140335083008, "start": 96, "tag": "NAME", "value": "Ragnar Svensson" }, { "context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ", "end": 129, "score": 0.999824583530426, "start": 113, "tag": "NAME", "value": "Christian Murray" }, { "context": "orld\n [name1 [CacheTestNode :scalar \"Jane\"]\n name2 [CacheTestNode :scalar \"Do", "end": 2846, "score": 0.9586354494094849, "start": 2842, "tag": "NAME", "value": "Jane" }, { "context": "ne\"]\n name2 [CacheTestNode :scalar \"Doe\"]\n combiner CacheTestNode\n e", "end": 2897, "score": 0.9979798793792725, "start": 2894, "tag": "NAME", "value": "Doe" }, { "context": " \"uncached values are unaffected\"\n (is (= \"Jane\" (g/node-value name1 :uncached-value)))))))\n\n(def", "end": 3503, "score": 0.999327540397644, "start": 3499, "tag": "NAME", "value": "Jane" }, { "context": "ve] (build-sample-project world)]\n (is (= \"Jane Doe\" (g/node-value combiner :derived-value)))\n ", "end": 3760, "score": 0.9993101954460144, "start": 3752, "tag": "NAME", "value": "Jane Doe" }, { "context": "ve] (build-sample-project world)]\n (is (= \"Jane Doe\" (g/node-value combiner :derived-value)))\n ", "end": 4664, "score": 0.9988700747489929, "start": 4656, "tag": "NAME", "value": "Jane Doe" }, { "context": "ly \"John\") []))\n (is (= \"John Doe\" (g/node-value combiner :derived-value)))))))\n\n ", "end": 4904, "score": 0.9994755983352661, "start": 4896, "tag": "NAME", "value": "John Doe" }, { "context": "ve] (build-sample-project world)]\n (is (= \"Jane\" (g/node-value combiner :nickname)))\n (exp", "end": 5476, "score": 0.9993425011634827, "start": 5472, "tag": "NAME", "value": "Jane" }, { "context": "ct (it/update-property name1 :scalar (constantly \"Mark\") []))\n (is (= \"Mark\" (g", "end": 5662, "score": 0.9998024106025696, "start": 5658, "tag": "NAME", "value": "Mark" }, { "context": "ly \"Mark\") []))\n (is (= \"Mark\" (g/node-value combiner :nickname))))\n (ex", "end": 5708, "score": 0.9998694658279419, "start": 5704, "tag": "NAME", "value": "Mark" }, { "context": "ct (it/update-property name2 :scalar (constantly \"Brandenburg\") []))\n (is (= \"Mark\"", "end": 5908, "score": 0.9995765089988708, "start": 5897, "tag": "NAME", "value": "Brandenburg" }, { "context": "nburg\") []))\n (is (= \"Mark\" (g/node-value combiner :nickname)))\n ", "end": 5957, "score": 0.9998650550842285, "start": 5953, "tag": "NAME", "value": "Mark" }, { "context": ":nickname)))\n (is (= \"Mark Brandenburg\" (g/node-value combiner :derived-value))))))))\n\n(", "end": 6048, "score": 0.9997541308403015, "start": 6032, "tag": "NAME", "value": "Mark Brandenburg" } ]
editor/test/internal/value_test.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.value-test (:require [clojure.test :refer :all] [dynamo.graph :as g] [internal.util :as util] [internal.node :as in] [internal.transaction :as it] [support.test-support :as ts] [internal.graph.error-values :as ie]) (:import [internal.graph.error_values ErrorValue])) (def ^:dynamic *calls*) (defn tally [node fn-symbol] (swap! *calls* update-in [node fn-symbol] (fnil inc 0))) (defn get-tally [node fn-symbol] (get-in @*calls* [node fn-symbol] 0)) (defmacro expect-call-when [node fn-symbol & body] `(let [calls-before# (get-tally ~node ~fn-symbol)] ~@body (is (= (inc calls-before#) (get-tally ~node ~fn-symbol))))) (defmacro expect-no-call-when [node fn-symbol & body] `(let [calls-before# (get-tally ~node ~fn-symbol)] ~@body (is (= calls-before# (get-tally ~node ~fn-symbol))))) (defn- cached? [cache node-id label] (contains? cache [node-id label])) (g/defnode CacheTestNode (input first-name g/Str) (input last-name g/Str) (input operand g/Str) (property scalar g/Str) (output uncached-value g/Str (g/fnk [_node-id scalar] (tally _node-id 'produce-simple-value) scalar)) (output expensive-value g/Str :cached (g/fnk [_node-id] (tally _node-id 'compute-expensive-value) "this took a long time to produce")) (output nickname g/Str :cached (g/fnk [_node-id first-name] (tally _node-id 'passthrough-first-name) first-name)) (output derived-value g/Str :cached (g/fnk [_node-id first-name last-name] (tally _node-id 'compute-derived-value) (str first-name " " last-name))) (output another-value g/Str :cached (g/fnk [_node-id] "this is distinct from the other outputs")) (output nil-value g/Str :cached (g/fnk [_this] (tally _this 'compute-nil-value) nil))) (defn build-sample-project [world] (g/tx-nodes-added (g/transact (g/make-nodes world [name1 [CacheTestNode :scalar "Jane"] name2 [CacheTestNode :scalar "Doe"] combiner CacheTestNode expensive CacheTestNode nil-val CacheTestNode] (g/connect name1 :uncached-value combiner :first-name) (g/connect name2 :uncached-value combiner :last-name) (g/connect name1 :uncached-value expensive :operand))))) (defn with-function-counts [f] (binding [*calls* (atom {})] (f))) (use-fixtures :each with-function-counts) (deftest project-cache (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (testing "uncached values are unaffected" (is (= "Jane" (g/node-value name1 :uncached-value))))))) (deftest caching-avoids-computation (testing "cached values are only computed once" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "Jane Doe" (g/node-value combiner :derived-value))) (expect-no-call-when combiner 'compute-derived-value (doseq [x (range 100)] (g/node-value combiner :derived-value)))))) (testing "cached nil values are only computed once" (ts/with-clean-system (let [[name1 name2 combiner expensive nil-value] (build-sample-project world)] (is (nil? (g/node-value nil-value :nil-value))) (expect-no-call-when nil-value 'compute-nil-value (doseq [x (range 100)] (g/node-value nil-value :nil-value))) (let [cache (g/cache)] (is (cached? cache nil-value :nil-value)))))) (testing "modifying inputs invalidates the cached value" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "Jane Doe" (g/node-value combiner :derived-value))) (expect-call-when combiner 'compute-derived-value (g/transact (it/update-property name1 :scalar (constantly "John") [])) (is (= "John Doe" (g/node-value combiner :derived-value))))))) (testing "cached values are distinct" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "this is distinct from the other outputs" (g/node-value combiner :another-value))) (is (not= (g/node-value combiner :another-value) (g/node-value combiner :expensive-value)))))) (testing "cache invalidation only hits dependent outputs" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "Jane" (g/node-value combiner :nickname))) (expect-call-when combiner 'passthrough-first-name (g/transact (it/update-property name1 :scalar (constantly "Mark") [])) (is (= "Mark" (g/node-value combiner :nickname)))) (expect-no-call-when combiner 'passthrough-first-name (g/transact (it/update-property name2 :scalar (constantly "Brandenburg") [])) (is (= "Mark" (g/node-value combiner :nickname))) (is (= "Mark Brandenburg" (g/node-value combiner :derived-value)))))))) (g/defnode OverrideValueNode (property int-prop g/Int) (property name g/Str) (input overridden g/Str) (input an-input g/Str) (output output g/Str (g/fnk [overridden] overridden)) (output foo g/Str (g/fnk [an-input] an-input))) (defn build-override-project [world] (let [nodes (ts/tx-nodes (g/make-node world OverrideValueNode) (g/make-node world CacheTestNode :scalar "Jane")) [override jane] nodes] (g/transact (g/connect jane :uncached-value override :overridden)) nodes)) (deftest invalid-resource-values (ts/with-clean-system (let [[override jane] (build-override-project world)] (testing "requesting a non-existent label throws" (is (thrown? AssertionError (g/node-value override :aint-no-thang))))))) (deftest update-sees-in-transaction-value (ts/with-clean-system (let [[node] (ts/tx-nodes (g/make-node world OverrideValueNode :name "a project" :int-prop 0)) after-transaction (g/transact (concat (g/update-property node :int-prop inc) (g/update-property node :int-prop inc) (g/update-property node :int-prop inc) (g/update-property node :int-prop inc)))] (is (= 4 (g/node-value node :int-prop)))))) (g/defnode OutputChaining (property a-property g/Int (default 0)) (output chained-output g/Int :cached (g/fnk [a-property] (inc a-property)))) (deftest output-caching-does-not-accidentally-cache-inputs (ts/with-clean-system (let [[node-id] (ts/tx-nodes (g/make-node world OutputChaining))] (g/node-value node-id :chained-output) (let [cache (g/cache)] (is (cached? cache node-id :chained-output)) (is (not (cached? cache node-id :a-property))))))) (g/defnode Source (property constant g/Keyword)) (g/defnode ValuePrecedence (property overloaded-output-input-property g/Keyword (default :property)) (output overloaded-output-input-property g/Keyword (g/fnk [] :output)) (input overloaded-input-property g/Keyword) (output overloaded-input-property g/Keyword (g/fnk [overloaded-input-property] overloaded-input-property)) (property the-property g/Keyword (default :property)) (output output-using-overloaded-output-input-property g/Keyword (g/fnk [overloaded-output-input-property] overloaded-output-input-property)) (input eponymous g/Keyword) (output eponymous g/Keyword (g/fnk [eponymous] eponymous)) (property position g/Keyword (default :position-property)) (output position g/Str (g/fnk [position] (name position))) (output transform g/Str (g/fnk [position] position)) (input renderables g/Keyword :array) (output renderables g/Str (g/fnk [renderables] (apply str (mapcat name renderables)))) (output transform-renderables g/Str (g/fnk [renderables] renderables))) (deftest node-value-precedence (ts/with-clean-system (let [[node s1] (ts/tx-nodes (g/make-node world ValuePrecedence) (g/make-node world Source :constant :input))] (g/transact (concat (g/connect s1 :constant node :overloaded-input-property) (g/connect s1 :constant node :eponymous))) (is (= :output (g/node-value node :overloaded-output-input-property))) (is (= :input (g/node-value node :overloaded-input-property))) (is (= :property (g/node-value node :the-property))) (is (= :output (g/node-value node :output-using-overloaded-output-input-property))) (is (= :input (g/node-value node :eponymous))) (is (= "position-property" (g/node-value node :transform))))) (testing "output uses another output, which is a function of an input with the same name" (ts/with-clean-system (let [[combiner s1 s2 s3] (ts/tx-nodes (g/make-node world ValuePrecedence) (g/make-node world Source :constant :source-1) (g/make-node world Source :constant :source-2) (g/make-node world Source :constant :source-3))] (g/transact (concat (g/connect s1 :constant combiner :renderables) (g/connect s2 :constant combiner :renderables) (g/connect s3 :constant combiner :renderables))) (is (= "source-1source-2source-3" (g/node-value combiner :transform-renderables))))))) (deftest invalidation-across-graphs (ts/with-clean-system (let [project-graph (g/make-graph! :history true) view-graph (g/make-graph! :volatility 100) [content-node aux-node] (ts/tx-nodes (g/make-node project-graph CacheTestNode :scalar "Snake") (g/make-node project-graph CacheTestNode :scalar "Plissken")) [view-node] (ts/tx-nodes (g/make-node view-graph CacheTestNode))] (g/transact [(g/connect content-node :scalar view-node :first-name) (g/connect aux-node :scalar view-node :last-name)]) (expect-call-when view-node 'compute-derived-value (is (= "Snake Plissken" (g/node-value view-node :derived-value)))) (g/transact (g/set-property aux-node :scalar "Solid")) (expect-call-when view-node 'compute-derived-value (is (= "Snake Solid" (g/node-value view-node :derived-value)))) (g/transact [(g/disconnect aux-node :scalar view-node :last-name) (g/disconnect content-node :scalar view-node :first-name) (g/connect aux-node :scalar view-node :first-name) (g/connect content-node :scalar view-node :last-name)]) (expect-call-when view-node 'compute-derived-value (is (= "Solid Snake" (g/node-value view-node :derived-value)))) (expect-no-call-when view-node 'compute-derived-value (is (= "Solid Snake" (g/node-value view-node :derived-value))))))) (g/defnode SubstitutingInputsNode (input unary-no-sub g/Any) (input multi-no-sub g/Any :array) (input unary-with-sub g/Any :substitute 99) (input multi-with-sub g/Any :array :substitute (fn [err] (util/map-vals #(if (g/error? %) 4848 %) err))) (output unary-no-sub g/Any (g/fnk [unary-no-sub] unary-no-sub)) (output multi-no-sub g/Any (g/fnk [multi-no-sub] multi-no-sub)) (output unary-with-sub g/Any (g/fnk [unary-with-sub] unary-with-sub)) (output multi-with-sub g/Any (g/fnk [multi-with-sub] multi-with-sub))) (g/defnode ConstantNode (output nil-output g/Any (g/fnk [] nil)) (output scalar-with-error g/Any (g/fnk [] (g/error-fatal :scalar))) (output scalar g/Any (g/fnk [] 1)) (output everything g/Any (g/fnk [] 42))) (defn arrange-sv-error [label connected? source-label] (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-node world SubstitutingInputsNode) (g/make-node world ConstantNode))] (when connected? (g/transact (g/connect const source-label receiver label))) (def sv-val (g/node-value receiver label)) (g/node-value receiver label)))) (deftest error-value-replacement (testing "source doesn't send errors" (ts/with-clean-system (are [label connected? source-label expected-pfn-val] (= expected-pfn-val (arrange-sv-error label connected? source-label)) ;; output-label connected? source-label expected-pfn :unary-no-sub false :dontcare nil :multi-no-sub false :dontcare '() :unary-with-sub false :dontcare nil :multi-with-sub false :dontcare '() :unary-no-sub true :nil-output nil :unary-with-sub true :nil-output nil :unary-no-sub true :scalar 1 :unary-with-sub true :everything 42 :multi-no-sub true :scalar '(1) :multi-with-sub true :everything '(42)))) (binding [in/*suppress-schema-warnings* true] (testing "source sends errors" (testing "unary inputs" (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-nodes world [receiver SubstitutingInputsNode const ConstantNode] (g/connect const :scalar-with-error receiver :unary-no-sub) (g/connect const :scalar-with-error receiver :unary-with-sub)))] (is (g/error? (g/node-value receiver :unary-no-sub))) (is (= 99 (g/node-value receiver :unary-with-sub)))))) (testing "multivalued inputs" (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-nodes world [receiver SubstitutingInputsNode const ConstantNode] (g/connect const :scalar receiver :multi-no-sub) (g/connect const :scalar-with-error receiver :multi-no-sub) (g/connect const :scalar receiver :multi-no-sub) (g/connect const :everything receiver :multi-no-sub) (g/connect const :scalar receiver :multi-with-sub) (g/connect const :scalar-with-error receiver :multi-with-sub) (g/connect const :scalar receiver :multi-with-sub) (g/connect const :everything receiver :multi-with-sub)))] (is (g/error? (g/node-value receiver :multi-no-sub))) (is (= [1 4848 1 42] (g/node-value receiver :multi-with-sub))))))))) (g/defnode StringInputIntOutputNode (input string-input g/Str) (output int-output g/Str (g/fnk [] 1)) (output combined g/Str (g/fnk [string-input] string-input))) (deftest input-schema-validation-warnings (binding [in/*suppress-schema-warnings* true] (testing "schema validations on inputs" (ts/with-clean-system (let [[node1] (ts/tx-nodes (g/make-node world StringInputIntOutputNode))] (g/transact (g/connect node1 :int-output node1 :string-input)) (is (thrown-with-msg? Exception #"SCHEMA-VALIDATION" (g/node-value node1 :combined)))))))) (g/defnode ConstantPropertyNode (property a-property g/Any)) (defn- cause [ev] (when (instance? ErrorValue ev) (first (:causes ev)))) (deftest error-values-are-not-wrapped-from-properties (ts/with-clean-system (let [[node] (ts/tx-nodes (g/make-node world ConstantPropertyNode)) _ (g/mark-defective! node (g/error-fatal "bad")) error-value (g/node-value node :a-property)] (is (g/error? error-value)) (is (empty? (:causes error-value))) (is (= node (:_node-id error-value))) (is (= :a-property (:_label error-value))) (is (= :fatal (:severity error-value)))))) (g/defnode ErrorReceiverNode (input single g/Any) (input multi g/Any :array) (output single-output g/Any (g/fnk [single] single)) (output multi-output g/Any (g/fnk [multi] multi))) (deftest error-values-are-aggregated (testing "single-valued input with an error results in single error out." (ts/with-clean-system (let [[sender receiver] (ts/tx-nodes (g/make-nodes world [sender ConstantPropertyNode receiver ErrorReceiverNode] (g/connect sender :a-property receiver :single))) _ (g/mark-defective! sender (g/error-fatal "Bad news, my friend.")) error-value (g/node-value receiver :single-output)] (are [node label sev e] (and (= node (:_node-id e)) (= label (:_label e)) (= sev (:severity error-value))) receiver :single-output :fatal error-value receiver :single :fatal (cause error-value) sender :a-property :fatal (cause (cause error-value)))))) (testing "multi-valued input with an error results in a single error out." (ts/with-clean-system (let [[sender1 sender2 sender3 receiver] (ts/tx-nodes (g/make-nodes world [sender1 [ConstantPropertyNode :a-property 1] sender2 [ConstantPropertyNode :a-property 2] sender3 [ConstantPropertyNode :a-property 3] receiver ErrorReceiverNode] (g/connect sender1 :a-property receiver :multi) (g/connect sender2 :a-property receiver :multi) (g/connect sender3 :a-property receiver :multi))) _ (g/mark-defective! sender2 (g/error-fatal "Bad things have happened")) error-value (g/node-value receiver :multi-output)] (are [node label sev e] (and (= node (:_node-id e)) (= label (:_label e)) (= sev (:severity error-value))) receiver :multi-output :fatal error-value receiver :multi :fatal (cause error-value) sender2 :a-property :fatal (cause (cause error-value))))))) (g/defnode ListOutput (output list-output g/Any (g/fnk [] (list 1))) (output recycle g/Any (g/fnk [list-output] list-output)) (output inner-list-output g/Any (g/fnk [] [(list 1)])) (output inner-recycle g/Any (g/fnk [inner-list-output] inner-list-output))) (g/defnode ListInput (input list-input g/Any) (input inner-list-input g/Any)) (g/defnode VecOutput (output vec-output g/Any (g/fnk [] [1])) (output recycle g/Any (g/fnk [vec-output] vec-output)) (output inner-vec-output g/Any (g/fnk [] (list [1]))) (output inner-recycle g/Any (g/fnk [inner-vec-output] inner-vec-output))) (g/defnode VecInput (input vec-input g/Any) (input inner-vec-input g/Any)) (deftest list-values-are-preserved (ts/with-clean-system (let [list-type (type (list 1)) [output input] (ts/tx-nodes (g/make-nodes world [output ListOutput input ListInput] (g/connect output :list-output input :list-input) (g/connect output :inner-list-output input :inner-list-input)))] (is (= list-type (type (g/node-value output :recycle)))) (is (= list-type (type (g/node-value input :list-input)))) (is (= list-type (type (first (g/node-value output :inner-recycle))))) (is (= list-type (type (first (g/node-value input :inner-list-input)))))))) (deftest vec-values-are-preserved (ts/with-clean-system (let [vec-type (type (vector 1)) [output input] (ts/tx-nodes (g/make-nodes world [output VecOutput input VecInput] (g/connect output :vec-output input :vec-input) (g/connect output :inner-vec-output input :inner-vec-input)))] (is (= vec-type (type (g/node-value output :recycle)))) (is (= vec-type (type (g/node-value input :vec-input)))) (is (= vec-type (type (first (g/node-value output :inner-recycle))))) (is (= vec-type (type (first (g/node-value input :inner-vec-input)))))))) (g/defnode ConstantOutputNode (property real-val g/Any (default (list 1))) (output val g/Any (g/fnk [real-val] real-val))) (deftest values-are-not-reconstructed-on-happy-path (ts/with-clean-system (let [[const input] (ts/tx-nodes (g/make-nodes world [const ConstantOutputNode input ListInput] (g/connect const :val input :list-input)))] (is (identical? (g/node-value const :val) (g/node-value const :val))) (is (identical? (g/node-value const :val) (g/node-value input :list-input))))))
121461
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.value-test (:require [clojure.test :refer :all] [dynamo.graph :as g] [internal.util :as util] [internal.node :as in] [internal.transaction :as it] [support.test-support :as ts] [internal.graph.error-values :as ie]) (:import [internal.graph.error_values ErrorValue])) (def ^:dynamic *calls*) (defn tally [node fn-symbol] (swap! *calls* update-in [node fn-symbol] (fnil inc 0))) (defn get-tally [node fn-symbol] (get-in @*calls* [node fn-symbol] 0)) (defmacro expect-call-when [node fn-symbol & body] `(let [calls-before# (get-tally ~node ~fn-symbol)] ~@body (is (= (inc calls-before#) (get-tally ~node ~fn-symbol))))) (defmacro expect-no-call-when [node fn-symbol & body] `(let [calls-before# (get-tally ~node ~fn-symbol)] ~@body (is (= calls-before# (get-tally ~node ~fn-symbol))))) (defn- cached? [cache node-id label] (contains? cache [node-id label])) (g/defnode CacheTestNode (input first-name g/Str) (input last-name g/Str) (input operand g/Str) (property scalar g/Str) (output uncached-value g/Str (g/fnk [_node-id scalar] (tally _node-id 'produce-simple-value) scalar)) (output expensive-value g/Str :cached (g/fnk [_node-id] (tally _node-id 'compute-expensive-value) "this took a long time to produce")) (output nickname g/Str :cached (g/fnk [_node-id first-name] (tally _node-id 'passthrough-first-name) first-name)) (output derived-value g/Str :cached (g/fnk [_node-id first-name last-name] (tally _node-id 'compute-derived-value) (str first-name " " last-name))) (output another-value g/Str :cached (g/fnk [_node-id] "this is distinct from the other outputs")) (output nil-value g/Str :cached (g/fnk [_this] (tally _this 'compute-nil-value) nil))) (defn build-sample-project [world] (g/tx-nodes-added (g/transact (g/make-nodes world [name1 [CacheTestNode :scalar "<NAME>"] name2 [CacheTestNode :scalar "<NAME>"] combiner CacheTestNode expensive CacheTestNode nil-val CacheTestNode] (g/connect name1 :uncached-value combiner :first-name) (g/connect name2 :uncached-value combiner :last-name) (g/connect name1 :uncached-value expensive :operand))))) (defn with-function-counts [f] (binding [*calls* (atom {})] (f))) (use-fixtures :each with-function-counts) (deftest project-cache (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (testing "uncached values are unaffected" (is (= "<NAME>" (g/node-value name1 :uncached-value))))))) (deftest caching-avoids-computation (testing "cached values are only computed once" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "<NAME>" (g/node-value combiner :derived-value))) (expect-no-call-when combiner 'compute-derived-value (doseq [x (range 100)] (g/node-value combiner :derived-value)))))) (testing "cached nil values are only computed once" (ts/with-clean-system (let [[name1 name2 combiner expensive nil-value] (build-sample-project world)] (is (nil? (g/node-value nil-value :nil-value))) (expect-no-call-when nil-value 'compute-nil-value (doseq [x (range 100)] (g/node-value nil-value :nil-value))) (let [cache (g/cache)] (is (cached? cache nil-value :nil-value)))))) (testing "modifying inputs invalidates the cached value" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "<NAME>" (g/node-value combiner :derived-value))) (expect-call-when combiner 'compute-derived-value (g/transact (it/update-property name1 :scalar (constantly "John") [])) (is (= "<NAME>" (g/node-value combiner :derived-value))))))) (testing "cached values are distinct" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "this is distinct from the other outputs" (g/node-value combiner :another-value))) (is (not= (g/node-value combiner :another-value) (g/node-value combiner :expensive-value)))))) (testing "cache invalidation only hits dependent outputs" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "<NAME>" (g/node-value combiner :nickname))) (expect-call-when combiner 'passthrough-first-name (g/transact (it/update-property name1 :scalar (constantly "<NAME>") [])) (is (= "<NAME>" (g/node-value combiner :nickname)))) (expect-no-call-when combiner 'passthrough-first-name (g/transact (it/update-property name2 :scalar (constantly "<NAME>") [])) (is (= "<NAME>" (g/node-value combiner :nickname))) (is (= "<NAME>" (g/node-value combiner :derived-value)))))))) (g/defnode OverrideValueNode (property int-prop g/Int) (property name g/Str) (input overridden g/Str) (input an-input g/Str) (output output g/Str (g/fnk [overridden] overridden)) (output foo g/Str (g/fnk [an-input] an-input))) (defn build-override-project [world] (let [nodes (ts/tx-nodes (g/make-node world OverrideValueNode) (g/make-node world CacheTestNode :scalar "Jane")) [override jane] nodes] (g/transact (g/connect jane :uncached-value override :overridden)) nodes)) (deftest invalid-resource-values (ts/with-clean-system (let [[override jane] (build-override-project world)] (testing "requesting a non-existent label throws" (is (thrown? AssertionError (g/node-value override :aint-no-thang))))))) (deftest update-sees-in-transaction-value (ts/with-clean-system (let [[node] (ts/tx-nodes (g/make-node world OverrideValueNode :name "a project" :int-prop 0)) after-transaction (g/transact (concat (g/update-property node :int-prop inc) (g/update-property node :int-prop inc) (g/update-property node :int-prop inc) (g/update-property node :int-prop inc)))] (is (= 4 (g/node-value node :int-prop)))))) (g/defnode OutputChaining (property a-property g/Int (default 0)) (output chained-output g/Int :cached (g/fnk [a-property] (inc a-property)))) (deftest output-caching-does-not-accidentally-cache-inputs (ts/with-clean-system (let [[node-id] (ts/tx-nodes (g/make-node world OutputChaining))] (g/node-value node-id :chained-output) (let [cache (g/cache)] (is (cached? cache node-id :chained-output)) (is (not (cached? cache node-id :a-property))))))) (g/defnode Source (property constant g/Keyword)) (g/defnode ValuePrecedence (property overloaded-output-input-property g/Keyword (default :property)) (output overloaded-output-input-property g/Keyword (g/fnk [] :output)) (input overloaded-input-property g/Keyword) (output overloaded-input-property g/Keyword (g/fnk [overloaded-input-property] overloaded-input-property)) (property the-property g/Keyword (default :property)) (output output-using-overloaded-output-input-property g/Keyword (g/fnk [overloaded-output-input-property] overloaded-output-input-property)) (input eponymous g/Keyword) (output eponymous g/Keyword (g/fnk [eponymous] eponymous)) (property position g/Keyword (default :position-property)) (output position g/Str (g/fnk [position] (name position))) (output transform g/Str (g/fnk [position] position)) (input renderables g/Keyword :array) (output renderables g/Str (g/fnk [renderables] (apply str (mapcat name renderables)))) (output transform-renderables g/Str (g/fnk [renderables] renderables))) (deftest node-value-precedence (ts/with-clean-system (let [[node s1] (ts/tx-nodes (g/make-node world ValuePrecedence) (g/make-node world Source :constant :input))] (g/transact (concat (g/connect s1 :constant node :overloaded-input-property) (g/connect s1 :constant node :eponymous))) (is (= :output (g/node-value node :overloaded-output-input-property))) (is (= :input (g/node-value node :overloaded-input-property))) (is (= :property (g/node-value node :the-property))) (is (= :output (g/node-value node :output-using-overloaded-output-input-property))) (is (= :input (g/node-value node :eponymous))) (is (= "position-property" (g/node-value node :transform))))) (testing "output uses another output, which is a function of an input with the same name" (ts/with-clean-system (let [[combiner s1 s2 s3] (ts/tx-nodes (g/make-node world ValuePrecedence) (g/make-node world Source :constant :source-1) (g/make-node world Source :constant :source-2) (g/make-node world Source :constant :source-3))] (g/transact (concat (g/connect s1 :constant combiner :renderables) (g/connect s2 :constant combiner :renderables) (g/connect s3 :constant combiner :renderables))) (is (= "source-1source-2source-3" (g/node-value combiner :transform-renderables))))))) (deftest invalidation-across-graphs (ts/with-clean-system (let [project-graph (g/make-graph! :history true) view-graph (g/make-graph! :volatility 100) [content-node aux-node] (ts/tx-nodes (g/make-node project-graph CacheTestNode :scalar "Snake") (g/make-node project-graph CacheTestNode :scalar "Plissken")) [view-node] (ts/tx-nodes (g/make-node view-graph CacheTestNode))] (g/transact [(g/connect content-node :scalar view-node :first-name) (g/connect aux-node :scalar view-node :last-name)]) (expect-call-when view-node 'compute-derived-value (is (= "Snake Plissken" (g/node-value view-node :derived-value)))) (g/transact (g/set-property aux-node :scalar "Solid")) (expect-call-when view-node 'compute-derived-value (is (= "Snake Solid" (g/node-value view-node :derived-value)))) (g/transact [(g/disconnect aux-node :scalar view-node :last-name) (g/disconnect content-node :scalar view-node :first-name) (g/connect aux-node :scalar view-node :first-name) (g/connect content-node :scalar view-node :last-name)]) (expect-call-when view-node 'compute-derived-value (is (= "Solid Snake" (g/node-value view-node :derived-value)))) (expect-no-call-when view-node 'compute-derived-value (is (= "Solid Snake" (g/node-value view-node :derived-value))))))) (g/defnode SubstitutingInputsNode (input unary-no-sub g/Any) (input multi-no-sub g/Any :array) (input unary-with-sub g/Any :substitute 99) (input multi-with-sub g/Any :array :substitute (fn [err] (util/map-vals #(if (g/error? %) 4848 %) err))) (output unary-no-sub g/Any (g/fnk [unary-no-sub] unary-no-sub)) (output multi-no-sub g/Any (g/fnk [multi-no-sub] multi-no-sub)) (output unary-with-sub g/Any (g/fnk [unary-with-sub] unary-with-sub)) (output multi-with-sub g/Any (g/fnk [multi-with-sub] multi-with-sub))) (g/defnode ConstantNode (output nil-output g/Any (g/fnk [] nil)) (output scalar-with-error g/Any (g/fnk [] (g/error-fatal :scalar))) (output scalar g/Any (g/fnk [] 1)) (output everything g/Any (g/fnk [] 42))) (defn arrange-sv-error [label connected? source-label] (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-node world SubstitutingInputsNode) (g/make-node world ConstantNode))] (when connected? (g/transact (g/connect const source-label receiver label))) (def sv-val (g/node-value receiver label)) (g/node-value receiver label)))) (deftest error-value-replacement (testing "source doesn't send errors" (ts/with-clean-system (are [label connected? source-label expected-pfn-val] (= expected-pfn-val (arrange-sv-error label connected? source-label)) ;; output-label connected? source-label expected-pfn :unary-no-sub false :dontcare nil :multi-no-sub false :dontcare '() :unary-with-sub false :dontcare nil :multi-with-sub false :dontcare '() :unary-no-sub true :nil-output nil :unary-with-sub true :nil-output nil :unary-no-sub true :scalar 1 :unary-with-sub true :everything 42 :multi-no-sub true :scalar '(1) :multi-with-sub true :everything '(42)))) (binding [in/*suppress-schema-warnings* true] (testing "source sends errors" (testing "unary inputs" (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-nodes world [receiver SubstitutingInputsNode const ConstantNode] (g/connect const :scalar-with-error receiver :unary-no-sub) (g/connect const :scalar-with-error receiver :unary-with-sub)))] (is (g/error? (g/node-value receiver :unary-no-sub))) (is (= 99 (g/node-value receiver :unary-with-sub)))))) (testing "multivalued inputs" (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-nodes world [receiver SubstitutingInputsNode const ConstantNode] (g/connect const :scalar receiver :multi-no-sub) (g/connect const :scalar-with-error receiver :multi-no-sub) (g/connect const :scalar receiver :multi-no-sub) (g/connect const :everything receiver :multi-no-sub) (g/connect const :scalar receiver :multi-with-sub) (g/connect const :scalar-with-error receiver :multi-with-sub) (g/connect const :scalar receiver :multi-with-sub) (g/connect const :everything receiver :multi-with-sub)))] (is (g/error? (g/node-value receiver :multi-no-sub))) (is (= [1 4848 1 42] (g/node-value receiver :multi-with-sub))))))))) (g/defnode StringInputIntOutputNode (input string-input g/Str) (output int-output g/Str (g/fnk [] 1)) (output combined g/Str (g/fnk [string-input] string-input))) (deftest input-schema-validation-warnings (binding [in/*suppress-schema-warnings* true] (testing "schema validations on inputs" (ts/with-clean-system (let [[node1] (ts/tx-nodes (g/make-node world StringInputIntOutputNode))] (g/transact (g/connect node1 :int-output node1 :string-input)) (is (thrown-with-msg? Exception #"SCHEMA-VALIDATION" (g/node-value node1 :combined)))))))) (g/defnode ConstantPropertyNode (property a-property g/Any)) (defn- cause [ev] (when (instance? ErrorValue ev) (first (:causes ev)))) (deftest error-values-are-not-wrapped-from-properties (ts/with-clean-system (let [[node] (ts/tx-nodes (g/make-node world ConstantPropertyNode)) _ (g/mark-defective! node (g/error-fatal "bad")) error-value (g/node-value node :a-property)] (is (g/error? error-value)) (is (empty? (:causes error-value))) (is (= node (:_node-id error-value))) (is (= :a-property (:_label error-value))) (is (= :fatal (:severity error-value)))))) (g/defnode ErrorReceiverNode (input single g/Any) (input multi g/Any :array) (output single-output g/Any (g/fnk [single] single)) (output multi-output g/Any (g/fnk [multi] multi))) (deftest error-values-are-aggregated (testing "single-valued input with an error results in single error out." (ts/with-clean-system (let [[sender receiver] (ts/tx-nodes (g/make-nodes world [sender ConstantPropertyNode receiver ErrorReceiverNode] (g/connect sender :a-property receiver :single))) _ (g/mark-defective! sender (g/error-fatal "Bad news, my friend.")) error-value (g/node-value receiver :single-output)] (are [node label sev e] (and (= node (:_node-id e)) (= label (:_label e)) (= sev (:severity error-value))) receiver :single-output :fatal error-value receiver :single :fatal (cause error-value) sender :a-property :fatal (cause (cause error-value)))))) (testing "multi-valued input with an error results in a single error out." (ts/with-clean-system (let [[sender1 sender2 sender3 receiver] (ts/tx-nodes (g/make-nodes world [sender1 [ConstantPropertyNode :a-property 1] sender2 [ConstantPropertyNode :a-property 2] sender3 [ConstantPropertyNode :a-property 3] receiver ErrorReceiverNode] (g/connect sender1 :a-property receiver :multi) (g/connect sender2 :a-property receiver :multi) (g/connect sender3 :a-property receiver :multi))) _ (g/mark-defective! sender2 (g/error-fatal "Bad things have happened")) error-value (g/node-value receiver :multi-output)] (are [node label sev e] (and (= node (:_node-id e)) (= label (:_label e)) (= sev (:severity error-value))) receiver :multi-output :fatal error-value receiver :multi :fatal (cause error-value) sender2 :a-property :fatal (cause (cause error-value))))))) (g/defnode ListOutput (output list-output g/Any (g/fnk [] (list 1))) (output recycle g/Any (g/fnk [list-output] list-output)) (output inner-list-output g/Any (g/fnk [] [(list 1)])) (output inner-recycle g/Any (g/fnk [inner-list-output] inner-list-output))) (g/defnode ListInput (input list-input g/Any) (input inner-list-input g/Any)) (g/defnode VecOutput (output vec-output g/Any (g/fnk [] [1])) (output recycle g/Any (g/fnk [vec-output] vec-output)) (output inner-vec-output g/Any (g/fnk [] (list [1]))) (output inner-recycle g/Any (g/fnk [inner-vec-output] inner-vec-output))) (g/defnode VecInput (input vec-input g/Any) (input inner-vec-input g/Any)) (deftest list-values-are-preserved (ts/with-clean-system (let [list-type (type (list 1)) [output input] (ts/tx-nodes (g/make-nodes world [output ListOutput input ListInput] (g/connect output :list-output input :list-input) (g/connect output :inner-list-output input :inner-list-input)))] (is (= list-type (type (g/node-value output :recycle)))) (is (= list-type (type (g/node-value input :list-input)))) (is (= list-type (type (first (g/node-value output :inner-recycle))))) (is (= list-type (type (first (g/node-value input :inner-list-input)))))))) (deftest vec-values-are-preserved (ts/with-clean-system (let [vec-type (type (vector 1)) [output input] (ts/tx-nodes (g/make-nodes world [output VecOutput input VecInput] (g/connect output :vec-output input :vec-input) (g/connect output :inner-vec-output input :inner-vec-input)))] (is (= vec-type (type (g/node-value output :recycle)))) (is (= vec-type (type (g/node-value input :vec-input)))) (is (= vec-type (type (first (g/node-value output :inner-recycle))))) (is (= vec-type (type (first (g/node-value input :inner-vec-input)))))))) (g/defnode ConstantOutputNode (property real-val g/Any (default (list 1))) (output val g/Any (g/fnk [real-val] real-val))) (deftest values-are-not-reconstructed-on-happy-path (ts/with-clean-system (let [[const input] (ts/tx-nodes (g/make-nodes world [const ConstantOutputNode input ListInput] (g/connect const :val input :list-input)))] (is (identical? (g/node-value const :val) (g/node-value const :val))) (is (identical? (g/node-value const :val) (g/node-value input :list-input))))))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.value-test (:require [clojure.test :refer :all] [dynamo.graph :as g] [internal.util :as util] [internal.node :as in] [internal.transaction :as it] [support.test-support :as ts] [internal.graph.error-values :as ie]) (:import [internal.graph.error_values ErrorValue])) (def ^:dynamic *calls*) (defn tally [node fn-symbol] (swap! *calls* update-in [node fn-symbol] (fnil inc 0))) (defn get-tally [node fn-symbol] (get-in @*calls* [node fn-symbol] 0)) (defmacro expect-call-when [node fn-symbol & body] `(let [calls-before# (get-tally ~node ~fn-symbol)] ~@body (is (= (inc calls-before#) (get-tally ~node ~fn-symbol))))) (defmacro expect-no-call-when [node fn-symbol & body] `(let [calls-before# (get-tally ~node ~fn-symbol)] ~@body (is (= calls-before# (get-tally ~node ~fn-symbol))))) (defn- cached? [cache node-id label] (contains? cache [node-id label])) (g/defnode CacheTestNode (input first-name g/Str) (input last-name g/Str) (input operand g/Str) (property scalar g/Str) (output uncached-value g/Str (g/fnk [_node-id scalar] (tally _node-id 'produce-simple-value) scalar)) (output expensive-value g/Str :cached (g/fnk [_node-id] (tally _node-id 'compute-expensive-value) "this took a long time to produce")) (output nickname g/Str :cached (g/fnk [_node-id first-name] (tally _node-id 'passthrough-first-name) first-name)) (output derived-value g/Str :cached (g/fnk [_node-id first-name last-name] (tally _node-id 'compute-derived-value) (str first-name " " last-name))) (output another-value g/Str :cached (g/fnk [_node-id] "this is distinct from the other outputs")) (output nil-value g/Str :cached (g/fnk [_this] (tally _this 'compute-nil-value) nil))) (defn build-sample-project [world] (g/tx-nodes-added (g/transact (g/make-nodes world [name1 [CacheTestNode :scalar "PI:NAME:<NAME>END_PI"] name2 [CacheTestNode :scalar "PI:NAME:<NAME>END_PI"] combiner CacheTestNode expensive CacheTestNode nil-val CacheTestNode] (g/connect name1 :uncached-value combiner :first-name) (g/connect name2 :uncached-value combiner :last-name) (g/connect name1 :uncached-value expensive :operand))))) (defn with-function-counts [f] (binding [*calls* (atom {})] (f))) (use-fixtures :each with-function-counts) (deftest project-cache (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (testing "uncached values are unaffected" (is (= "PI:NAME:<NAME>END_PI" (g/node-value name1 :uncached-value))))))) (deftest caching-avoids-computation (testing "cached values are only computed once" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :derived-value))) (expect-no-call-when combiner 'compute-derived-value (doseq [x (range 100)] (g/node-value combiner :derived-value)))))) (testing "cached nil values are only computed once" (ts/with-clean-system (let [[name1 name2 combiner expensive nil-value] (build-sample-project world)] (is (nil? (g/node-value nil-value :nil-value))) (expect-no-call-when nil-value 'compute-nil-value (doseq [x (range 100)] (g/node-value nil-value :nil-value))) (let [cache (g/cache)] (is (cached? cache nil-value :nil-value)))))) (testing "modifying inputs invalidates the cached value" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :derived-value))) (expect-call-when combiner 'compute-derived-value (g/transact (it/update-property name1 :scalar (constantly "John") [])) (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :derived-value))))))) (testing "cached values are distinct" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "this is distinct from the other outputs" (g/node-value combiner :another-value))) (is (not= (g/node-value combiner :another-value) (g/node-value combiner :expensive-value)))))) (testing "cache invalidation only hits dependent outputs" (ts/with-clean-system (let [[name1 name2 combiner expensive] (build-sample-project world)] (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :nickname))) (expect-call-when combiner 'passthrough-first-name (g/transact (it/update-property name1 :scalar (constantly "PI:NAME:<NAME>END_PI") [])) (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :nickname)))) (expect-no-call-when combiner 'passthrough-first-name (g/transact (it/update-property name2 :scalar (constantly "PI:NAME:<NAME>END_PI") [])) (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :nickname))) (is (= "PI:NAME:<NAME>END_PI" (g/node-value combiner :derived-value)))))))) (g/defnode OverrideValueNode (property int-prop g/Int) (property name g/Str) (input overridden g/Str) (input an-input g/Str) (output output g/Str (g/fnk [overridden] overridden)) (output foo g/Str (g/fnk [an-input] an-input))) (defn build-override-project [world] (let [nodes (ts/tx-nodes (g/make-node world OverrideValueNode) (g/make-node world CacheTestNode :scalar "Jane")) [override jane] nodes] (g/transact (g/connect jane :uncached-value override :overridden)) nodes)) (deftest invalid-resource-values (ts/with-clean-system (let [[override jane] (build-override-project world)] (testing "requesting a non-existent label throws" (is (thrown? AssertionError (g/node-value override :aint-no-thang))))))) (deftest update-sees-in-transaction-value (ts/with-clean-system (let [[node] (ts/tx-nodes (g/make-node world OverrideValueNode :name "a project" :int-prop 0)) after-transaction (g/transact (concat (g/update-property node :int-prop inc) (g/update-property node :int-prop inc) (g/update-property node :int-prop inc) (g/update-property node :int-prop inc)))] (is (= 4 (g/node-value node :int-prop)))))) (g/defnode OutputChaining (property a-property g/Int (default 0)) (output chained-output g/Int :cached (g/fnk [a-property] (inc a-property)))) (deftest output-caching-does-not-accidentally-cache-inputs (ts/with-clean-system (let [[node-id] (ts/tx-nodes (g/make-node world OutputChaining))] (g/node-value node-id :chained-output) (let [cache (g/cache)] (is (cached? cache node-id :chained-output)) (is (not (cached? cache node-id :a-property))))))) (g/defnode Source (property constant g/Keyword)) (g/defnode ValuePrecedence (property overloaded-output-input-property g/Keyword (default :property)) (output overloaded-output-input-property g/Keyword (g/fnk [] :output)) (input overloaded-input-property g/Keyword) (output overloaded-input-property g/Keyword (g/fnk [overloaded-input-property] overloaded-input-property)) (property the-property g/Keyword (default :property)) (output output-using-overloaded-output-input-property g/Keyword (g/fnk [overloaded-output-input-property] overloaded-output-input-property)) (input eponymous g/Keyword) (output eponymous g/Keyword (g/fnk [eponymous] eponymous)) (property position g/Keyword (default :position-property)) (output position g/Str (g/fnk [position] (name position))) (output transform g/Str (g/fnk [position] position)) (input renderables g/Keyword :array) (output renderables g/Str (g/fnk [renderables] (apply str (mapcat name renderables)))) (output transform-renderables g/Str (g/fnk [renderables] renderables))) (deftest node-value-precedence (ts/with-clean-system (let [[node s1] (ts/tx-nodes (g/make-node world ValuePrecedence) (g/make-node world Source :constant :input))] (g/transact (concat (g/connect s1 :constant node :overloaded-input-property) (g/connect s1 :constant node :eponymous))) (is (= :output (g/node-value node :overloaded-output-input-property))) (is (= :input (g/node-value node :overloaded-input-property))) (is (= :property (g/node-value node :the-property))) (is (= :output (g/node-value node :output-using-overloaded-output-input-property))) (is (= :input (g/node-value node :eponymous))) (is (= "position-property" (g/node-value node :transform))))) (testing "output uses another output, which is a function of an input with the same name" (ts/with-clean-system (let [[combiner s1 s2 s3] (ts/tx-nodes (g/make-node world ValuePrecedence) (g/make-node world Source :constant :source-1) (g/make-node world Source :constant :source-2) (g/make-node world Source :constant :source-3))] (g/transact (concat (g/connect s1 :constant combiner :renderables) (g/connect s2 :constant combiner :renderables) (g/connect s3 :constant combiner :renderables))) (is (= "source-1source-2source-3" (g/node-value combiner :transform-renderables))))))) (deftest invalidation-across-graphs (ts/with-clean-system (let [project-graph (g/make-graph! :history true) view-graph (g/make-graph! :volatility 100) [content-node aux-node] (ts/tx-nodes (g/make-node project-graph CacheTestNode :scalar "Snake") (g/make-node project-graph CacheTestNode :scalar "Plissken")) [view-node] (ts/tx-nodes (g/make-node view-graph CacheTestNode))] (g/transact [(g/connect content-node :scalar view-node :first-name) (g/connect aux-node :scalar view-node :last-name)]) (expect-call-when view-node 'compute-derived-value (is (= "Snake Plissken" (g/node-value view-node :derived-value)))) (g/transact (g/set-property aux-node :scalar "Solid")) (expect-call-when view-node 'compute-derived-value (is (= "Snake Solid" (g/node-value view-node :derived-value)))) (g/transact [(g/disconnect aux-node :scalar view-node :last-name) (g/disconnect content-node :scalar view-node :first-name) (g/connect aux-node :scalar view-node :first-name) (g/connect content-node :scalar view-node :last-name)]) (expect-call-when view-node 'compute-derived-value (is (= "Solid Snake" (g/node-value view-node :derived-value)))) (expect-no-call-when view-node 'compute-derived-value (is (= "Solid Snake" (g/node-value view-node :derived-value))))))) (g/defnode SubstitutingInputsNode (input unary-no-sub g/Any) (input multi-no-sub g/Any :array) (input unary-with-sub g/Any :substitute 99) (input multi-with-sub g/Any :array :substitute (fn [err] (util/map-vals #(if (g/error? %) 4848 %) err))) (output unary-no-sub g/Any (g/fnk [unary-no-sub] unary-no-sub)) (output multi-no-sub g/Any (g/fnk [multi-no-sub] multi-no-sub)) (output unary-with-sub g/Any (g/fnk [unary-with-sub] unary-with-sub)) (output multi-with-sub g/Any (g/fnk [multi-with-sub] multi-with-sub))) (g/defnode ConstantNode (output nil-output g/Any (g/fnk [] nil)) (output scalar-with-error g/Any (g/fnk [] (g/error-fatal :scalar))) (output scalar g/Any (g/fnk [] 1)) (output everything g/Any (g/fnk [] 42))) (defn arrange-sv-error [label connected? source-label] (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-node world SubstitutingInputsNode) (g/make-node world ConstantNode))] (when connected? (g/transact (g/connect const source-label receiver label))) (def sv-val (g/node-value receiver label)) (g/node-value receiver label)))) (deftest error-value-replacement (testing "source doesn't send errors" (ts/with-clean-system (are [label connected? source-label expected-pfn-val] (= expected-pfn-val (arrange-sv-error label connected? source-label)) ;; output-label connected? source-label expected-pfn :unary-no-sub false :dontcare nil :multi-no-sub false :dontcare '() :unary-with-sub false :dontcare nil :multi-with-sub false :dontcare '() :unary-no-sub true :nil-output nil :unary-with-sub true :nil-output nil :unary-no-sub true :scalar 1 :unary-with-sub true :everything 42 :multi-no-sub true :scalar '(1) :multi-with-sub true :everything '(42)))) (binding [in/*suppress-schema-warnings* true] (testing "source sends errors" (testing "unary inputs" (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-nodes world [receiver SubstitutingInputsNode const ConstantNode] (g/connect const :scalar-with-error receiver :unary-no-sub) (g/connect const :scalar-with-error receiver :unary-with-sub)))] (is (g/error? (g/node-value receiver :unary-no-sub))) (is (= 99 (g/node-value receiver :unary-with-sub)))))) (testing "multivalued inputs" (ts/with-clean-system (let [[receiver const] (ts/tx-nodes (g/make-nodes world [receiver SubstitutingInputsNode const ConstantNode] (g/connect const :scalar receiver :multi-no-sub) (g/connect const :scalar-with-error receiver :multi-no-sub) (g/connect const :scalar receiver :multi-no-sub) (g/connect const :everything receiver :multi-no-sub) (g/connect const :scalar receiver :multi-with-sub) (g/connect const :scalar-with-error receiver :multi-with-sub) (g/connect const :scalar receiver :multi-with-sub) (g/connect const :everything receiver :multi-with-sub)))] (is (g/error? (g/node-value receiver :multi-no-sub))) (is (= [1 4848 1 42] (g/node-value receiver :multi-with-sub))))))))) (g/defnode StringInputIntOutputNode (input string-input g/Str) (output int-output g/Str (g/fnk [] 1)) (output combined g/Str (g/fnk [string-input] string-input))) (deftest input-schema-validation-warnings (binding [in/*suppress-schema-warnings* true] (testing "schema validations on inputs" (ts/with-clean-system (let [[node1] (ts/tx-nodes (g/make-node world StringInputIntOutputNode))] (g/transact (g/connect node1 :int-output node1 :string-input)) (is (thrown-with-msg? Exception #"SCHEMA-VALIDATION" (g/node-value node1 :combined)))))))) (g/defnode ConstantPropertyNode (property a-property g/Any)) (defn- cause [ev] (when (instance? ErrorValue ev) (first (:causes ev)))) (deftest error-values-are-not-wrapped-from-properties (ts/with-clean-system (let [[node] (ts/tx-nodes (g/make-node world ConstantPropertyNode)) _ (g/mark-defective! node (g/error-fatal "bad")) error-value (g/node-value node :a-property)] (is (g/error? error-value)) (is (empty? (:causes error-value))) (is (= node (:_node-id error-value))) (is (= :a-property (:_label error-value))) (is (= :fatal (:severity error-value)))))) (g/defnode ErrorReceiverNode (input single g/Any) (input multi g/Any :array) (output single-output g/Any (g/fnk [single] single)) (output multi-output g/Any (g/fnk [multi] multi))) (deftest error-values-are-aggregated (testing "single-valued input with an error results in single error out." (ts/with-clean-system (let [[sender receiver] (ts/tx-nodes (g/make-nodes world [sender ConstantPropertyNode receiver ErrorReceiverNode] (g/connect sender :a-property receiver :single))) _ (g/mark-defective! sender (g/error-fatal "Bad news, my friend.")) error-value (g/node-value receiver :single-output)] (are [node label sev e] (and (= node (:_node-id e)) (= label (:_label e)) (= sev (:severity error-value))) receiver :single-output :fatal error-value receiver :single :fatal (cause error-value) sender :a-property :fatal (cause (cause error-value)))))) (testing "multi-valued input with an error results in a single error out." (ts/with-clean-system (let [[sender1 sender2 sender3 receiver] (ts/tx-nodes (g/make-nodes world [sender1 [ConstantPropertyNode :a-property 1] sender2 [ConstantPropertyNode :a-property 2] sender3 [ConstantPropertyNode :a-property 3] receiver ErrorReceiverNode] (g/connect sender1 :a-property receiver :multi) (g/connect sender2 :a-property receiver :multi) (g/connect sender3 :a-property receiver :multi))) _ (g/mark-defective! sender2 (g/error-fatal "Bad things have happened")) error-value (g/node-value receiver :multi-output)] (are [node label sev e] (and (= node (:_node-id e)) (= label (:_label e)) (= sev (:severity error-value))) receiver :multi-output :fatal error-value receiver :multi :fatal (cause error-value) sender2 :a-property :fatal (cause (cause error-value))))))) (g/defnode ListOutput (output list-output g/Any (g/fnk [] (list 1))) (output recycle g/Any (g/fnk [list-output] list-output)) (output inner-list-output g/Any (g/fnk [] [(list 1)])) (output inner-recycle g/Any (g/fnk [inner-list-output] inner-list-output))) (g/defnode ListInput (input list-input g/Any) (input inner-list-input g/Any)) (g/defnode VecOutput (output vec-output g/Any (g/fnk [] [1])) (output recycle g/Any (g/fnk [vec-output] vec-output)) (output inner-vec-output g/Any (g/fnk [] (list [1]))) (output inner-recycle g/Any (g/fnk [inner-vec-output] inner-vec-output))) (g/defnode VecInput (input vec-input g/Any) (input inner-vec-input g/Any)) (deftest list-values-are-preserved (ts/with-clean-system (let [list-type (type (list 1)) [output input] (ts/tx-nodes (g/make-nodes world [output ListOutput input ListInput] (g/connect output :list-output input :list-input) (g/connect output :inner-list-output input :inner-list-input)))] (is (= list-type (type (g/node-value output :recycle)))) (is (= list-type (type (g/node-value input :list-input)))) (is (= list-type (type (first (g/node-value output :inner-recycle))))) (is (= list-type (type (first (g/node-value input :inner-list-input)))))))) (deftest vec-values-are-preserved (ts/with-clean-system (let [vec-type (type (vector 1)) [output input] (ts/tx-nodes (g/make-nodes world [output VecOutput input VecInput] (g/connect output :vec-output input :vec-input) (g/connect output :inner-vec-output input :inner-vec-input)))] (is (= vec-type (type (g/node-value output :recycle)))) (is (= vec-type (type (g/node-value input :vec-input)))) (is (= vec-type (type (first (g/node-value output :inner-recycle))))) (is (= vec-type (type (first (g/node-value input :inner-vec-input)))))))) (g/defnode ConstantOutputNode (property real-val g/Any (default (list 1))) (output val g/Any (g/fnk [real-val] real-val))) (deftest values-are-not-reconstructed-on-happy-path (ts/with-clean-system (let [[const input] (ts/tx-nodes (g/make-nodes world [const ConstantOutputNode input ListInput] (g/connect const :val input :list-input)))] (is (identical? (g/node-value const :val) (g/node-value const :val))) (is (identical? (g/node-value const :val) (g/node-value input :list-input))))))
[ { "context": " \"acl\" [\"john:rwx\" \"fred:rwx\"]})}\n {:resource \"2\" :parameters nil})", "end": 978, "score": 0.634812593460083, "start": 975, "tag": "NAME", "value": "red" }, { "context": ":name \"acl\" :value (db-serialize [\"john:rwx\" \"fred:rwx\"])})\n (sql/insert-records\n :cert", "end": 1361, "score": 0.9344388246536255, "start": 1358, "tag": "NAME", "value": "red" }, { "context": "\"\n :acl [\"john:rwx\" \"fred:rwx\"]}}\n :bar2 {:certname \"two.local\"\n ", "end": 4433, "score": 0.9070946574211121, "start": 4430, "tag": "NAME", "value": "red" } ]
test/puppetlabs/puppetdb/testutils/resources.clj
DemonShi/puppetdb
0
(ns puppetlabs.puppetdb.testutils.resources (:require [clojure.java.jdbc :as sql] [clojure.test :refer :all] [ring.mock.request :refer :all] [clj-time.core :refer [now]] [puppetlabs.puppetdb.fixtures :refer :all] [puppetlabs.puppetdb.jdbc :refer [with-transacted-connection]] [puppetlabs.puppetdb.scf.storage :refer [add-facts! ensure-environment]] [puppetlabs.puppetdb.scf.storage-utils :refer [db-serialize to-jdbc-varchar-array]])) (defn store-example-resources ([] (store-example-resources true)) ([environment?] (with-transacted-connection *db* (sql/insert-records :resource_params_cache {:resource "1" :parameters (db-serialize {"ensure" "file" "owner" "root" "group" "root" "acl" ["john:rwx" "fred:rwx"]})} {:resource "2" :parameters nil}) (sql/insert-records :resource_params {:resource "1" :name "ensure" :value (db-serialize "file")} {:resource "1" :name "owner" :value (db-serialize "root")} {:resource "1" :name "group" :value (db-serialize "root")} {:resource "1" :name "acl" :value (db-serialize ["john:rwx" "fred:rwx"])}) (sql/insert-records :certnames {:name "one.local"} {:name "two.local"}) (sql/insert-records :catalogs {:id 1 :hash "foo" :api_version 1 :catalog_version "12" :certname "one.local" :environment_id (when environment? (ensure-environment "DEV"))} {:id 2 :hash "bar" :api_version 1 :catalog_version "14" :certname "two.local" :environment_id (when environment? (ensure-environment "PROD"))}) (add-facts! {:name "one.local" :values {"operatingsystem" "Debian" "kernel" "Linux" "uptime_seconds" 50000} :timestamp (now) :environment "DEV" :producer-timestamp nil}) (add-facts! {:name "two.local" :values {"operatingsystem" "Ubuntu" "kernel" "Linux" "uptime_seconds" 10000 "message" "hello"} :timestamp (now) :environment "DEV" :producer-timestamp nil}) (sql/insert-records :catalog_resources {:catalog_id 1 :resource "1" :type "File" :title "/etc/passwd" :exported false :tags (to-jdbc-varchar-array ["one" "two"])} {:catalog_id 1 :resource "2" :type "Notify" :title "hello" :exported false :tags (to-jdbc-varchar-array [])} {:catalog_id 2 :resource "1" :type "File" :title "/etc/passwd" :exported false :tags (to-jdbc-varchar-array ["one" "two"])} {:catalog_id 2 :resource "2" :type "Notify" :title "hello" :exported true :file "/foo/bar" :line 22 :tags (to-jdbc-varchar-array [])})) {:foo1 {:certname "one.local" :resource "1" :type "File" :title "/etc/passwd" :tags ["one" "two"] :exported false :file nil :line nil :environment (when environment? "DEV") :parameters {:ensure "file" :owner "root" :group "root" :acl ["john:rwx" "fred:rwx"]}} :foo2 {:certname "one.local" :resource "2" :type "Notify" :title "hello" :tags [] :exported false :file nil :line nil :environment (when environment? "DEV") :parameters {}} :bar1 {:certname "two.local" :resource "1" :type "File" :title "/etc/passwd" :tags ["one" "two"] :exported false :file nil :line nil :environment (when environment? "PROD") :parameters {:ensure "file" :owner "root" :group "root" :acl ["john:rwx" "fred:rwx"]}} :bar2 {:certname "two.local" :resource "2" :type "Notify" :title "hello" :tags [] :exported true :file "/foo/bar" :line 22 :environment (when environment? "PROD") :parameters {}}}))
116958
(ns puppetlabs.puppetdb.testutils.resources (:require [clojure.java.jdbc :as sql] [clojure.test :refer :all] [ring.mock.request :refer :all] [clj-time.core :refer [now]] [puppetlabs.puppetdb.fixtures :refer :all] [puppetlabs.puppetdb.jdbc :refer [with-transacted-connection]] [puppetlabs.puppetdb.scf.storage :refer [add-facts! ensure-environment]] [puppetlabs.puppetdb.scf.storage-utils :refer [db-serialize to-jdbc-varchar-array]])) (defn store-example-resources ([] (store-example-resources true)) ([environment?] (with-transacted-connection *db* (sql/insert-records :resource_params_cache {:resource "1" :parameters (db-serialize {"ensure" "file" "owner" "root" "group" "root" "acl" ["john:rwx" "f<NAME>:rwx"]})} {:resource "2" :parameters nil}) (sql/insert-records :resource_params {:resource "1" :name "ensure" :value (db-serialize "file")} {:resource "1" :name "owner" :value (db-serialize "root")} {:resource "1" :name "group" :value (db-serialize "root")} {:resource "1" :name "acl" :value (db-serialize ["john:rwx" "f<NAME>:rwx"])}) (sql/insert-records :certnames {:name "one.local"} {:name "two.local"}) (sql/insert-records :catalogs {:id 1 :hash "foo" :api_version 1 :catalog_version "12" :certname "one.local" :environment_id (when environment? (ensure-environment "DEV"))} {:id 2 :hash "bar" :api_version 1 :catalog_version "14" :certname "two.local" :environment_id (when environment? (ensure-environment "PROD"))}) (add-facts! {:name "one.local" :values {"operatingsystem" "Debian" "kernel" "Linux" "uptime_seconds" 50000} :timestamp (now) :environment "DEV" :producer-timestamp nil}) (add-facts! {:name "two.local" :values {"operatingsystem" "Ubuntu" "kernel" "Linux" "uptime_seconds" 10000 "message" "hello"} :timestamp (now) :environment "DEV" :producer-timestamp nil}) (sql/insert-records :catalog_resources {:catalog_id 1 :resource "1" :type "File" :title "/etc/passwd" :exported false :tags (to-jdbc-varchar-array ["one" "two"])} {:catalog_id 1 :resource "2" :type "Notify" :title "hello" :exported false :tags (to-jdbc-varchar-array [])} {:catalog_id 2 :resource "1" :type "File" :title "/etc/passwd" :exported false :tags (to-jdbc-varchar-array ["one" "two"])} {:catalog_id 2 :resource "2" :type "Notify" :title "hello" :exported true :file "/foo/bar" :line 22 :tags (to-jdbc-varchar-array [])})) {:foo1 {:certname "one.local" :resource "1" :type "File" :title "/etc/passwd" :tags ["one" "two"] :exported false :file nil :line nil :environment (when environment? "DEV") :parameters {:ensure "file" :owner "root" :group "root" :acl ["john:rwx" "fred:rwx"]}} :foo2 {:certname "one.local" :resource "2" :type "Notify" :title "hello" :tags [] :exported false :file nil :line nil :environment (when environment? "DEV") :parameters {}} :bar1 {:certname "two.local" :resource "1" :type "File" :title "/etc/passwd" :tags ["one" "two"] :exported false :file nil :line nil :environment (when environment? "PROD") :parameters {:ensure "file" :owner "root" :group "root" :acl ["john:rwx" "f<NAME>:rwx"]}} :bar2 {:certname "two.local" :resource "2" :type "Notify" :title "hello" :tags [] :exported true :file "/foo/bar" :line 22 :environment (when environment? "PROD") :parameters {}}}))
true
(ns puppetlabs.puppetdb.testutils.resources (:require [clojure.java.jdbc :as sql] [clojure.test :refer :all] [ring.mock.request :refer :all] [clj-time.core :refer [now]] [puppetlabs.puppetdb.fixtures :refer :all] [puppetlabs.puppetdb.jdbc :refer [with-transacted-connection]] [puppetlabs.puppetdb.scf.storage :refer [add-facts! ensure-environment]] [puppetlabs.puppetdb.scf.storage-utils :refer [db-serialize to-jdbc-varchar-array]])) (defn store-example-resources ([] (store-example-resources true)) ([environment?] (with-transacted-connection *db* (sql/insert-records :resource_params_cache {:resource "1" :parameters (db-serialize {"ensure" "file" "owner" "root" "group" "root" "acl" ["john:rwx" "fPI:NAME:<NAME>END_PI:rwx"]})} {:resource "2" :parameters nil}) (sql/insert-records :resource_params {:resource "1" :name "ensure" :value (db-serialize "file")} {:resource "1" :name "owner" :value (db-serialize "root")} {:resource "1" :name "group" :value (db-serialize "root")} {:resource "1" :name "acl" :value (db-serialize ["john:rwx" "fPI:NAME:<NAME>END_PI:rwx"])}) (sql/insert-records :certnames {:name "one.local"} {:name "two.local"}) (sql/insert-records :catalogs {:id 1 :hash "foo" :api_version 1 :catalog_version "12" :certname "one.local" :environment_id (when environment? (ensure-environment "DEV"))} {:id 2 :hash "bar" :api_version 1 :catalog_version "14" :certname "two.local" :environment_id (when environment? (ensure-environment "PROD"))}) (add-facts! {:name "one.local" :values {"operatingsystem" "Debian" "kernel" "Linux" "uptime_seconds" 50000} :timestamp (now) :environment "DEV" :producer-timestamp nil}) (add-facts! {:name "two.local" :values {"operatingsystem" "Ubuntu" "kernel" "Linux" "uptime_seconds" 10000 "message" "hello"} :timestamp (now) :environment "DEV" :producer-timestamp nil}) (sql/insert-records :catalog_resources {:catalog_id 1 :resource "1" :type "File" :title "/etc/passwd" :exported false :tags (to-jdbc-varchar-array ["one" "two"])} {:catalog_id 1 :resource "2" :type "Notify" :title "hello" :exported false :tags (to-jdbc-varchar-array [])} {:catalog_id 2 :resource "1" :type "File" :title "/etc/passwd" :exported false :tags (to-jdbc-varchar-array ["one" "two"])} {:catalog_id 2 :resource "2" :type "Notify" :title "hello" :exported true :file "/foo/bar" :line 22 :tags (to-jdbc-varchar-array [])})) {:foo1 {:certname "one.local" :resource "1" :type "File" :title "/etc/passwd" :tags ["one" "two"] :exported false :file nil :line nil :environment (when environment? "DEV") :parameters {:ensure "file" :owner "root" :group "root" :acl ["john:rwx" "fred:rwx"]}} :foo2 {:certname "one.local" :resource "2" :type "Notify" :title "hello" :tags [] :exported false :file nil :line nil :environment (when environment? "DEV") :parameters {}} :bar1 {:certname "two.local" :resource "1" :type "File" :title "/etc/passwd" :tags ["one" "two"] :exported false :file nil :line nil :environment (when environment? "PROD") :parameters {:ensure "file" :owner "root" :group "root" :acl ["john:rwx" "fPI:NAME:<NAME>END_PI:rwx"]}} :bar2 {:certname "two.local" :resource "2" :type "Notify" :title "hello" :tags [] :exported true :file "/foo/bar" :line 22 :environment (when environment? "PROD") :parameters {}}}))
[ { "context": "{:url \"https://repo.clojars.org/\",\n :password :gpg,\n :username :gpg}]],\n :description\n \"Various g", "end": 602, "score": 0.988900899887085, "start": 599, "tag": "PASSWORD", "value": "gpg" }, { "context": "]*\\\\.(SF|RSA|DSA)$\\\"\"],\n :url \"https://github.com/tisnik/cljgfx\",\n :version \"0.1.0-SNAPSHOT\"}\n", "end": 3304, "score": 0.9782334566116333, "start": 3298, "tag": "USERNAME", "value": "tisnik" } ]
doc/details.clj
tisnik/cljgfx
0
{:aliases {"downgrade" "upgrade"}, :checkout-deps-shares [:source-paths :test-paths :resource-paths :compile-path "#'leiningen.core.classpath/checkout-deps-paths"], :clean-targets [:target-path], :compile-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target/classes", :dependencies ([org.clojure/clojure "1.10.1"] [nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])] [clojure-complete/clojure-complete "0.2.5" :exclusions ([org.clojure/clojure])] [venantius/ultra "0.6.0"]), :deploy-repositories [["clojars" {:url "https://repo.clojars.org/", :password :gpg, :username :gpg}]], :description "Various graphics-related utility functions for the Clojure", :eval-in :subprocess, :global-vars {}, :group "cljgfx", :jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""], :jvm-opts ["-XX:-OmitStackTraceInFastThrow" "-XX:+TieredCompilation" "-XX:TieredStopAtLevel=1"], :license {:name "Eclipse Public License", :url "http://www.eclipse.org/legal/epl-v10.html"}, :main cljgfx.core, :monkeypatch-clojure-test false, :name "cljgfx", :native-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target/native", :offline? false, :pedantic? ranges, :plugin-repositories [["central" {:url "https://repo1.maven.org/maven2/", :snapshots false}] ["clojars" {:url "https://repo.clojars.org/"}]], :plugins ([lein-codox/lein-codox "0.10.7"] [test2junit/test2junit "1.1.0"] [lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit/lein-kibit "0.1.8"] [lein-clean-m2/lein-clean-m2 "0.1.2"] [lein-project-edn/lein-project-edn "0.3.0"] [lein-marginalia/lein-marginalia "0.9.1"] [venantius/ultra "0.6.0"]), :prep-tasks ["javac" "compile"], :profiles {:whidbey/repl {:dependencies [[mvxcvi/whidbey "RELEASE"]], :repl-options {:init (do nil (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil)), :custom-init (do nil (whidbey.repl/update-print-fn!)), :nrepl-context {:interactive-eval {:printer whidbey.repl/render-str}}}}}, :project-edn {:output-file "doc/details.clj"}, :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]], :repl-options {:init (do (do (clojure.core/require 'ultra.hardcore) (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil) (ultra.hardcore/configure! {:repl {:print-meta false, :map-delimiter "", :print-fallback :print, :sort-keys true}})))}, :repositories [["central" {:url "https://repo1.maven.org/maven2/", :snapshots false}] ["clojars" {:url "https://repo.clojars.org/"}]], :resource-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/dev-resources" "/home/ptisnovs/src/clojure/xrepos/cljgfx/resources"), :root "/home/ptisnovs/src/clojure/xrepos/cljgfx", :source-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/src"), :target-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target", :test-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/test"), :test-selectors {:default (constantly true)}, :uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""], :url "https://github.com/tisnik/cljgfx", :version "0.1.0-SNAPSHOT"}
46878
{:aliases {"downgrade" "upgrade"}, :checkout-deps-shares [:source-paths :test-paths :resource-paths :compile-path "#'leiningen.core.classpath/checkout-deps-paths"], :clean-targets [:target-path], :compile-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target/classes", :dependencies ([org.clojure/clojure "1.10.1"] [nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])] [clojure-complete/clojure-complete "0.2.5" :exclusions ([org.clojure/clojure])] [venantius/ultra "0.6.0"]), :deploy-repositories [["clojars" {:url "https://repo.clojars.org/", :password :<PASSWORD>, :username :gpg}]], :description "Various graphics-related utility functions for the Clojure", :eval-in :subprocess, :global-vars {}, :group "cljgfx", :jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""], :jvm-opts ["-XX:-OmitStackTraceInFastThrow" "-XX:+TieredCompilation" "-XX:TieredStopAtLevel=1"], :license {:name "Eclipse Public License", :url "http://www.eclipse.org/legal/epl-v10.html"}, :main cljgfx.core, :monkeypatch-clojure-test false, :name "cljgfx", :native-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target/native", :offline? false, :pedantic? ranges, :plugin-repositories [["central" {:url "https://repo1.maven.org/maven2/", :snapshots false}] ["clojars" {:url "https://repo.clojars.org/"}]], :plugins ([lein-codox/lein-codox "0.10.7"] [test2junit/test2junit "1.1.0"] [lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit/lein-kibit "0.1.8"] [lein-clean-m2/lein-clean-m2 "0.1.2"] [lein-project-edn/lein-project-edn "0.3.0"] [lein-marginalia/lein-marginalia "0.9.1"] [venantius/ultra "0.6.0"]), :prep-tasks ["javac" "compile"], :profiles {:whidbey/repl {:dependencies [[mvxcvi/whidbey "RELEASE"]], :repl-options {:init (do nil (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil)), :custom-init (do nil (whidbey.repl/update-print-fn!)), :nrepl-context {:interactive-eval {:printer whidbey.repl/render-str}}}}}, :project-edn {:output-file "doc/details.clj"}, :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]], :repl-options {:init (do (do (clojure.core/require 'ultra.hardcore) (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil) (ultra.hardcore/configure! {:repl {:print-meta false, :map-delimiter "", :print-fallback :print, :sort-keys true}})))}, :repositories [["central" {:url "https://repo1.maven.org/maven2/", :snapshots false}] ["clojars" {:url "https://repo.clojars.org/"}]], :resource-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/dev-resources" "/home/ptisnovs/src/clojure/xrepos/cljgfx/resources"), :root "/home/ptisnovs/src/clojure/xrepos/cljgfx", :source-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/src"), :target-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target", :test-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/test"), :test-selectors {:default (constantly true)}, :uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""], :url "https://github.com/tisnik/cljgfx", :version "0.1.0-SNAPSHOT"}
true
{:aliases {"downgrade" "upgrade"}, :checkout-deps-shares [:source-paths :test-paths :resource-paths :compile-path "#'leiningen.core.classpath/checkout-deps-paths"], :clean-targets [:target-path], :compile-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target/classes", :dependencies ([org.clojure/clojure "1.10.1"] [nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])] [clojure-complete/clojure-complete "0.2.5" :exclusions ([org.clojure/clojure])] [venantius/ultra "0.6.0"]), :deploy-repositories [["clojars" {:url "https://repo.clojars.org/", :password :PI:PASSWORD:<PASSWORD>END_PI, :username :gpg}]], :description "Various graphics-related utility functions for the Clojure", :eval-in :subprocess, :global-vars {}, :group "cljgfx", :jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""], :jvm-opts ["-XX:-OmitStackTraceInFastThrow" "-XX:+TieredCompilation" "-XX:TieredStopAtLevel=1"], :license {:name "Eclipse Public License", :url "http://www.eclipse.org/legal/epl-v10.html"}, :main cljgfx.core, :monkeypatch-clojure-test false, :name "cljgfx", :native-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target/native", :offline? false, :pedantic? ranges, :plugin-repositories [["central" {:url "https://repo1.maven.org/maven2/", :snapshots false}] ["clojars" {:url "https://repo.clojars.org/"}]], :plugins ([lein-codox/lein-codox "0.10.7"] [test2junit/test2junit "1.1.0"] [lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit/lein-kibit "0.1.8"] [lein-clean-m2/lein-clean-m2 "0.1.2"] [lein-project-edn/lein-project-edn "0.3.0"] [lein-marginalia/lein-marginalia "0.9.1"] [venantius/ultra "0.6.0"]), :prep-tasks ["javac" "compile"], :profiles {:whidbey/repl {:dependencies [[mvxcvi/whidbey "RELEASE"]], :repl-options {:init (do nil (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil)), :custom-init (do nil (whidbey.repl/update-print-fn!)), :nrepl-context {:interactive-eval {:printer whidbey.repl/render-str}}}}}, :project-edn {:output-file "doc/details.clj"}, :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]], :repl-options {:init (do (do (clojure.core/require 'ultra.hardcore) (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil) (ultra.hardcore/configure! {:repl {:print-meta false, :map-delimiter "", :print-fallback :print, :sort-keys true}})))}, :repositories [["central" {:url "https://repo1.maven.org/maven2/", :snapshots false}] ["clojars" {:url "https://repo.clojars.org/"}]], :resource-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/dev-resources" "/home/ptisnovs/src/clojure/xrepos/cljgfx/resources"), :root "/home/ptisnovs/src/clojure/xrepos/cljgfx", :source-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/src"), :target-path "/home/ptisnovs/src/clojure/xrepos/cljgfx/target", :test-paths ("/home/ptisnovs/src/clojure/xrepos/cljgfx/test"), :test-selectors {:default (constantly true)}, :uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""], :url "https://github.com/tisnik/cljgfx", :version "0.1.0-SNAPSHOT"}
[ { "context": "eanstalk Royalties\" \"Hedge Fund\" \"Project Beale\" \"Ben Musashi\"]}})\n (core/gain state :corp :click 10)\n ", "end": 2485, "score": 0.9997785687446594, "start": 2474, "tag": "NAME", "value": "Ben Musashi" }, { "context": "t, zero cost\")\n (play-from-hand state :corp \"Ben Musashi\" \"Server 1\")\n (is (last-log-contains? state ", "end": 3150, "score": 0.999567985534668, "start": 3139, "tag": "NAME", "value": "Ben Musashi" }, { "context": "redit 10)\n (play-from-hand state :runner \"Corroder\")\n (run-on state :hq)\n (let [cor (ge", "end": 8524, "score": 0.5882826447486877, "start": 8522, "tag": "NAME", "value": "ro" } ]
test/clj/game_test/engine/costs.clj
usairman82/netrunner
0
(ns game-test.engine.costs (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (deftest merge-costs (testing "Non-damage costs" (testing "No defaults, already merged" (is (= [[:credit 1]] (core/merge-costs [[:credit 1]])))) (testing "Costs are already flattened" (is (= [[:credit 1] [:click 1]] (core/merge-costs [[:credit 1 :click 1]])))) (testing "Passed as a flattened vec" (is (= [[:credit 1]] (core/merge-costs [:credit 1])))) (testing "Default type is only element" (is (= [[:credit 1]] (core/merge-costs [[:credit]])))) (testing "Default plus explicit" (is (= [[:click 1] [:credit 1]] (core/merge-costs [[:click :credit 1]])))) (testing "Costs ending with defaults expand" (is (= [[:credit 1] [:click 1]] (core/merge-costs [[:credit 1 :click]])))) (testing "Non-damage costs aren't reordered" (is (not= [[:credit 1] [:click 1]] (core/merge-costs [[:click 1 :credit 1]])))) (testing "Costs with all defaults are expanded" (is (= [[:click 1] [:credit 1]] (core/merge-costs [[:click :credit]])))) (testing "Non-damage costs are combined" (is (= [[:click 4] [:credit 2]] (core/merge-costs [[:click 1] [:click 3] [:credit 1] [:credit 1]])))) (testing "Deeply nested costs are flattened" (is (= [[:click 3]] (core/merge-costs [[[[[:click 1]]] [[[[[:click 1]]]]]] :click 1])))) (testing "Empty costs return an empty list" (is (= '() (core/merge-costs [])))) (testing "nil costs return an empty list" (is (= '() (core/merge-costs nil))))) (testing "Damage costs" (testing "Damage costs are moved to the end" (is (= [[:credit 1] [:net 1]] (core/merge-costs [[:net 1 :credit 1]])))) (testing "Damage isn't combined" (is (= [[:net 1] [:net 1]] (core/merge-costs [[:net 1 :net 1]])))) (testing "Net, meat, and brain damage are recognized" (is (= [[:net 1] [:meat 1] [:brain 1]] (core/merge-costs [[:net 1] [:meat 1] [:brain 1]])))))) (deftest pay-credits (testing "Testing several cost messages" (do-game (new-game {:runner {:hand ["Diesel" "Daily Casts" "Clot" "Career Fair" "Daily Casts" "Sure Gamble" "Misdirection"]} :corp {:hand [(qty "Ice Wall" 2) "Turtlebacks" "Beanstalk Royalties" "Hedge Fund" "Project Beale" "Ben Musashi"]}}) (core/gain state :corp :click 10) (play-from-hand state :corp "Ice Wall" "HQ") (is (last-log-contains? state "Corp spends \\[Click\\] and pays 0 \\[Credits\\] to install ICE protecting HQ.") "Install ICE, zero cost") (play-from-hand state :corp "Ice Wall" "HQ") (is (last-log-contains? state "Corp spends \\[Click\\] and pays 1 \\[Credits\\] to install ICE protecting HQ.") "Install ICE, one cost") (play-from-hand state :corp "Turtlebacks" "New remote") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 1.") "Install asset, zero cost") (play-from-hand state :corp "Ben Musashi" "Server 1") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 1.") "Install upgrade, zero cost") (play-from-hand state :corp "Project Beale" "New remote") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 2.") "Install agenda, zero cost") (play-from-hand state :corp "Beanstalk Royalties") (is (second-last-log-contains? state "Corp spends \\[Click\\] and pays 0 \\[Credits\\] to play Beanstalk Royalties.") "Play operation, zero cost") (play-from-hand state :corp "Hedge Fund") (is (second-last-log-contains? state "Corp spends \\[Click\\] and pays 5 \\[Credits\\] to play Hedge Fund.") "Play operation, five cost") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Diesel") (is (second-last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to play Diesel.") "Play event, zero cost") (play-from-hand state :runner "Sure Gamble") (is (second-last-log-contains? state "Runner spends \\[Click\\] and pays 5 \\[Credits\\] to play Sure Gamble.") "Play event, five cost") (play-from-hand state :runner "Clot") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 2 \\[Credits\\] to install Clot.") "Install program, two cost") (play-from-hand state :runner "Misdirection") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to install Misdirection.") "Install program, zero cost") (play-from-hand state :runner "Career Fair") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to play Career Fair.") "Play Career Fair, zero cost") (click-card state :runner (find-card "Daily Casts" (:hand (get-runner)))) (is (last-log-contains? state "Runner pays 0 \\[Credits\\] to install Daily Casts.") "Choose Daily cast, zero cost install") (play-from-hand state :runner "Daily Casts") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 3 \\[Credits\\] to install Daily Casts.") "Install resource, three cost") (run-on state :archives) (is (last-log-contains? state "Runner spends \\[Click\\] to make a run on Archives.") "Initiate run, zero cost"))) (testing "Issue #4295: Auto-pumping Icebreaker with pay-credits prompt" (do-game (new-game {:runner {:hand ["Corroder" "Net Mercur" "Cloak"]} :corp {:hand ["Fire Wall"]}}) (play-from-hand state :corp "Fire Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Net Mercur") (run-on state :hq) (let [cre (:credit (get-runner)) cor (get-program state 0) clo (get-program state 1) nm (get-resource state 0)] (is (= 2 (:current-strength (refresh cor))) "Corroder starts at 2 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (click-card state :runner clo) (click-prompt state :runner "Place 1 [Credits]") (is (= 5 (:current-strength (refresh cor))) "Corroder is at 5 strength") (is (= (- cre 2) (:credit (get-runner))) "Spent 2 (+1 from Cloak) to pump"))))) (deftest pump-and-break (testing "Basic test" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (is (= 2 (:current-strength (refresh cor))) "Corroder starts at 2 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder now at 3 strength") (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken")))) (testing "Auto-pump first" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder now at 3 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken")))) (testing "Auto-pump and break some subs manually first" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder is now at 3 strength") (card-ability state :runner (refresh cor) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (= 4 (count (remove :broken (:subroutines (refresh hive))))) "Only broken 1 sub") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken"))))) (deftest run-additional-costs (testing "If runner cannot pay additional cost, server not shown as an option for run events or click to run button" (do-game (new-game {:corp {:deck ["Ruhr Valley"]} :runner {:deck ["Dirty Laundry"]}}) (play-from-hand state :corp "Ruhr Valley" "HQ") (take-credits state :corp) (let [ruhr (get-content state :hq 0)] (core/rez state :corp ruhr) (core/gain state :runner :click -3) (is (= 1 (:click (get-runner)))) (play-from-hand state :runner "Dirty Laundry") (is (= 2 (-> (get-runner) :prompt first :choices count)) "Runner should only get choice of Archives or R&D") (is (not (some #{"HQ"} (-> (get-runner) :prompt first :choices))) "Runner should only get choice of Archives or R&D")))))
53058
(ns game-test.engine.costs (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (deftest merge-costs (testing "Non-damage costs" (testing "No defaults, already merged" (is (= [[:credit 1]] (core/merge-costs [[:credit 1]])))) (testing "Costs are already flattened" (is (= [[:credit 1] [:click 1]] (core/merge-costs [[:credit 1 :click 1]])))) (testing "Passed as a flattened vec" (is (= [[:credit 1]] (core/merge-costs [:credit 1])))) (testing "Default type is only element" (is (= [[:credit 1]] (core/merge-costs [[:credit]])))) (testing "Default plus explicit" (is (= [[:click 1] [:credit 1]] (core/merge-costs [[:click :credit 1]])))) (testing "Costs ending with defaults expand" (is (= [[:credit 1] [:click 1]] (core/merge-costs [[:credit 1 :click]])))) (testing "Non-damage costs aren't reordered" (is (not= [[:credit 1] [:click 1]] (core/merge-costs [[:click 1 :credit 1]])))) (testing "Costs with all defaults are expanded" (is (= [[:click 1] [:credit 1]] (core/merge-costs [[:click :credit]])))) (testing "Non-damage costs are combined" (is (= [[:click 4] [:credit 2]] (core/merge-costs [[:click 1] [:click 3] [:credit 1] [:credit 1]])))) (testing "Deeply nested costs are flattened" (is (= [[:click 3]] (core/merge-costs [[[[[:click 1]]] [[[[[:click 1]]]]]] :click 1])))) (testing "Empty costs return an empty list" (is (= '() (core/merge-costs [])))) (testing "nil costs return an empty list" (is (= '() (core/merge-costs nil))))) (testing "Damage costs" (testing "Damage costs are moved to the end" (is (= [[:credit 1] [:net 1]] (core/merge-costs [[:net 1 :credit 1]])))) (testing "Damage isn't combined" (is (= [[:net 1] [:net 1]] (core/merge-costs [[:net 1 :net 1]])))) (testing "Net, meat, and brain damage are recognized" (is (= [[:net 1] [:meat 1] [:brain 1]] (core/merge-costs [[:net 1] [:meat 1] [:brain 1]])))))) (deftest pay-credits (testing "Testing several cost messages" (do-game (new-game {:runner {:hand ["Diesel" "Daily Casts" "Clot" "Career Fair" "Daily Casts" "Sure Gamble" "Misdirection"]} :corp {:hand [(qty "Ice Wall" 2) "Turtlebacks" "Beanstalk Royalties" "Hedge Fund" "Project Beale" "<NAME>"]}}) (core/gain state :corp :click 10) (play-from-hand state :corp "Ice Wall" "HQ") (is (last-log-contains? state "Corp spends \\[Click\\] and pays 0 \\[Credits\\] to install ICE protecting HQ.") "Install ICE, zero cost") (play-from-hand state :corp "Ice Wall" "HQ") (is (last-log-contains? state "Corp spends \\[Click\\] and pays 1 \\[Credits\\] to install ICE protecting HQ.") "Install ICE, one cost") (play-from-hand state :corp "Turtlebacks" "New remote") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 1.") "Install asset, zero cost") (play-from-hand state :corp "<NAME>" "Server 1") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 1.") "Install upgrade, zero cost") (play-from-hand state :corp "Project Beale" "New remote") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 2.") "Install agenda, zero cost") (play-from-hand state :corp "Beanstalk Royalties") (is (second-last-log-contains? state "Corp spends \\[Click\\] and pays 0 \\[Credits\\] to play Beanstalk Royalties.") "Play operation, zero cost") (play-from-hand state :corp "Hedge Fund") (is (second-last-log-contains? state "Corp spends \\[Click\\] and pays 5 \\[Credits\\] to play Hedge Fund.") "Play operation, five cost") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Diesel") (is (second-last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to play Diesel.") "Play event, zero cost") (play-from-hand state :runner "Sure Gamble") (is (second-last-log-contains? state "Runner spends \\[Click\\] and pays 5 \\[Credits\\] to play Sure Gamble.") "Play event, five cost") (play-from-hand state :runner "Clot") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 2 \\[Credits\\] to install Clot.") "Install program, two cost") (play-from-hand state :runner "Misdirection") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to install Misdirection.") "Install program, zero cost") (play-from-hand state :runner "Career Fair") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to play Career Fair.") "Play Career Fair, zero cost") (click-card state :runner (find-card "Daily Casts" (:hand (get-runner)))) (is (last-log-contains? state "Runner pays 0 \\[Credits\\] to install Daily Casts.") "Choose Daily cast, zero cost install") (play-from-hand state :runner "Daily Casts") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 3 \\[Credits\\] to install Daily Casts.") "Install resource, three cost") (run-on state :archives) (is (last-log-contains? state "Runner spends \\[Click\\] to make a run on Archives.") "Initiate run, zero cost"))) (testing "Issue #4295: Auto-pumping Icebreaker with pay-credits prompt" (do-game (new-game {:runner {:hand ["Corroder" "Net Mercur" "Cloak"]} :corp {:hand ["Fire Wall"]}}) (play-from-hand state :corp "Fire Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Net Mercur") (run-on state :hq) (let [cre (:credit (get-runner)) cor (get-program state 0) clo (get-program state 1) nm (get-resource state 0)] (is (= 2 (:current-strength (refresh cor))) "Corroder starts at 2 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (click-card state :runner clo) (click-prompt state :runner "Place 1 [Credits]") (is (= 5 (:current-strength (refresh cor))) "Corroder is at 5 strength") (is (= (- cre 2) (:credit (get-runner))) "Spent 2 (+1 from Cloak) to pump"))))) (deftest pump-and-break (testing "Basic test" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (is (= 2 (:current-strength (refresh cor))) "Corroder starts at 2 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder now at 3 strength") (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken")))) (testing "Auto-pump first" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder now at 3 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken")))) (testing "Auto-pump and break some subs manually first" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Cor<NAME>der") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder is now at 3 strength") (card-ability state :runner (refresh cor) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (= 4 (count (remove :broken (:subroutines (refresh hive))))) "Only broken 1 sub") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken"))))) (deftest run-additional-costs (testing "If runner cannot pay additional cost, server not shown as an option for run events or click to run button" (do-game (new-game {:corp {:deck ["Ruhr Valley"]} :runner {:deck ["Dirty Laundry"]}}) (play-from-hand state :corp "Ruhr Valley" "HQ") (take-credits state :corp) (let [ruhr (get-content state :hq 0)] (core/rez state :corp ruhr) (core/gain state :runner :click -3) (is (= 1 (:click (get-runner)))) (play-from-hand state :runner "Dirty Laundry") (is (= 2 (-> (get-runner) :prompt first :choices count)) "Runner should only get choice of Archives or R&D") (is (not (some #{"HQ"} (-> (get-runner) :prompt first :choices))) "Runner should only get choice of Archives or R&D")))))
true
(ns game-test.engine.costs (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (deftest merge-costs (testing "Non-damage costs" (testing "No defaults, already merged" (is (= [[:credit 1]] (core/merge-costs [[:credit 1]])))) (testing "Costs are already flattened" (is (= [[:credit 1] [:click 1]] (core/merge-costs [[:credit 1 :click 1]])))) (testing "Passed as a flattened vec" (is (= [[:credit 1]] (core/merge-costs [:credit 1])))) (testing "Default type is only element" (is (= [[:credit 1]] (core/merge-costs [[:credit]])))) (testing "Default plus explicit" (is (= [[:click 1] [:credit 1]] (core/merge-costs [[:click :credit 1]])))) (testing "Costs ending with defaults expand" (is (= [[:credit 1] [:click 1]] (core/merge-costs [[:credit 1 :click]])))) (testing "Non-damage costs aren't reordered" (is (not= [[:credit 1] [:click 1]] (core/merge-costs [[:click 1 :credit 1]])))) (testing "Costs with all defaults are expanded" (is (= [[:click 1] [:credit 1]] (core/merge-costs [[:click :credit]])))) (testing "Non-damage costs are combined" (is (= [[:click 4] [:credit 2]] (core/merge-costs [[:click 1] [:click 3] [:credit 1] [:credit 1]])))) (testing "Deeply nested costs are flattened" (is (= [[:click 3]] (core/merge-costs [[[[[:click 1]]] [[[[[:click 1]]]]]] :click 1])))) (testing "Empty costs return an empty list" (is (= '() (core/merge-costs [])))) (testing "nil costs return an empty list" (is (= '() (core/merge-costs nil))))) (testing "Damage costs" (testing "Damage costs are moved to the end" (is (= [[:credit 1] [:net 1]] (core/merge-costs [[:net 1 :credit 1]])))) (testing "Damage isn't combined" (is (= [[:net 1] [:net 1]] (core/merge-costs [[:net 1 :net 1]])))) (testing "Net, meat, and brain damage are recognized" (is (= [[:net 1] [:meat 1] [:brain 1]] (core/merge-costs [[:net 1] [:meat 1] [:brain 1]])))))) (deftest pay-credits (testing "Testing several cost messages" (do-game (new-game {:runner {:hand ["Diesel" "Daily Casts" "Clot" "Career Fair" "Daily Casts" "Sure Gamble" "Misdirection"]} :corp {:hand [(qty "Ice Wall" 2) "Turtlebacks" "Beanstalk Royalties" "Hedge Fund" "Project Beale" "PI:NAME:<NAME>END_PI"]}}) (core/gain state :corp :click 10) (play-from-hand state :corp "Ice Wall" "HQ") (is (last-log-contains? state "Corp spends \\[Click\\] and pays 0 \\[Credits\\] to install ICE protecting HQ.") "Install ICE, zero cost") (play-from-hand state :corp "Ice Wall" "HQ") (is (last-log-contains? state "Corp spends \\[Click\\] and pays 1 \\[Credits\\] to install ICE protecting HQ.") "Install ICE, one cost") (play-from-hand state :corp "Turtlebacks" "New remote") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 1.") "Install asset, zero cost") (play-from-hand state :corp "PI:NAME:<NAME>END_PI" "Server 1") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 1.") "Install upgrade, zero cost") (play-from-hand state :corp "Project Beale" "New remote") (is (last-log-contains? state "Corp spends \\[Click\\] to install a card in Server 2.") "Install agenda, zero cost") (play-from-hand state :corp "Beanstalk Royalties") (is (second-last-log-contains? state "Corp spends \\[Click\\] and pays 0 \\[Credits\\] to play Beanstalk Royalties.") "Play operation, zero cost") (play-from-hand state :corp "Hedge Fund") (is (second-last-log-contains? state "Corp spends \\[Click\\] and pays 5 \\[Credits\\] to play Hedge Fund.") "Play operation, five cost") (take-credits state :corp) (core/gain state :runner :click 10) (play-from-hand state :runner "Diesel") (is (second-last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to play Diesel.") "Play event, zero cost") (play-from-hand state :runner "Sure Gamble") (is (second-last-log-contains? state "Runner spends \\[Click\\] and pays 5 \\[Credits\\] to play Sure Gamble.") "Play event, five cost") (play-from-hand state :runner "Clot") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 2 \\[Credits\\] to install Clot.") "Install program, two cost") (play-from-hand state :runner "Misdirection") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to install Misdirection.") "Install program, zero cost") (play-from-hand state :runner "Career Fair") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 0 \\[Credits\\] to play Career Fair.") "Play Career Fair, zero cost") (click-card state :runner (find-card "Daily Casts" (:hand (get-runner)))) (is (last-log-contains? state "Runner pays 0 \\[Credits\\] to install Daily Casts.") "Choose Daily cast, zero cost install") (play-from-hand state :runner "Daily Casts") (is (last-log-contains? state "Runner spends \\[Click\\] and pays 3 \\[Credits\\] to install Daily Casts.") "Install resource, three cost") (run-on state :archives) (is (last-log-contains? state "Runner spends \\[Click\\] to make a run on Archives.") "Initiate run, zero cost"))) (testing "Issue #4295: Auto-pumping Icebreaker with pay-credits prompt" (do-game (new-game {:runner {:hand ["Corroder" "Net Mercur" "Cloak"]} :corp {:hand ["Fire Wall"]}}) (play-from-hand state :corp "Fire Wall" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (play-from-hand state :runner "Cloak") (play-from-hand state :runner "Net Mercur") (run-on state :hq) (let [cre (:credit (get-runner)) cor (get-program state 0) clo (get-program state 1) nm (get-resource state 0)] (is (= 2 (:current-strength (refresh cor))) "Corroder starts at 2 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (click-card state :runner clo) (click-prompt state :runner "Place 1 [Credits]") (is (= 5 (:current-strength (refresh cor))) "Corroder is at 5 strength") (is (= (- cre 2) (:credit (get-runner))) "Spent 2 (+1 from Cloak) to pump"))))) (deftest pump-and-break (testing "Basic test" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (is (= 2 (:current-strength (refresh cor))) "Corroder starts at 2 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder now at 3 strength") (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken")))) (testing "Auto-pump first" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "Corroder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder now at 3 strength") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken")))) (testing "Auto-pump and break some subs manually first" (do-game (new-game {:runner {:hand ["Corroder"]} :corp {:hand ["Hive"]}}) (play-from-hand state :corp "Hive" "HQ") (take-credits state :corp) (core/gain state :runner :credit 10) (play-from-hand state :runner "CorPI:NAME:<NAME>END_PIder") (run-on state :hq) (let [cor (get-program state 0) hive (get-ice state :hq 0)] (core/rez state :corp hive) (core/play-dynamic-ability state :runner {:dynamic "auto-pump" :card (refresh cor)}) (is (= 3 (:current-strength (refresh cor))) "Corroder is now at 3 strength") (card-ability state :runner (refresh cor) 0) (click-prompt state :runner "End the run") (click-prompt state :runner "Done") (is (= 4 (count (remove :broken (:subroutines (refresh hive))))) "Only broken 1 sub") (core/play-dynamic-ability state :runner {:dynamic "auto-pump-and-break" :card (refresh cor)}) (is (empty? (remove :broken (:subroutines (refresh hive)))) "Hive is now fully broken"))))) (deftest run-additional-costs (testing "If runner cannot pay additional cost, server not shown as an option for run events or click to run button" (do-game (new-game {:corp {:deck ["Ruhr Valley"]} :runner {:deck ["Dirty Laundry"]}}) (play-from-hand state :corp "Ruhr Valley" "HQ") (take-credits state :corp) (let [ruhr (get-content state :hq 0)] (core/rez state :corp ruhr) (core/gain state :runner :click -3) (is (= 1 (:click (get-runner)))) (play-from-hand state :runner "Dirty Laundry") (is (= 2 (-> (get-runner) :prompt first :choices count)) "Runner should only get choice of Archives or R&D") (is (not (some #{"HQ"} (-> (get-runner) :prompt first :choices))) "Runner should only get choice of Archives or R&D")))))
[ { "context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998846054077148, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
src/territory_bro/events.clj
JessRoberts/territory_assistant
0
;; Copyright © 2015-2019 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.events (:require [schema-refined.core :as refined] [schema-tools.core :as tools] [schema.coerce :as coerce] [schema.core :as s] [schema.utils] [territory-bro.json :as json]) (:import (java.time Instant) (java.util UUID))) (def ^:dynamic *current-time* nil) (def ^:dynamic *current-user* nil) (def ^:dynamic *current-system* nil) (defn defaults ([] (defaults (or *current-time* (Instant/now)))) ([^Instant now] (cond-> {:event/version 1 :event/time now} *current-user* (assoc :event/user *current-user*) *current-system* (assoc :event/system *current-system*)))) (def ^:private key-order (->> [:event/type :event/version :event/user :event/system :event/time :event/stream-id :event/stream-revision :event/global-revision] (map-indexed (fn [idx k] [k idx])) (into {}))) (defn- key-comparator [x y] (compare [(get key-order x 100) x] [(get key-order y 100) y])) (defn sorted-keys [event] (into (sorted-map-by key-comparator) event)) ;;;; Schemas (s/defschema EventBase {(s/optional-key :event/stream-id) UUID (s/optional-key :event/stream-revision) s/Int (s/optional-key :event/global-revision) s/Int :event/type s/Keyword :event/version s/Int :event/time Instant (s/optional-key :event/user) UUID (s/optional-key :event/system) s/Str}) ;;; Congregation (s/defschema CongregationCreated (assoc EventBase :event/type (s/eq :congregation.event/congregation-created) :event/version (s/eq 1) :congregation/id UUID :congregation/name s/Str :congregation/schema-name s/Str)) (s/defschema CongregationRenamed (assoc EventBase :event/type (s/eq :congregation.event/congregation-renamed) :event/version (s/eq 1) :congregation/id UUID :congregation/name s/Str)) (s/defschema PermissionId (s/enum :view-congregation :configure-congregation :gis-access)) (s/defschema PermissionGranted (assoc EventBase :event/type (s/eq :congregation.event/permission-granted) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :permission/id PermissionId)) (s/defschema PermissionRevoked (assoc EventBase :event/type (s/eq :congregation.event/permission-revoked) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :permission/id PermissionId)) (s/defschema GisUserCreated (assoc EventBase :event/type (s/eq :congregation.event/gis-user-created) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :gis-user/username s/Str :gis-user/password s/Str)) (s/defschema GisUserDeleted (assoc EventBase :event/type (s/eq :congregation.event/gis-user-deleted) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) ;;; DB Admin (s/defschema GisSchemaIsPresent (assoc EventBase :event/type (s/eq :db-admin.event/gis-schema-is-present) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :congregation/schema-name s/Str)) (s/defschema GisUserIsPresent (assoc EventBase :event/type (s/eq :db-admin.event/gis-user-is-present) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) (s/defschema GisUserIsAbsent (assoc EventBase :event/type (s/eq :db-admin.event/gis-user-is-absent) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) (def event-schemas {:congregation.event/congregation-created CongregationCreated :congregation.event/congregation-renamed CongregationRenamed :congregation.event/permission-granted PermissionGranted :congregation.event/permission-revoked PermissionRevoked :congregation.event/gis-user-created GisUserCreated :congregation.event/gis-user-deleted GisUserDeleted :db-admin.event/gis-schema-is-present GisSchemaIsPresent :db-admin.event/gis-user-is-present GisUserIsPresent :db-admin.event/gis-user-is-absent GisUserIsAbsent}) (s/defschema Event (s/constrained (apply refined/dispatch-on :event/type (flatten (seq event-schemas))) (fn [event] (not= (contains? event :event/user) (contains? event :event/system))) '(xor-required-key :event/user :event/system))) ;;;; Validation (defn validate-event [event] (when-not (contains? event-schemas (:event/type event)) (throw (ex-info (str "Unknown event type " (pr-str (:event/type event))) {:event event}))) (assert (contains? event-schemas (:event/type event)) {:error [:unknown-event-type (:event/type event)] :event event}) (s/validate Event event)) (defn validate-events [events] (doseq [event events] (validate-event event)) events) ;;;; Serialization (defn- string->instant [s] (if (string? s) (Instant/parse s) s)) (def ^:private datestring-coercion-matcher {Instant string->instant}) (defn- coercion-matcher [schema] (or (datestring-coercion-matcher schema) (coerce/string-coercion-matcher schema))) (def ^:private coerce-event-commons (coerce/coercer (tools/open-schema EventBase) coercion-matcher)) (def ^:private coerce-event-specifics (coerce/coercer Event coercion-matcher)) (defn- coerce-event [event] ;; must coerce the common fields first, so that Event can ;; choose the right event schema based on the event type (let [result (coerce-event-commons event)] (if (schema.utils/error? result) result (coerce-event-specifics result)))) (defn json->event [json] (when json (let [result (coerce-event (json/parse-string json))] (when (schema.utils/error? result) (throw (ex-info "Event schema validation failed" {:json json :error result}))) result))) (defn event->json [event] (json/generate-string (validate-event event)))
80474
;; Copyright © 2015-2019 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.events (:require [schema-refined.core :as refined] [schema-tools.core :as tools] [schema.coerce :as coerce] [schema.core :as s] [schema.utils] [territory-bro.json :as json]) (:import (java.time Instant) (java.util UUID))) (def ^:dynamic *current-time* nil) (def ^:dynamic *current-user* nil) (def ^:dynamic *current-system* nil) (defn defaults ([] (defaults (or *current-time* (Instant/now)))) ([^Instant now] (cond-> {:event/version 1 :event/time now} *current-user* (assoc :event/user *current-user*) *current-system* (assoc :event/system *current-system*)))) (def ^:private key-order (->> [:event/type :event/version :event/user :event/system :event/time :event/stream-id :event/stream-revision :event/global-revision] (map-indexed (fn [idx k] [k idx])) (into {}))) (defn- key-comparator [x y] (compare [(get key-order x 100) x] [(get key-order y 100) y])) (defn sorted-keys [event] (into (sorted-map-by key-comparator) event)) ;;;; Schemas (s/defschema EventBase {(s/optional-key :event/stream-id) UUID (s/optional-key :event/stream-revision) s/Int (s/optional-key :event/global-revision) s/Int :event/type s/Keyword :event/version s/Int :event/time Instant (s/optional-key :event/user) UUID (s/optional-key :event/system) s/Str}) ;;; Congregation (s/defschema CongregationCreated (assoc EventBase :event/type (s/eq :congregation.event/congregation-created) :event/version (s/eq 1) :congregation/id UUID :congregation/name s/Str :congregation/schema-name s/Str)) (s/defschema CongregationRenamed (assoc EventBase :event/type (s/eq :congregation.event/congregation-renamed) :event/version (s/eq 1) :congregation/id UUID :congregation/name s/Str)) (s/defschema PermissionId (s/enum :view-congregation :configure-congregation :gis-access)) (s/defschema PermissionGranted (assoc EventBase :event/type (s/eq :congregation.event/permission-granted) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :permission/id PermissionId)) (s/defschema PermissionRevoked (assoc EventBase :event/type (s/eq :congregation.event/permission-revoked) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :permission/id PermissionId)) (s/defschema GisUserCreated (assoc EventBase :event/type (s/eq :congregation.event/gis-user-created) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :gis-user/username s/Str :gis-user/password s/Str)) (s/defschema GisUserDeleted (assoc EventBase :event/type (s/eq :congregation.event/gis-user-deleted) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) ;;; DB Admin (s/defschema GisSchemaIsPresent (assoc EventBase :event/type (s/eq :db-admin.event/gis-schema-is-present) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :congregation/schema-name s/Str)) (s/defschema GisUserIsPresent (assoc EventBase :event/type (s/eq :db-admin.event/gis-user-is-present) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) (s/defschema GisUserIsAbsent (assoc EventBase :event/type (s/eq :db-admin.event/gis-user-is-absent) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) (def event-schemas {:congregation.event/congregation-created CongregationCreated :congregation.event/congregation-renamed CongregationRenamed :congregation.event/permission-granted PermissionGranted :congregation.event/permission-revoked PermissionRevoked :congregation.event/gis-user-created GisUserCreated :congregation.event/gis-user-deleted GisUserDeleted :db-admin.event/gis-schema-is-present GisSchemaIsPresent :db-admin.event/gis-user-is-present GisUserIsPresent :db-admin.event/gis-user-is-absent GisUserIsAbsent}) (s/defschema Event (s/constrained (apply refined/dispatch-on :event/type (flatten (seq event-schemas))) (fn [event] (not= (contains? event :event/user) (contains? event :event/system))) '(xor-required-key :event/user :event/system))) ;;;; Validation (defn validate-event [event] (when-not (contains? event-schemas (:event/type event)) (throw (ex-info (str "Unknown event type " (pr-str (:event/type event))) {:event event}))) (assert (contains? event-schemas (:event/type event)) {:error [:unknown-event-type (:event/type event)] :event event}) (s/validate Event event)) (defn validate-events [events] (doseq [event events] (validate-event event)) events) ;;;; Serialization (defn- string->instant [s] (if (string? s) (Instant/parse s) s)) (def ^:private datestring-coercion-matcher {Instant string->instant}) (defn- coercion-matcher [schema] (or (datestring-coercion-matcher schema) (coerce/string-coercion-matcher schema))) (def ^:private coerce-event-commons (coerce/coercer (tools/open-schema EventBase) coercion-matcher)) (def ^:private coerce-event-specifics (coerce/coercer Event coercion-matcher)) (defn- coerce-event [event] ;; must coerce the common fields first, so that Event can ;; choose the right event schema based on the event type (let [result (coerce-event-commons event)] (if (schema.utils/error? result) result (coerce-event-specifics result)))) (defn json->event [json] (when json (let [result (coerce-event (json/parse-string json))] (when (schema.utils/error? result) (throw (ex-info "Event schema validation failed" {:json json :error result}))) result))) (defn event->json [event] (json/generate-string (validate-event event)))
true
;; Copyright © 2015-2019 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.events (:require [schema-refined.core :as refined] [schema-tools.core :as tools] [schema.coerce :as coerce] [schema.core :as s] [schema.utils] [territory-bro.json :as json]) (:import (java.time Instant) (java.util UUID))) (def ^:dynamic *current-time* nil) (def ^:dynamic *current-user* nil) (def ^:dynamic *current-system* nil) (defn defaults ([] (defaults (or *current-time* (Instant/now)))) ([^Instant now] (cond-> {:event/version 1 :event/time now} *current-user* (assoc :event/user *current-user*) *current-system* (assoc :event/system *current-system*)))) (def ^:private key-order (->> [:event/type :event/version :event/user :event/system :event/time :event/stream-id :event/stream-revision :event/global-revision] (map-indexed (fn [idx k] [k idx])) (into {}))) (defn- key-comparator [x y] (compare [(get key-order x 100) x] [(get key-order y 100) y])) (defn sorted-keys [event] (into (sorted-map-by key-comparator) event)) ;;;; Schemas (s/defschema EventBase {(s/optional-key :event/stream-id) UUID (s/optional-key :event/stream-revision) s/Int (s/optional-key :event/global-revision) s/Int :event/type s/Keyword :event/version s/Int :event/time Instant (s/optional-key :event/user) UUID (s/optional-key :event/system) s/Str}) ;;; Congregation (s/defschema CongregationCreated (assoc EventBase :event/type (s/eq :congregation.event/congregation-created) :event/version (s/eq 1) :congregation/id UUID :congregation/name s/Str :congregation/schema-name s/Str)) (s/defschema CongregationRenamed (assoc EventBase :event/type (s/eq :congregation.event/congregation-renamed) :event/version (s/eq 1) :congregation/id UUID :congregation/name s/Str)) (s/defschema PermissionId (s/enum :view-congregation :configure-congregation :gis-access)) (s/defschema PermissionGranted (assoc EventBase :event/type (s/eq :congregation.event/permission-granted) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :permission/id PermissionId)) (s/defschema PermissionRevoked (assoc EventBase :event/type (s/eq :congregation.event/permission-revoked) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :permission/id PermissionId)) (s/defschema GisUserCreated (assoc EventBase :event/type (s/eq :congregation.event/gis-user-created) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :gis-user/username s/Str :gis-user/password s/Str)) (s/defschema GisUserDeleted (assoc EventBase :event/type (s/eq :congregation.event/gis-user-deleted) :event/version (s/eq 1) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) ;;; DB Admin (s/defschema GisSchemaIsPresent (assoc EventBase :event/type (s/eq :db-admin.event/gis-schema-is-present) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :congregation/schema-name s/Str)) (s/defschema GisUserIsPresent (assoc EventBase :event/type (s/eq :db-admin.event/gis-user-is-present) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) (s/defschema GisUserIsAbsent (assoc EventBase :event/type (s/eq :db-admin.event/gis-user-is-absent) :event/version (s/eq 1) :event/transient? (s/eq true) :congregation/id UUID :user/id UUID :gis-user/username s/Str)) (def event-schemas {:congregation.event/congregation-created CongregationCreated :congregation.event/congregation-renamed CongregationRenamed :congregation.event/permission-granted PermissionGranted :congregation.event/permission-revoked PermissionRevoked :congregation.event/gis-user-created GisUserCreated :congregation.event/gis-user-deleted GisUserDeleted :db-admin.event/gis-schema-is-present GisSchemaIsPresent :db-admin.event/gis-user-is-present GisUserIsPresent :db-admin.event/gis-user-is-absent GisUserIsAbsent}) (s/defschema Event (s/constrained (apply refined/dispatch-on :event/type (flatten (seq event-schemas))) (fn [event] (not= (contains? event :event/user) (contains? event :event/system))) '(xor-required-key :event/user :event/system))) ;;;; Validation (defn validate-event [event] (when-not (contains? event-schemas (:event/type event)) (throw (ex-info (str "Unknown event type " (pr-str (:event/type event))) {:event event}))) (assert (contains? event-schemas (:event/type event)) {:error [:unknown-event-type (:event/type event)] :event event}) (s/validate Event event)) (defn validate-events [events] (doseq [event events] (validate-event event)) events) ;;;; Serialization (defn- string->instant [s] (if (string? s) (Instant/parse s) s)) (def ^:private datestring-coercion-matcher {Instant string->instant}) (defn- coercion-matcher [schema] (or (datestring-coercion-matcher schema) (coerce/string-coercion-matcher schema))) (def ^:private coerce-event-commons (coerce/coercer (tools/open-schema EventBase) coercion-matcher)) (def ^:private coerce-event-specifics (coerce/coercer Event coercion-matcher)) (defn- coerce-event [event] ;; must coerce the common fields first, so that Event can ;; choose the right event schema based on the event type (let [result (coerce-event-commons event)] (if (schema.utils/error? result) result (coerce-event-specifics result)))) (defn json->event [json] (when json (let [result (coerce-event (json/parse-string json))] (when (schema.utils/error? result) (throw (ex-info "Event schema validation failed" {:json json :error result}))) result))) (defn event->json [event] (json/generate-string (validate-event event)))
[ { "context": "(\n ; Context map\n {}\n\n \"0\"\n \"nulla\"\n \"zero\"\n (number 0)\n\n \"1\"\n \"uno\"\n (number 1", "end": 38, "score": 0.9935812950134277, "start": 33, "tag": "NAME", "value": "nulla" }, { "context": "\n\n \"0\"\n \"nulla\"\n \"zero\"\n (number 0)\n\n \"1\"\n \"uno\"\n (number 1)\n \n \"2\"\n \"due\"\n (number 2)\n \n ", "end": 75, "score": 0.8684960603713989, "start": 72, "tag": "NAME", "value": "uno" }, { "context": "mber 1)\n \n \"2\"\n \"due\"\n (number 2)\n \n \"3\"\n \"tre\"\n (number 3)\n \n \"4\"\n \"quattro\"\n (number 4)\n ", "end": 135, "score": 0.7286314964294434, "start": 132, "tag": "NAME", "value": "tre" }, { "context": "mber 2)\n \n \"3\"\n \"tre\"\n (number 3)\n \n \"4\"\n \"quattro\"\n (number 4)\n \n \"5\"\n \"cinque\"\n (number 5)\n ", "end": 169, "score": 0.9988880157470703, "start": 162, "tag": "NAME", "value": "quattro" }, { "context": " 3)\n \n \"4\"\n \"quattro\"\n (number 4)\n \n \"5\"\n \"cinque\"\n (number 5)\n \n \"6\"\n \"sei\"\n (number 6)\n \n ", "end": 202, "score": 0.9745416045188904, "start": 196, "tag": "NAME", "value": "cinque" }, { "context": "mber 5)\n \n \"6\"\n \"sei\"\n (number 6)\n \n \"7\"\n \"sette\"\n (number 7)\n \n \"8\"\n \"otto\"\n (number 8)\n \n ", "end": 264, "score": 0.7965091466903687, "start": 259, "tag": "NAME", "value": "sette" }, { "context": "ber 7)\n \n \"8\"\n \"otto\"\n (number 8)\n \n \"9\"\n \"nove\"\n (number 9)\n \n \"10\"\n \"dieci\"\n (number 10)\n ", "end": 326, "score": 0.9752932786941528, "start": 322, "tag": "NAME", "value": "nove" }, { "context": "er 8)\n \n \"9\"\n \"nove\"\n (number 9)\n \n \"10\"\n \"dieci\"\n (number 10)\n \n \"33\"\n \"trentatré\"\n \"0033\"\n ", "end": 359, "score": 0.9857162237167358, "start": 354, "tag": "NAME", "value": "dieci" }, { "context": "9)\n \n \"10\"\n \"dieci\"\n (number 10)\n \n \"33\"\n \"trentatré\"\n \"0033\"\n (number 33)\n \n \"14\"\n \"quattordici\"", "end": 397, "score": 0.9986287355422974, "start": 388, "tag": "NAME", "value": "trentatré" }, { "context": " \"trentatré\"\n \"0033\"\n (number 33)\n \n \"14\"\n \"quattordici\"\n (number 14)\n \n \"16\"\n \"sedici\"\n (number 16)", "end": 446, "score": 0.9995468854904175, "start": 435, "tag": "NAME", "value": "quattordici" }, { "context": " \"14\"\n \"quattordici\"\n (number 14)\n \n \"16\"\n \"sedici\"\n (number 16)\n\n \"17\"\n \"diciassette\"\n (number ", "end": 481, "score": 0.9991037249565125, "start": 475, "tag": "NAME", "value": "sedici" }, { "context": "14)\n \n \"16\"\n \"sedici\"\n (number 16)\n\n \"17\"\n \"diciassette\"\n (number 17)\n\n \"18\"\n \"diciotto\"\n (number 18)", "end": 519, "score": 0.9976159334182739, "start": 508, "tag": "NAME", "value": "diciassette" }, { "context": "\n\n \"17\"\n \"diciassette\"\n (number 17)\n\n \"18\"\n \"diciotto\"\n (number 18)\n\n \"1,1\"\n \"1,10\"\n \"01,10\"\n (num", "end": 554, "score": 0.9963178634643555, "start": 546, "tag": "NAME", "value": "diciotto" } ]
resources/languages/it/corpus/numbers.clj
irvingflores/duckling
0
( ; Context map {} "0" "nulla" "zero" (number 0) "1" "uno" (number 1) "2" "due" (number 2) "3" "tre" (number 3) "4" "quattro" (number 4) "5" "cinque" (number 5) "6" "sei" (number 6) "7" "sette" (number 7) "8" "otto" (number 8) "9" "nove" (number 9) "10" "dieci" (number 10) "33" "trentatré" "0033" (number 33) "14" "quattordici" (number 14) "16" "sedici" (number 16) "17" "diciassette" (number 17) "18" "diciotto" (number 18) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "meno 1.200.000" "negativo 1200000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "primo" "1°" "1ª" (ordinal 1) "4°" "4ª" (ordinal 4) )
3754
( ; Context map {} "0" "<NAME>" "zero" (number 0) "1" "<NAME>" (number 1) "2" "due" (number 2) "3" "<NAME>" (number 3) "4" "<NAME>" (number 4) "5" "<NAME>" (number 5) "6" "sei" (number 6) "7" "<NAME>" (number 7) "8" "otto" (number 8) "9" "<NAME>" (number 9) "10" "<NAME>" (number 10) "33" "<NAME>" "0033" (number 33) "14" "<NAME>" (number 14) "16" "<NAME>" (number 16) "17" "<NAME>" (number 17) "18" "<NAME>" (number 18) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "meno 1.200.000" "negativo 1200000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "primo" "1°" "1ª" (ordinal 1) "4°" "4ª" (ordinal 4) )
true
( ; Context map {} "0" "PI:NAME:<NAME>END_PI" "zero" (number 0) "1" "PI:NAME:<NAME>END_PI" (number 1) "2" "due" (number 2) "3" "PI:NAME:<NAME>END_PI" (number 3) "4" "PI:NAME:<NAME>END_PI" (number 4) "5" "PI:NAME:<NAME>END_PI" (number 5) "6" "sei" (number 6) "7" "PI:NAME:<NAME>END_PI" (number 7) "8" "otto" (number 8) "9" "PI:NAME:<NAME>END_PI" (number 9) "10" "PI:NAME:<NAME>END_PI" (number 10) "33" "PI:NAME:<NAME>END_PI" "0033" (number 33) "14" "PI:NAME:<NAME>END_PI" (number 14) "16" "PI:NAME:<NAME>END_PI" (number 16) "17" "PI:NAME:<NAME>END_PI" (number 17) "18" "PI:NAME:<NAME>END_PI" (number 18) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "meno 1.200.000" "negativo 1200000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "primo" "1°" "1ª" (ordinal 1) "4°" "4ª" (ordinal 4) )
[ { "context": " be solved by another level of\n;; indirection.\" -- David Wheeler\n;; \n\n", "end": 1637, "score": 0.9993067979812622, "start": 1624, "tag": "NAME", "value": "David Wheeler" } ]
func-prog/fp-oo/solutions/pieces/class-3.clj
tannerwelsh/code-training
0
;;; Exercise 3 (def my-point (make Point 1 2)) (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :origin (fn [this] (make Point 0 0)) ;; ^^^^^== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to my-point :origin) ;; Redefining a class changes the behavior of existing instances ;; because having an instance's :__class_symbol__ be a symbol that's ;; later `eval`ed adds a level of indirection. If the value were a ;; class map itself, changing the binding or association of `Point` ;; would have no effect on existing instances, just new ones. ;; ;; You could see that with this code: ;; user=> (def Point "the original definition of Point") ;; user=> (def a-point {:__class_NOT_symbol__ Point}) ;; user=> (def Point "the new definition of Point") ;; user=> a-point ;; {:__class_NOT_symbol__ "the original definition of Point"} ;; ;; If that's not clear, apply the substitution rule to the `def` lines. ;; (Note that `def` is another special symbol. It does not evaluate its ;; first argument, just the second.) ;; ;; "All problems in computer science can be solved by another level of ;; indirection." -- David Wheeler ;;
87870
;;; Exercise 3 (def my-point (make Point 1 2)) (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :origin (fn [this] (make Point 0 0)) ;; ^^^^^== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to my-point :origin) ;; Redefining a class changes the behavior of existing instances ;; because having an instance's :__class_symbol__ be a symbol that's ;; later `eval`ed adds a level of indirection. If the value were a ;; class map itself, changing the binding or association of `Point` ;; would have no effect on existing instances, just new ones. ;; ;; You could see that with this code: ;; user=> (def Point "the original definition of Point") ;; user=> (def a-point {:__class_NOT_symbol__ Point}) ;; user=> (def Point "the new definition of Point") ;; user=> a-point ;; {:__class_NOT_symbol__ "the original definition of Point"} ;; ;; If that's not clear, apply the substitution rule to the `def` lines. ;; (Note that `def` is another special symbol. It does not evaluate its ;; first argument, just the second.) ;; ;; "All problems in computer science can be solved by another level of ;; indirection." -- <NAME> ;;
true
;;; Exercise 3 (def my-point (make Point 1 2)) (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :origin (fn [this] (make Point 0 0)) ;; ^^^^^== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to my-point :origin) ;; Redefining a class changes the behavior of existing instances ;; because having an instance's :__class_symbol__ be a symbol that's ;; later `eval`ed adds a level of indirection. If the value were a ;; class map itself, changing the binding or association of `Point` ;; would have no effect on existing instances, just new ones. ;; ;; You could see that with this code: ;; user=> (def Point "the original definition of Point") ;; user=> (def a-point {:__class_NOT_symbol__ Point}) ;; user=> (def Point "the new definition of Point") ;; user=> a-point ;; {:__class_NOT_symbol__ "the original definition of Point"} ;; ;; If that's not clear, apply the substitution rule to the `def` lines. ;; (Note that `def` is another special symbol. It does not evaluate its ;; first argument, just the second.) ;; ;; "All problems in computer science can be solved by another level of ;; indirection." -- PI:NAME:<NAME>END_PI ;;
[ { "context": ".com/archiva/repository/internal\\\"\n :username \\\"durin\\\" :password \\\"mellon\\\"}\n\nSNAPSHOT versions will b", "end": 2838, "score": 0.999281644821167, "start": 2833, "tag": "USERNAME", "value": "durin" }, { "context": "ory/internal\\\"\n :username \\\"durin\\\" :password \\\"mellon\\\"}\n\nSNAPSHOT versions will be deployed to :snapsh", "end": 2859, "score": 0.9994261264801025, "start": 2853, "tag": "PASSWORD", "value": "mellon" }, { "context": "ningen-auth {\\\"http://secr.et/repo\\\" {:password \\\"reindeerflotilla\\\"}\n \\\"file:///var/repo {:pa", "end": 3217, "score": 0.9993681907653809, "start": 3201, "tag": "PASSWORD", "value": "reindeerflotilla" }, { "context": " \\\"file:///var/repo {:passphrase \\\"vorpalbunny\\\"}})\"\n ([project & opts]\n (doto (DeployTask.", "end": 3289, "score": 0.9983256459236145, "start": 3278, "tag": "PASSWORD", "value": "vorpalbunny" } ]
test/conflicts/mined/leiningen-9ee9fd1784453b98b35868003ec302b6c46a2207-ed28764804af01661dd82aa967eed7eb6d7de28/M.clj
nazrhom/vcs-clojure
3
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [lancet]) (:use [leiningen.core :only [abort]] [leiningen.jar :only [jar]] [leiningen.pom :only [pom snapshot?]] [leiningen.util.maven :only [make-model make-artifact]] [leiningen.deps :only [make-repository make-auth]] [clojure.java.io :only [file]]) (:import [org.apache.maven.artifact.ant DeployTask Pom Authentication] [org.apache.maven.project MavenProject])) (defn- make-maven-project [project] (doto (MavenProject. (make-model project)) (.setArtifact (make-artifact (make-model project))))) ;; for supporting command-line options (defn- keywordize-opts [options] (let [options (apply hash-map options)] (zipmap (map keyword (keys options)) (vals options)))) <<<<<<< A.clj (defn make-target-repo [repo-url auth-options] (let [repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url auth-options)] ||||||| O.clj (defn make-auth [url options] (let [auth (Authentication.) user-options (when-let [user-opts (resolve 'user/leiningen-auth)] (get @user-opts url)) {:keys [username password passphrase private-key]} (merge user-options options)] (when username (.setUserName auth username)) (when password (.setPassword auth password)) (when passphrase (.setPassphrase auth passphrase)) (when private-key (.setPrivateKey auth private-key)) auth)) (defn make-target-repo [repo-url auth-options] (let [repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url auth-options)] ======= (defn make-auth [url options] (let [auth (Authentication.) user-options (when-let [user-opts (resolve 'user/leiningen-auth)] (get @user-opts url)) {:keys [username password passphrase private-key]} (merge user-options options)] (when username (.setUserName auth username)) (when password (.setPassword auth password)) (when passphrase (.setPassphrase auth passphrase)) (when private-key (.setPrivateKey auth private-key)) auth)) (defn make-target-repo [project options] (let [deploy-opts (merge (:deploy-to project) options) repo-url (if (snapshot? project) (:snapshots deploy-opts) (:releases deploy-opts)) repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url options)] >>>>>>> B.clj (.addAuthentication repo auth)) repo)) (defn deploy "Build and deploy jar to remote repository. Set :deploy-to in project.clj: {:snapshots \"http://secret.com/archiva/repository/snapshots\" :releases \"http://secret.com/archiva/repository/internal\" :username \"durin\" :password \"mellon\"} SNAPSHOT versions will be deployed to :snapshots repository, releases go to :releases. Also supported are :private-key and :passphrase. You can set authentication options keyed by repository URL in ~/.lein/init.clj to avoid checking sensitive information into source control: (def leiningen-auth {\"http://secr.et/repo\" {:password \"reindeerflotilla\"} \"file:///var/repo {:passphrase \"vorpalbunny\"}})" ([project & opts] (doto (DeployTask.) (.setProject lancet/ant-project) (.getSupportedProtocols) ;; see note re: exceptions in deps.clj (.setFile (file (jar project))) (.addPom (doto (Pom.) (.setMavenProject (make-maven-project project)) (.setFile (file (pom project))))) (.addRemoteRepository (make-target-repo project (keywordize-opts opts))) (.execute))) ([project] (if-let [target (:deploy-to project)] (deploy target) (do (println "Either set :deploy-to in project.clj or" "provide deploy target options.") 1))))
121579
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [lancet]) (:use [leiningen.core :only [abort]] [leiningen.jar :only [jar]] [leiningen.pom :only [pom snapshot?]] [leiningen.util.maven :only [make-model make-artifact]] [leiningen.deps :only [make-repository make-auth]] [clojure.java.io :only [file]]) (:import [org.apache.maven.artifact.ant DeployTask Pom Authentication] [org.apache.maven.project MavenProject])) (defn- make-maven-project [project] (doto (MavenProject. (make-model project)) (.setArtifact (make-artifact (make-model project))))) ;; for supporting command-line options (defn- keywordize-opts [options] (let [options (apply hash-map options)] (zipmap (map keyword (keys options)) (vals options)))) <<<<<<< A.clj (defn make-target-repo [repo-url auth-options] (let [repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url auth-options)] ||||||| O.clj (defn make-auth [url options] (let [auth (Authentication.) user-options (when-let [user-opts (resolve 'user/leiningen-auth)] (get @user-opts url)) {:keys [username password passphrase private-key]} (merge user-options options)] (when username (.setUserName auth username)) (when password (.setPassword auth password)) (when passphrase (.setPassphrase auth passphrase)) (when private-key (.setPrivateKey auth private-key)) auth)) (defn make-target-repo [repo-url auth-options] (let [repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url auth-options)] ======= (defn make-auth [url options] (let [auth (Authentication.) user-options (when-let [user-opts (resolve 'user/leiningen-auth)] (get @user-opts url)) {:keys [username password passphrase private-key]} (merge user-options options)] (when username (.setUserName auth username)) (when password (.setPassword auth password)) (when passphrase (.setPassphrase auth passphrase)) (when private-key (.setPrivateKey auth private-key)) auth)) (defn make-target-repo [project options] (let [deploy-opts (merge (:deploy-to project) options) repo-url (if (snapshot? project) (:snapshots deploy-opts) (:releases deploy-opts)) repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url options)] >>>>>>> B.clj (.addAuthentication repo auth)) repo)) (defn deploy "Build and deploy jar to remote repository. Set :deploy-to in project.clj: {:snapshots \"http://secret.com/archiva/repository/snapshots\" :releases \"http://secret.com/archiva/repository/internal\" :username \"durin\" :password \"<PASSWORD>\"} SNAPSHOT versions will be deployed to :snapshots repository, releases go to :releases. Also supported are :private-key and :passphrase. You can set authentication options keyed by repository URL in ~/.lein/init.clj to avoid checking sensitive information into source control: (def leiningen-auth {\"http://secr.et/repo\" {:password \"<PASSWORD>\"} \"file:///var/repo {:passphrase \"<PASSWORD>\"}})" ([project & opts] (doto (DeployTask.) (.setProject lancet/ant-project) (.getSupportedProtocols) ;; see note re: exceptions in deps.clj (.setFile (file (jar project))) (.addPom (doto (Pom.) (.setMavenProject (make-maven-project project)) (.setFile (file (pom project))))) (.addRemoteRepository (make-target-repo project (keywordize-opts opts))) (.execute))) ([project] (if-let [target (:deploy-to project)] (deploy target) (do (println "Either set :deploy-to in project.clj or" "provide deploy target options.") 1))))
true
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [lancet]) (:use [leiningen.core :only [abort]] [leiningen.jar :only [jar]] [leiningen.pom :only [pom snapshot?]] [leiningen.util.maven :only [make-model make-artifact]] [leiningen.deps :only [make-repository make-auth]] [clojure.java.io :only [file]]) (:import [org.apache.maven.artifact.ant DeployTask Pom Authentication] [org.apache.maven.project MavenProject])) (defn- make-maven-project [project] (doto (MavenProject. (make-model project)) (.setArtifact (make-artifact (make-model project))))) ;; for supporting command-line options (defn- keywordize-opts [options] (let [options (apply hash-map options)] (zipmap (map keyword (keys options)) (vals options)))) <<<<<<< A.clj (defn make-target-repo [repo-url auth-options] (let [repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url auth-options)] ||||||| O.clj (defn make-auth [url options] (let [auth (Authentication.) user-options (when-let [user-opts (resolve 'user/leiningen-auth)] (get @user-opts url)) {:keys [username password passphrase private-key]} (merge user-options options)] (when username (.setUserName auth username)) (when password (.setPassword auth password)) (when passphrase (.setPassphrase auth passphrase)) (when private-key (.setPrivateKey auth private-key)) auth)) (defn make-target-repo [repo-url auth-options] (let [repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url auth-options)] ======= (defn make-auth [url options] (let [auth (Authentication.) user-options (when-let [user-opts (resolve 'user/leiningen-auth)] (get @user-opts url)) {:keys [username password passphrase private-key]} (merge user-options options)] (when username (.setUserName auth username)) (when password (.setPassword auth password)) (when passphrase (.setPassphrase auth passphrase)) (when private-key (.setPrivateKey auth private-key)) auth)) (defn make-target-repo [project options] (let [deploy-opts (merge (:deploy-to project) options) repo-url (if (snapshot? project) (:snapshots deploy-opts) (:releases deploy-opts)) repo (make-repository ["remote repository" repo-url])] (when-let [auth (make-auth repo-url options)] >>>>>>> B.clj (.addAuthentication repo auth)) repo)) (defn deploy "Build and deploy jar to remote repository. Set :deploy-to in project.clj: {:snapshots \"http://secret.com/archiva/repository/snapshots\" :releases \"http://secret.com/archiva/repository/internal\" :username \"durin\" :password \"PI:PASSWORD:<PASSWORD>END_PI\"} SNAPSHOT versions will be deployed to :snapshots repository, releases go to :releases. Also supported are :private-key and :passphrase. You can set authentication options keyed by repository URL in ~/.lein/init.clj to avoid checking sensitive information into source control: (def leiningen-auth {\"http://secr.et/repo\" {:password \"PI:PASSWORD:<PASSWORD>END_PI\"} \"file:///var/repo {:passphrase \"PI:PASSWORD:<PASSWORD>END_PI\"}})" ([project & opts] (doto (DeployTask.) (.setProject lancet/ant-project) (.getSupportedProtocols) ;; see note re: exceptions in deps.clj (.setFile (file (jar project))) (.addPom (doto (Pom.) (.setMavenProject (make-maven-project project)) (.setFile (file (pom project))))) (.addRemoteRepository (make-target-repo project (keywordize-opts opts))) (.execute))) ([project] (if-let [target (:deploy-to project)] (deploy target) (do (println "Either set :deploy-to in project.clj or" "provide deploy target options.") 1))))
[ { "context": "ng new validators and validator sets\"\n {:author \"Leonardo Borges\"}\n #+clj (:require [clj-time.format :as f])\n #+", "end": 177, "score": 0.9998838305473328, "start": 162, "tag": "NAME", "value": "Leonardo Borges" } ]
src/bouncer/validators.cljx
edgibbs/bouncer
0
(ns bouncer.validators "This namespace contains all built-in validators as well as macros for defining new validators and validator sets" {:author "Leonardo Borges"} #+clj (:require [clj-time.format :as f]) #+cljs (:require [cljs-time.format :as f]) #+cljs (:require-macros [bouncer.validators :refer [defvalidator]])) ;; ## Customization support ;; ;; The following functions and macros support creating custom validators (defmacro defvalidator "Defines a new validating function using args & body semantics as provided by \"defn\". docstring and opts-map are optional opts-map is a map of key-value pairs and may be one of: - `:default-message-format` used when the client of this validator doesn't provide a message (consider using custom message functions) - `:optional` whether the validation should be run only if the given key has a non-nil value in the map. Defaults to false. or any other key-value pair which will be available in the validation result under the `:metadata` key. The function will be called with the value being validated as its first argument. Any extra arguments will be passed along to the function in the order they were used in the \"validate\" call. e.g.: (defvalidator member [value coll] (some #{value} coll)) (validate {:age 10} :age [[member (range 5)]]) This means the validator `member` will be called with the arguments `10` and `(0 1 2 3 4)`, in that order. " {:arglists '([name docstring? opts-map? [args*] & body])} [name & options] (let [[docstring options] (if (string? (first options)) [(first options) (next options)] [nil options]) [fn-meta [args & body]] (if (map? (first options)) [(first options) (next options)] [nil options]) fn-meta (assoc fn-meta :validator (keyword (str *ns*) (str name)))] (let [arglists ''([name])] `(do (def ~name (with-meta (fn ~name ([~@args] ~@body)) ~fn-meta)))))) ;; ## Built-in validators (defvalidator required "Validates value is present. If the value is a string, it makes sure it's not empty, otherwise it checks for nils. For use with validation functions such as `validate` or `valid?` " {:default-message-format "%s must be present"} [value] (if (string? value) (not (empty? value)) (not (nil? value)))) (defvalidator number "Validates maybe-a-number is a valid number. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a number" :optional true} [maybe-a-number] (number? maybe-a-number)) (defvalidator positive "Validates number is a number and is greater than zero. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a positive number" :optional true} [number] (> number 0)) (defvalidator member "Validates value is a member of coll. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be one of the values in the list"} [value coll] (some #{value} coll)) (defvalidator custom "Validates pred is true for the given value. For use with validation functions such as `validate` or `valid?`" [value pred] (println "Warning: bouncer.validators/custom is deprecated and will be removed. Use plain functions instead.") (pred value)) (defvalidator every "Validates pred is true for every item in coll. For use with validation functions such as `validate` or `valid?`" {:default-message-format "All items in %s must satisfy the predicate"} [coll pred] (every? pred coll)) (defvalidator matches "Validates value satisfies the given regex pattern. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must satisfy the given pattern" :optional true} [value re] ((complement empty?) (re-seq re value))) (defvalidator email "Validates value is an email address. It implements a simple check to verify there's only a '@' and at least one point after the '@' For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a valid email address"} [value] (and (required value) (matches value #"^[^@]+@[^@\\.]+[\\.].+"))) (defvalidator datetime "Validates value is a date(time). Optionally, takes a formatter argument which may be either an existing clj-time formatter, or a string representing a custom datetime formatter. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a valid date"} [value & [opt & _]] (let [formatter (if (string? opt) (f/formatter opt) opt)] (try (if formatter (f/parse formatter value) (f/parse value)) #+clj (catch IllegalArgumentException e false) #+cljs (catch js/Error e false))))
17259
(ns bouncer.validators "This namespace contains all built-in validators as well as macros for defining new validators and validator sets" {:author "<NAME>"} #+clj (:require [clj-time.format :as f]) #+cljs (:require [cljs-time.format :as f]) #+cljs (:require-macros [bouncer.validators :refer [defvalidator]])) ;; ## Customization support ;; ;; The following functions and macros support creating custom validators (defmacro defvalidator "Defines a new validating function using args & body semantics as provided by \"defn\". docstring and opts-map are optional opts-map is a map of key-value pairs and may be one of: - `:default-message-format` used when the client of this validator doesn't provide a message (consider using custom message functions) - `:optional` whether the validation should be run only if the given key has a non-nil value in the map. Defaults to false. or any other key-value pair which will be available in the validation result under the `:metadata` key. The function will be called with the value being validated as its first argument. Any extra arguments will be passed along to the function in the order they were used in the \"validate\" call. e.g.: (defvalidator member [value coll] (some #{value} coll)) (validate {:age 10} :age [[member (range 5)]]) This means the validator `member` will be called with the arguments `10` and `(0 1 2 3 4)`, in that order. " {:arglists '([name docstring? opts-map? [args*] & body])} [name & options] (let [[docstring options] (if (string? (first options)) [(first options) (next options)] [nil options]) [fn-meta [args & body]] (if (map? (first options)) [(first options) (next options)] [nil options]) fn-meta (assoc fn-meta :validator (keyword (str *ns*) (str name)))] (let [arglists ''([name])] `(do (def ~name (with-meta (fn ~name ([~@args] ~@body)) ~fn-meta)))))) ;; ## Built-in validators (defvalidator required "Validates value is present. If the value is a string, it makes sure it's not empty, otherwise it checks for nils. For use with validation functions such as `validate` or `valid?` " {:default-message-format "%s must be present"} [value] (if (string? value) (not (empty? value)) (not (nil? value)))) (defvalidator number "Validates maybe-a-number is a valid number. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a number" :optional true} [maybe-a-number] (number? maybe-a-number)) (defvalidator positive "Validates number is a number and is greater than zero. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a positive number" :optional true} [number] (> number 0)) (defvalidator member "Validates value is a member of coll. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be one of the values in the list"} [value coll] (some #{value} coll)) (defvalidator custom "Validates pred is true for the given value. For use with validation functions such as `validate` or `valid?`" [value pred] (println "Warning: bouncer.validators/custom is deprecated and will be removed. Use plain functions instead.") (pred value)) (defvalidator every "Validates pred is true for every item in coll. For use with validation functions such as `validate` or `valid?`" {:default-message-format "All items in %s must satisfy the predicate"} [coll pred] (every? pred coll)) (defvalidator matches "Validates value satisfies the given regex pattern. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must satisfy the given pattern" :optional true} [value re] ((complement empty?) (re-seq re value))) (defvalidator email "Validates value is an email address. It implements a simple check to verify there's only a '@' and at least one point after the '@' For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a valid email address"} [value] (and (required value) (matches value #"^[^@]+@[^@\\.]+[\\.].+"))) (defvalidator datetime "Validates value is a date(time). Optionally, takes a formatter argument which may be either an existing clj-time formatter, or a string representing a custom datetime formatter. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a valid date"} [value & [opt & _]] (let [formatter (if (string? opt) (f/formatter opt) opt)] (try (if formatter (f/parse formatter value) (f/parse value)) #+clj (catch IllegalArgumentException e false) #+cljs (catch js/Error e false))))
true
(ns bouncer.validators "This namespace contains all built-in validators as well as macros for defining new validators and validator sets" {:author "PI:NAME:<NAME>END_PI"} #+clj (:require [clj-time.format :as f]) #+cljs (:require [cljs-time.format :as f]) #+cljs (:require-macros [bouncer.validators :refer [defvalidator]])) ;; ## Customization support ;; ;; The following functions and macros support creating custom validators (defmacro defvalidator "Defines a new validating function using args & body semantics as provided by \"defn\". docstring and opts-map are optional opts-map is a map of key-value pairs and may be one of: - `:default-message-format` used when the client of this validator doesn't provide a message (consider using custom message functions) - `:optional` whether the validation should be run only if the given key has a non-nil value in the map. Defaults to false. or any other key-value pair which will be available in the validation result under the `:metadata` key. The function will be called with the value being validated as its first argument. Any extra arguments will be passed along to the function in the order they were used in the \"validate\" call. e.g.: (defvalidator member [value coll] (some #{value} coll)) (validate {:age 10} :age [[member (range 5)]]) This means the validator `member` will be called with the arguments `10` and `(0 1 2 3 4)`, in that order. " {:arglists '([name docstring? opts-map? [args*] & body])} [name & options] (let [[docstring options] (if (string? (first options)) [(first options) (next options)] [nil options]) [fn-meta [args & body]] (if (map? (first options)) [(first options) (next options)] [nil options]) fn-meta (assoc fn-meta :validator (keyword (str *ns*) (str name)))] (let [arglists ''([name])] `(do (def ~name (with-meta (fn ~name ([~@args] ~@body)) ~fn-meta)))))) ;; ## Built-in validators (defvalidator required "Validates value is present. If the value is a string, it makes sure it's not empty, otherwise it checks for nils. For use with validation functions such as `validate` or `valid?` " {:default-message-format "%s must be present"} [value] (if (string? value) (not (empty? value)) (not (nil? value)))) (defvalidator number "Validates maybe-a-number is a valid number. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a number" :optional true} [maybe-a-number] (number? maybe-a-number)) (defvalidator positive "Validates number is a number and is greater than zero. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a positive number" :optional true} [number] (> number 0)) (defvalidator member "Validates value is a member of coll. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be one of the values in the list"} [value coll] (some #{value} coll)) (defvalidator custom "Validates pred is true for the given value. For use with validation functions such as `validate` or `valid?`" [value pred] (println "Warning: bouncer.validators/custom is deprecated and will be removed. Use plain functions instead.") (pred value)) (defvalidator every "Validates pred is true for every item in coll. For use with validation functions such as `validate` or `valid?`" {:default-message-format "All items in %s must satisfy the predicate"} [coll pred] (every? pred coll)) (defvalidator matches "Validates value satisfies the given regex pattern. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must satisfy the given pattern" :optional true} [value re] ((complement empty?) (re-seq re value))) (defvalidator email "Validates value is an email address. It implements a simple check to verify there's only a '@' and at least one point after the '@' For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a valid email address"} [value] (and (required value) (matches value #"^[^@]+@[^@\\.]+[\\.].+"))) (defvalidator datetime "Validates value is a date(time). Optionally, takes a formatter argument which may be either an existing clj-time formatter, or a string representing a custom datetime formatter. For use with validation functions such as `validate` or `valid?`" {:default-message-format "%s must be a valid date"} [value & [opt & _]] (let [formatter (if (string? opt) (f/formatter opt) opt)] (try (if formatter (f/parse formatter value) (f/parse value)) #+clj (catch IllegalArgumentException e false) #+cljs (catch js/Error e false))))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998077154159546, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
ext/clojure-clojurescript-bef56a7/samples/twitterbuzz/src/twitterbuzz/dom-helpers.cljs
yokolet/clementine
35
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns twitterbuzz.dom-helpers (:require [clojure.string :as string] [goog.dom :as dom])) (defn get-element "Return the element with the passed id." [id] (dom/getElement (name id))) (defn append "Append all children to parent." [parent & children] (do (doseq [child children] (dom/appendChild parent child)) parent)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (let [e (if (keyword? e) (get-element e) e)] (doto e (dom/setTextContent s)))) (defn normalize-args [tag args] (let [parts (string/split (name tag) #"(\.|#)") [tag attrs] [(first parts) (apply hash-map (map #(cond (= % ".") :class (= % "#") :id :else %) (rest parts)))]] (if (map? (first args)) [tag (merge attrs (first args)) (rest args)] [tag attrs args]))) (defn element "Create a dom element using a keyword for the element name and a map for the attributes. Append all children to parent. If the first child is a string then the string will be set as the text content of the parent and all remaining children will be appended." [tag & args] (let [[tag attrs children] (normalize-args tag args) parent (dom/createDom (name tag) (reduce (fn [o [k v]] (aset o k v)) (js-obj) (map #(vector (name %1) %2) (keys attrs) (vals attrs)))) [parent children] (if (string? (first children)) [(set-text (element tag attrs) (first children)) (rest children)] [parent children])] (apply append parent children))) (defn remove-children "Remove all children from the element with the passed id." [id] (let [parent (dom/getElement (name id))] (do (dom/removeChildren parent)))) (defn html "Create a dom element from an html string." [s] (dom/htmlToDocumentFragment s)) (defn- element-arg? [x] (or (keyword? x) (map? x) (string? x))) (defn build "Build up a dom element from nested vectors." [x] (if (vector? x) (let [[parent children] (if (keyword? (first x)) [(apply element (take-while element-arg? x)) (drop-while element-arg? x)] [(first x) (rest x)]) children (map build children)] (apply append parent children)) x)) (defn insert-at "Insert a child element at a specific location." [parent child index] (dom/insertChildAt parent child index))
47438
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns twitterbuzz.dom-helpers (:require [clojure.string :as string] [goog.dom :as dom])) (defn get-element "Return the element with the passed id." [id] (dom/getElement (name id))) (defn append "Append all children to parent." [parent & children] (do (doseq [child children] (dom/appendChild parent child)) parent)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (let [e (if (keyword? e) (get-element e) e)] (doto e (dom/setTextContent s)))) (defn normalize-args [tag args] (let [parts (string/split (name tag) #"(\.|#)") [tag attrs] [(first parts) (apply hash-map (map #(cond (= % ".") :class (= % "#") :id :else %) (rest parts)))]] (if (map? (first args)) [tag (merge attrs (first args)) (rest args)] [tag attrs args]))) (defn element "Create a dom element using a keyword for the element name and a map for the attributes. Append all children to parent. If the first child is a string then the string will be set as the text content of the parent and all remaining children will be appended." [tag & args] (let [[tag attrs children] (normalize-args tag args) parent (dom/createDom (name tag) (reduce (fn [o [k v]] (aset o k v)) (js-obj) (map #(vector (name %1) %2) (keys attrs) (vals attrs)))) [parent children] (if (string? (first children)) [(set-text (element tag attrs) (first children)) (rest children)] [parent children])] (apply append parent children))) (defn remove-children "Remove all children from the element with the passed id." [id] (let [parent (dom/getElement (name id))] (do (dom/removeChildren parent)))) (defn html "Create a dom element from an html string." [s] (dom/htmlToDocumentFragment s)) (defn- element-arg? [x] (or (keyword? x) (map? x) (string? x))) (defn build "Build up a dom element from nested vectors." [x] (if (vector? x) (let [[parent children] (if (keyword? (first x)) [(apply element (take-while element-arg? x)) (drop-while element-arg? x)] [(first x) (rest x)]) children (map build children)] (apply append parent children)) x)) (defn insert-at "Insert a child element at a specific location." [parent child index] (dom/insertChildAt parent child index))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns twitterbuzz.dom-helpers (:require [clojure.string :as string] [goog.dom :as dom])) (defn get-element "Return the element with the passed id." [id] (dom/getElement (name id))) (defn append "Append all children to parent." [parent & children] (do (doseq [child children] (dom/appendChild parent child)) parent)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (let [e (if (keyword? e) (get-element e) e)] (doto e (dom/setTextContent s)))) (defn normalize-args [tag args] (let [parts (string/split (name tag) #"(\.|#)") [tag attrs] [(first parts) (apply hash-map (map #(cond (= % ".") :class (= % "#") :id :else %) (rest parts)))]] (if (map? (first args)) [tag (merge attrs (first args)) (rest args)] [tag attrs args]))) (defn element "Create a dom element using a keyword for the element name and a map for the attributes. Append all children to parent. If the first child is a string then the string will be set as the text content of the parent and all remaining children will be appended." [tag & args] (let [[tag attrs children] (normalize-args tag args) parent (dom/createDom (name tag) (reduce (fn [o [k v]] (aset o k v)) (js-obj) (map #(vector (name %1) %2) (keys attrs) (vals attrs)))) [parent children] (if (string? (first children)) [(set-text (element tag attrs) (first children)) (rest children)] [parent children])] (apply append parent children))) (defn remove-children "Remove all children from the element with the passed id." [id] (let [parent (dom/getElement (name id))] (do (dom/removeChildren parent)))) (defn html "Create a dom element from an html string." [s] (dom/htmlToDocumentFragment s)) (defn- element-arg? [x] (or (keyword? x) (map? x) (string? x))) (defn build "Build up a dom element from nested vectors." [x] (if (vector? x) (let [[parent children] (if (keyword? (first x)) [(apply element (take-while element-arg? x)) (drop-while element-arg? x)] [(first x) (rest x)]) children (map build children)] (apply append parent children)) x)) (defn insert-at "Insert a child element at a specific location." [parent child index] (dom/insertChildAt parent child index))