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": "[{:title \"Code Complete 2nd Edition\"\n :author \"Steve McConnell\"\n :year 2004}\n {:title \"Clean Code\"\n :a", "end": 109, "score": 0.9998871684074402, "start": 94, "tag": "NAME", "value": "Steve McConnell" }, { "context": "year 2004}\n {:title \"Clean Code\"\n :author \"Robert C. Martin\"\n :year 2008}\n {:title \"The Last Lecture\"\n", "end": 182, "score": 0.9998918771743774, "start": 166, "tag": "NAME", "value": "Robert C. Martin" }, { "context": "008}\n {:title \"The Last Lecture\"\n :author \"Randy Pausch\"\n :year 2008}])\n", "end": 258, "score": 0.9998865127563477, "start": 246, "tag": "NAME", "value": "Randy Pausch" } ]
04-clojure/01-examples/03-get-and-docker/src/core/books.clj
jersson/microservices-templates
1
(ns core.books) (defn get-all-books [] [{:title "Code Complete 2nd Edition" :author "Steve McConnell" :year 2004} {:title "Clean Code" :author "Robert C. Martin" :year 2008} {:title "The Last Lecture" :author "Randy Pausch" :year 2008}])
101550
(ns core.books) (defn get-all-books [] [{:title "Code Complete 2nd Edition" :author "<NAME>" :year 2004} {:title "Clean Code" :author "<NAME>" :year 2008} {:title "The Last Lecture" :author "<NAME>" :year 2008}])
true
(ns core.books) (defn get-all-books [] [{:title "Code Complete 2nd Edition" :author "PI:NAME:<NAME>END_PI" :year 2004} {:title "Clean Code" :author "PI:NAME:<NAME>END_PI" :year 2008} {:title "The Last Lecture" :author "PI:NAME:<NAME>END_PI" :year 2008}])
[ { "context": " @response#))\n token# (auth/make-jwt \"ben\" [:unifydb/user])\n ~token-header-name (", "end": 1580, "score": 0.5252312421798706, "start": 1577, "tag": "KEY", "value": "ben" }, { "context": " queue-backend auth-header]\n '[[[:unifydb/add \"ben\" :name \"Ben Bitdiddle\"]\n [:unifydb/add \"ben", "end": 2189, "score": 0.897418200969696, "start": 2186, "tag": "NAME", "value": "ben" }, { "context": "nd auth-header]\n '[[[:unifydb/add \"ben\" :name \"Ben Bitdiddle\"]\n [:unifydb/add \"ben\" :job [\"computer\" \"wi", "end": 2211, "score": 0.9998705387115479, "start": 2198, "tag": "NAME", "value": "Ben Bitdiddle" }, { "context": "alary 60000]\n [:unifydb/add \"alyssa\" :name \"Alyssa P. Hacker\"]\n [:unifydb/add \"alyssa\" :job [\"computer\" ", "end": 2364, "score": 0.9997448921203613, "start": 2348, "tag": "NAME", "value": "Alyssa P. Hacker" }, { "context": "cation/edn\"}\n :body \"[[\\\"Alyssa P. Hacker\\\"] [\\\"Ben Bitdiddle\\\"]]\"}))))))\n\n(deftest transac", "end": 3308, "score": 0.9779804944992065, "start": 3292, "tag": "NAME", "value": "Alyssa P. Hacker" }, { "context": " :body \"[[\\\"Alyssa P. Hacker\\\"] [\\\"Ben Bitdiddle\\\"]]\"}))))))\n\n(deftest transact-endpoint\n (with-s", "end": 3328, "score": 0.9958053231239319, "start": 3315, "tag": "NAME", "value": "Ben Bitdiddle" }, { "context": " {:tx-data [[:unifydb/add \"ben\" :name \"Ben Bitdiddle\"]\n ", "end": 3874, "score": 0.6708932518959045, "start": 3871, "tag": "NAME", "value": "ben" }, { "context": " {:tx-data [[:unifydb/add \"ben\" :name \"Ben Bitdiddle\"]\n [:unif", "end": 3896, "score": 0.9998519420623779, "start": 3883, "tag": "NAME", "value": "Ben Bitdiddle" }, { "context": " [:unifydb/add \"alyssa\" :name \"Alyssa P. Hacker\"]\n [:unif", "end": 3986, "score": 0.9998592734336853, "start": 3970, "tag": "NAME", "value": "Alyssa P. Hacker" }, { "context": " [:unifydb/add \"alyssa\" :supervisor \"ben\"]]})})\n tx-instant (as-> (:body respon", "end": 4069, "score": 0.7231484055519104, "start": 4066, "tag": "NAME", "value": "ben" }, { "context": "}\n :tx-data [[#unifydb/id 1 :name \"Ben Bitdiddle\" #unifydb/id 3 true]\n [#", "end": 4573, "score": 0.9998536705970764, "start": 4560, "tag": "NAME", "value": "Ben Bitdiddle" }, { "context": "]\n [#unifydb/id 2 :name \"Alyssa P. Hacker\" #unifydb/id 3 true]\n [#", "end": 4659, "score": 0.99986332654953, "start": 4643, "tag": "NAME", "value": "Alyssa P. Hacker" }, { "context": "t #unifydb/id 3 true]]\n :tempids {\"ben\" #unifydb/id 1\n \"alyssa\"", "end": 4890, "score": 0.8141607642173767, "start": 4887, "tag": "NAME", "value": "ben" }, { "context": "r]\n '[[[:unifydb/add \"user\" :unifydb/username \"ben\"]\n [:unifydb/add \"user\" :unifydb/password \"", "end": 5199, "score": 0.9925406575202942, "start": 5196, "tag": "USERNAME", "value": "ben" }, { "context": "\"]\n [:unifydb/add \"user\" :unifydb/password \"top secret\"]\n [:unifydb/add \"thing\" :id \"foo-thing\"]\n ", "end": 5259, "score": 0.9990236163139343, "start": 5249, "tag": "PASSWORD", "value": "top secret" }, { "context": " :query-string \"username=ben\"\n :headers {\"a", "end": 6240, "score": 0.9985719323158264, "start": 6237, "tag": "USERNAME", "value": "ben" }, { "context": " (is (= 200 (:status response)))\n (is (= \"ben\" (:username body)))\n (is (not (nil? (:salt", "end": 6430, "score": 0.9986831545829773, "start": 6427, "tag": "USERNAME", "value": "ben" }, { "context": " :query-string \"username=ben\"\n :headers", "end": 6920, "score": 0.9987363219261169, "start": 6917, "tag": "USERNAME", "value": "ben" }, { "context": " :password hashed-password\n ", "end": 7832, "score": 0.9906587600708008, "start": 7817, "tag": "PASSWORD", "value": "hashed-password" }, { "context": " (is (= 200 (:status response)))\n (is (= \"ben\" (:username response-body)))\n (is (not (ni", "end": 8096, "score": 0.997215986251831, "start": 8093, "tag": "USERNAME", "value": "ben" }, { "context": " :query-string \"username=ben\"\n :headers", "end": 8441, "score": 0.9994398951530457, "start": 8438, "tag": "USERNAME", "value": "ben" }, { "context": "\"accept\" \"application/edn\"}})\n {:keys [username\n salt\n nonc", "end": 8551, "score": 0.9980915784835815, "start": 8543, "tag": "USERNAME", "value": "username" }, { "context": " :body (prn-str {:username username\n ", "end": 9249, "score": 0.9980243444442749, "start": 9241, "tag": "USERNAME", "value": "username" }, { "context": " :password hashed-password\n ", "end": 9318, "score": 0.5138010382652283, "start": 9318, "tag": "PASSWORD", "value": "" }, { "context": " :query-string \"username=ben\"\n :headers", "end": 9747, "score": 0.9993388652801514, "start": 9744, "tag": "USERNAME", "value": "ben" }, { "context": "\"accept\" \"application/edn\"}})\n {:keys [username\n salt\n nonc", "end": 9857, "score": 0.9959830045700073, "start": 9849, "tag": "USERNAME", "value": "username" }, { "context": " :body (prn-str {:username username\n ", "end": 10606, "score": 0.9988308548927307, "start": 10598, "tag": "USERNAME", "value": "username" }, { "context": " :password hashed-password\n ", "end": 10689, "score": 0.9805207252502441, "start": 10674, "tag": "PASSWORD", "value": "hashed-password" } ]
test/unifydb/server_test.clj
jdormit/unifydb
15
(ns unifydb.server-test {:clj-kondo/config '{:linters {:unresolved-symbol {:exclude [(unifydb.server-test/with-server)]}}}} (:require [buddy.core.bytes :as bytes] [buddy.core.codecs :as codecs] [buddy.core.codecs.base64 :as base64] [buddy.core.hash :as hash] [clojure.test :refer [deftest testing is]] [unifydb.auth :as auth] [unifydb.cache.memory :as memcache] [unifydb.config :as config] [unifydb.edn :as edn] [unifydb.kvstore :as kvstore] [unifydb.kvstore.memory :as memstore] [unifydb.messagequeue :as queue] [unifydb.messagequeue.memory :as memq] [unifydb.query :as query] [unifydb.server :as server] [unifydb.service :as service] [unifydb.storage :as store] [unifydb.transact :as transact])) (defmacro with-server [[req-fn store-name queue-name token-header-name] txs & body] `(config/with-config {:secret "secret"} (let [~queue-name (memq/new) ~store-name (kvstore/new (memstore/new)) query# (query/new ~queue-name (store/new! ~store-name)) transact# (transact/new ~queue-name (store/new! ~store-name)) cache# (memcache/new) server# (server/new ~queue-name cache#) ~req-fn (fn [request#] (let [app# (server/app (:state server#)) response# (app# request#)] @response#)) token# (auth/make-jwt "ben" [:unifydb/user]) ~token-header-name (format "Bearer %s" token#)] (try (service/start! query#) (service/start! transact#) (service/start! server#) (doseq [tx# ~txs] (queue/publish ~queue-name :transact {:tx-data tx#})) (Thread/sleep 5) ;; give the transaction time to process ~@body (finally (service/stop! server#) (service/stop! transact#) (service/stop! query#)))))) (deftest query-endpoint (with-server [make-request store queue-backend auth-header] '[[[:unifydb/add "ben" :name "Ben Bitdiddle"] [:unifydb/add "ben" :job ["computer" "wizard"]] [:unifydb/add "ben" :salary 60000] [:unifydb/add "alyssa" :name "Alyssa P. Hacker"] [:unifydb/add "alyssa" :job ["computer" "programmer"]] [:unifydb/add "alyssa" :salary 40000] [:unifydb/add "alyssa" :supervisor "ben"]]] (testing "/query (EDN)" (let [response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" auth-header} :body (prn-str {:tx-id #unifydb/id 3 :query '{:find [?name] :where [[?e :job ["computer" _]] [?e :name ?name]]}})})] (is (= response '{:status 200 :headers {"Content-Type" "application/edn"} :body "[[\"Alyssa P. Hacker\"] [\"Ben Bitdiddle\"]]"})))))) (deftest transact-endpoint (with-server [make-request store queue-backend auth-header] [] (testing "/transact (EDN)" (let [response (make-request {:request-method :post :uri "/transact" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" auth-header} :body (prn-str {:tx-data [[:unifydb/add "ben" :name "Ben Bitdiddle"] [:unifydb/add "alyssa" :name "Alyssa P. Hacker"] [:unifydb/add "alyssa" :supervisor "ben"]]})}) tx-instant (as-> (:body response) v (edn/read-string v) (:tx-data v) (filter #(= :unifydb/txInstant (second %)) v) (first v) (nth v 2))] (is (= (:status response) 200)) (is (= (:headers response) {"Content-Type" "application/edn"})) (is (= {:db-after {:tx-id #unifydb/id 3} :tx-data [[#unifydb/id 1 :name "Ben Bitdiddle" #unifydb/id 3 true] [#unifydb/id 2 :name "Alyssa P. Hacker" #unifydb/id 3 true] [#unifydb/id 2 :supervisor #unifydb/id 1 #unifydb/id 3 true] [#unifydb/id 3 :unifydb/txInstant tx-instant #unifydb/id 3 true]] :tempids {"ben" #unifydb/id 1 "alyssa" #unifydb/id 2 "unifydb.tx" #unifydb/id 3}} (edn/read-string (:body response)))))))) (deftest test-auth (with-server [make-request store queue-backend _auth-header] '[[[:unifydb/add "user" :unifydb/username "ben"] [:unifydb/add "user" :unifydb/password "top secret"] [:unifydb/add "thing" :id "foo-thing"] [:unifydb/add "thing" :foo "bar"]]] (testing "missing authentication" (let [response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str '{:tx-id :latest :query {:find [?foo] :where [[?thing :id "foo-thing"] [?thing :foo ?foo]]}})})] (is (= 401 (:status response))))) (testing "authenticate GET request" (let [response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) body (edn/read-string (:body response))] (is (= 200 (:status response))) (is (= "ben" (:username body))) (is (not (nil? (:salt body)))) (is (string? (:salt body))) (is (not (nil? (:nonce-key body)))) (is (string? (:nonce-key body))) (is (not (nil? (:nonce body)))) (is (string? (:nonce body))))) (testing "authenticate POST request" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password hashed-password :nonce nonce :nonce-key nonce-key})}) response-body (edn/read-string (:body response))] (is (= 200 (:status response))) (is (= "ben" (:username response-body))) (is (not (nil? (:token response-body)))) (is (string? (:token response-body))))) (testing "invalid nonce" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password hashed-password :nonce "wrong" :nonce-key nonce-key})})] (is (= 400 (:status response))))) (testing "token-authenticated request" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) post-response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password hashed-password :nonce-key nonce-key :nonce nonce})}) {:keys [token]} (edn/read-string (:body post-response)) response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" (format "Bearer %s" token)} :body (prn-str '{:tx-id :latest :query {:find [?foo] :where [[?thing :id "foo-thing"] [?thing :foo ?foo]]}})})] (is (= 200 (:status response))) (is (= [["bar"]] (edn/read-string (:body response)))))) (testing "not found" (let [response (make-request {:request-method :get :uri "/does-not-exist"})] (is (= 404 (:status response)))))))
54644
(ns unifydb.server-test {:clj-kondo/config '{:linters {:unresolved-symbol {:exclude [(unifydb.server-test/with-server)]}}}} (:require [buddy.core.bytes :as bytes] [buddy.core.codecs :as codecs] [buddy.core.codecs.base64 :as base64] [buddy.core.hash :as hash] [clojure.test :refer [deftest testing is]] [unifydb.auth :as auth] [unifydb.cache.memory :as memcache] [unifydb.config :as config] [unifydb.edn :as edn] [unifydb.kvstore :as kvstore] [unifydb.kvstore.memory :as memstore] [unifydb.messagequeue :as queue] [unifydb.messagequeue.memory :as memq] [unifydb.query :as query] [unifydb.server :as server] [unifydb.service :as service] [unifydb.storage :as store] [unifydb.transact :as transact])) (defmacro with-server [[req-fn store-name queue-name token-header-name] txs & body] `(config/with-config {:secret "secret"} (let [~queue-name (memq/new) ~store-name (kvstore/new (memstore/new)) query# (query/new ~queue-name (store/new! ~store-name)) transact# (transact/new ~queue-name (store/new! ~store-name)) cache# (memcache/new) server# (server/new ~queue-name cache#) ~req-fn (fn [request#] (let [app# (server/app (:state server#)) response# (app# request#)] @response#)) token# (auth/make-jwt "<KEY>" [:unifydb/user]) ~token-header-name (format "Bearer %s" token#)] (try (service/start! query#) (service/start! transact#) (service/start! server#) (doseq [tx# ~txs] (queue/publish ~queue-name :transact {:tx-data tx#})) (Thread/sleep 5) ;; give the transaction time to process ~@body (finally (service/stop! server#) (service/stop! transact#) (service/stop! query#)))))) (deftest query-endpoint (with-server [make-request store queue-backend auth-header] '[[[:unifydb/add "<KEY>" :name "<NAME>"] [:unifydb/add "ben" :job ["computer" "wizard"]] [:unifydb/add "ben" :salary 60000] [:unifydb/add "alyssa" :name "<NAME>"] [:unifydb/add "alyssa" :job ["computer" "programmer"]] [:unifydb/add "alyssa" :salary 40000] [:unifydb/add "alyssa" :supervisor "ben"]]] (testing "/query (EDN)" (let [response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" auth-header} :body (prn-str {:tx-id #unifydb/id 3 :query '{:find [?name] :where [[?e :job ["computer" _]] [?e :name ?name]]}})})] (is (= response '{:status 200 :headers {"Content-Type" "application/edn"} :body "[[\"<NAME>\"] [\"<NAME>\"]]"})))))) (deftest transact-endpoint (with-server [make-request store queue-backend auth-header] [] (testing "/transact (EDN)" (let [response (make-request {:request-method :post :uri "/transact" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" auth-header} :body (prn-str {:tx-data [[:unifydb/add "<KEY>" :name "<NAME>"] [:unifydb/add "alyssa" :name "<NAME>"] [:unifydb/add "alyssa" :supervisor "<KEY>"]]})}) tx-instant (as-> (:body response) v (edn/read-string v) (:tx-data v) (filter #(= :unifydb/txInstant (second %)) v) (first v) (nth v 2))] (is (= (:status response) 200)) (is (= (:headers response) {"Content-Type" "application/edn"})) (is (= {:db-after {:tx-id #unifydb/id 3} :tx-data [[#unifydb/id 1 :name "<NAME>" #unifydb/id 3 true] [#unifydb/id 2 :name "<NAME>" #unifydb/id 3 true] [#unifydb/id 2 :supervisor #unifydb/id 1 #unifydb/id 3 true] [#unifydb/id 3 :unifydb/txInstant tx-instant #unifydb/id 3 true]] :tempids {"<KEY>" #unifydb/id 1 "alyssa" #unifydb/id 2 "unifydb.tx" #unifydb/id 3}} (edn/read-string (:body response)))))))) (deftest test-auth (with-server [make-request store queue-backend _auth-header] '[[[:unifydb/add "user" :unifydb/username "ben"] [:unifydb/add "user" :unifydb/password "<PASSWORD>"] [:unifydb/add "thing" :id "foo-thing"] [:unifydb/add "thing" :foo "bar"]]] (testing "missing authentication" (let [response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str '{:tx-id :latest :query {:find [?foo] :where [[?thing :id "foo-thing"] [?thing :foo ?foo]]}})})] (is (= 401 (:status response))))) (testing "authenticate GET request" (let [response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) body (edn/read-string (:body response))] (is (= 200 (:status response))) (is (= "ben" (:username body))) (is (not (nil? (:salt body)))) (is (string? (:salt body))) (is (not (nil? (:nonce-key body)))) (is (string? (:nonce-key body))) (is (not (nil? (:nonce body)))) (is (string? (:nonce body))))) (testing "authenticate POST request" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password <PASSWORD> :nonce nonce :nonce-key nonce-key})}) response-body (edn/read-string (:body response))] (is (= 200 (:status response))) (is (= "ben" (:username response-body))) (is (not (nil? (:token response-body)))) (is (string? (:token response-body))))) (testing "invalid nonce" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password hashed<PASSWORD>-password :nonce "wrong" :nonce-key nonce-key})})] (is (= 400 (:status response))))) (testing "token-authenticated request" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) post-response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password <PASSWORD> :nonce-key nonce-key :nonce nonce})}) {:keys [token]} (edn/read-string (:body post-response)) response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" (format "Bearer %s" token)} :body (prn-str '{:tx-id :latest :query {:find [?foo] :where [[?thing :id "foo-thing"] [?thing :foo ?foo]]}})})] (is (= 200 (:status response))) (is (= [["bar"]] (edn/read-string (:body response)))))) (testing "not found" (let [response (make-request {:request-method :get :uri "/does-not-exist"})] (is (= 404 (:status response)))))))
true
(ns unifydb.server-test {:clj-kondo/config '{:linters {:unresolved-symbol {:exclude [(unifydb.server-test/with-server)]}}}} (:require [buddy.core.bytes :as bytes] [buddy.core.codecs :as codecs] [buddy.core.codecs.base64 :as base64] [buddy.core.hash :as hash] [clojure.test :refer [deftest testing is]] [unifydb.auth :as auth] [unifydb.cache.memory :as memcache] [unifydb.config :as config] [unifydb.edn :as edn] [unifydb.kvstore :as kvstore] [unifydb.kvstore.memory :as memstore] [unifydb.messagequeue :as queue] [unifydb.messagequeue.memory :as memq] [unifydb.query :as query] [unifydb.server :as server] [unifydb.service :as service] [unifydb.storage :as store] [unifydb.transact :as transact])) (defmacro with-server [[req-fn store-name queue-name token-header-name] txs & body] `(config/with-config {:secret "secret"} (let [~queue-name (memq/new) ~store-name (kvstore/new (memstore/new)) query# (query/new ~queue-name (store/new! ~store-name)) transact# (transact/new ~queue-name (store/new! ~store-name)) cache# (memcache/new) server# (server/new ~queue-name cache#) ~req-fn (fn [request#] (let [app# (server/app (:state server#)) response# (app# request#)] @response#)) token# (auth/make-jwt "PI:KEY:<KEY>END_PI" [:unifydb/user]) ~token-header-name (format "Bearer %s" token#)] (try (service/start! query#) (service/start! transact#) (service/start! server#) (doseq [tx# ~txs] (queue/publish ~queue-name :transact {:tx-data tx#})) (Thread/sleep 5) ;; give the transaction time to process ~@body (finally (service/stop! server#) (service/stop! transact#) (service/stop! query#)))))) (deftest query-endpoint (with-server [make-request store queue-backend auth-header] '[[[:unifydb/add "PI:NAME:<KEY>END_PI" :name "PI:NAME:<NAME>END_PI"] [:unifydb/add "ben" :job ["computer" "wizard"]] [:unifydb/add "ben" :salary 60000] [:unifydb/add "alyssa" :name "PI:NAME:<NAME>END_PI"] [:unifydb/add "alyssa" :job ["computer" "programmer"]] [:unifydb/add "alyssa" :salary 40000] [:unifydb/add "alyssa" :supervisor "ben"]]] (testing "/query (EDN)" (let [response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" auth-header} :body (prn-str {:tx-id #unifydb/id 3 :query '{:find [?name] :where [[?e :job ["computer" _]] [?e :name ?name]]}})})] (is (= response '{:status 200 :headers {"Content-Type" "application/edn"} :body "[[\"PI:NAME:<NAME>END_PI\"] [\"PI:NAME:<NAME>END_PI\"]]"})))))) (deftest transact-endpoint (with-server [make-request store queue-backend auth-header] [] (testing "/transact (EDN)" (let [response (make-request {:request-method :post :uri "/transact" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" auth-header} :body (prn-str {:tx-data [[:unifydb/add "PI:NAME:<KEY>END_PI" :name "PI:NAME:<NAME>END_PI"] [:unifydb/add "alyssa" :name "PI:NAME:<NAME>END_PI"] [:unifydb/add "alyssa" :supervisor "PI:NAME:<KEY>END_PI"]]})}) tx-instant (as-> (:body response) v (edn/read-string v) (:tx-data v) (filter #(= :unifydb/txInstant (second %)) v) (first v) (nth v 2))] (is (= (:status response) 200)) (is (= (:headers response) {"Content-Type" "application/edn"})) (is (= {:db-after {:tx-id #unifydb/id 3} :tx-data [[#unifydb/id 1 :name "PI:NAME:<NAME>END_PI" #unifydb/id 3 true] [#unifydb/id 2 :name "PI:NAME:<NAME>END_PI" #unifydb/id 3 true] [#unifydb/id 2 :supervisor #unifydb/id 1 #unifydb/id 3 true] [#unifydb/id 3 :unifydb/txInstant tx-instant #unifydb/id 3 true]] :tempids {"PI:NAME:<KEY>END_PI" #unifydb/id 1 "alyssa" #unifydb/id 2 "unifydb.tx" #unifydb/id 3}} (edn/read-string (:body response)))))))) (deftest test-auth (with-server [make-request store queue-backend _auth-header] '[[[:unifydb/add "user" :unifydb/username "ben"] [:unifydb/add "user" :unifydb/password "PI:PASSWORD:<PASSWORD>END_PI"] [:unifydb/add "thing" :id "foo-thing"] [:unifydb/add "thing" :foo "bar"]]] (testing "missing authentication" (let [response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str '{:tx-id :latest :query {:find [?foo] :where [[?thing :id "foo-thing"] [?thing :foo ?foo]]}})})] (is (= 401 (:status response))))) (testing "authenticate GET request" (let [response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) body (edn/read-string (:body response))] (is (= 200 (:status response))) (is (= "ben" (:username body))) (is (not (nil? (:salt body)))) (is (string? (:salt body))) (is (not (nil? (:nonce-key body)))) (is (string? (:nonce-key body))) (is (not (nil? (:nonce body)))) (is (string? (:nonce body))))) (testing "authenticate POST request" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password PI:PASSWORD:<PASSWORD>END_PI :nonce nonce :nonce-key nonce-key})}) response-body (edn/read-string (:body response))] (is (= 200 (:status response))) (is (= "ben" (:username response-body))) (is (not (nil? (:token response-body)))) (is (string? (:token response-body))))) (testing "invalid nonce" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password hashedPI:PASSWORD:<PASSWORD>END_PI-password :nonce "wrong" :nonce-key nonce-key})})] (is (= 400 (:status response))))) (testing "token-authenticated request" (let [get-response (make-request {:request-method :get :uri "/authenticate" :query-string "username=ben" :headers {"accept" "application/edn"}}) {:keys [username salt nonce nonce-key]} (edn/read-string (:body get-response)) hashed-password (codecs/bytes->str (base64/encode (hash/sha512 (bytes/concat (codecs/str->bytes "top secret") (base64/decode salt))))) post-response (make-request {:request-method :post :uri "/authenticate" :headers {"content-type" "application/edn" "accept" "application/edn"} :body (prn-str {:username username :password PI:PASSWORD:<PASSWORD>END_PI :nonce-key nonce-key :nonce nonce})}) {:keys [token]} (edn/read-string (:body post-response)) response (make-request {:request-method :post :uri "/query" :headers {"content-type" "application/edn" "accept" "application/edn" "authorization" (format "Bearer %s" token)} :body (prn-str '{:tx-id :latest :query {:find [?foo] :where [[?thing :id "foo-thing"] [?thing :foo ?foo]]}})})] (is (= 200 (:status response))) (is (= [["bar"]] (edn/read-string (:body response)))))) (testing "not found" (let [response (make-request {:request-method :get :uri "/does-not-exist"})] (is (= 404 (:status response)))))))
[ { "context": ":ID :Salary :Department)\n\n(def data\n (->> '((\"Tyler Bennett\" E10297 32000 D101)\n (\"John Rappl\" E21", "end": 142, "score": 0.9998844861984253, "start": 129, "tag": "NAME", "value": "Tyler Bennett" }, { "context": "(\"Tyler Bennett\" E10297 32000 D101)\n (\"John Rappl\" E21437 47000 D050)\n (\"George Woltman\"", "end": 187, "score": 0.9998903274536133, "start": 177, "tag": "NAME", "value": "John Rappl" }, { "context": " (\"John Rappl\" E21437 47000 D050)\n (\"George Woltman\" E00127 53500 D101)\n (\"Adam Smith\" E63", "end": 236, "score": 0.9998824000358582, "start": 222, "tag": "NAME", "value": "George Woltman" }, { "context": "\"George Woltman\" E00127 53500 D101)\n (\"Adam Smith\" E63535 18000 D202)\n (\"Claire Buckman\"", "end": 281, "score": 0.9998500347137451, "start": 271, "tag": "NAME", "value": "Adam Smith" }, { "context": " (\"Adam Smith\" E63535 18000 D202)\n (\"Claire Buckman\" E39876 27800 D202)\n (\"David McClellan", "end": 330, "score": 0.9998781085014343, "start": 316, "tag": "NAME", "value": "Claire Buckman" }, { "context": "\"Claire Buckman\" E39876 27800 D202)\n (\"David McClellan\" E04242 41500 D101)\n (\"Rich Holcomb\" E", "end": 380, "score": 0.999880313873291, "start": 365, "tag": "NAME", "value": "David McClellan" }, { "context": "David McClellan\" E04242 41500 D101)\n (\"Rich Holcomb\" E01234 49500 D202)\n (\"Nathan Adams\" E", "end": 427, "score": 0.9998836517333984, "start": 415, "tag": "NAME", "value": "Rich Holcomb" }, { "context": " (\"Rich Holcomb\" E01234 49500 D202)\n (\"Nathan Adams\" E41298 21900 D050)\n (\"Richard Potter\"", "end": 474, "score": 0.9998776912689209, "start": 462, "tag": "NAME", "value": "Nathan Adams" }, { "context": " (\"Nathan Adams\" E41298 21900 D050)\n (\"Richard Potter\" E43128 15900 D101)\n (\"David Motsinger", "end": 523, "score": 0.999846339225769, "start": 509, "tag": "NAME", "value": "Richard Potter" }, { "context": "\"Richard Potter\" E43128 15900 D101)\n (\"David Motsinger\" E27002 19250 D202)\n (\"Tim Sampair\" E0", "end": 573, "score": 0.999873697757721, "start": 558, "tag": "NAME", "value": "David Motsinger" }, { "context": "David Motsinger\" E27002 19250 D202)\n (\"Tim Sampair\" E03033 27000 D101)\n (\"Kim Arlich\" E10", "end": 619, "score": 0.9998787045478821, "start": 608, "tag": "NAME", "value": "Tim Sampair" }, { "context": " (\"Tim Sampair\" E03033 27000 D101)\n (\"Kim Arlich\" E10001 57000 D190)\n (\"Timothy Grove\" ", "end": 664, "score": 0.9998822212219238, "start": 654, "tag": "NAME", "value": "Kim Arlich" }, { "context": " (\"Kim Arlich\" E10001 57000 D190)\n (\"Timothy Grove\" E16398 29900 D190))\n (map #(apply (part", "end": 712, "score": 0.9998706579208374, "start": 699, "tag": "NAME", "value": "Timothy Grove" } ]
Task/Top-rank-per-group/Clojure/top-rank-per-group.clj
LaudateCorpus1/RosettaCodeData
1
(use '[clojure.contrib.seq-utils :only (group-by)]) (defstruct employee :Name :ID :Salary :Department) (def data (->> '(("Tyler Bennett" E10297 32000 D101) ("John Rappl" E21437 47000 D050) ("George Woltman" E00127 53500 D101) ("Adam Smith" E63535 18000 D202) ("Claire Buckman" E39876 27800 D202) ("David McClellan" E04242 41500 D101) ("Rich Holcomb" E01234 49500 D202) ("Nathan Adams" E41298 21900 D050) ("Richard Potter" E43128 15900 D101) ("David Motsinger" E27002 19250 D202) ("Tim Sampair" E03033 27000 D101) ("Kim Arlich" E10001 57000 D190) ("Timothy Grove" E16398 29900 D190)) (map #(apply (partial struct employee) %)))) (doseq [[dep emps] (group-by :Department data)] (println "Department:" dep) (doseq [e (take 3 (reverse (sort-by :Salary emps)))] (println e)))
88591
(use '[clojure.contrib.seq-utils :only (group-by)]) (defstruct employee :Name :ID :Salary :Department) (def data (->> '(("<NAME>" E10297 32000 D101) ("<NAME>" E21437 47000 D050) ("<NAME>" E00127 53500 D101) ("<NAME>" E63535 18000 D202) ("<NAME>" E39876 27800 D202) ("<NAME>" E04242 41500 D101) ("<NAME>" E01234 49500 D202) ("<NAME>" E41298 21900 D050) ("<NAME>" E43128 15900 D101) ("<NAME>" E27002 19250 D202) ("<NAME>" E03033 27000 D101) ("<NAME>" E10001 57000 D190) ("<NAME>" E16398 29900 D190)) (map #(apply (partial struct employee) %)))) (doseq [[dep emps] (group-by :Department data)] (println "Department:" dep) (doseq [e (take 3 (reverse (sort-by :Salary emps)))] (println e)))
true
(use '[clojure.contrib.seq-utils :only (group-by)]) (defstruct employee :Name :ID :Salary :Department) (def data (->> '(("PI:NAME:<NAME>END_PI" E10297 32000 D101) ("PI:NAME:<NAME>END_PI" E21437 47000 D050) ("PI:NAME:<NAME>END_PI" E00127 53500 D101) ("PI:NAME:<NAME>END_PI" E63535 18000 D202) ("PI:NAME:<NAME>END_PI" E39876 27800 D202) ("PI:NAME:<NAME>END_PI" E04242 41500 D101) ("PI:NAME:<NAME>END_PI" E01234 49500 D202) ("PI:NAME:<NAME>END_PI" E41298 21900 D050) ("PI:NAME:<NAME>END_PI" E43128 15900 D101) ("PI:NAME:<NAME>END_PI" E27002 19250 D202) ("PI:NAME:<NAME>END_PI" E03033 27000 D101) ("PI:NAME:<NAME>END_PI" E10001 57000 D190) ("PI:NAME:<NAME>END_PI" E16398 29900 D190)) (map #(apply (partial struct employee) %)))) (doseq [[dep emps] (group-by :Department data)] (println "Department:" dep) (doseq [e (take 3 (reverse (sort-by :Salary emps)))] (println e)))
[ { "context": "hor :date :files] :as state}]]\n (let [doc {:name name\n :eaf (eaf30/create-eaf {:author aut", "end": 1868, "score": 0.9963790774345398, "start": 1864, "tag": "NAME", "value": "name" }, { "context": "name\n :eaf (eaf30/create-eaf {:author author\n :date (.toI", "end": 1921, "score": 0.900300145149231, "start": 1915, "tag": "NAME", "value": "author" }, { "context": "ame :eaf :files] :as state}]]\n\n (let [doc {:name name\n :eaf eaf\n :_attachment", "end": 2849, "score": 0.9977688193321228, "start": 2845, "tag": "NAME", "value": "name" } ]
src/cljs/ewan/project/core.cljs
lgessler/EWAN
0
(ns ewan.project.core (:require [re-frame.core :as rf] [ewan.eaf30.core :as eaf30] [ewan.project.new-form :refer [new-project-dialog-form]] [ewan.project.upload-form :refer [upload-project-dialog-form]] [ewan.project.edit.core :refer [project-edit-panel-body]] [cljsjs.material-ui] [cljs-react-material-ui.core] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as ic] [reagent.core :as r])) ;; used in db.cljs (def ^:export default-db {::projects [] ::new-project-dialog-open false ::upload-project-dialog-open false}) ;; ---------------------------------------------------------------------------- ;; subs ;; ---------------------------------------------------------------------------- (rf/reg-sub ::available-projects (fn [db _] (::projects db))) (rf/reg-sub ::new-project-dialog-open (fn [db _] (::new-project-dialog-open db))) (rf/reg-sub ::upload-project-dialog-open (fn [db _] (::upload-project-dialog-open db))) ;; ---------------------------------------------------------------------------- ;; events ;; ---------------------------------------------------------------------------- (rf/reg-event-db ::open-new-project-dialog (fn [db _] (assoc db ::new-project-dialog-open true))) (rf/reg-event-db ::close-new-project-dialog (fn [db _] (assoc db ::new-project-dialog-open false))) (rf/reg-event-db ::open-upload-project-dialog (fn [db _] (assoc db ::upload-project-dialog-open true))) (rf/reg-event-db ::close-upload-project-dialog (fn [db _] (assoc db ::upload-project-dialog-open false))) ;; When a user submits the create new project form, this event is fired. (rf/reg-event-fx ::create-new-project (fn [{:keys [db]} [_ {:keys [:name :author :date :files] :as state}]] (let [doc {:name name :eaf (eaf30/create-eaf {:author author :date (.toISOString date) :media-descriptors (for [file files] {:media-url (.-name file) :mime-type (.-type file)})}) :_attachments (into {} (for [file files] [(.-name file) {:content_type (.-type file) :data file}]))}] {:db db :pouchdb {:method "post" :args [doc {} (fn [err response] (if err (throw err) (rf/dispatch [::new-project-created response])))]}}))) ;; Similar event, but for uploading a project (rf/reg-event-fx ::upload-new-project (fn [{:keys [db]} [_ {:keys [:name :eaf :files] :as state}]] (let [doc {:name name :eaf eaf :_attachments (into {} (for [file files] [(.-name file) {:content_type (.-type file) :data file}]))}] {:db db :pouchdb {:method "post" :args [doc {} (fn [err response] (if err (throw err) (rf/dispatch [::new-project-created response])))]}}))) ;; Because PouchDB's `post` method is async, ::create-new-project initiates ;; the creation of the PDB document, and this event is fired after the ;; document is created. ;; TODO: proper error handling (rf/reg-event-fx ::new-project-created (fn [{:keys [db]} [_ response]] (if-not (.-ok response) (throw response) {:db db :pouchdb {:method "get" :args [(.-id response) {} (fn [err doc] (if err (throw err) (rf/dispatch [::new-project-doc-fetched doc])))]}}))) ;; Since `post` only tells you whether or not the document was successfully ;; created and does not give you the document's value, we need to call `get` ;; so we can update re-frame's DB with the value of the new document. (rf/reg-event-db ::new-project-doc-fetched (fn [db [_ doc]] (update db ::projects conj (js->clj doc :keywordize-keys true)))) ;; ---------------------------------------------------------------------------- ;; views ;; ---------------------------------------------------------------------------- ;; dialog -- a popup window that contains a form for creating a new project ;; new project dialog --------------------------------------------------------- (defn- open-new-project-dialog [] (rf/dispatch [::open-new-project-dialog])) (defn- close-new-project-dialog [] (rf/dispatch [::close-new-project-dialog])) ;; dialog's actions prop expects a js array (def ^{:private true} new-project-dialog-actions #js[(r/as-element [ui/flat-button {:label "Create" :primary true :type "submit" :form "new-project-dialog-form"}]) (r/as-element [ui/flat-button {:label "Cancel" :primary false :on-click close-new-project-dialog}])]) (defn- new-form-submitted-callback [state] (close-new-project-dialog) (rf/dispatch [::create-new-project state])) (defn- new-project-dialog [] (r/with-let [open (rf/subscribe [::new-project-dialog-open])] ;; for form ID [ui/dialog {:title "Create a new project" :modal false :open @open :actions (r/as-element new-project-dialog-actions) :on-request-close close-new-project-dialog :auto-scroll-body-content true} [new-project-dialog-form new-form-submitted-callback]])) ;; upload project dialog ------------------------------------------------------ (defn- open-upload-project-dialog [] (rf/dispatch [::open-upload-project-dialog])) (defn- close-upload-project-dialog [] (rf/dispatch [::close-upload-project-dialog])) ;; dialog's actions prop expects a js array (def ^{:private true} upload-project-dialog-actions #js[(r/as-element [ui/flat-button {:label "Create" :primary true :type "submit" :form "upload-project-dialog-form"}]) (r/as-element [ui/flat-button {:label "Cancel" :primary false :on-click close-upload-project-dialog}])]) (defn- upload-form-submitted-callback [state] (close-upload-project-dialog) (rf/dispatch [::upload-new-project state])) (defn- upload-project-dialog [] (r/with-let [open (rf/subscribe [::upload-project-dialog-open])] ;; for form ID [ui/dialog {:title "Create a project" :modal false :open @open :actions (r/as-element upload-project-dialog-actions) :on-request-close close-upload-project-dialog :auto-scroll-body-content true} [upload-project-dialog-form upload-form-submitted-callback]])) (defn- new-project-buttons [] [:ul {:class-name "new-project__buttons"} [:li [ui/raised-button {:label "New Project" :label-position "after" :primary true ;:icon (ic/content-add) :on-click open-new-project-dialog}]] [:li [ui/raised-button {:label "Upload ELAN file" :label-position "after" :primary false ;:icon [ic/file-file-upload] :on-click open-upload-project-dialog}]]]) (defn- download-button [{:keys [eaf name]}] [ui/icon-button {:tooltip "Download EAF file" :tooltip-position "top-center" :touch true :on-click (fn [e] (.stopPropagation e) (let [anchor (js/document.createElement "a") blob (js/Blob. #js[(eaf30/hiccup->eaf-str eaf)] #js{:type "text/plain;charset=utf-8"})] (.setAttribute anchor "target" "_blank") (.setAttribute anchor "href" (js/URL.createObjectURL blob)) (.setAttribute anchor "download" (str name ".eaf")) (.appendChild js/document.body anchor) (.click anchor) (.removeChild js/document.body anchor))) ;; :right-icon-button doesn't set position properly, so we need to hack it :style {:position "absolute" :left "80%" :top "14px"} :tooltip-styles {:top "4px"}} [ic/content-save]]) ;; top level panels ;; ----------------------------------------------------------------------------- ;; panel select panel (defn project-select-panel [] (r/with-let [projects (rf/subscribe [::available-projects])] [ui/paper {:style {:margin "1em" :padding "1em"}} [:h2 "Available projects"] [ui/list (for [project @projects] ^{:key (:_id project)} [ui/list-item {:primary-text (:name project) :secondary-text (-> project :eaf eaf30/get-date js/Date. .toLocaleDateString) :on-click #(set! (.-location js/document) (str "#/project/" (:_id project))) :right-icon-button (r/as-element [download-button project])}])] [new-project-buttons] [new-project-dialog] [upload-project-dialog]])) ;; project edit panel ;; ----------------------------------------------------------------------------- (defn project-edit-panel [] [project-edit-panel-body])
68288
(ns ewan.project.core (:require [re-frame.core :as rf] [ewan.eaf30.core :as eaf30] [ewan.project.new-form :refer [new-project-dialog-form]] [ewan.project.upload-form :refer [upload-project-dialog-form]] [ewan.project.edit.core :refer [project-edit-panel-body]] [cljsjs.material-ui] [cljs-react-material-ui.core] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as ic] [reagent.core :as r])) ;; used in db.cljs (def ^:export default-db {::projects [] ::new-project-dialog-open false ::upload-project-dialog-open false}) ;; ---------------------------------------------------------------------------- ;; subs ;; ---------------------------------------------------------------------------- (rf/reg-sub ::available-projects (fn [db _] (::projects db))) (rf/reg-sub ::new-project-dialog-open (fn [db _] (::new-project-dialog-open db))) (rf/reg-sub ::upload-project-dialog-open (fn [db _] (::upload-project-dialog-open db))) ;; ---------------------------------------------------------------------------- ;; events ;; ---------------------------------------------------------------------------- (rf/reg-event-db ::open-new-project-dialog (fn [db _] (assoc db ::new-project-dialog-open true))) (rf/reg-event-db ::close-new-project-dialog (fn [db _] (assoc db ::new-project-dialog-open false))) (rf/reg-event-db ::open-upload-project-dialog (fn [db _] (assoc db ::upload-project-dialog-open true))) (rf/reg-event-db ::close-upload-project-dialog (fn [db _] (assoc db ::upload-project-dialog-open false))) ;; When a user submits the create new project form, this event is fired. (rf/reg-event-fx ::create-new-project (fn [{:keys [db]} [_ {:keys [:name :author :date :files] :as state}]] (let [doc {:name <NAME> :eaf (eaf30/create-eaf {:author <NAME> :date (.toISOString date) :media-descriptors (for [file files] {:media-url (.-name file) :mime-type (.-type file)})}) :_attachments (into {} (for [file files] [(.-name file) {:content_type (.-type file) :data file}]))}] {:db db :pouchdb {:method "post" :args [doc {} (fn [err response] (if err (throw err) (rf/dispatch [::new-project-created response])))]}}))) ;; Similar event, but for uploading a project (rf/reg-event-fx ::upload-new-project (fn [{:keys [db]} [_ {:keys [:name :eaf :files] :as state}]] (let [doc {:name <NAME> :eaf eaf :_attachments (into {} (for [file files] [(.-name file) {:content_type (.-type file) :data file}]))}] {:db db :pouchdb {:method "post" :args [doc {} (fn [err response] (if err (throw err) (rf/dispatch [::new-project-created response])))]}}))) ;; Because PouchDB's `post` method is async, ::create-new-project initiates ;; the creation of the PDB document, and this event is fired after the ;; document is created. ;; TODO: proper error handling (rf/reg-event-fx ::new-project-created (fn [{:keys [db]} [_ response]] (if-not (.-ok response) (throw response) {:db db :pouchdb {:method "get" :args [(.-id response) {} (fn [err doc] (if err (throw err) (rf/dispatch [::new-project-doc-fetched doc])))]}}))) ;; Since `post` only tells you whether or not the document was successfully ;; created and does not give you the document's value, we need to call `get` ;; so we can update re-frame's DB with the value of the new document. (rf/reg-event-db ::new-project-doc-fetched (fn [db [_ doc]] (update db ::projects conj (js->clj doc :keywordize-keys true)))) ;; ---------------------------------------------------------------------------- ;; views ;; ---------------------------------------------------------------------------- ;; dialog -- a popup window that contains a form for creating a new project ;; new project dialog --------------------------------------------------------- (defn- open-new-project-dialog [] (rf/dispatch [::open-new-project-dialog])) (defn- close-new-project-dialog [] (rf/dispatch [::close-new-project-dialog])) ;; dialog's actions prop expects a js array (def ^{:private true} new-project-dialog-actions #js[(r/as-element [ui/flat-button {:label "Create" :primary true :type "submit" :form "new-project-dialog-form"}]) (r/as-element [ui/flat-button {:label "Cancel" :primary false :on-click close-new-project-dialog}])]) (defn- new-form-submitted-callback [state] (close-new-project-dialog) (rf/dispatch [::create-new-project state])) (defn- new-project-dialog [] (r/with-let [open (rf/subscribe [::new-project-dialog-open])] ;; for form ID [ui/dialog {:title "Create a new project" :modal false :open @open :actions (r/as-element new-project-dialog-actions) :on-request-close close-new-project-dialog :auto-scroll-body-content true} [new-project-dialog-form new-form-submitted-callback]])) ;; upload project dialog ------------------------------------------------------ (defn- open-upload-project-dialog [] (rf/dispatch [::open-upload-project-dialog])) (defn- close-upload-project-dialog [] (rf/dispatch [::close-upload-project-dialog])) ;; dialog's actions prop expects a js array (def ^{:private true} upload-project-dialog-actions #js[(r/as-element [ui/flat-button {:label "Create" :primary true :type "submit" :form "upload-project-dialog-form"}]) (r/as-element [ui/flat-button {:label "Cancel" :primary false :on-click close-upload-project-dialog}])]) (defn- upload-form-submitted-callback [state] (close-upload-project-dialog) (rf/dispatch [::upload-new-project state])) (defn- upload-project-dialog [] (r/with-let [open (rf/subscribe [::upload-project-dialog-open])] ;; for form ID [ui/dialog {:title "Create a project" :modal false :open @open :actions (r/as-element upload-project-dialog-actions) :on-request-close close-upload-project-dialog :auto-scroll-body-content true} [upload-project-dialog-form upload-form-submitted-callback]])) (defn- new-project-buttons [] [:ul {:class-name "new-project__buttons"} [:li [ui/raised-button {:label "New Project" :label-position "after" :primary true ;:icon (ic/content-add) :on-click open-new-project-dialog}]] [:li [ui/raised-button {:label "Upload ELAN file" :label-position "after" :primary false ;:icon [ic/file-file-upload] :on-click open-upload-project-dialog}]]]) (defn- download-button [{:keys [eaf name]}] [ui/icon-button {:tooltip "Download EAF file" :tooltip-position "top-center" :touch true :on-click (fn [e] (.stopPropagation e) (let [anchor (js/document.createElement "a") blob (js/Blob. #js[(eaf30/hiccup->eaf-str eaf)] #js{:type "text/plain;charset=utf-8"})] (.setAttribute anchor "target" "_blank") (.setAttribute anchor "href" (js/URL.createObjectURL blob)) (.setAttribute anchor "download" (str name ".eaf")) (.appendChild js/document.body anchor) (.click anchor) (.removeChild js/document.body anchor))) ;; :right-icon-button doesn't set position properly, so we need to hack it :style {:position "absolute" :left "80%" :top "14px"} :tooltip-styles {:top "4px"}} [ic/content-save]]) ;; top level panels ;; ----------------------------------------------------------------------------- ;; panel select panel (defn project-select-panel [] (r/with-let [projects (rf/subscribe [::available-projects])] [ui/paper {:style {:margin "1em" :padding "1em"}} [:h2 "Available projects"] [ui/list (for [project @projects] ^{:key (:_id project)} [ui/list-item {:primary-text (:name project) :secondary-text (-> project :eaf eaf30/get-date js/Date. .toLocaleDateString) :on-click #(set! (.-location js/document) (str "#/project/" (:_id project))) :right-icon-button (r/as-element [download-button project])}])] [new-project-buttons] [new-project-dialog] [upload-project-dialog]])) ;; project edit panel ;; ----------------------------------------------------------------------------- (defn project-edit-panel [] [project-edit-panel-body])
true
(ns ewan.project.core (:require [re-frame.core :as rf] [ewan.eaf30.core :as eaf30] [ewan.project.new-form :refer [new-project-dialog-form]] [ewan.project.upload-form :refer [upload-project-dialog-form]] [ewan.project.edit.core :refer [project-edit-panel-body]] [cljsjs.material-ui] [cljs-react-material-ui.core] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as ic] [reagent.core :as r])) ;; used in db.cljs (def ^:export default-db {::projects [] ::new-project-dialog-open false ::upload-project-dialog-open false}) ;; ---------------------------------------------------------------------------- ;; subs ;; ---------------------------------------------------------------------------- (rf/reg-sub ::available-projects (fn [db _] (::projects db))) (rf/reg-sub ::new-project-dialog-open (fn [db _] (::new-project-dialog-open db))) (rf/reg-sub ::upload-project-dialog-open (fn [db _] (::upload-project-dialog-open db))) ;; ---------------------------------------------------------------------------- ;; events ;; ---------------------------------------------------------------------------- (rf/reg-event-db ::open-new-project-dialog (fn [db _] (assoc db ::new-project-dialog-open true))) (rf/reg-event-db ::close-new-project-dialog (fn [db _] (assoc db ::new-project-dialog-open false))) (rf/reg-event-db ::open-upload-project-dialog (fn [db _] (assoc db ::upload-project-dialog-open true))) (rf/reg-event-db ::close-upload-project-dialog (fn [db _] (assoc db ::upload-project-dialog-open false))) ;; When a user submits the create new project form, this event is fired. (rf/reg-event-fx ::create-new-project (fn [{:keys [db]} [_ {:keys [:name :author :date :files] :as state}]] (let [doc {:name PI:NAME:<NAME>END_PI :eaf (eaf30/create-eaf {:author PI:NAME:<NAME>END_PI :date (.toISOString date) :media-descriptors (for [file files] {:media-url (.-name file) :mime-type (.-type file)})}) :_attachments (into {} (for [file files] [(.-name file) {:content_type (.-type file) :data file}]))}] {:db db :pouchdb {:method "post" :args [doc {} (fn [err response] (if err (throw err) (rf/dispatch [::new-project-created response])))]}}))) ;; Similar event, but for uploading a project (rf/reg-event-fx ::upload-new-project (fn [{:keys [db]} [_ {:keys [:name :eaf :files] :as state}]] (let [doc {:name PI:NAME:<NAME>END_PI :eaf eaf :_attachments (into {} (for [file files] [(.-name file) {:content_type (.-type file) :data file}]))}] {:db db :pouchdb {:method "post" :args [doc {} (fn [err response] (if err (throw err) (rf/dispatch [::new-project-created response])))]}}))) ;; Because PouchDB's `post` method is async, ::create-new-project initiates ;; the creation of the PDB document, and this event is fired after the ;; document is created. ;; TODO: proper error handling (rf/reg-event-fx ::new-project-created (fn [{:keys [db]} [_ response]] (if-not (.-ok response) (throw response) {:db db :pouchdb {:method "get" :args [(.-id response) {} (fn [err doc] (if err (throw err) (rf/dispatch [::new-project-doc-fetched doc])))]}}))) ;; Since `post` only tells you whether or not the document was successfully ;; created and does not give you the document's value, we need to call `get` ;; so we can update re-frame's DB with the value of the new document. (rf/reg-event-db ::new-project-doc-fetched (fn [db [_ doc]] (update db ::projects conj (js->clj doc :keywordize-keys true)))) ;; ---------------------------------------------------------------------------- ;; views ;; ---------------------------------------------------------------------------- ;; dialog -- a popup window that contains a form for creating a new project ;; new project dialog --------------------------------------------------------- (defn- open-new-project-dialog [] (rf/dispatch [::open-new-project-dialog])) (defn- close-new-project-dialog [] (rf/dispatch [::close-new-project-dialog])) ;; dialog's actions prop expects a js array (def ^{:private true} new-project-dialog-actions #js[(r/as-element [ui/flat-button {:label "Create" :primary true :type "submit" :form "new-project-dialog-form"}]) (r/as-element [ui/flat-button {:label "Cancel" :primary false :on-click close-new-project-dialog}])]) (defn- new-form-submitted-callback [state] (close-new-project-dialog) (rf/dispatch [::create-new-project state])) (defn- new-project-dialog [] (r/with-let [open (rf/subscribe [::new-project-dialog-open])] ;; for form ID [ui/dialog {:title "Create a new project" :modal false :open @open :actions (r/as-element new-project-dialog-actions) :on-request-close close-new-project-dialog :auto-scroll-body-content true} [new-project-dialog-form new-form-submitted-callback]])) ;; upload project dialog ------------------------------------------------------ (defn- open-upload-project-dialog [] (rf/dispatch [::open-upload-project-dialog])) (defn- close-upload-project-dialog [] (rf/dispatch [::close-upload-project-dialog])) ;; dialog's actions prop expects a js array (def ^{:private true} upload-project-dialog-actions #js[(r/as-element [ui/flat-button {:label "Create" :primary true :type "submit" :form "upload-project-dialog-form"}]) (r/as-element [ui/flat-button {:label "Cancel" :primary false :on-click close-upload-project-dialog}])]) (defn- upload-form-submitted-callback [state] (close-upload-project-dialog) (rf/dispatch [::upload-new-project state])) (defn- upload-project-dialog [] (r/with-let [open (rf/subscribe [::upload-project-dialog-open])] ;; for form ID [ui/dialog {:title "Create a project" :modal false :open @open :actions (r/as-element upload-project-dialog-actions) :on-request-close close-upload-project-dialog :auto-scroll-body-content true} [upload-project-dialog-form upload-form-submitted-callback]])) (defn- new-project-buttons [] [:ul {:class-name "new-project__buttons"} [:li [ui/raised-button {:label "New Project" :label-position "after" :primary true ;:icon (ic/content-add) :on-click open-new-project-dialog}]] [:li [ui/raised-button {:label "Upload ELAN file" :label-position "after" :primary false ;:icon [ic/file-file-upload] :on-click open-upload-project-dialog}]]]) (defn- download-button [{:keys [eaf name]}] [ui/icon-button {:tooltip "Download EAF file" :tooltip-position "top-center" :touch true :on-click (fn [e] (.stopPropagation e) (let [anchor (js/document.createElement "a") blob (js/Blob. #js[(eaf30/hiccup->eaf-str eaf)] #js{:type "text/plain;charset=utf-8"})] (.setAttribute anchor "target" "_blank") (.setAttribute anchor "href" (js/URL.createObjectURL blob)) (.setAttribute anchor "download" (str name ".eaf")) (.appendChild js/document.body anchor) (.click anchor) (.removeChild js/document.body anchor))) ;; :right-icon-button doesn't set position properly, so we need to hack it :style {:position "absolute" :left "80%" :top "14px"} :tooltip-styles {:top "4px"}} [ic/content-save]]) ;; top level panels ;; ----------------------------------------------------------------------------- ;; panel select panel (defn project-select-panel [] (r/with-let [projects (rf/subscribe [::available-projects])] [ui/paper {:style {:margin "1em" :padding "1em"}} [:h2 "Available projects"] [ui/list (for [project @projects] ^{:key (:_id project)} [ui/list-item {:primary-text (:name project) :secondary-text (-> project :eaf eaf30/get-date js/Date. .toLocaleDateString) :on-click #(set! (.-location js/document) (str "#/project/" (:_id project))) :right-icon-button (r/as-element [download-button project])}])] [new-project-buttons] [new-project-dialog] [upload-project-dialog]])) ;; project edit panel ;; ----------------------------------------------------------------------------- (defn project-edit-panel [] [project-edit-panel-body])
[ { "context": "(ns\n ^{:doc \"Util synths\"\n :author \"Sam Aaron & Jeff Rose\"}\n overtone.studio.util\n (:use [ove", "end": 50, "score": 0.9998775124549866, "start": 41, "tag": "NAME", "value": "Sam Aaron" }, { "context": "s\n ^{:doc \"Util synths\"\n :author \"Sam Aaron & Jeff Rose\"}\n overtone.studio.util\n (:use [overtone.libs e", "end": 62, "score": 0.9998559355735779, "start": 53, "tag": "NAME", "value": "Jeff Rose" } ]
src/overtone/studio/util.clj
rosejn/overtone
4
(ns ^{:doc "Util synths" :author "Sam Aaron & Jeff Rose"} overtone.studio.util (:use [overtone.libs event] [overtone.sc synth ugens])) ;; Some utility synths for signal routing and scoping (defonce __UTIL-SYNTHS__ (do (defsynth bus->buf [bus 20 buf 0] (record-buf (in bus) buf)) (defsynth bus->bus [in-bus 20 out-bus 0] (out out-bus (in in-bus)))))
115272
(ns ^{:doc "Util synths" :author "<NAME> & <NAME>"} overtone.studio.util (:use [overtone.libs event] [overtone.sc synth ugens])) ;; Some utility synths for signal routing and scoping (defonce __UTIL-SYNTHS__ (do (defsynth bus->buf [bus 20 buf 0] (record-buf (in bus) buf)) (defsynth bus->bus [in-bus 20 out-bus 0] (out out-bus (in in-bus)))))
true
(ns ^{:doc "Util synths" :author "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"} overtone.studio.util (:use [overtone.libs event] [overtone.sc synth ugens])) ;; Some utility synths for signal routing and scoping (defonce __UTIL-SYNTHS__ (do (defsynth bus->buf [bus 20 buf 0] (record-buf (in bus) buf)) (defsynth bus->bus [in-bus 20 out-bus 0] (out out-bus (in in-bus)))))
[ { "context": " :db-password \"bobby-tables\"\n :", "end": 422, "score": 0.9992940425872803, "start": 410, "tag": "PASSWORD", "value": "bobby-tables" } ]
test/fail/utils.clj
lispyclouds/fail
0
(ns fail.utils (:require [com.stuartsierra.component :as component] [next.jdbc :as jdbc] [fail.system :as sys])) (defn with-system [test-fn] (let [system (component/system-map :database (sys/map->Database {:db-name "contacts-test" :db-user "bob" :db-password "bobby-tables" :db-host "localhost" :db-port 5433})) {:keys [database] :as com} (component/start system)] (try (test-fn (sys/conn database)) (finally (jdbc/execute! (sys/conn database) ["DROP TABLE contacts;"]) (component/stop com)))))
118961
(ns fail.utils (:require [com.stuartsierra.component :as component] [next.jdbc :as jdbc] [fail.system :as sys])) (defn with-system [test-fn] (let [system (component/system-map :database (sys/map->Database {:db-name "contacts-test" :db-user "bob" :db-password "<PASSWORD>" :db-host "localhost" :db-port 5433})) {:keys [database] :as com} (component/start system)] (try (test-fn (sys/conn database)) (finally (jdbc/execute! (sys/conn database) ["DROP TABLE contacts;"]) (component/stop com)))))
true
(ns fail.utils (:require [com.stuartsierra.component :as component] [next.jdbc :as jdbc] [fail.system :as sys])) (defn with-system [test-fn] (let [system (component/system-map :database (sys/map->Database {:db-name "contacts-test" :db-user "bob" :db-password "PI:PASSWORD:<PASSWORD>END_PI" :db-host "localhost" :db-port 5433})) {:keys [database] :as com} (component/start system)] (try (test-fn (sys/conn database)) (finally (jdbc/execute! (sys/conn database) ["DROP TABLE contacts;"]) (component/stop com)))))
[ { "context": " \"password=\\\"%s\\\" \"\n ", "end": 1218, "score": 0.998536229133606, "start": 1216, "tag": "PASSWORD", "value": "%s" } ]
src/afrolabs/components/confluent.clj
Afrolabs/afrolabs-clj
0
(ns afrolabs.components.confluent (:require [afrolabs.components.kafka :as -kafka]) (:import [afrolabs.components.kafka IUpdateConsumerConfigHook IUpdateProducerConfigHook IUpdateAdminClientConfigHook])) (-kafka/defstrategy ConfluentCloud ;; "Sets the required and recommended config to connect to a kafka cluster in confluent cloud. ;; Based on: https://docs.confluent.io/cloud/current/client-apps/config-client.html#java-client" [& {:keys [api-key api-secret]}] (letfn [(merge-common [cfg] (cond-> cfg true (merge {"client.dns.lookup" "use_all_dns_ips" "reconnect.backoff.max.ms" "10000" "request.timeout.ms" "30000"}) (and api-key (seq api-key) api-secret (seq api-secret)) (merge {"sasl.mechanism" "PLAIN" "sasl.jaas.config" (format (str "org.apache.kafka.common.security.plain.PlainLoginModule required " "username=\"%s\" " "password=\"%s\" " ";") api-key api-secret) "security.protocol" "SASL_SSL"})))] (reify IUpdateConsumerConfigHook (update-consumer-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"session.timeout.ms" "45000"}))) IUpdateProducerConfigHook (update-producer-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"acks" "all" "linger.ms" "5"}))) IUpdateAdminClientConfigHook (update-admin-client-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"default.api.timeout.ms" "300000"}))))))
55328
(ns afrolabs.components.confluent (:require [afrolabs.components.kafka :as -kafka]) (:import [afrolabs.components.kafka IUpdateConsumerConfigHook IUpdateProducerConfigHook IUpdateAdminClientConfigHook])) (-kafka/defstrategy ConfluentCloud ;; "Sets the required and recommended config to connect to a kafka cluster in confluent cloud. ;; Based on: https://docs.confluent.io/cloud/current/client-apps/config-client.html#java-client" [& {:keys [api-key api-secret]}] (letfn [(merge-common [cfg] (cond-> cfg true (merge {"client.dns.lookup" "use_all_dns_ips" "reconnect.backoff.max.ms" "10000" "request.timeout.ms" "30000"}) (and api-key (seq api-key) api-secret (seq api-secret)) (merge {"sasl.mechanism" "PLAIN" "sasl.jaas.config" (format (str "org.apache.kafka.common.security.plain.PlainLoginModule required " "username=\"%s\" " "password=\"<PASSWORD>\" " ";") api-key api-secret) "security.protocol" "SASL_SSL"})))] (reify IUpdateConsumerConfigHook (update-consumer-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"session.timeout.ms" "45000"}))) IUpdateProducerConfigHook (update-producer-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"acks" "all" "linger.ms" "5"}))) IUpdateAdminClientConfigHook (update-admin-client-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"default.api.timeout.ms" "300000"}))))))
true
(ns afrolabs.components.confluent (:require [afrolabs.components.kafka :as -kafka]) (:import [afrolabs.components.kafka IUpdateConsumerConfigHook IUpdateProducerConfigHook IUpdateAdminClientConfigHook])) (-kafka/defstrategy ConfluentCloud ;; "Sets the required and recommended config to connect to a kafka cluster in confluent cloud. ;; Based on: https://docs.confluent.io/cloud/current/client-apps/config-client.html#java-client" [& {:keys [api-key api-secret]}] (letfn [(merge-common [cfg] (cond-> cfg true (merge {"client.dns.lookup" "use_all_dns_ips" "reconnect.backoff.max.ms" "10000" "request.timeout.ms" "30000"}) (and api-key (seq api-key) api-secret (seq api-secret)) (merge {"sasl.mechanism" "PLAIN" "sasl.jaas.config" (format (str "org.apache.kafka.common.security.plain.PlainLoginModule required " "username=\"%s\" " "password=\"PI:PASSWORD:<PASSWORD>END_PI\" " ";") api-key api-secret) "security.protocol" "SASL_SSL"})))] (reify IUpdateConsumerConfigHook (update-consumer-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"session.timeout.ms" "45000"}))) IUpdateProducerConfigHook (update-producer-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"acks" "all" "linger.ms" "5"}))) IUpdateAdminClientConfigHook (update-admin-client-cfg-hook [_ cfg] (-> cfg (merge-common) (merge {"default.api.timeout.ms" "300000"}))))))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998580813407898, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ml for the\n dependency info.\"\n :author \"Rich Hickey\"}\n clojure.core.reducers\n (:refer-clojure :excl", "end": 728, "score": 0.9998767375946045, "start": 717, "tag": "NAME", "value": "Rich Hickey" } ]
ext/clojure-clojurescript-bef56a7/src/cljs/clojure/core/reducers.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 ^{:doc "A library for reduction and parallel folding. Alpha and subject to change. Note that fold and its derivatives require jsr166y.jar for fork/join support. See Clojure's pom.xml for the dependency info." :author "Rich Hickey"} clojure.core.reducers (:refer-clojure :exclude [reduce map mapcat filter remove take take-while drop flatten]) (:require [clojure.walk :as walk] [cljs.core :as core])) (defn reduce "Like core/reduce except: When init is not provided, (f) is used. Maps are reduced with reduce-kv" ([f coll] (reduce f (f) coll)) ([f init coll] (if (map? coll) (-kv-reduce coll f init) (-reduce coll f init)))) #_ (defprotocol CollFold (coll-fold [coll n combinef reducef])) ;;; TODO: update docstring for CLJS #_ (defn fold "Reduces a collection using a (potentially parallel) reduce-combine strategy. The collection is partitioned into groups of approximately n (default 512), each of which is reduced with reducef (with a seed value obtained by calling (combinef) with no arguments). The results of these reductions are then reduced with combinef (default reducef). combinef must be associative, and, when called with no arguments, (combinef) must produce its identity element. These operations may be performed in parallel, but the results will preserve order." ([reducef coll] (fold reducef reducef coll)) ([combinef reducef coll] (fold 512 combinef reducef coll)) ([n combinef reducef coll] (coll-fold coll n combinef reducef))) (def fold reduce) (defn reducer "Given a reducible collection, and a transformation function xf, returns a reducible collection, where any supplied reducing fn will be transformed by xf. xf is a function of reducing fn to reducing fn." ([coll xf] (reify cljs.core/IReduce (-reduce [this f1] (-reduce this f1 (f1))) (-reduce [_ f1 init] (-reduce coll (xf f1) init))))) (defn folder "Given a foldable collection, and a transformation function xf, returns a foldable collection, where any supplied reducing fn will be transformed by xf. xf is a function of reducing fn to reducing fn." ([coll xf] (reify cljs.core/IReduce (-reduce [_ f1] (-reduce coll (xf f1) (f1))) (-reduce [_ f1 init] (-reduce coll (xf f1) init)) #_ CollFold #_ (coll-fold [_ n combinef reducef] (coll-fold coll n combinef (xf reducef)))))) (defcurried map "Applies f to every value in the reduction of coll. Foldable." {} [f coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (f1 ret (f k v))))))) (defcurried mapcat "Applies f to every value in the reduction of coll, concatenating the result colls of (f val). Foldable." {} [f coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (reduce f1 ret (f k v))))))) (defcurried filter "Retains values in the reduction of coll for which (pred val) returns logical true. Foldable." {} [pred coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (if (pred k v) (f1 ret k v) ret)))))) (defcurried flatten "Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat foldable collection." {} [coll] (folder coll (fn [f1] (fn ([] (f1)) ([ret v] (if (sequential? v) (-reduce (flatten v) f1 ret) (f1 ret v))))))) (defcurried remove "Removes values in the reduction of coll for which (pred val) returns logical true. Foldable." {} [pred coll] (filter (complement pred) coll)) (defcurried take-while "Ends the reduction of coll when (pred val) returns logical false." {} [pred coll] (reducer coll (fn [f1] (rfn [f1 k] ([ret k v] (if (pred k v) (f1 ret k v) (reduced ret))))))) (defcurried take "Ends the reduction of coll after consuming n values." {} [n coll] (reducer coll (fn [f1] (let [cnt (atom n)] (rfn [f1 k] ([ret k v] (swap! cnt dec) (if (neg? @cnt) (reduced ret) (f1 ret k v)))))))) (defcurried drop "Elides the first n values from the reduction of coll." {} [n coll] (reducer coll (fn [f1] (let [cnt (atom n)] (rfn [f1 k] ([ret k v] (swap! cnt dec) (if (neg? @cnt) (f1 ret k v) ret))))))) ;;do not construct this directly, use cat (deftype Cat [cnt left right] cljs.core/ICounted (-count [_] cnt) cljs.core/ISeqable (-seq [_] (concat (seq left) (seq right))) cljs.core/IReduce (-reduce [this f1] (-reduce this f1 (f1))) (-reduce [_ f1 init] (-reduce right f1 (-reduce left f1 init))) #_ CollFold #_ (coll-fold [this n combinef reducef] (-reduce this reducef))) (defn cat "A high-performance combining fn that yields the catenation of the reduced values. The result is reducible, foldable, seqable and counted, providing the identity collections are reducible, seqable and counted. The single argument version will build a combining fn with the supplied identity constructor. Tests for identity with (zero? (count x)). See also foldcat." ([] (array)) ([ctor] (fn ([] (ctor)) ([left right] (cat left right)))) ([left right] (cond (zero? (count left)) right (zero? (count right)) left :else (Cat. (+ (count left) (count right)) left right)))) (defn append! ".adds x to acc and returns acc" [acc x] (doto acc (.add x))) (defn foldcat "Equivalent to (fold cat append! coll)" [coll] (fold cat append! coll)) (defn monoid "Builds a combining fn out of the supplied operator and identity constructor. op must be associative and ctor called with no args must return an identity value for it." [op ctor] (fn m ([] (ctor)) ([a b] (op a b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (require '[clojure.core.reduce :as r]) (def v (take 1000000 (range))) (reduce + 0 (r/map inc [1 2 3 4])) (into [] (r/take 12 (range 100))) (into [] (r/drop 12 (range 100))) (reduce + 0 (r/filter even? [1 2 3 4])) (into [] (r/filter even? [1 2 3 4])) (reduce + (filter even? [1 2 3 4])) (dotimes [_ 10] (time (reduce + 0 (r/map inc v)))) (dotimes [_ 10] (time (reduce + 0 (map inc v)))) (dotimes [_ 100] (time (reduce + 0 v))) (dotimes [_ 100] (time (reduce + 0 v))) (dotimes [_ 20] (time (reduce + 0 (r/map inc (r/filter even? v))))) (dotimes [_ 20] (time (reduce + 0 (map inc (filter even? v))))) (reduce + 0 (r/take-while even? [2 4 3])) (into [] (r/filter even? (r/flatten (r/remove #{4} [[1 2 3] 4 [5 [6 7 8]] [9] 10])))) (into [] (r/flatten nil)) ) (comment ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fold impls ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- foldvec [v n combinef reducef] (cond (empty? v) (combinef) (<= (count v) n) (reduce reducef (combinef) v) :else (let [split (quot (count v) 2) v1 (subvec v 0 split) v2 (subvec v split (count v)) fc (fn [child] #(foldvec child n combinef reducef))] (fjinvoke #(let [f1 (fc v1) t2 (fjtask (fc v2))] (fjfork t2) (combinef (f1) (fjjoin t2))))))) (extend-protocol CollFold Object (coll-fold [coll n combinef reducef] ;;can't fold, single reduce (reduce reducef (combinef) coll)) clojure.lang.IPersistentVector (coll-fold [v n combinef reducef] (foldvec v n combinef reducef)) clojure.lang.PersistentHashMap (coll-fold [m n combinef reducef] (.fold m n combinef reducef fjinvoke fjtask fjfork fjjoin))) )
103887
; 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 "A library for reduction and parallel folding. Alpha and subject to change. Note that fold and its derivatives require jsr166y.jar for fork/join support. See Clojure's pom.xml for the dependency info." :author "<NAME>"} clojure.core.reducers (:refer-clojure :exclude [reduce map mapcat filter remove take take-while drop flatten]) (:require [clojure.walk :as walk] [cljs.core :as core])) (defn reduce "Like core/reduce except: When init is not provided, (f) is used. Maps are reduced with reduce-kv" ([f coll] (reduce f (f) coll)) ([f init coll] (if (map? coll) (-kv-reduce coll f init) (-reduce coll f init)))) #_ (defprotocol CollFold (coll-fold [coll n combinef reducef])) ;;; TODO: update docstring for CLJS #_ (defn fold "Reduces a collection using a (potentially parallel) reduce-combine strategy. The collection is partitioned into groups of approximately n (default 512), each of which is reduced with reducef (with a seed value obtained by calling (combinef) with no arguments). The results of these reductions are then reduced with combinef (default reducef). combinef must be associative, and, when called with no arguments, (combinef) must produce its identity element. These operations may be performed in parallel, but the results will preserve order." ([reducef coll] (fold reducef reducef coll)) ([combinef reducef coll] (fold 512 combinef reducef coll)) ([n combinef reducef coll] (coll-fold coll n combinef reducef))) (def fold reduce) (defn reducer "Given a reducible collection, and a transformation function xf, returns a reducible collection, where any supplied reducing fn will be transformed by xf. xf is a function of reducing fn to reducing fn." ([coll xf] (reify cljs.core/IReduce (-reduce [this f1] (-reduce this f1 (f1))) (-reduce [_ f1 init] (-reduce coll (xf f1) init))))) (defn folder "Given a foldable collection, and a transformation function xf, returns a foldable collection, where any supplied reducing fn will be transformed by xf. xf is a function of reducing fn to reducing fn." ([coll xf] (reify cljs.core/IReduce (-reduce [_ f1] (-reduce coll (xf f1) (f1))) (-reduce [_ f1 init] (-reduce coll (xf f1) init)) #_ CollFold #_ (coll-fold [_ n combinef reducef] (coll-fold coll n combinef (xf reducef)))))) (defcurried map "Applies f to every value in the reduction of coll. Foldable." {} [f coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (f1 ret (f k v))))))) (defcurried mapcat "Applies f to every value in the reduction of coll, concatenating the result colls of (f val). Foldable." {} [f coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (reduce f1 ret (f k v))))))) (defcurried filter "Retains values in the reduction of coll for which (pred val) returns logical true. Foldable." {} [pred coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (if (pred k v) (f1 ret k v) ret)))))) (defcurried flatten "Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat foldable collection." {} [coll] (folder coll (fn [f1] (fn ([] (f1)) ([ret v] (if (sequential? v) (-reduce (flatten v) f1 ret) (f1 ret v))))))) (defcurried remove "Removes values in the reduction of coll for which (pred val) returns logical true. Foldable." {} [pred coll] (filter (complement pred) coll)) (defcurried take-while "Ends the reduction of coll when (pred val) returns logical false." {} [pred coll] (reducer coll (fn [f1] (rfn [f1 k] ([ret k v] (if (pred k v) (f1 ret k v) (reduced ret))))))) (defcurried take "Ends the reduction of coll after consuming n values." {} [n coll] (reducer coll (fn [f1] (let [cnt (atom n)] (rfn [f1 k] ([ret k v] (swap! cnt dec) (if (neg? @cnt) (reduced ret) (f1 ret k v)))))))) (defcurried drop "Elides the first n values from the reduction of coll." {} [n coll] (reducer coll (fn [f1] (let [cnt (atom n)] (rfn [f1 k] ([ret k v] (swap! cnt dec) (if (neg? @cnt) (f1 ret k v) ret))))))) ;;do not construct this directly, use cat (deftype Cat [cnt left right] cljs.core/ICounted (-count [_] cnt) cljs.core/ISeqable (-seq [_] (concat (seq left) (seq right))) cljs.core/IReduce (-reduce [this f1] (-reduce this f1 (f1))) (-reduce [_ f1 init] (-reduce right f1 (-reduce left f1 init))) #_ CollFold #_ (coll-fold [this n combinef reducef] (-reduce this reducef))) (defn cat "A high-performance combining fn that yields the catenation of the reduced values. The result is reducible, foldable, seqable and counted, providing the identity collections are reducible, seqable and counted. The single argument version will build a combining fn with the supplied identity constructor. Tests for identity with (zero? (count x)). See also foldcat." ([] (array)) ([ctor] (fn ([] (ctor)) ([left right] (cat left right)))) ([left right] (cond (zero? (count left)) right (zero? (count right)) left :else (Cat. (+ (count left) (count right)) left right)))) (defn append! ".adds x to acc and returns acc" [acc x] (doto acc (.add x))) (defn foldcat "Equivalent to (fold cat append! coll)" [coll] (fold cat append! coll)) (defn monoid "Builds a combining fn out of the supplied operator and identity constructor. op must be associative and ctor called with no args must return an identity value for it." [op ctor] (fn m ([] (ctor)) ([a b] (op a b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (require '[clojure.core.reduce :as r]) (def v (take 1000000 (range))) (reduce + 0 (r/map inc [1 2 3 4])) (into [] (r/take 12 (range 100))) (into [] (r/drop 12 (range 100))) (reduce + 0 (r/filter even? [1 2 3 4])) (into [] (r/filter even? [1 2 3 4])) (reduce + (filter even? [1 2 3 4])) (dotimes [_ 10] (time (reduce + 0 (r/map inc v)))) (dotimes [_ 10] (time (reduce + 0 (map inc v)))) (dotimes [_ 100] (time (reduce + 0 v))) (dotimes [_ 100] (time (reduce + 0 v))) (dotimes [_ 20] (time (reduce + 0 (r/map inc (r/filter even? v))))) (dotimes [_ 20] (time (reduce + 0 (map inc (filter even? v))))) (reduce + 0 (r/take-while even? [2 4 3])) (into [] (r/filter even? (r/flatten (r/remove #{4} [[1 2 3] 4 [5 [6 7 8]] [9] 10])))) (into [] (r/flatten nil)) ) (comment ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fold impls ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- foldvec [v n combinef reducef] (cond (empty? v) (combinef) (<= (count v) n) (reduce reducef (combinef) v) :else (let [split (quot (count v) 2) v1 (subvec v 0 split) v2 (subvec v split (count v)) fc (fn [child] #(foldvec child n combinef reducef))] (fjinvoke #(let [f1 (fc v1) t2 (fjtask (fc v2))] (fjfork t2) (combinef (f1) (fjjoin t2))))))) (extend-protocol CollFold Object (coll-fold [coll n combinef reducef] ;;can't fold, single reduce (reduce reducef (combinef) coll)) clojure.lang.IPersistentVector (coll-fold [v n combinef reducef] (foldvec v n combinef reducef)) clojure.lang.PersistentHashMap (coll-fold [m n combinef reducef] (.fold m n combinef reducef fjinvoke fjtask fjfork fjjoin))) )
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 "A library for reduction and parallel folding. Alpha and subject to change. Note that fold and its derivatives require jsr166y.jar for fork/join support. See Clojure's pom.xml for the dependency info." :author "PI:NAME:<NAME>END_PI"} clojure.core.reducers (:refer-clojure :exclude [reduce map mapcat filter remove take take-while drop flatten]) (:require [clojure.walk :as walk] [cljs.core :as core])) (defn reduce "Like core/reduce except: When init is not provided, (f) is used. Maps are reduced with reduce-kv" ([f coll] (reduce f (f) coll)) ([f init coll] (if (map? coll) (-kv-reduce coll f init) (-reduce coll f init)))) #_ (defprotocol CollFold (coll-fold [coll n combinef reducef])) ;;; TODO: update docstring for CLJS #_ (defn fold "Reduces a collection using a (potentially parallel) reduce-combine strategy. The collection is partitioned into groups of approximately n (default 512), each of which is reduced with reducef (with a seed value obtained by calling (combinef) with no arguments). The results of these reductions are then reduced with combinef (default reducef). combinef must be associative, and, when called with no arguments, (combinef) must produce its identity element. These operations may be performed in parallel, but the results will preserve order." ([reducef coll] (fold reducef reducef coll)) ([combinef reducef coll] (fold 512 combinef reducef coll)) ([n combinef reducef coll] (coll-fold coll n combinef reducef))) (def fold reduce) (defn reducer "Given a reducible collection, and a transformation function xf, returns a reducible collection, where any supplied reducing fn will be transformed by xf. xf is a function of reducing fn to reducing fn." ([coll xf] (reify cljs.core/IReduce (-reduce [this f1] (-reduce this f1 (f1))) (-reduce [_ f1 init] (-reduce coll (xf f1) init))))) (defn folder "Given a foldable collection, and a transformation function xf, returns a foldable collection, where any supplied reducing fn will be transformed by xf. xf is a function of reducing fn to reducing fn." ([coll xf] (reify cljs.core/IReduce (-reduce [_ f1] (-reduce coll (xf f1) (f1))) (-reduce [_ f1 init] (-reduce coll (xf f1) init)) #_ CollFold #_ (coll-fold [_ n combinef reducef] (coll-fold coll n combinef (xf reducef)))))) (defcurried map "Applies f to every value in the reduction of coll. Foldable." {} [f coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (f1 ret (f k v))))))) (defcurried mapcat "Applies f to every value in the reduction of coll, concatenating the result colls of (f val). Foldable." {} [f coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (reduce f1 ret (f k v))))))) (defcurried filter "Retains values in the reduction of coll for which (pred val) returns logical true. Foldable." {} [pred coll] (folder coll (fn [f1] (rfn [f1 k] ([ret k v] (if (pred k v) (f1 ret k v) ret)))))) (defcurried flatten "Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat foldable collection." {} [coll] (folder coll (fn [f1] (fn ([] (f1)) ([ret v] (if (sequential? v) (-reduce (flatten v) f1 ret) (f1 ret v))))))) (defcurried remove "Removes values in the reduction of coll for which (pred val) returns logical true. Foldable." {} [pred coll] (filter (complement pred) coll)) (defcurried take-while "Ends the reduction of coll when (pred val) returns logical false." {} [pred coll] (reducer coll (fn [f1] (rfn [f1 k] ([ret k v] (if (pred k v) (f1 ret k v) (reduced ret))))))) (defcurried take "Ends the reduction of coll after consuming n values." {} [n coll] (reducer coll (fn [f1] (let [cnt (atom n)] (rfn [f1 k] ([ret k v] (swap! cnt dec) (if (neg? @cnt) (reduced ret) (f1 ret k v)))))))) (defcurried drop "Elides the first n values from the reduction of coll." {} [n coll] (reducer coll (fn [f1] (let [cnt (atom n)] (rfn [f1 k] ([ret k v] (swap! cnt dec) (if (neg? @cnt) (f1 ret k v) ret))))))) ;;do not construct this directly, use cat (deftype Cat [cnt left right] cljs.core/ICounted (-count [_] cnt) cljs.core/ISeqable (-seq [_] (concat (seq left) (seq right))) cljs.core/IReduce (-reduce [this f1] (-reduce this f1 (f1))) (-reduce [_ f1 init] (-reduce right f1 (-reduce left f1 init))) #_ CollFold #_ (coll-fold [this n combinef reducef] (-reduce this reducef))) (defn cat "A high-performance combining fn that yields the catenation of the reduced values. The result is reducible, foldable, seqable and counted, providing the identity collections are reducible, seqable and counted. The single argument version will build a combining fn with the supplied identity constructor. Tests for identity with (zero? (count x)). See also foldcat." ([] (array)) ([ctor] (fn ([] (ctor)) ([left right] (cat left right)))) ([left right] (cond (zero? (count left)) right (zero? (count right)) left :else (Cat. (+ (count left) (count right)) left right)))) (defn append! ".adds x to acc and returns acc" [acc x] (doto acc (.add x))) (defn foldcat "Equivalent to (fold cat append! coll)" [coll] (fold cat append! coll)) (defn monoid "Builds a combining fn out of the supplied operator and identity constructor. op must be associative and ctor called with no args must return an identity value for it." [op ctor] (fn m ([] (ctor)) ([a b] (op a b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (require '[clojure.core.reduce :as r]) (def v (take 1000000 (range))) (reduce + 0 (r/map inc [1 2 3 4])) (into [] (r/take 12 (range 100))) (into [] (r/drop 12 (range 100))) (reduce + 0 (r/filter even? [1 2 3 4])) (into [] (r/filter even? [1 2 3 4])) (reduce + (filter even? [1 2 3 4])) (dotimes [_ 10] (time (reduce + 0 (r/map inc v)))) (dotimes [_ 10] (time (reduce + 0 (map inc v)))) (dotimes [_ 100] (time (reduce + 0 v))) (dotimes [_ 100] (time (reduce + 0 v))) (dotimes [_ 20] (time (reduce + 0 (r/map inc (r/filter even? v))))) (dotimes [_ 20] (time (reduce + 0 (map inc (filter even? v))))) (reduce + 0 (r/take-while even? [2 4 3])) (into [] (r/filter even? (r/flatten (r/remove #{4} [[1 2 3] 4 [5 [6 7 8]] [9] 10])))) (into [] (r/flatten nil)) ) (comment ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fold impls ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- foldvec [v n combinef reducef] (cond (empty? v) (combinef) (<= (count v) n) (reduce reducef (combinef) v) :else (let [split (quot (count v) 2) v1 (subvec v 0 split) v2 (subvec v split (count v)) fc (fn [child] #(foldvec child n combinef reducef))] (fjinvoke #(let [f1 (fc v1) t2 (fjtask (fc v2))] (fjfork t2) (combinef (f1) (fjjoin t2))))))) (extend-protocol CollFold Object (coll-fold [coll n combinef reducef] ;;can't fold, single reduce (reduce reducef (combinef) coll)) clojure.lang.IPersistentVector (coll-fold [v n combinef reducef] (foldvec v n combinef reducef)) clojure.lang.PersistentHashMap (coll-fold [m n combinef reducef] (.fold m n combinef reducef fjinvoke fjtask fjfork fjjoin))) )
[ { "context": "ffer x))\n\n;; TODO: add options\n\n(def REDUCER-KEY \"mapred.reduce.tasks\")\n\n(defn set-reducers\n \"Set the number of reduce", "end": 7216, "score": 0.9839000701904297, "start": 7197, "tag": "KEY", "value": "mapred.reduce.tasks" } ]
cascalog-core/src/clj/cascalog/cascading/operations.clj
bhiles/cascalog
0
(ns cascalog.cascading.operations (:require [clojure.tools.macro :refer (name-with-attributes)] [clojure.set :as set :refer (subset? difference intersection)] [cascalog.logic.fn :as serfn] [cascalog.logic.vars :as v] [cascalog.logic.algebra :refer (sum)] [cascalog.cascading.util :as casc :refer (fields default-output)] [cascalog.cascading.tap :as tap] [cascalog.cascading.types :refer (generator to-sink)] [jackknife.core :refer (safe-assert throw-illegal uuid)] [jackknife.seq :as s :refer (unweave collectify)]) (:import [cascading.tuple Fields] [cascalog.ops KryoInsert] [cascading.operation Identity Debug NoOp] [cascading.operation.filter Sample] [cascading.operation.aggregator First Count Sum Min Max] [cascading.pipe Pipe Each Every GroupBy CoGroup Merge HashJoin] [cascading.pipe.joiner Joiner InnerJoin LeftJoin RightJoin OuterJoin] [cascading.pipe.joiner CascalogJoiner CascalogJoiner$JoinType] [cascading.pipe.assembly Rename AggregateBy] [cascalog ClojureFilter ClojureMapcat ClojureMap ClojureBuffer ClojureBufferIter FastFirst MultiGroupBy ClojureMultibuffer] [cascalog.aggregator ClojureAggregator ClojureMonoidAggregator ClojureMonoidFunctor ClojureAggregateBy CombinerSpec])) ;; ## Operations ;; ;; All of these operations work on implementers of the Generator ;; protocol, defined in cascalog.cascading.types. (defmacro assembly [args & ops] `(fn [flow# ~@args] (-> flow# ~@ops))) (defn add-op "Accepts a generator and a function from pipe to pipe and applies the operation to the active head pipe." [flow fn] (update-in (generator flow) [:pipe] fn)) (defmacro defop "Defines a flow operation." [f-name & tail] (let [[f-name [args & body]] (name-with-attributes f-name tail)] `(defn ~f-name {:arglists '([~'flow ~@args])} [flow# ~@args] (add-op flow# ~@body)))) (defop each "Accepts a flow, a function from result fields => cascading Function, input fields and output fields and returns a new flow." [f from-fields to-fields] (let [from-fields (fields from-fields) to-fields (fields to-fields)] (fn [pipe] (Each. pipe from-fields (f to-fields) (default-output from-fields to-fields))))) (defn name-flow "Assigns a new name to the clojure flow." [gen name] (-> (generator gen) (assoc :name name))) (defn rename-pipe ([gen] (rename-pipe gen (uuid))) ([gen name] (add-op gen #(Pipe. name %)))) (defop select* "Remove all but the supplied fields from the given flow." [keep-fields] #(Each. % (fields keep-fields) (Identity. (fields keep-fields)))) (defn identity* "Mirrors the supplied set of input fields into the output fields." [flow input output] (each flow #(Identity. %) input output)) (defop discard* "Discard the supplied fields." [drop-fields] #(Each. % (fields drop-fields) (NoOp.) Fields/SWAP)) (defop debug* "Prints all tuples that pass through the StdOut." [] #(Each. % (Debug.))) (defn insert* "Accepts a flow and alternating field/value pairs and inserts these items into the flow." [flow & field-v-pairs] (let [[out-fields vals] (unweave field-v-pairs)] (each flow #(KryoInsert. % (into-array Object vals)) Fields/NONE out-fields))) (defn sample* "Sample some percentage of elements within this pipe. percent should be between 0.00 (0%) and 1.00 (100%) you can provide a seed to get reproducible results." ([flow percent] (add-op flow #(Each. % (Sample. percent)))) ([flow percent seed] (add-op flow #(Each. % (Sample. percent seed))))) ;; TODO: rename* should accept a map of old fieldname -> new ;; fieldname. (defn rename* "rename old-fields to new-fields." ([flow new-fields] (rename* flow Fields/ALL new-fields)) ([flow old-fields new-fields] (add-op flow #(Rename. % (fields old-fields) (fields new-fields))))) (defop filter* [op-var in-fields] #(->> (ClojureFilter. op-var) (Each. % (fields in-fields)))) (defn map* [flow op-var in-fields out-fields] (each flow #(ClojureMap. % op-var) in-fields out-fields)) (defn mapcat* [flow op-var in-fields out-fields] (each flow #(ClojureMapcat. % op-var) in-fields out-fields)) ;; ## Aggregations ;; ;; TODO: Convert away from this protocol approach. Redefining these ;; namespaces causes issues, when the aggregators suddenly aren't ;; instances and don't respond to isa? ;; ;; We need to make sure that we can jack in other aggregators from ;;Cascading directly, or at least let the user chain a raw every and a ;;raw groupBy. These should take appropriate keyword options. (defprotocol IAggregateBy (aggregate-by [_])) (defprotocol IAggregator (add-aggregator [_ pipe])) (defprotocol IBuffer (add-buffer [_ pipe])) (defn parallel-agg "Creates a parallel aggregation operation." [agg-fn in-fields out-fields & {:keys [init-var present-var]}] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IAggregateBy (aggregate-by [_] (let [map-spec (-> (CombinerSpec. agg-fn) (.setPrepareFn init-var)) reduce-spec (-> (CombinerSpec. agg-fn) (.setPresentFn present-var))] (ClojureAggregateBy. in-fields (ClojureMonoidFunctor. out-fields map-spec) (ClojureMonoidAggregator. out-fields reduce-spec)))) IAggregator (add-aggregator [_ pipe] (let [spec (-> (CombinerSpec. agg-fn) (.setPrepareFn init-var) (.setPresentFn present-var))] (Every. pipe in-fields (ClojureMonoidAggregator. out-fields spec))))))) (defn agg "Returns in instance of IAggregator that adds a reduce-side-only aggregation to its supplied pipe." [agg-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IAggregator (add-aggregator [_ pipe] (Every. pipe in-fields (ClojureAggregator. out-fields agg-fn)))))) (defn bufferiter [buffer-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IBuffer (add-buffer [_ pipe] (Every. pipe in-fields (ClojureBufferIter. out-fields buffer-fn)))))) (defn buffer [buffer-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IBuffer (add-buffer [_ pipe] (Every. pipe in-fields (ClojureBuffer. out-fields buffer-fn)))))) (defn aggregator? [x] (satisfies? IAggregator x)) (defn parallel-agg? [x] (satisfies? IAggregateBy x)) (defn buffer? [x] (satisfies? IBuffer x)) ;; TODO: add options (def REDUCER-KEY "mapred.reduce.tasks") (defn set-reducers "Set the number of reducers for this step in the pipe." [pipe reducers] (if-not reducers pipe (cond (pos? reducers) (do (-> pipe (.getStepConfigDef) (.setProperty REDUCER-KEY, (str reducers))) pipe) (= -1 reducers) pipe :else (throw-illegal "Number of reducers must be non-negative.")))) (defn aggregate-mode "Accepts a sequence of aggregators and a boolean force-reduce? flag and returns a keyword representing the aggregation type." [aggregators force-reduce?] (cond (some buffer? aggregators) (if (> (count aggregators) 1) (throw-illegal "Cannot use both aggregators and buffers in the same grouping.") ::buffer) (and (not force-reduce?) (every? parallel-agg? aggregators)) ::parallel :else ::aggregate)) (defn- groupby "Adds a raw GroupBy operation to the pipe. Don't use this directly." [pipe group-fields sort-fields reverse?] (if sort-fields (GroupBy. pipe group-fields (fields sort-fields) (boolean reverse?)) (GroupBy. pipe group-fields))) (defn- aggby [pipe group-fields spill-threshold aggs] (let [aggs (->> aggs (map aggregate-by) (into-array AggregateBy))] (AggregateBy. pipe (fields group-fields) spill-threshold aggs))) ;; TODO: Add proper assertions around sorting. (We can't sort when ;; we're in AggregateBy, for example. ;; ;; Note that sorting fields will force a reduce step. (defop group-by* "Applies a grouping operation to the supplied generator." [group-fields aggs & {:keys [reducers spill-threshold sort-fields reverse? reduce-only] :or {spill-threshold 0}}] (fn [pipe] (let [group-fields (fields group-fields) build-group (fn [thunk] (thunk (groupby pipe group-fields (fields sort-fields) reverse?))) mode (aggregate-mode aggs (or reduce-only sort-fields))] (case mode ::buffer (build-group #(add-buffer (first aggs) %)) ::aggregate (build-group (fn [grouped] (reduce (fn [p op] (add-aggregator op p)) grouped aggs))) ::parallel (aggby pipe group-fields spill-threshold aggs) (throw-illegal "Unsupported aggregation mode: " mode))))) (defn unique-aggregator [] (reify IAggregator (add-aggregator [_ pipe] (Every. pipe (FastFirst.) Fields/RESULTS)))) (defn unique "Performs a unique on the input pipe by the supplied fields." ([flow] (unique flow Fields/ALL)) ([flow unique-fields & options] (apply group-by* flow unique-fields [(unique-aggregator)] options))) (defn union* "Merges the supplied flows and ensures uniqueness of the resulting tuples." [& flows] (unique (sum flows))) ;; ## Join Operations (defn join->joiner "Converts the supplier joiner instance or keyword to a Cascading Joiner." [join] (if (instance? Joiner join) join (case join :inner (InnerJoin.) :outer (OuterJoin.) (throw-illegal "Can't create joiner from " join)))) (defmacro build-join-group [group-op pipes group-fields decl-fields join] `(let [group-fields# (into-array Fields (map fields ~group-fields)) joiner# (join->joiner ~join) d# ~decl-fields decl-fields# (when d# (fields d#))] (~group-op ~pipes group-fields# decl-fields# joiner#))) (defn- add-co-group-aggs [pipe aggs] (let [mode (aggregate-mode aggs true)] (case mode ::buffer (add-buffer (first aggs) pipe) ::aggregate (reduce (fn [p op] (add-aggregator op p)) pipe aggs)))) (defn lift-pipes [flows] (map #(add-op % (fn [p] (into-array Pipe [p]))) flows)) (defn- ensure-unique-pipes [flows] (map rename-pipe flows)) (defn co-group* [flows group-fields & {:keys [decl-fields aggs reducers join] :or {join :inner}}] (-> flows ensure-unique-pipes lift-pipes sum (add-op (fn [pipes] (-> (build-join-group CoGroup. pipes group-fields decl-fields join) (set-reducers reducers) (add-co-group-aggs (or aggs []))))))) (defn join-with-smaller [larger-flow fields1 smaller-flow fields2 & opts] (apply co-group* [larger-flow smaller-flow] [fields1 fields2] (concat opts [:join (InnerJoin.)]))) (defn join-with-larger [smaller-flow fields1 larger-flow fields2 group-fields aggs & opts] (apply join-with-smaller larger-flow fields2 smaller-flow fields1 opts)) (defn left-join-with-smaller [larger-flow fields1 smaller-flow fields2 aggs & opts] (apply co-group* [larger-flow smaller-flow] [fields1 fields2] (concat opts [:join (LeftJoin.)]))) (defn left-join-with-larger [smaller-flow fields1 larger-flow fields2 aggs & {:as opts}] (apply co-group* [larger-flow smaller-flow] [fields2 fields1] (concat opts [:join (RightJoin.)]))) (defn- cascalog-joiner-type [join] (case join :inner CascalogJoiner$JoinType/INNER :outer CascalogJoiner$JoinType/OUTER :exists CascalogJoiner$JoinType/EXISTS)) (defn join-many "Takes a sequence of [pipe, join-fields, join-type] triplets along with other co-group arguments and performs a mixed join. Allowed join types are :inner, :outer, and :exists." [flow-joins decl-fields options] (let [[flows group-fields join-types] (apply map vector flow-joins) join-types (map cascalog-joiner-type join-types)] (apply co-group* flows group-fields (concat options [:decl-fields decl-fields :join (CascalogJoiner. join-types)])))) (defn hash-join* "Performs a map-side join of flows on join-fields. By default does an inner join, but callers can specify a join type using :join keyword argument, which can be :inner, :outer, or a Cascading Joiner implementation. Note: full or right outer joins have odd behavior in hash joins. See Cascading documentation for details." [flows join-fields & {:keys [join decl-fields] :or {join :inner}}] (safe-assert (= (count flows) (count join-fields)) "Expected same number of flows and join fields") (-> flows ensure-unique-pipes lift-pipes sum (add-op (fn [pipes] (build-join-group HashJoin. pipes join-fields decl-fields join))))) (defn hash-join-with-tiny [larger-flow fields1 tiny-flow fields2] (hash-join* [larger-flow tiny-flow] [fields1 fields2])) (defn left-hash-join-with-tiny [larger-flow fields1 tiny-flow fields2] (hash-join* [larger-flow tiny-flow] [fields1 fields2] :join (LeftJoin.))) (defn hash-join-many "Takes a sequence of [pipe, join-fields, join-type] triplets along with other hash-join arguments and performs a mixed join. Allowed join types are :inner, :outer, and :exists. The first entry must be of join type :inner." [flow-joins decl-fields] (safe-assert (= :inner (-> flow-joins (first) (nth 2))) "First (left-most) flow must be inner joined.") (let [[flows group-fields join-types] (apply map vector flow-joins) join-types (map cascalog-joiner-type join-types)] (hash-join* flows group-fields :decl-fields decl-fields :join (CascalogJoiner. join-types)))) (defn generate-join-fields [numfields numpipes] (repeatedly numpipes (partial v/gen-nullable-vars numfields))) (defn replace-join-fields [join-fields join-renames fields] (let [replace-map (zipmap join-fields join-renames)] (reduce (fn [ret f] (let [newf (-> (replace-map f) (or f))] (conj ret newf))) [] fields))) (defn declared-fields "Accepts a sequence of join fields and a sequence of field-seqs (each containing the join-fields, presumably) and returns a full vector of unique field names, suitable for the return value of a co-group." [join-fields renames infields] (flatten (map (partial replace-join-fields join-fields) renames infields))) (defn join-fields-selector "Returns a selector that's used to go pull out groups from the join that aren't all nil." [num-fields] (serfn/fn [& args] (let [joins (partition num-fields args)] (or (s/find-first (partial s/some? (complement nil?)) joins) (repeat num-fields nil))))) (defn new-pipe-name [joined-seq] (.getName (:pipe (:gen (first joined-seq))))) (defrecord Inner [gen available-fields]) (defrecord Outer [gen available-fields]) (defrecord Existence [gen available-fields out-field]) (defn fields-to-keep "We want to keep the out-field of Existence nodes and all available fields of the Inner and Outer nodes." [gen-seq] (let [grouped (group-by type gen-seq)] (vec (set (concat (mapcat :available-fields (grouped Inner)) (mapcat :available-fields (grouped Outer)) (map :out-field (grouped Existence))))))) (defn ensure-project "Makes sure that the declared fields are in the proper order." [gen-seq] (let [grouped (group-by type gen-seq)] (->> (concat (grouped Inner) (grouped Outer) (grouped Existence)) (map (fn [g] (update-in g [:gen] #(-> % (select* (:available-fields g)) (rename-pipe)))))))) (defn build-triplet [gen join-fields] [(:gen gen) join-fields (condp instance? gen Inner :inner Outer :outer Existence :exists)]) (defn cascalog-join [gen-seq join-fields options] (let [final-name (new-pipe-name gen-seq) gen-seq (ensure-project gen-seq) in-fields (map :available-fields gen-seq) join-size (count join-fields) renames (generate-join-fields join-size (count gen-seq)) declared (declared-fields join-fields renames in-fields) to-keep (fields-to-keep gen-seq) select-exists (fn [joined] (->> (mapcat (fn [g join-renames] (if (instance? Existence g) [[(first join-renames) (:out-field g)]])) gen-seq renames) (reduce (fn [flow [in out]] (-> flow (identity* in out))) joined)))] (-> (join-many (map #(build-triplet % join-fields) gen-seq) declared options) (select-exists) (map* (join-fields-selector join-size) (flatten renames) join-fields) (select* to-keep) (rename-pipe final-name)))) ;; ## MultiGroup (defn multigroup "Take a sequence of pairs of [pipe, join-fields]" [pairs declared-group-vars op out-fields] (safe-assert (seq declared-group-vars) "Cannot do global grouping with multigroup") (let [flows (map (comp generator first) pairs) out-vars (map second pairs) group-vars (apply set/intersection (map set out-vars)) num-vars (reduce + (map count out-vars))] (safe-assert (= (set group-vars) (set declared-group-vars)) "Declared group vars must be same as intersection of vars of all subqueries") (-> flows lift-pipes sum (add-op (fn [pipes] (MultiGroupBy. pipes (casc/fields declared-group-vars) num-vars (ClojureMultibuffer. (casc/fields out-fields) op))))))) ;; ## Output Operations ;; ;; This section covers output and traps (defn lazy-generator "Returns a cascalog generator on the supplied sequence of tuples. `lazy-generator` serializes each item in the lazy sequence into a sequencefile located at the supplied temporary directory and returns a tap for the data in that directory. It's recommended to wrap queries that use this tap with `cascalog.cascading.io/with-fs-tmp`; for example, (with-fs-tmp [_ tmp-dir] (let [lazy-tap (lazy-generator tmp-dir lazy-seq)] (?<- (stdout) [?field1 ?field2 ... etc] (lazy-tap ?field1 ?field2) ...)))" [tmp-path [tuple :as l-seq]] {:pre [(coll? tuple)]} (let [tap (:sink (tap/hfs-seqfile tmp-path)) n-fields (count tuple)] (tap/fill-tap! tap l-seq) (rename* tap (v/gen-nullable-vars n-fields)))) (defn in-branch "Accepts a temporary name and a function from flow => flow and performs the operation within a renamed branch." ([flow f] (in-branch flow (uuid) f)) ([flow name f] (-> flow (rename-pipe name) (f name) (rename-pipe)))) (defn write* [flow sink] (let [sink (to-sink sink)] (-> flow (in-branch (uuid) (fn [subflow name] (-> subflow (update-in [:tails] conj (:pipe subflow)) (update-in [:sink-map] assoc name sink))))))) (defn trap* "Applies a trap to the current branch of the supplied flow." [flow trap] (let [trap (to-sink trap) id (.getIdentifier trap)] (-> flow (rename-pipe id) (update-in [:trap-map] assoc id trap)))) ;; TODO: Figure out if I really understand what's going on with the ;; trap options. Do this by testing the traps with a few throws inside ;; and one after. Make sure the throw after causes a failure, but not ;; inside. ;; ;; TODO: Add "checkpoint" function, injecting a checkpoint pipe. (defn with-trap* "Applies a trap to everything that occurs within the supplied function of flow => flow." [flow trap f] (-> flow (trap* trap) f (rename-pipe))) ;; ## Logic Variable Substitution Rules (defn with-duplicate-inputs "Accepts a flow, some fields, and a function from (flow, unique-fields, new-fields) => flow and appropriately handles duplicate entries inside of the fields. The fields passed to the supplied function will be guaranteed unique. New fields are passed as a third option to the supplying function, which may decide to call (discard* delta) if the fields are still around." [flow from-fields f] (if (or (empty? from-fields) (apply distinct? (collectify from-fields))) (f flow from-fields []) (let [[delta cleaned-fields] (v/replace-dups from-fields)] (-> (reduce (fn [subflow [field gen]] (if (= field gen) subflow (identity* subflow field gen))) flow (map vector from-fields cleaned-fields)) (f cleaned-fields (seq delta)))))) ;; TODO: If we have some sort of ignored variable coming out of a ;; Cascalog query, we want to strip all operations out at that ;; point. Probably when we're building up a generator. (defn substitute-if "Returns [newseq {map of newvals to oldvals}]" [pred subfn aseq] (reduce (fn [[newseq subs] val] (let [[newval sub] (if (pred val) (let [subbed (subfn val)] [subbed {subbed val}]) [val {}])] [(conj newseq newval) (merge subs sub)])) [[] {}] aseq)) (defn constant-substitutions "Returns a 2-vector of the form [new variables, {map of newvars to values to substitute}]" [vars] (substitute-if (complement v/cascalog-var?) (fn [_] (v/gen-nullable-var)) (collectify vars))) (defn insert-subs [flow sub-m] (if (empty? sub-m) flow (apply insert* flow (apply concat sub-m)))) (defn with-constants "Allows constant substitution on inputs." [gen in-fields f] (let [[new-input sub-m] (constant-substitutions in-fields) ignored (keys sub-m) gen (-> (insert-subs gen sub-m) (f new-input))] (if (seq ignored) (discard* gen (fields ignored)) gen))) (defn- replace-ignored-vars "Replaces all ignored variables with a nullable cascalog variable. " [vars] (map (fn [v] (if (= "_" v) (v/gen-nullable-var) v)) (collectify vars))) (defn not-nil? [& xs] (every? (complement nil?) xs)) (defn filter-nullable-vars "If there are any nullable variables present in the output, filter nulls out now." [flow fields] (if-let [non-null-fields (seq (filter v/non-nullable-var? fields))] (filter* flow #'not-nil? non-null-fields) flow)) (defn no-overlap? [large small] (empty? (intersection (set (collectify large)) (set (collectify small))))) ;; The enhance-predicate logic in predicate.clj sort of does this ;;"accept the function, do something around it" logic. (defn logically "Accepts a flow, input fields, output fields and a function that accepts the same things and allows for the following features: Any variables not prefixed with !, !! or ? are treated as constants in the flow. This allows for (map* flow + 10 [\"?a\"] [\"?b\"]) to work properly and clean up its fields without hassle. Any non-nullable output variables (prefixed with ?) are removed from the flow. Duplicate input fields are allowed. It is currently NOT allowed to output one of the input variables. In Cascalog, this triggers an implicit filter; this needs to be supplied at another layer." [gen in-fields out-fields f] {:pre [(no-overlap? out-fields in-fields)]} (let [new-output (replace-ignored-vars out-fields) ignored (difference (set new-output) (set (collectify out-fields)))] (with-constants gen in-fields (fn [gen in] (with-duplicate-inputs gen in (fn [gen in delta] (let [gen (-> gen (f (fields in) (fields new-output))) gen (if-let [to-discard (not-empty (fields (concat delta ignored)))] (discard* gen to-discard) gen)] (filter-nullable-vars gen new-output)))))))) (comment "This one works, since all inputs are logical variables." (-> [1 2 3 4] (rename* "?a") (map* inc "?a" "?other") (logically ["?a" 10 "?other"] "?b" (fn [gen in out] (-> gen (map* * in out)))) (cascalog.cascading.flow/to-memory)) "This one fails, since one of the inputs is interpreted as a constant." (-> [1 2 3 4] (rename* "?a") (map* inc "?a" "other") (logically ["?a" 10 "other"] "?b" (fn [gen in out] (-> gen (map* * in out)))) (to-memory)) "TODO: in logically, we need to start enforcing some rules. no one can push an actual instance of Fields in at this point. It doesn't make sense with these logical rules. We do now have some notion of an assembly -- an assembly is a function from one flow to another. I think we need a typeclass to chain some operation. add-op shouldn't have to take a generator -- it can definitely augment just a pipe, or even another function that's going to modify a pipe (by composition).")
57022
(ns cascalog.cascading.operations (:require [clojure.tools.macro :refer (name-with-attributes)] [clojure.set :as set :refer (subset? difference intersection)] [cascalog.logic.fn :as serfn] [cascalog.logic.vars :as v] [cascalog.logic.algebra :refer (sum)] [cascalog.cascading.util :as casc :refer (fields default-output)] [cascalog.cascading.tap :as tap] [cascalog.cascading.types :refer (generator to-sink)] [jackknife.core :refer (safe-assert throw-illegal uuid)] [jackknife.seq :as s :refer (unweave collectify)]) (:import [cascading.tuple Fields] [cascalog.ops KryoInsert] [cascading.operation Identity Debug NoOp] [cascading.operation.filter Sample] [cascading.operation.aggregator First Count Sum Min Max] [cascading.pipe Pipe Each Every GroupBy CoGroup Merge HashJoin] [cascading.pipe.joiner Joiner InnerJoin LeftJoin RightJoin OuterJoin] [cascading.pipe.joiner CascalogJoiner CascalogJoiner$JoinType] [cascading.pipe.assembly Rename AggregateBy] [cascalog ClojureFilter ClojureMapcat ClojureMap ClojureBuffer ClojureBufferIter FastFirst MultiGroupBy ClojureMultibuffer] [cascalog.aggregator ClojureAggregator ClojureMonoidAggregator ClojureMonoidFunctor ClojureAggregateBy CombinerSpec])) ;; ## Operations ;; ;; All of these operations work on implementers of the Generator ;; protocol, defined in cascalog.cascading.types. (defmacro assembly [args & ops] `(fn [flow# ~@args] (-> flow# ~@ops))) (defn add-op "Accepts a generator and a function from pipe to pipe and applies the operation to the active head pipe." [flow fn] (update-in (generator flow) [:pipe] fn)) (defmacro defop "Defines a flow operation." [f-name & tail] (let [[f-name [args & body]] (name-with-attributes f-name tail)] `(defn ~f-name {:arglists '([~'flow ~@args])} [flow# ~@args] (add-op flow# ~@body)))) (defop each "Accepts a flow, a function from result fields => cascading Function, input fields and output fields and returns a new flow." [f from-fields to-fields] (let [from-fields (fields from-fields) to-fields (fields to-fields)] (fn [pipe] (Each. pipe from-fields (f to-fields) (default-output from-fields to-fields))))) (defn name-flow "Assigns a new name to the clojure flow." [gen name] (-> (generator gen) (assoc :name name))) (defn rename-pipe ([gen] (rename-pipe gen (uuid))) ([gen name] (add-op gen #(Pipe. name %)))) (defop select* "Remove all but the supplied fields from the given flow." [keep-fields] #(Each. % (fields keep-fields) (Identity. (fields keep-fields)))) (defn identity* "Mirrors the supplied set of input fields into the output fields." [flow input output] (each flow #(Identity. %) input output)) (defop discard* "Discard the supplied fields." [drop-fields] #(Each. % (fields drop-fields) (NoOp.) Fields/SWAP)) (defop debug* "Prints all tuples that pass through the StdOut." [] #(Each. % (Debug.))) (defn insert* "Accepts a flow and alternating field/value pairs and inserts these items into the flow." [flow & field-v-pairs] (let [[out-fields vals] (unweave field-v-pairs)] (each flow #(KryoInsert. % (into-array Object vals)) Fields/NONE out-fields))) (defn sample* "Sample some percentage of elements within this pipe. percent should be between 0.00 (0%) and 1.00 (100%) you can provide a seed to get reproducible results." ([flow percent] (add-op flow #(Each. % (Sample. percent)))) ([flow percent seed] (add-op flow #(Each. % (Sample. percent seed))))) ;; TODO: rename* should accept a map of old fieldname -> new ;; fieldname. (defn rename* "rename old-fields to new-fields." ([flow new-fields] (rename* flow Fields/ALL new-fields)) ([flow old-fields new-fields] (add-op flow #(Rename. % (fields old-fields) (fields new-fields))))) (defop filter* [op-var in-fields] #(->> (ClojureFilter. op-var) (Each. % (fields in-fields)))) (defn map* [flow op-var in-fields out-fields] (each flow #(ClojureMap. % op-var) in-fields out-fields)) (defn mapcat* [flow op-var in-fields out-fields] (each flow #(ClojureMapcat. % op-var) in-fields out-fields)) ;; ## Aggregations ;; ;; TODO: Convert away from this protocol approach. Redefining these ;; namespaces causes issues, when the aggregators suddenly aren't ;; instances and don't respond to isa? ;; ;; We need to make sure that we can jack in other aggregators from ;;Cascading directly, or at least let the user chain a raw every and a ;;raw groupBy. These should take appropriate keyword options. (defprotocol IAggregateBy (aggregate-by [_])) (defprotocol IAggregator (add-aggregator [_ pipe])) (defprotocol IBuffer (add-buffer [_ pipe])) (defn parallel-agg "Creates a parallel aggregation operation." [agg-fn in-fields out-fields & {:keys [init-var present-var]}] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IAggregateBy (aggregate-by [_] (let [map-spec (-> (CombinerSpec. agg-fn) (.setPrepareFn init-var)) reduce-spec (-> (CombinerSpec. agg-fn) (.setPresentFn present-var))] (ClojureAggregateBy. in-fields (ClojureMonoidFunctor. out-fields map-spec) (ClojureMonoidAggregator. out-fields reduce-spec)))) IAggregator (add-aggregator [_ pipe] (let [spec (-> (CombinerSpec. agg-fn) (.setPrepareFn init-var) (.setPresentFn present-var))] (Every. pipe in-fields (ClojureMonoidAggregator. out-fields spec))))))) (defn agg "Returns in instance of IAggregator that adds a reduce-side-only aggregation to its supplied pipe." [agg-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IAggregator (add-aggregator [_ pipe] (Every. pipe in-fields (ClojureAggregator. out-fields agg-fn)))))) (defn bufferiter [buffer-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IBuffer (add-buffer [_ pipe] (Every. pipe in-fields (ClojureBufferIter. out-fields buffer-fn)))))) (defn buffer [buffer-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IBuffer (add-buffer [_ pipe] (Every. pipe in-fields (ClojureBuffer. out-fields buffer-fn)))))) (defn aggregator? [x] (satisfies? IAggregator x)) (defn parallel-agg? [x] (satisfies? IAggregateBy x)) (defn buffer? [x] (satisfies? IBuffer x)) ;; TODO: add options (def REDUCER-KEY "<KEY>") (defn set-reducers "Set the number of reducers for this step in the pipe." [pipe reducers] (if-not reducers pipe (cond (pos? reducers) (do (-> pipe (.getStepConfigDef) (.setProperty REDUCER-KEY, (str reducers))) pipe) (= -1 reducers) pipe :else (throw-illegal "Number of reducers must be non-negative.")))) (defn aggregate-mode "Accepts a sequence of aggregators and a boolean force-reduce? flag and returns a keyword representing the aggregation type." [aggregators force-reduce?] (cond (some buffer? aggregators) (if (> (count aggregators) 1) (throw-illegal "Cannot use both aggregators and buffers in the same grouping.") ::buffer) (and (not force-reduce?) (every? parallel-agg? aggregators)) ::parallel :else ::aggregate)) (defn- groupby "Adds a raw GroupBy operation to the pipe. Don't use this directly." [pipe group-fields sort-fields reverse?] (if sort-fields (GroupBy. pipe group-fields (fields sort-fields) (boolean reverse?)) (GroupBy. pipe group-fields))) (defn- aggby [pipe group-fields spill-threshold aggs] (let [aggs (->> aggs (map aggregate-by) (into-array AggregateBy))] (AggregateBy. pipe (fields group-fields) spill-threshold aggs))) ;; TODO: Add proper assertions around sorting. (We can't sort when ;; we're in AggregateBy, for example. ;; ;; Note that sorting fields will force a reduce step. (defop group-by* "Applies a grouping operation to the supplied generator." [group-fields aggs & {:keys [reducers spill-threshold sort-fields reverse? reduce-only] :or {spill-threshold 0}}] (fn [pipe] (let [group-fields (fields group-fields) build-group (fn [thunk] (thunk (groupby pipe group-fields (fields sort-fields) reverse?))) mode (aggregate-mode aggs (or reduce-only sort-fields))] (case mode ::buffer (build-group #(add-buffer (first aggs) %)) ::aggregate (build-group (fn [grouped] (reduce (fn [p op] (add-aggregator op p)) grouped aggs))) ::parallel (aggby pipe group-fields spill-threshold aggs) (throw-illegal "Unsupported aggregation mode: " mode))))) (defn unique-aggregator [] (reify IAggregator (add-aggregator [_ pipe] (Every. pipe (FastFirst.) Fields/RESULTS)))) (defn unique "Performs a unique on the input pipe by the supplied fields." ([flow] (unique flow Fields/ALL)) ([flow unique-fields & options] (apply group-by* flow unique-fields [(unique-aggregator)] options))) (defn union* "Merges the supplied flows and ensures uniqueness of the resulting tuples." [& flows] (unique (sum flows))) ;; ## Join Operations (defn join->joiner "Converts the supplier joiner instance or keyword to a Cascading Joiner." [join] (if (instance? Joiner join) join (case join :inner (InnerJoin.) :outer (OuterJoin.) (throw-illegal "Can't create joiner from " join)))) (defmacro build-join-group [group-op pipes group-fields decl-fields join] `(let [group-fields# (into-array Fields (map fields ~group-fields)) joiner# (join->joiner ~join) d# ~decl-fields decl-fields# (when d# (fields d#))] (~group-op ~pipes group-fields# decl-fields# joiner#))) (defn- add-co-group-aggs [pipe aggs] (let [mode (aggregate-mode aggs true)] (case mode ::buffer (add-buffer (first aggs) pipe) ::aggregate (reduce (fn [p op] (add-aggregator op p)) pipe aggs)))) (defn lift-pipes [flows] (map #(add-op % (fn [p] (into-array Pipe [p]))) flows)) (defn- ensure-unique-pipes [flows] (map rename-pipe flows)) (defn co-group* [flows group-fields & {:keys [decl-fields aggs reducers join] :or {join :inner}}] (-> flows ensure-unique-pipes lift-pipes sum (add-op (fn [pipes] (-> (build-join-group CoGroup. pipes group-fields decl-fields join) (set-reducers reducers) (add-co-group-aggs (or aggs []))))))) (defn join-with-smaller [larger-flow fields1 smaller-flow fields2 & opts] (apply co-group* [larger-flow smaller-flow] [fields1 fields2] (concat opts [:join (InnerJoin.)]))) (defn join-with-larger [smaller-flow fields1 larger-flow fields2 group-fields aggs & opts] (apply join-with-smaller larger-flow fields2 smaller-flow fields1 opts)) (defn left-join-with-smaller [larger-flow fields1 smaller-flow fields2 aggs & opts] (apply co-group* [larger-flow smaller-flow] [fields1 fields2] (concat opts [:join (LeftJoin.)]))) (defn left-join-with-larger [smaller-flow fields1 larger-flow fields2 aggs & {:as opts}] (apply co-group* [larger-flow smaller-flow] [fields2 fields1] (concat opts [:join (RightJoin.)]))) (defn- cascalog-joiner-type [join] (case join :inner CascalogJoiner$JoinType/INNER :outer CascalogJoiner$JoinType/OUTER :exists CascalogJoiner$JoinType/EXISTS)) (defn join-many "Takes a sequence of [pipe, join-fields, join-type] triplets along with other co-group arguments and performs a mixed join. Allowed join types are :inner, :outer, and :exists." [flow-joins decl-fields options] (let [[flows group-fields join-types] (apply map vector flow-joins) join-types (map cascalog-joiner-type join-types)] (apply co-group* flows group-fields (concat options [:decl-fields decl-fields :join (CascalogJoiner. join-types)])))) (defn hash-join* "Performs a map-side join of flows on join-fields. By default does an inner join, but callers can specify a join type using :join keyword argument, which can be :inner, :outer, or a Cascading Joiner implementation. Note: full or right outer joins have odd behavior in hash joins. See Cascading documentation for details." [flows join-fields & {:keys [join decl-fields] :or {join :inner}}] (safe-assert (= (count flows) (count join-fields)) "Expected same number of flows and join fields") (-> flows ensure-unique-pipes lift-pipes sum (add-op (fn [pipes] (build-join-group HashJoin. pipes join-fields decl-fields join))))) (defn hash-join-with-tiny [larger-flow fields1 tiny-flow fields2] (hash-join* [larger-flow tiny-flow] [fields1 fields2])) (defn left-hash-join-with-tiny [larger-flow fields1 tiny-flow fields2] (hash-join* [larger-flow tiny-flow] [fields1 fields2] :join (LeftJoin.))) (defn hash-join-many "Takes a sequence of [pipe, join-fields, join-type] triplets along with other hash-join arguments and performs a mixed join. Allowed join types are :inner, :outer, and :exists. The first entry must be of join type :inner." [flow-joins decl-fields] (safe-assert (= :inner (-> flow-joins (first) (nth 2))) "First (left-most) flow must be inner joined.") (let [[flows group-fields join-types] (apply map vector flow-joins) join-types (map cascalog-joiner-type join-types)] (hash-join* flows group-fields :decl-fields decl-fields :join (CascalogJoiner. join-types)))) (defn generate-join-fields [numfields numpipes] (repeatedly numpipes (partial v/gen-nullable-vars numfields))) (defn replace-join-fields [join-fields join-renames fields] (let [replace-map (zipmap join-fields join-renames)] (reduce (fn [ret f] (let [newf (-> (replace-map f) (or f))] (conj ret newf))) [] fields))) (defn declared-fields "Accepts a sequence of join fields and a sequence of field-seqs (each containing the join-fields, presumably) and returns a full vector of unique field names, suitable for the return value of a co-group." [join-fields renames infields] (flatten (map (partial replace-join-fields join-fields) renames infields))) (defn join-fields-selector "Returns a selector that's used to go pull out groups from the join that aren't all nil." [num-fields] (serfn/fn [& args] (let [joins (partition num-fields args)] (or (s/find-first (partial s/some? (complement nil?)) joins) (repeat num-fields nil))))) (defn new-pipe-name [joined-seq] (.getName (:pipe (:gen (first joined-seq))))) (defrecord Inner [gen available-fields]) (defrecord Outer [gen available-fields]) (defrecord Existence [gen available-fields out-field]) (defn fields-to-keep "We want to keep the out-field of Existence nodes and all available fields of the Inner and Outer nodes." [gen-seq] (let [grouped (group-by type gen-seq)] (vec (set (concat (mapcat :available-fields (grouped Inner)) (mapcat :available-fields (grouped Outer)) (map :out-field (grouped Existence))))))) (defn ensure-project "Makes sure that the declared fields are in the proper order." [gen-seq] (let [grouped (group-by type gen-seq)] (->> (concat (grouped Inner) (grouped Outer) (grouped Existence)) (map (fn [g] (update-in g [:gen] #(-> % (select* (:available-fields g)) (rename-pipe)))))))) (defn build-triplet [gen join-fields] [(:gen gen) join-fields (condp instance? gen Inner :inner Outer :outer Existence :exists)]) (defn cascalog-join [gen-seq join-fields options] (let [final-name (new-pipe-name gen-seq) gen-seq (ensure-project gen-seq) in-fields (map :available-fields gen-seq) join-size (count join-fields) renames (generate-join-fields join-size (count gen-seq)) declared (declared-fields join-fields renames in-fields) to-keep (fields-to-keep gen-seq) select-exists (fn [joined] (->> (mapcat (fn [g join-renames] (if (instance? Existence g) [[(first join-renames) (:out-field g)]])) gen-seq renames) (reduce (fn [flow [in out]] (-> flow (identity* in out))) joined)))] (-> (join-many (map #(build-triplet % join-fields) gen-seq) declared options) (select-exists) (map* (join-fields-selector join-size) (flatten renames) join-fields) (select* to-keep) (rename-pipe final-name)))) ;; ## MultiGroup (defn multigroup "Take a sequence of pairs of [pipe, join-fields]" [pairs declared-group-vars op out-fields] (safe-assert (seq declared-group-vars) "Cannot do global grouping with multigroup") (let [flows (map (comp generator first) pairs) out-vars (map second pairs) group-vars (apply set/intersection (map set out-vars)) num-vars (reduce + (map count out-vars))] (safe-assert (= (set group-vars) (set declared-group-vars)) "Declared group vars must be same as intersection of vars of all subqueries") (-> flows lift-pipes sum (add-op (fn [pipes] (MultiGroupBy. pipes (casc/fields declared-group-vars) num-vars (ClojureMultibuffer. (casc/fields out-fields) op))))))) ;; ## Output Operations ;; ;; This section covers output and traps (defn lazy-generator "Returns a cascalog generator on the supplied sequence of tuples. `lazy-generator` serializes each item in the lazy sequence into a sequencefile located at the supplied temporary directory and returns a tap for the data in that directory. It's recommended to wrap queries that use this tap with `cascalog.cascading.io/with-fs-tmp`; for example, (with-fs-tmp [_ tmp-dir] (let [lazy-tap (lazy-generator tmp-dir lazy-seq)] (?<- (stdout) [?field1 ?field2 ... etc] (lazy-tap ?field1 ?field2) ...)))" [tmp-path [tuple :as l-seq]] {:pre [(coll? tuple)]} (let [tap (:sink (tap/hfs-seqfile tmp-path)) n-fields (count tuple)] (tap/fill-tap! tap l-seq) (rename* tap (v/gen-nullable-vars n-fields)))) (defn in-branch "Accepts a temporary name and a function from flow => flow and performs the operation within a renamed branch." ([flow f] (in-branch flow (uuid) f)) ([flow name f] (-> flow (rename-pipe name) (f name) (rename-pipe)))) (defn write* [flow sink] (let [sink (to-sink sink)] (-> flow (in-branch (uuid) (fn [subflow name] (-> subflow (update-in [:tails] conj (:pipe subflow)) (update-in [:sink-map] assoc name sink))))))) (defn trap* "Applies a trap to the current branch of the supplied flow." [flow trap] (let [trap (to-sink trap) id (.getIdentifier trap)] (-> flow (rename-pipe id) (update-in [:trap-map] assoc id trap)))) ;; TODO: Figure out if I really understand what's going on with the ;; trap options. Do this by testing the traps with a few throws inside ;; and one after. Make sure the throw after causes a failure, but not ;; inside. ;; ;; TODO: Add "checkpoint" function, injecting a checkpoint pipe. (defn with-trap* "Applies a trap to everything that occurs within the supplied function of flow => flow." [flow trap f] (-> flow (trap* trap) f (rename-pipe))) ;; ## Logic Variable Substitution Rules (defn with-duplicate-inputs "Accepts a flow, some fields, and a function from (flow, unique-fields, new-fields) => flow and appropriately handles duplicate entries inside of the fields. The fields passed to the supplied function will be guaranteed unique. New fields are passed as a third option to the supplying function, which may decide to call (discard* delta) if the fields are still around." [flow from-fields f] (if (or (empty? from-fields) (apply distinct? (collectify from-fields))) (f flow from-fields []) (let [[delta cleaned-fields] (v/replace-dups from-fields)] (-> (reduce (fn [subflow [field gen]] (if (= field gen) subflow (identity* subflow field gen))) flow (map vector from-fields cleaned-fields)) (f cleaned-fields (seq delta)))))) ;; TODO: If we have some sort of ignored variable coming out of a ;; Cascalog query, we want to strip all operations out at that ;; point. Probably when we're building up a generator. (defn substitute-if "Returns [newseq {map of newvals to oldvals}]" [pred subfn aseq] (reduce (fn [[newseq subs] val] (let [[newval sub] (if (pred val) (let [subbed (subfn val)] [subbed {subbed val}]) [val {}])] [(conj newseq newval) (merge subs sub)])) [[] {}] aseq)) (defn constant-substitutions "Returns a 2-vector of the form [new variables, {map of newvars to values to substitute}]" [vars] (substitute-if (complement v/cascalog-var?) (fn [_] (v/gen-nullable-var)) (collectify vars))) (defn insert-subs [flow sub-m] (if (empty? sub-m) flow (apply insert* flow (apply concat sub-m)))) (defn with-constants "Allows constant substitution on inputs." [gen in-fields f] (let [[new-input sub-m] (constant-substitutions in-fields) ignored (keys sub-m) gen (-> (insert-subs gen sub-m) (f new-input))] (if (seq ignored) (discard* gen (fields ignored)) gen))) (defn- replace-ignored-vars "Replaces all ignored variables with a nullable cascalog variable. " [vars] (map (fn [v] (if (= "_" v) (v/gen-nullable-var) v)) (collectify vars))) (defn not-nil? [& xs] (every? (complement nil?) xs)) (defn filter-nullable-vars "If there are any nullable variables present in the output, filter nulls out now." [flow fields] (if-let [non-null-fields (seq (filter v/non-nullable-var? fields))] (filter* flow #'not-nil? non-null-fields) flow)) (defn no-overlap? [large small] (empty? (intersection (set (collectify large)) (set (collectify small))))) ;; The enhance-predicate logic in predicate.clj sort of does this ;;"accept the function, do something around it" logic. (defn logically "Accepts a flow, input fields, output fields and a function that accepts the same things and allows for the following features: Any variables not prefixed with !, !! or ? are treated as constants in the flow. This allows for (map* flow + 10 [\"?a\"] [\"?b\"]) to work properly and clean up its fields without hassle. Any non-nullable output variables (prefixed with ?) are removed from the flow. Duplicate input fields are allowed. It is currently NOT allowed to output one of the input variables. In Cascalog, this triggers an implicit filter; this needs to be supplied at another layer." [gen in-fields out-fields f] {:pre [(no-overlap? out-fields in-fields)]} (let [new-output (replace-ignored-vars out-fields) ignored (difference (set new-output) (set (collectify out-fields)))] (with-constants gen in-fields (fn [gen in] (with-duplicate-inputs gen in (fn [gen in delta] (let [gen (-> gen (f (fields in) (fields new-output))) gen (if-let [to-discard (not-empty (fields (concat delta ignored)))] (discard* gen to-discard) gen)] (filter-nullable-vars gen new-output)))))))) (comment "This one works, since all inputs are logical variables." (-> [1 2 3 4] (rename* "?a") (map* inc "?a" "?other") (logically ["?a" 10 "?other"] "?b" (fn [gen in out] (-> gen (map* * in out)))) (cascalog.cascading.flow/to-memory)) "This one fails, since one of the inputs is interpreted as a constant." (-> [1 2 3 4] (rename* "?a") (map* inc "?a" "other") (logically ["?a" 10 "other"] "?b" (fn [gen in out] (-> gen (map* * in out)))) (to-memory)) "TODO: in logically, we need to start enforcing some rules. no one can push an actual instance of Fields in at this point. It doesn't make sense with these logical rules. We do now have some notion of an assembly -- an assembly is a function from one flow to another. I think we need a typeclass to chain some operation. add-op shouldn't have to take a generator -- it can definitely augment just a pipe, or even another function that's going to modify a pipe (by composition).")
true
(ns cascalog.cascading.operations (:require [clojure.tools.macro :refer (name-with-attributes)] [clojure.set :as set :refer (subset? difference intersection)] [cascalog.logic.fn :as serfn] [cascalog.logic.vars :as v] [cascalog.logic.algebra :refer (sum)] [cascalog.cascading.util :as casc :refer (fields default-output)] [cascalog.cascading.tap :as tap] [cascalog.cascading.types :refer (generator to-sink)] [jackknife.core :refer (safe-assert throw-illegal uuid)] [jackknife.seq :as s :refer (unweave collectify)]) (:import [cascading.tuple Fields] [cascalog.ops KryoInsert] [cascading.operation Identity Debug NoOp] [cascading.operation.filter Sample] [cascading.operation.aggregator First Count Sum Min Max] [cascading.pipe Pipe Each Every GroupBy CoGroup Merge HashJoin] [cascading.pipe.joiner Joiner InnerJoin LeftJoin RightJoin OuterJoin] [cascading.pipe.joiner CascalogJoiner CascalogJoiner$JoinType] [cascading.pipe.assembly Rename AggregateBy] [cascalog ClojureFilter ClojureMapcat ClojureMap ClojureBuffer ClojureBufferIter FastFirst MultiGroupBy ClojureMultibuffer] [cascalog.aggregator ClojureAggregator ClojureMonoidAggregator ClojureMonoidFunctor ClojureAggregateBy CombinerSpec])) ;; ## Operations ;; ;; All of these operations work on implementers of the Generator ;; protocol, defined in cascalog.cascading.types. (defmacro assembly [args & ops] `(fn [flow# ~@args] (-> flow# ~@ops))) (defn add-op "Accepts a generator and a function from pipe to pipe and applies the operation to the active head pipe." [flow fn] (update-in (generator flow) [:pipe] fn)) (defmacro defop "Defines a flow operation." [f-name & tail] (let [[f-name [args & body]] (name-with-attributes f-name tail)] `(defn ~f-name {:arglists '([~'flow ~@args])} [flow# ~@args] (add-op flow# ~@body)))) (defop each "Accepts a flow, a function from result fields => cascading Function, input fields and output fields and returns a new flow." [f from-fields to-fields] (let [from-fields (fields from-fields) to-fields (fields to-fields)] (fn [pipe] (Each. pipe from-fields (f to-fields) (default-output from-fields to-fields))))) (defn name-flow "Assigns a new name to the clojure flow." [gen name] (-> (generator gen) (assoc :name name))) (defn rename-pipe ([gen] (rename-pipe gen (uuid))) ([gen name] (add-op gen #(Pipe. name %)))) (defop select* "Remove all but the supplied fields from the given flow." [keep-fields] #(Each. % (fields keep-fields) (Identity. (fields keep-fields)))) (defn identity* "Mirrors the supplied set of input fields into the output fields." [flow input output] (each flow #(Identity. %) input output)) (defop discard* "Discard the supplied fields." [drop-fields] #(Each. % (fields drop-fields) (NoOp.) Fields/SWAP)) (defop debug* "Prints all tuples that pass through the StdOut." [] #(Each. % (Debug.))) (defn insert* "Accepts a flow and alternating field/value pairs and inserts these items into the flow." [flow & field-v-pairs] (let [[out-fields vals] (unweave field-v-pairs)] (each flow #(KryoInsert. % (into-array Object vals)) Fields/NONE out-fields))) (defn sample* "Sample some percentage of elements within this pipe. percent should be between 0.00 (0%) and 1.00 (100%) you can provide a seed to get reproducible results." ([flow percent] (add-op flow #(Each. % (Sample. percent)))) ([flow percent seed] (add-op flow #(Each. % (Sample. percent seed))))) ;; TODO: rename* should accept a map of old fieldname -> new ;; fieldname. (defn rename* "rename old-fields to new-fields." ([flow new-fields] (rename* flow Fields/ALL new-fields)) ([flow old-fields new-fields] (add-op flow #(Rename. % (fields old-fields) (fields new-fields))))) (defop filter* [op-var in-fields] #(->> (ClojureFilter. op-var) (Each. % (fields in-fields)))) (defn map* [flow op-var in-fields out-fields] (each flow #(ClojureMap. % op-var) in-fields out-fields)) (defn mapcat* [flow op-var in-fields out-fields] (each flow #(ClojureMapcat. % op-var) in-fields out-fields)) ;; ## Aggregations ;; ;; TODO: Convert away from this protocol approach. Redefining these ;; namespaces causes issues, when the aggregators suddenly aren't ;; instances and don't respond to isa? ;; ;; We need to make sure that we can jack in other aggregators from ;;Cascading directly, or at least let the user chain a raw every and a ;;raw groupBy. These should take appropriate keyword options. (defprotocol IAggregateBy (aggregate-by [_])) (defprotocol IAggregator (add-aggregator [_ pipe])) (defprotocol IBuffer (add-buffer [_ pipe])) (defn parallel-agg "Creates a parallel aggregation operation." [agg-fn in-fields out-fields & {:keys [init-var present-var]}] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IAggregateBy (aggregate-by [_] (let [map-spec (-> (CombinerSpec. agg-fn) (.setPrepareFn init-var)) reduce-spec (-> (CombinerSpec. agg-fn) (.setPresentFn present-var))] (ClojureAggregateBy. in-fields (ClojureMonoidFunctor. out-fields map-spec) (ClojureMonoidAggregator. out-fields reduce-spec)))) IAggregator (add-aggregator [_ pipe] (let [spec (-> (CombinerSpec. agg-fn) (.setPrepareFn init-var) (.setPresentFn present-var))] (Every. pipe in-fields (ClojureMonoidAggregator. out-fields spec))))))) (defn agg "Returns in instance of IAggregator that adds a reduce-side-only aggregation to its supplied pipe." [agg-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IAggregator (add-aggregator [_ pipe] (Every. pipe in-fields (ClojureAggregator. out-fields agg-fn)))))) (defn bufferiter [buffer-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IBuffer (add-buffer [_ pipe] (Every. pipe in-fields (ClojureBufferIter. out-fields buffer-fn)))))) (defn buffer [buffer-fn in-fields out-fields] (let [in-fields (fields in-fields) out-fields (fields out-fields)] (reify IBuffer (add-buffer [_ pipe] (Every. pipe in-fields (ClojureBuffer. out-fields buffer-fn)))))) (defn aggregator? [x] (satisfies? IAggregator x)) (defn parallel-agg? [x] (satisfies? IAggregateBy x)) (defn buffer? [x] (satisfies? IBuffer x)) ;; TODO: add options (def REDUCER-KEY "PI:KEY:<KEY>END_PI") (defn set-reducers "Set the number of reducers for this step in the pipe." [pipe reducers] (if-not reducers pipe (cond (pos? reducers) (do (-> pipe (.getStepConfigDef) (.setProperty REDUCER-KEY, (str reducers))) pipe) (= -1 reducers) pipe :else (throw-illegal "Number of reducers must be non-negative.")))) (defn aggregate-mode "Accepts a sequence of aggregators and a boolean force-reduce? flag and returns a keyword representing the aggregation type." [aggregators force-reduce?] (cond (some buffer? aggregators) (if (> (count aggregators) 1) (throw-illegal "Cannot use both aggregators and buffers in the same grouping.") ::buffer) (and (not force-reduce?) (every? parallel-agg? aggregators)) ::parallel :else ::aggregate)) (defn- groupby "Adds a raw GroupBy operation to the pipe. Don't use this directly." [pipe group-fields sort-fields reverse?] (if sort-fields (GroupBy. pipe group-fields (fields sort-fields) (boolean reverse?)) (GroupBy. pipe group-fields))) (defn- aggby [pipe group-fields spill-threshold aggs] (let [aggs (->> aggs (map aggregate-by) (into-array AggregateBy))] (AggregateBy. pipe (fields group-fields) spill-threshold aggs))) ;; TODO: Add proper assertions around sorting. (We can't sort when ;; we're in AggregateBy, for example. ;; ;; Note that sorting fields will force a reduce step. (defop group-by* "Applies a grouping operation to the supplied generator." [group-fields aggs & {:keys [reducers spill-threshold sort-fields reverse? reduce-only] :or {spill-threshold 0}}] (fn [pipe] (let [group-fields (fields group-fields) build-group (fn [thunk] (thunk (groupby pipe group-fields (fields sort-fields) reverse?))) mode (aggregate-mode aggs (or reduce-only sort-fields))] (case mode ::buffer (build-group #(add-buffer (first aggs) %)) ::aggregate (build-group (fn [grouped] (reduce (fn [p op] (add-aggregator op p)) grouped aggs))) ::parallel (aggby pipe group-fields spill-threshold aggs) (throw-illegal "Unsupported aggregation mode: " mode))))) (defn unique-aggregator [] (reify IAggregator (add-aggregator [_ pipe] (Every. pipe (FastFirst.) Fields/RESULTS)))) (defn unique "Performs a unique on the input pipe by the supplied fields." ([flow] (unique flow Fields/ALL)) ([flow unique-fields & options] (apply group-by* flow unique-fields [(unique-aggregator)] options))) (defn union* "Merges the supplied flows and ensures uniqueness of the resulting tuples." [& flows] (unique (sum flows))) ;; ## Join Operations (defn join->joiner "Converts the supplier joiner instance or keyword to a Cascading Joiner." [join] (if (instance? Joiner join) join (case join :inner (InnerJoin.) :outer (OuterJoin.) (throw-illegal "Can't create joiner from " join)))) (defmacro build-join-group [group-op pipes group-fields decl-fields join] `(let [group-fields# (into-array Fields (map fields ~group-fields)) joiner# (join->joiner ~join) d# ~decl-fields decl-fields# (when d# (fields d#))] (~group-op ~pipes group-fields# decl-fields# joiner#))) (defn- add-co-group-aggs [pipe aggs] (let [mode (aggregate-mode aggs true)] (case mode ::buffer (add-buffer (first aggs) pipe) ::aggregate (reduce (fn [p op] (add-aggregator op p)) pipe aggs)))) (defn lift-pipes [flows] (map #(add-op % (fn [p] (into-array Pipe [p]))) flows)) (defn- ensure-unique-pipes [flows] (map rename-pipe flows)) (defn co-group* [flows group-fields & {:keys [decl-fields aggs reducers join] :or {join :inner}}] (-> flows ensure-unique-pipes lift-pipes sum (add-op (fn [pipes] (-> (build-join-group CoGroup. pipes group-fields decl-fields join) (set-reducers reducers) (add-co-group-aggs (or aggs []))))))) (defn join-with-smaller [larger-flow fields1 smaller-flow fields2 & opts] (apply co-group* [larger-flow smaller-flow] [fields1 fields2] (concat opts [:join (InnerJoin.)]))) (defn join-with-larger [smaller-flow fields1 larger-flow fields2 group-fields aggs & opts] (apply join-with-smaller larger-flow fields2 smaller-flow fields1 opts)) (defn left-join-with-smaller [larger-flow fields1 smaller-flow fields2 aggs & opts] (apply co-group* [larger-flow smaller-flow] [fields1 fields2] (concat opts [:join (LeftJoin.)]))) (defn left-join-with-larger [smaller-flow fields1 larger-flow fields2 aggs & {:as opts}] (apply co-group* [larger-flow smaller-flow] [fields2 fields1] (concat opts [:join (RightJoin.)]))) (defn- cascalog-joiner-type [join] (case join :inner CascalogJoiner$JoinType/INNER :outer CascalogJoiner$JoinType/OUTER :exists CascalogJoiner$JoinType/EXISTS)) (defn join-many "Takes a sequence of [pipe, join-fields, join-type] triplets along with other co-group arguments and performs a mixed join. Allowed join types are :inner, :outer, and :exists." [flow-joins decl-fields options] (let [[flows group-fields join-types] (apply map vector flow-joins) join-types (map cascalog-joiner-type join-types)] (apply co-group* flows group-fields (concat options [:decl-fields decl-fields :join (CascalogJoiner. join-types)])))) (defn hash-join* "Performs a map-side join of flows on join-fields. By default does an inner join, but callers can specify a join type using :join keyword argument, which can be :inner, :outer, or a Cascading Joiner implementation. Note: full or right outer joins have odd behavior in hash joins. See Cascading documentation for details." [flows join-fields & {:keys [join decl-fields] :or {join :inner}}] (safe-assert (= (count flows) (count join-fields)) "Expected same number of flows and join fields") (-> flows ensure-unique-pipes lift-pipes sum (add-op (fn [pipes] (build-join-group HashJoin. pipes join-fields decl-fields join))))) (defn hash-join-with-tiny [larger-flow fields1 tiny-flow fields2] (hash-join* [larger-flow tiny-flow] [fields1 fields2])) (defn left-hash-join-with-tiny [larger-flow fields1 tiny-flow fields2] (hash-join* [larger-flow tiny-flow] [fields1 fields2] :join (LeftJoin.))) (defn hash-join-many "Takes a sequence of [pipe, join-fields, join-type] triplets along with other hash-join arguments and performs a mixed join. Allowed join types are :inner, :outer, and :exists. The first entry must be of join type :inner." [flow-joins decl-fields] (safe-assert (= :inner (-> flow-joins (first) (nth 2))) "First (left-most) flow must be inner joined.") (let [[flows group-fields join-types] (apply map vector flow-joins) join-types (map cascalog-joiner-type join-types)] (hash-join* flows group-fields :decl-fields decl-fields :join (CascalogJoiner. join-types)))) (defn generate-join-fields [numfields numpipes] (repeatedly numpipes (partial v/gen-nullable-vars numfields))) (defn replace-join-fields [join-fields join-renames fields] (let [replace-map (zipmap join-fields join-renames)] (reduce (fn [ret f] (let [newf (-> (replace-map f) (or f))] (conj ret newf))) [] fields))) (defn declared-fields "Accepts a sequence of join fields and a sequence of field-seqs (each containing the join-fields, presumably) and returns a full vector of unique field names, suitable for the return value of a co-group." [join-fields renames infields] (flatten (map (partial replace-join-fields join-fields) renames infields))) (defn join-fields-selector "Returns a selector that's used to go pull out groups from the join that aren't all nil." [num-fields] (serfn/fn [& args] (let [joins (partition num-fields args)] (or (s/find-first (partial s/some? (complement nil?)) joins) (repeat num-fields nil))))) (defn new-pipe-name [joined-seq] (.getName (:pipe (:gen (first joined-seq))))) (defrecord Inner [gen available-fields]) (defrecord Outer [gen available-fields]) (defrecord Existence [gen available-fields out-field]) (defn fields-to-keep "We want to keep the out-field of Existence nodes and all available fields of the Inner and Outer nodes." [gen-seq] (let [grouped (group-by type gen-seq)] (vec (set (concat (mapcat :available-fields (grouped Inner)) (mapcat :available-fields (grouped Outer)) (map :out-field (grouped Existence))))))) (defn ensure-project "Makes sure that the declared fields are in the proper order." [gen-seq] (let [grouped (group-by type gen-seq)] (->> (concat (grouped Inner) (grouped Outer) (grouped Existence)) (map (fn [g] (update-in g [:gen] #(-> % (select* (:available-fields g)) (rename-pipe)))))))) (defn build-triplet [gen join-fields] [(:gen gen) join-fields (condp instance? gen Inner :inner Outer :outer Existence :exists)]) (defn cascalog-join [gen-seq join-fields options] (let [final-name (new-pipe-name gen-seq) gen-seq (ensure-project gen-seq) in-fields (map :available-fields gen-seq) join-size (count join-fields) renames (generate-join-fields join-size (count gen-seq)) declared (declared-fields join-fields renames in-fields) to-keep (fields-to-keep gen-seq) select-exists (fn [joined] (->> (mapcat (fn [g join-renames] (if (instance? Existence g) [[(first join-renames) (:out-field g)]])) gen-seq renames) (reduce (fn [flow [in out]] (-> flow (identity* in out))) joined)))] (-> (join-many (map #(build-triplet % join-fields) gen-seq) declared options) (select-exists) (map* (join-fields-selector join-size) (flatten renames) join-fields) (select* to-keep) (rename-pipe final-name)))) ;; ## MultiGroup (defn multigroup "Take a sequence of pairs of [pipe, join-fields]" [pairs declared-group-vars op out-fields] (safe-assert (seq declared-group-vars) "Cannot do global grouping with multigroup") (let [flows (map (comp generator first) pairs) out-vars (map second pairs) group-vars (apply set/intersection (map set out-vars)) num-vars (reduce + (map count out-vars))] (safe-assert (= (set group-vars) (set declared-group-vars)) "Declared group vars must be same as intersection of vars of all subqueries") (-> flows lift-pipes sum (add-op (fn [pipes] (MultiGroupBy. pipes (casc/fields declared-group-vars) num-vars (ClojureMultibuffer. (casc/fields out-fields) op))))))) ;; ## Output Operations ;; ;; This section covers output and traps (defn lazy-generator "Returns a cascalog generator on the supplied sequence of tuples. `lazy-generator` serializes each item in the lazy sequence into a sequencefile located at the supplied temporary directory and returns a tap for the data in that directory. It's recommended to wrap queries that use this tap with `cascalog.cascading.io/with-fs-tmp`; for example, (with-fs-tmp [_ tmp-dir] (let [lazy-tap (lazy-generator tmp-dir lazy-seq)] (?<- (stdout) [?field1 ?field2 ... etc] (lazy-tap ?field1 ?field2) ...)))" [tmp-path [tuple :as l-seq]] {:pre [(coll? tuple)]} (let [tap (:sink (tap/hfs-seqfile tmp-path)) n-fields (count tuple)] (tap/fill-tap! tap l-seq) (rename* tap (v/gen-nullable-vars n-fields)))) (defn in-branch "Accepts a temporary name and a function from flow => flow and performs the operation within a renamed branch." ([flow f] (in-branch flow (uuid) f)) ([flow name f] (-> flow (rename-pipe name) (f name) (rename-pipe)))) (defn write* [flow sink] (let [sink (to-sink sink)] (-> flow (in-branch (uuid) (fn [subflow name] (-> subflow (update-in [:tails] conj (:pipe subflow)) (update-in [:sink-map] assoc name sink))))))) (defn trap* "Applies a trap to the current branch of the supplied flow." [flow trap] (let [trap (to-sink trap) id (.getIdentifier trap)] (-> flow (rename-pipe id) (update-in [:trap-map] assoc id trap)))) ;; TODO: Figure out if I really understand what's going on with the ;; trap options. Do this by testing the traps with a few throws inside ;; and one after. Make sure the throw after causes a failure, but not ;; inside. ;; ;; TODO: Add "checkpoint" function, injecting a checkpoint pipe. (defn with-trap* "Applies a trap to everything that occurs within the supplied function of flow => flow." [flow trap f] (-> flow (trap* trap) f (rename-pipe))) ;; ## Logic Variable Substitution Rules (defn with-duplicate-inputs "Accepts a flow, some fields, and a function from (flow, unique-fields, new-fields) => flow and appropriately handles duplicate entries inside of the fields. The fields passed to the supplied function will be guaranteed unique. New fields are passed as a third option to the supplying function, which may decide to call (discard* delta) if the fields are still around." [flow from-fields f] (if (or (empty? from-fields) (apply distinct? (collectify from-fields))) (f flow from-fields []) (let [[delta cleaned-fields] (v/replace-dups from-fields)] (-> (reduce (fn [subflow [field gen]] (if (= field gen) subflow (identity* subflow field gen))) flow (map vector from-fields cleaned-fields)) (f cleaned-fields (seq delta)))))) ;; TODO: If we have some sort of ignored variable coming out of a ;; Cascalog query, we want to strip all operations out at that ;; point. Probably when we're building up a generator. (defn substitute-if "Returns [newseq {map of newvals to oldvals}]" [pred subfn aseq] (reduce (fn [[newseq subs] val] (let [[newval sub] (if (pred val) (let [subbed (subfn val)] [subbed {subbed val}]) [val {}])] [(conj newseq newval) (merge subs sub)])) [[] {}] aseq)) (defn constant-substitutions "Returns a 2-vector of the form [new variables, {map of newvars to values to substitute}]" [vars] (substitute-if (complement v/cascalog-var?) (fn [_] (v/gen-nullable-var)) (collectify vars))) (defn insert-subs [flow sub-m] (if (empty? sub-m) flow (apply insert* flow (apply concat sub-m)))) (defn with-constants "Allows constant substitution on inputs." [gen in-fields f] (let [[new-input sub-m] (constant-substitutions in-fields) ignored (keys sub-m) gen (-> (insert-subs gen sub-m) (f new-input))] (if (seq ignored) (discard* gen (fields ignored)) gen))) (defn- replace-ignored-vars "Replaces all ignored variables with a nullable cascalog variable. " [vars] (map (fn [v] (if (= "_" v) (v/gen-nullable-var) v)) (collectify vars))) (defn not-nil? [& xs] (every? (complement nil?) xs)) (defn filter-nullable-vars "If there are any nullable variables present in the output, filter nulls out now." [flow fields] (if-let [non-null-fields (seq (filter v/non-nullable-var? fields))] (filter* flow #'not-nil? non-null-fields) flow)) (defn no-overlap? [large small] (empty? (intersection (set (collectify large)) (set (collectify small))))) ;; The enhance-predicate logic in predicate.clj sort of does this ;;"accept the function, do something around it" logic. (defn logically "Accepts a flow, input fields, output fields and a function that accepts the same things and allows for the following features: Any variables not prefixed with !, !! or ? are treated as constants in the flow. This allows for (map* flow + 10 [\"?a\"] [\"?b\"]) to work properly and clean up its fields without hassle. Any non-nullable output variables (prefixed with ?) are removed from the flow. Duplicate input fields are allowed. It is currently NOT allowed to output one of the input variables. In Cascalog, this triggers an implicit filter; this needs to be supplied at another layer." [gen in-fields out-fields f] {:pre [(no-overlap? out-fields in-fields)]} (let [new-output (replace-ignored-vars out-fields) ignored (difference (set new-output) (set (collectify out-fields)))] (with-constants gen in-fields (fn [gen in] (with-duplicate-inputs gen in (fn [gen in delta] (let [gen (-> gen (f (fields in) (fields new-output))) gen (if-let [to-discard (not-empty (fields (concat delta ignored)))] (discard* gen to-discard) gen)] (filter-nullable-vars gen new-output)))))))) (comment "This one works, since all inputs are logical variables." (-> [1 2 3 4] (rename* "?a") (map* inc "?a" "?other") (logically ["?a" 10 "?other"] "?b" (fn [gen in out] (-> gen (map* * in out)))) (cascalog.cascading.flow/to-memory)) "This one fails, since one of the inputs is interpreted as a constant." (-> [1 2 3 4] (rename* "?a") (map* inc "?a" "other") (logically ["?a" 10 "other"] "?b" (fn [gen in out] (-> gen (map* * in out)))) (to-memory)) "TODO: in logically, we need to start enforcing some rules. no one can push an actual instance of Fields in at this point. It doesn't make sense with these logical rules. We do now have some notion of an assembly -- an assembly is a function from one flow to another. I think we need a typeclass to chain some operation. add-op shouldn't have to take a generator -- it can definitely augment just a pipe, or even another function that's going to modify a pipe (by composition).")
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998119473457336, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
libs/clojurescript/cljs/source_map.cljs
jmshelby/elevatorsaga
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 cljs.source-map (:require [goog.object :as gobj] [clojure.string :as string] [clojure.set :as set] [cljs.source-map.base64-vlq :as base64-vlq])) ;; ============================================================================= ;; Source map code in the file assumes the following in memory ;; representation of source map data. ;; ;; { gline[Integer] ;; { gcol[Integer] ;; [{ :line ..., :col ..., :name ..., :source ... }] } } ;; ;; Reverse source map code in the file assumes the following in memory ;; representation of source map data. ;; ;; { file-name[String] ;; { line[Integer] ;; { col[Integer] ;; [{ :gline ..., :gcol ..., :name ... }] } } ;; ----------------------------------------------------------------------------- ;; Utilities (defn indexed-sources "Take a seq of source file names and return a map from file number to integer index. For reverse source maps." [sources] (->> sources (map-indexed (fn [a b] [a b])) (reduce (fn [m [i v]] (assoc m v i)) {}))) (defn source-compare "Take a seq of source file names and return a comparator that can be used to construct a sorted map. For reverse source maps." [sources] (let [sources (indexed-sources sources)] (fn [a b] (compare (sources a) (sources b))))) ;; ----------------------------------------------------------------------------- ;; Decoding (defn seg->map "Take a source map segment represented as a vector and return a map." [seg source-map] (let [[gcol source line col name] seg] {:gcol gcol :source (aget (gobj/get source-map "sources") source) :line line :col col :name (when-let [name (-> seg meta :name)] (aget (gobj/get source-map "names") name))})) (defn seg-combine "Combine a source map segment vector and a relative source map segment vector and combine them to get an absolute segment posititon information as a vector." [seg relseg] (let [[gcol source line col name] seg [rgcol rsource rline rcol rname] relseg nseg [(+ gcol rgcol) (+ (or source 0) rsource) (+ (or line 0) rline) (+ (or col 0) rcol) (+ (or name 0) rname)]] (if name (with-meta nseg {:name (+ name rname)}) nseg))) (defn update-reverse-result "Helper for decode-reverse. Take a reverse source map and update it with a segment map." [result segmap gline] (let [{:keys [gcol source line col name]} segmap d {:gline gline :gcol gcol} d (if name (assoc d :name name) d)] (update-in result [source] (fnil (fn [m] (update-in m [line] (fnil (fn [m] (update-in m [col] (fnil (fn [v] (conj v d)) []))) (sorted-map)))) (sorted-map))))) (defn decode-reverse "Convert a v3 source map JSON object into a reverse source map mapping original ClojureScript source locations to the generated JavaScript." ([source-map] (decode-reverse (gobj/get source-map "mappings") source-map)) ([mappings source-map] (let [sources (gobj/get source-map "sources") relseg-init [0 0 0 0 0] lines (seq (string/split mappings #";"))] (loop [gline 0 lines lines relseg relseg-init result (sorted-map-by (source-compare sources))] (if lines (let [line (first lines) [result relseg] (if (string/blank? line) [result relseg] (let [segs (seq (string/split line #","))] (loop [segs segs relseg relseg result result] (if segs (let [seg (first segs) nrelseg (seg-combine (base64-vlq/decode seg) relseg)] (recur (next segs) nrelseg (update-reverse-result result (seg->map nrelseg source-map) gline))) [result relseg]))))] (recur (inc gline) (next lines) (assoc relseg 0 0) result)) result))))) (defn update-result "Helper for decode. Take a source map and update it based on a segment map." [result segmap gline] (let [{:keys [gcol source line col name]} segmap d {:line line :col col :source source} d (if name (assoc d :name name) d)] (update-in result [gline] (fnil (fn [m] (update-in m [gcol] (fnil #(conj % d) []))) (sorted-map))))) (defn decode "Convert a v3 source map JSON object into a source map mapping generated JavaScript source locations to the original ClojureScript." ([source-map] (decode (gobj/get source-map "mappings") source-map)) ([mappings source-map] (let [sources (gobj/get source-map "sources") relseg-init [0 0 0 0 0] lines (seq (string/split mappings #";"))] (loop [gline 0 lines lines relseg relseg-init result {}] (if lines (let [line (first lines) [result relseg] (if (string/blank? line) [result relseg] (let [segs (seq (string/split line #","))] (loop [segs segs relseg relseg result result] (if segs (let [seg (first segs) nrelseg (seg-combine (base64-vlq/decode seg) relseg)] (recur (next segs) nrelseg (update-result result (seg->map nrelseg source-map) gline))) [result relseg]))))] (recur (inc gline) (next lines) (assoc relseg 0 0) result)) result))))) ;; ----------------------------------------------------------------------------- ;; Encoding (defn lines->segs "Take a nested sorted map encoding line and column information for a file and return a vector of vectors of encoded segments. Each vector represents a line, and the internal vectors are segments representing the contents of the line." [lines] (let [relseg (atom [0 0 0 0 0])] (reduce (fn [segs cols] (swap! relseg (fn [[_ source line col name]] [0 source line col name])) (conj segs (reduce (fn [cols [gcol sidx line col name :as seg]] (let [offset (map - seg @relseg)] (swap! relseg (fn [[_ _ _ _ lname]] [gcol sidx line col (or name lname)])) (conj cols (base64-vlq/encode offset)))) [] cols))) [] lines))) (defn encode "Take an internal source map representation represented as nested sorted maps of file, line, column and return a source map v3 JSON string." [m opts] (let [lines (atom [[]]) names->idx (atom {}) name-idx (atom 0) preamble-lines (take (or (:preamble-line-count opts) 0) (repeat [])) info->segv (fn [info source-idx line col] (let [segv [(:gcol info) source-idx line col]] (if-let [name (:name info)] (let [idx (if-let [idx (get @names->idx name)] idx (let [cidx @name-idx] (swap! names->idx assoc name cidx) (swap! name-idx inc) cidx))] (conj segv idx)) segv))) encode-cols (fn [infos source-idx line col] (doseq [info infos] (let [segv (info->segv info source-idx line col) gline (:gline info) lc (count @lines)] (if (> gline (dec lc)) (swap! lines (fn [lines] (conj (into lines (repeat (dec (- gline (dec lc))) [])) [segv]))) (swap! lines (fn [lines] (update-in lines [gline] conj segv)))))))] (doseq [[source-idx [_ lines]] (map-indexed (fn [i v] [i v]) m)] (doseq [[line cols] lines] (doseq [[col infos] cols] (encode-cols infos source-idx line col)))) (let [source-map-file-contents (cond-> #js {"version" 3 "file" (:file opts) "sources" (let [paths (keys m) f (comp (if (true? (:source-map-timestamp opts)) #(str % "?rel=" (.valueOf (js/Date.))) identity) #(last (string/split % #"/")))] (->> paths (map f) (into-array))) "lineCount" (:lines opts) "mappings" (->> (lines->segs (concat preamble-lines @lines)) (map #(string/join "," %)) (string/join ";")) "names" (into-array (map (set/map-invert @names->idx) (range (count @names->idx))))} (:sources-content opts) (doto (gobj/set "sourcesContent" (into-array (:sources-content opts)))))] (.stringify js/JSON source-map-file-contents)))) ;; ----------------------------------------------------------------------------- ;; Merging (defn merge-source-maps "Merge an internal source map representation of a single ClojureScript file mapping original to generated with a second source map mapping original JS to generated JS. The is to support source maps that work through multiple compilation steps like Google Closure optimization passes." [cljs-map js-map] (loop [line-map-seq (seq cljs-map) new-lines (sorted-map)] (if line-map-seq (let [[line col-map] (first line-map-seq) new-cols (loop [col-map-seq (seq col-map) new-cols (sorted-map)] (if col-map-seq (let [[col infos] (first col-map-seq)] (recur (next col-map-seq) (assoc new-cols col (reduce (fn [v {:keys [gline gcol]}] (into v (get-in js-map [gline gcol]))) [] infos)))) new-cols))] (recur (next line-map-seq) (assoc new-lines line new-cols))) new-lines))) ;; ----------------------------------------------------------------------------- ;; Reverse Source Map Inversion (defn invert-reverse-map "Given a ClojureScript to JavaScript source map, invert it. Useful when mapping JavaScript stack traces when environment support is unavailable." [reverse-map] (let [inverted (atom (sorted-map))] (doseq [[line columns] reverse-map] (doseq [[column column-info] columns] (doseq [{:keys [gline gcol name]} column-info] (swap! inverted update-in [gline] (fnil (fn [columns] (update-in columns [gcol] (fnil conj []) {:line line :col column :name name})) (sorted-map)))))) @inverted)) (comment (invert-reverse-map {1 {1 [{:gcol 0, :gline 0, :name "cljs.core/map"}], 5 [{:gcol 24, :gline 0, :name "cljs.core/inc"}]}}) )
93999
; 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 cljs.source-map (:require [goog.object :as gobj] [clojure.string :as string] [clojure.set :as set] [cljs.source-map.base64-vlq :as base64-vlq])) ;; ============================================================================= ;; Source map code in the file assumes the following in memory ;; representation of source map data. ;; ;; { gline[Integer] ;; { gcol[Integer] ;; [{ :line ..., :col ..., :name ..., :source ... }] } } ;; ;; Reverse source map code in the file assumes the following in memory ;; representation of source map data. ;; ;; { file-name[String] ;; { line[Integer] ;; { col[Integer] ;; [{ :gline ..., :gcol ..., :name ... }] } } ;; ----------------------------------------------------------------------------- ;; Utilities (defn indexed-sources "Take a seq of source file names and return a map from file number to integer index. For reverse source maps." [sources] (->> sources (map-indexed (fn [a b] [a b])) (reduce (fn [m [i v]] (assoc m v i)) {}))) (defn source-compare "Take a seq of source file names and return a comparator that can be used to construct a sorted map. For reverse source maps." [sources] (let [sources (indexed-sources sources)] (fn [a b] (compare (sources a) (sources b))))) ;; ----------------------------------------------------------------------------- ;; Decoding (defn seg->map "Take a source map segment represented as a vector and return a map." [seg source-map] (let [[gcol source line col name] seg] {:gcol gcol :source (aget (gobj/get source-map "sources") source) :line line :col col :name (when-let [name (-> seg meta :name)] (aget (gobj/get source-map "names") name))})) (defn seg-combine "Combine a source map segment vector and a relative source map segment vector and combine them to get an absolute segment posititon information as a vector." [seg relseg] (let [[gcol source line col name] seg [rgcol rsource rline rcol rname] relseg nseg [(+ gcol rgcol) (+ (or source 0) rsource) (+ (or line 0) rline) (+ (or col 0) rcol) (+ (or name 0) rname)]] (if name (with-meta nseg {:name (+ name rname)}) nseg))) (defn update-reverse-result "Helper for decode-reverse. Take a reverse source map and update it with a segment map." [result segmap gline] (let [{:keys [gcol source line col name]} segmap d {:gline gline :gcol gcol} d (if name (assoc d :name name) d)] (update-in result [source] (fnil (fn [m] (update-in m [line] (fnil (fn [m] (update-in m [col] (fnil (fn [v] (conj v d)) []))) (sorted-map)))) (sorted-map))))) (defn decode-reverse "Convert a v3 source map JSON object into a reverse source map mapping original ClojureScript source locations to the generated JavaScript." ([source-map] (decode-reverse (gobj/get source-map "mappings") source-map)) ([mappings source-map] (let [sources (gobj/get source-map "sources") relseg-init [0 0 0 0 0] lines (seq (string/split mappings #";"))] (loop [gline 0 lines lines relseg relseg-init result (sorted-map-by (source-compare sources))] (if lines (let [line (first lines) [result relseg] (if (string/blank? line) [result relseg] (let [segs (seq (string/split line #","))] (loop [segs segs relseg relseg result result] (if segs (let [seg (first segs) nrelseg (seg-combine (base64-vlq/decode seg) relseg)] (recur (next segs) nrelseg (update-reverse-result result (seg->map nrelseg source-map) gline))) [result relseg]))))] (recur (inc gline) (next lines) (assoc relseg 0 0) result)) result))))) (defn update-result "Helper for decode. Take a source map and update it based on a segment map." [result segmap gline] (let [{:keys [gcol source line col name]} segmap d {:line line :col col :source source} d (if name (assoc d :name name) d)] (update-in result [gline] (fnil (fn [m] (update-in m [gcol] (fnil #(conj % d) []))) (sorted-map))))) (defn decode "Convert a v3 source map JSON object into a source map mapping generated JavaScript source locations to the original ClojureScript." ([source-map] (decode (gobj/get source-map "mappings") source-map)) ([mappings source-map] (let [sources (gobj/get source-map "sources") relseg-init [0 0 0 0 0] lines (seq (string/split mappings #";"))] (loop [gline 0 lines lines relseg relseg-init result {}] (if lines (let [line (first lines) [result relseg] (if (string/blank? line) [result relseg] (let [segs (seq (string/split line #","))] (loop [segs segs relseg relseg result result] (if segs (let [seg (first segs) nrelseg (seg-combine (base64-vlq/decode seg) relseg)] (recur (next segs) nrelseg (update-result result (seg->map nrelseg source-map) gline))) [result relseg]))))] (recur (inc gline) (next lines) (assoc relseg 0 0) result)) result))))) ;; ----------------------------------------------------------------------------- ;; Encoding (defn lines->segs "Take a nested sorted map encoding line and column information for a file and return a vector of vectors of encoded segments. Each vector represents a line, and the internal vectors are segments representing the contents of the line." [lines] (let [relseg (atom [0 0 0 0 0])] (reduce (fn [segs cols] (swap! relseg (fn [[_ source line col name]] [0 source line col name])) (conj segs (reduce (fn [cols [gcol sidx line col name :as seg]] (let [offset (map - seg @relseg)] (swap! relseg (fn [[_ _ _ _ lname]] [gcol sidx line col (or name lname)])) (conj cols (base64-vlq/encode offset)))) [] cols))) [] lines))) (defn encode "Take an internal source map representation represented as nested sorted maps of file, line, column and return a source map v3 JSON string." [m opts] (let [lines (atom [[]]) names->idx (atom {}) name-idx (atom 0) preamble-lines (take (or (:preamble-line-count opts) 0) (repeat [])) info->segv (fn [info source-idx line col] (let [segv [(:gcol info) source-idx line col]] (if-let [name (:name info)] (let [idx (if-let [idx (get @names->idx name)] idx (let [cidx @name-idx] (swap! names->idx assoc name cidx) (swap! name-idx inc) cidx))] (conj segv idx)) segv))) encode-cols (fn [infos source-idx line col] (doseq [info infos] (let [segv (info->segv info source-idx line col) gline (:gline info) lc (count @lines)] (if (> gline (dec lc)) (swap! lines (fn [lines] (conj (into lines (repeat (dec (- gline (dec lc))) [])) [segv]))) (swap! lines (fn [lines] (update-in lines [gline] conj segv)))))))] (doseq [[source-idx [_ lines]] (map-indexed (fn [i v] [i v]) m)] (doseq [[line cols] lines] (doseq [[col infos] cols] (encode-cols infos source-idx line col)))) (let [source-map-file-contents (cond-> #js {"version" 3 "file" (:file opts) "sources" (let [paths (keys m) f (comp (if (true? (:source-map-timestamp opts)) #(str % "?rel=" (.valueOf (js/Date.))) identity) #(last (string/split % #"/")))] (->> paths (map f) (into-array))) "lineCount" (:lines opts) "mappings" (->> (lines->segs (concat preamble-lines @lines)) (map #(string/join "," %)) (string/join ";")) "names" (into-array (map (set/map-invert @names->idx) (range (count @names->idx))))} (:sources-content opts) (doto (gobj/set "sourcesContent" (into-array (:sources-content opts)))))] (.stringify js/JSON source-map-file-contents)))) ;; ----------------------------------------------------------------------------- ;; Merging (defn merge-source-maps "Merge an internal source map representation of a single ClojureScript file mapping original to generated with a second source map mapping original JS to generated JS. The is to support source maps that work through multiple compilation steps like Google Closure optimization passes." [cljs-map js-map] (loop [line-map-seq (seq cljs-map) new-lines (sorted-map)] (if line-map-seq (let [[line col-map] (first line-map-seq) new-cols (loop [col-map-seq (seq col-map) new-cols (sorted-map)] (if col-map-seq (let [[col infos] (first col-map-seq)] (recur (next col-map-seq) (assoc new-cols col (reduce (fn [v {:keys [gline gcol]}] (into v (get-in js-map [gline gcol]))) [] infos)))) new-cols))] (recur (next line-map-seq) (assoc new-lines line new-cols))) new-lines))) ;; ----------------------------------------------------------------------------- ;; Reverse Source Map Inversion (defn invert-reverse-map "Given a ClojureScript to JavaScript source map, invert it. Useful when mapping JavaScript stack traces when environment support is unavailable." [reverse-map] (let [inverted (atom (sorted-map))] (doseq [[line columns] reverse-map] (doseq [[column column-info] columns] (doseq [{:keys [gline gcol name]} column-info] (swap! inverted update-in [gline] (fnil (fn [columns] (update-in columns [gcol] (fnil conj []) {:line line :col column :name name})) (sorted-map)))))) @inverted)) (comment (invert-reverse-map {1 {1 [{:gcol 0, :gline 0, :name "cljs.core/map"}], 5 [{:gcol 24, :gline 0, :name "cljs.core/inc"}]}}) )
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 cljs.source-map (:require [goog.object :as gobj] [clojure.string :as string] [clojure.set :as set] [cljs.source-map.base64-vlq :as base64-vlq])) ;; ============================================================================= ;; Source map code in the file assumes the following in memory ;; representation of source map data. ;; ;; { gline[Integer] ;; { gcol[Integer] ;; [{ :line ..., :col ..., :name ..., :source ... }] } } ;; ;; Reverse source map code in the file assumes the following in memory ;; representation of source map data. ;; ;; { file-name[String] ;; { line[Integer] ;; { col[Integer] ;; [{ :gline ..., :gcol ..., :name ... }] } } ;; ----------------------------------------------------------------------------- ;; Utilities (defn indexed-sources "Take a seq of source file names and return a map from file number to integer index. For reverse source maps." [sources] (->> sources (map-indexed (fn [a b] [a b])) (reduce (fn [m [i v]] (assoc m v i)) {}))) (defn source-compare "Take a seq of source file names and return a comparator that can be used to construct a sorted map. For reverse source maps." [sources] (let [sources (indexed-sources sources)] (fn [a b] (compare (sources a) (sources b))))) ;; ----------------------------------------------------------------------------- ;; Decoding (defn seg->map "Take a source map segment represented as a vector and return a map." [seg source-map] (let [[gcol source line col name] seg] {:gcol gcol :source (aget (gobj/get source-map "sources") source) :line line :col col :name (when-let [name (-> seg meta :name)] (aget (gobj/get source-map "names") name))})) (defn seg-combine "Combine a source map segment vector and a relative source map segment vector and combine them to get an absolute segment posititon information as a vector." [seg relseg] (let [[gcol source line col name] seg [rgcol rsource rline rcol rname] relseg nseg [(+ gcol rgcol) (+ (or source 0) rsource) (+ (or line 0) rline) (+ (or col 0) rcol) (+ (or name 0) rname)]] (if name (with-meta nseg {:name (+ name rname)}) nseg))) (defn update-reverse-result "Helper for decode-reverse. Take a reverse source map and update it with a segment map." [result segmap gline] (let [{:keys [gcol source line col name]} segmap d {:gline gline :gcol gcol} d (if name (assoc d :name name) d)] (update-in result [source] (fnil (fn [m] (update-in m [line] (fnil (fn [m] (update-in m [col] (fnil (fn [v] (conj v d)) []))) (sorted-map)))) (sorted-map))))) (defn decode-reverse "Convert a v3 source map JSON object into a reverse source map mapping original ClojureScript source locations to the generated JavaScript." ([source-map] (decode-reverse (gobj/get source-map "mappings") source-map)) ([mappings source-map] (let [sources (gobj/get source-map "sources") relseg-init [0 0 0 0 0] lines (seq (string/split mappings #";"))] (loop [gline 0 lines lines relseg relseg-init result (sorted-map-by (source-compare sources))] (if lines (let [line (first lines) [result relseg] (if (string/blank? line) [result relseg] (let [segs (seq (string/split line #","))] (loop [segs segs relseg relseg result result] (if segs (let [seg (first segs) nrelseg (seg-combine (base64-vlq/decode seg) relseg)] (recur (next segs) nrelseg (update-reverse-result result (seg->map nrelseg source-map) gline))) [result relseg]))))] (recur (inc gline) (next lines) (assoc relseg 0 0) result)) result))))) (defn update-result "Helper for decode. Take a source map and update it based on a segment map." [result segmap gline] (let [{:keys [gcol source line col name]} segmap d {:line line :col col :source source} d (if name (assoc d :name name) d)] (update-in result [gline] (fnil (fn [m] (update-in m [gcol] (fnil #(conj % d) []))) (sorted-map))))) (defn decode "Convert a v3 source map JSON object into a source map mapping generated JavaScript source locations to the original ClojureScript." ([source-map] (decode (gobj/get source-map "mappings") source-map)) ([mappings source-map] (let [sources (gobj/get source-map "sources") relseg-init [0 0 0 0 0] lines (seq (string/split mappings #";"))] (loop [gline 0 lines lines relseg relseg-init result {}] (if lines (let [line (first lines) [result relseg] (if (string/blank? line) [result relseg] (let [segs (seq (string/split line #","))] (loop [segs segs relseg relseg result result] (if segs (let [seg (first segs) nrelseg (seg-combine (base64-vlq/decode seg) relseg)] (recur (next segs) nrelseg (update-result result (seg->map nrelseg source-map) gline))) [result relseg]))))] (recur (inc gline) (next lines) (assoc relseg 0 0) result)) result))))) ;; ----------------------------------------------------------------------------- ;; Encoding (defn lines->segs "Take a nested sorted map encoding line and column information for a file and return a vector of vectors of encoded segments. Each vector represents a line, and the internal vectors are segments representing the contents of the line." [lines] (let [relseg (atom [0 0 0 0 0])] (reduce (fn [segs cols] (swap! relseg (fn [[_ source line col name]] [0 source line col name])) (conj segs (reduce (fn [cols [gcol sidx line col name :as seg]] (let [offset (map - seg @relseg)] (swap! relseg (fn [[_ _ _ _ lname]] [gcol sidx line col (or name lname)])) (conj cols (base64-vlq/encode offset)))) [] cols))) [] lines))) (defn encode "Take an internal source map representation represented as nested sorted maps of file, line, column and return a source map v3 JSON string." [m opts] (let [lines (atom [[]]) names->idx (atom {}) name-idx (atom 0) preamble-lines (take (or (:preamble-line-count opts) 0) (repeat [])) info->segv (fn [info source-idx line col] (let [segv [(:gcol info) source-idx line col]] (if-let [name (:name info)] (let [idx (if-let [idx (get @names->idx name)] idx (let [cidx @name-idx] (swap! names->idx assoc name cidx) (swap! name-idx inc) cidx))] (conj segv idx)) segv))) encode-cols (fn [infos source-idx line col] (doseq [info infos] (let [segv (info->segv info source-idx line col) gline (:gline info) lc (count @lines)] (if (> gline (dec lc)) (swap! lines (fn [lines] (conj (into lines (repeat (dec (- gline (dec lc))) [])) [segv]))) (swap! lines (fn [lines] (update-in lines [gline] conj segv)))))))] (doseq [[source-idx [_ lines]] (map-indexed (fn [i v] [i v]) m)] (doseq [[line cols] lines] (doseq [[col infos] cols] (encode-cols infos source-idx line col)))) (let [source-map-file-contents (cond-> #js {"version" 3 "file" (:file opts) "sources" (let [paths (keys m) f (comp (if (true? (:source-map-timestamp opts)) #(str % "?rel=" (.valueOf (js/Date.))) identity) #(last (string/split % #"/")))] (->> paths (map f) (into-array))) "lineCount" (:lines opts) "mappings" (->> (lines->segs (concat preamble-lines @lines)) (map #(string/join "," %)) (string/join ";")) "names" (into-array (map (set/map-invert @names->idx) (range (count @names->idx))))} (:sources-content opts) (doto (gobj/set "sourcesContent" (into-array (:sources-content opts)))))] (.stringify js/JSON source-map-file-contents)))) ;; ----------------------------------------------------------------------------- ;; Merging (defn merge-source-maps "Merge an internal source map representation of a single ClojureScript file mapping original to generated with a second source map mapping original JS to generated JS. The is to support source maps that work through multiple compilation steps like Google Closure optimization passes." [cljs-map js-map] (loop [line-map-seq (seq cljs-map) new-lines (sorted-map)] (if line-map-seq (let [[line col-map] (first line-map-seq) new-cols (loop [col-map-seq (seq col-map) new-cols (sorted-map)] (if col-map-seq (let [[col infos] (first col-map-seq)] (recur (next col-map-seq) (assoc new-cols col (reduce (fn [v {:keys [gline gcol]}] (into v (get-in js-map [gline gcol]))) [] infos)))) new-cols))] (recur (next line-map-seq) (assoc new-lines line new-cols))) new-lines))) ;; ----------------------------------------------------------------------------- ;; Reverse Source Map Inversion (defn invert-reverse-map "Given a ClojureScript to JavaScript source map, invert it. Useful when mapping JavaScript stack traces when environment support is unavailable." [reverse-map] (let [inverted (atom (sorted-map))] (doseq [[line columns] reverse-map] (doseq [[column column-info] columns] (doseq [{:keys [gline gcol name]} column-info] (swap! inverted update-in [gline] (fnil (fn [columns] (update-in columns [gcol] (fnil conj []) {:line line :col column :name name})) (sorted-map)))))) @inverted)) (comment (invert-reverse-map {1 {1 [{:gcol 0, :gline 0, :name "cljs.core/map"}], 5 [{:gcol 24, :gline 0, :name "cljs.core/inc"}]}}) )
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.twisty.codec\n\n ", "end": 597, "score": 0.9998577237129211, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/twisty/codec.clj
llnek/crypto
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.twisty.codec "Password Encoders & Decoders." (:require [clojure.string :as cs] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.basal.core :as c]) (:import [org.bouncycastle.crypto.params DESedeParameters KeyParameter] [org.bouncycastle.crypto.paddings PaddedBufferedBlockCipher] [java.security.spec PKCS8EncodedKeySpec X509EncodedKeySpec] [org.bouncycastle.crypto.generators DESedeKeyGenerator] [org.jasypt.encryption.pbe StandardPBEStringEncryptor] [org.bouncycastle.crypto KeyGenerationParameters] [org.apache.commons.codec.binary Base64] [javax.crypto.spec SecretKeySpec] [org.jasypt.util.text StrongTextEncryptor] [java.io ByteArrayOutputStream] [java.security Key KeyFactory SecureRandom] [javax.crypto Cipher] [org.mindrot.jbcrypt BCrypt] [org.bouncycastle.crypto.engines BlowfishEngine AESEngine RSAEngine DESedeEngine] [org.bouncycastle.crypto.modes CBCBlockCipher])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;; AES (128,256) ;; DES (8) ;; DESede (TripleDES - 8 x 3 = 24bytes -> 192 bits) ;; RSA 1024 + ;; Blowfish ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DO NOT change this string as it is used by the caesar.js. Make sure ;; you change both the front-end and back-end version of this string! (c/def- ^{:tag "[C"} VISCHS (i/x->chars (str " @N/\\Ri2}aP`(xeT4F3mt;8~%r0v:L5$+Z{'V)\"CKIc>z.*" "fJEwSU7juYg<klO&1?[h9=n,yoQGsW]BMHpXb6A|D#q^_d!-"))) (c/def- ^{:tag "[C"} CKEY (i/x->chars "ed8xwl2XukYfdgR2aAddrg0lqzQjFhbs")) (c/def- VISCHS-LEN (alength VISCHS)) (c/def- s-ascii-chars (-> (str "abcdefghijklmnopqrstuvqxyz1234567890" "-_ABCDEFGHIJKLMNOPQRSTUVWXYZ") u/shuffle i/x->chars)) (c/def- s-pwd-chars (-> (str "abcdefghijklmnopqrstuvqxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "`1234567890-_~!@#$%^&*()") u/shuffle i/x->chars)) (c/def- ^String pwd-pfx "crypt:") (c/def- pwd-pfxlen 6) (c/def- CZERO (char-array 0)) ;; default javax supports this ;; TripleDES (c/def- ^String t3-des "DESede") (c/def- ^String c-algo t3-des) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Cryptor (cr-algo [_] "Encryption algorithm used") (decrypt [_ pvkey data] "Decrypt some data") (encrypt [_ pukey data] "Encrypt some data")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- ensure-key-size "Key has enough bits?" ^bytes [^bytes kee algo] (let [bits (* 8 (alength kee))] (if (and (< bits 192) (c/eq? t3-des algo)) ;; 8x 3 = 24 bytes (u/throw-BadArg "TripleDES key length must be 192.")) (if (and (< bits 128) (c/eq? "AES" algo)) (u/throw-BadArg "AES key length must be 128 or 256.")) ;ok kee)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- key->bits "Sanitize the key, maybe chop length." ^bytes [^bytes pwd algo] (let [blen (alength pwd) bits (* 8 blen)] (cond (c/eq? "AES" algo) (cond (> bits 256) ;; 32 bytes (c/vargs Byte/TYPE (take 32 pwd)) ;; 128 => 16 bytes (and (> bits 128) (< bits 256)) (c/vargs Byte/TYPE (take 16 pwd)) :else pwd) (= algo t3-des) (if (> blen 24) ;; 24 bytes (c/vargs Byte/TYPE (take 24 pwd)) pwd) :else pwd))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; caesar cipher (c/defmacro- ident-ch "Get a character." [pos] `(aget VISCHS (int ~pos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- locate-ch "Locate a character." ^Integer [ch] (or (some #(if (= ^Character ch (aget VISCHS %1)) %1) (range VISCHS-LEN)) -1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slide-forward [delta cpos] (let [ptr (+ cpos delta)] (-> (if (>= ptr VISCHS-LEN) (- ptr VISCHS-LEN) ptr) ident-ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slide-back [delta cpos] (let [ptr (- cpos delta)] (-> (if (neg? ptr) (+ VISCHS-LEN ptr) ptr) ident-ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- shiftenc [shift delta cpos] (if (neg? shift) (slide-forward delta cpos) (slide-back delta cpos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- shiftdec [shift delta cpos] (if (neg? shift) (slide-back delta cpos) (slide-forward delta cpos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- caesar-amap-expr ^Character [^chars ca pos shiftFunc] (let [ch (aget ca pos) p (locate-ch ch)] (if (neg? p) ch (shiftFunc p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn caesar<> "Encrypt by character rotation." {:arglists '([])} [] (let [F (fn [shiftpos text func'] (if (or (c/nichts? text) (c/szero? shiftpos)) text (let [delta (mod (Math/abs (int shiftpos)) VISCHS-LEN) pf (partial func' shiftpos delta) ca (i/x->chars text)] (i/x->str (amap ca pos ret (caesar-amap-expr ca pos pf))))))] (reify Cryptor (encrypt [_ shiftpos text] (F shiftpos text shiftenc)) (cr-algo [_] "caesar") (decrypt [_ shiftpos text] (F shiftpos text shiftdec))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn jasypt<> "A Cryptor using Jasypt's implementation." {:arglists '([])} [] (let [F #(doto (StrongTextEncryptor.) (.setPasswordCharArray (i/x->chars %1)))] (reify Cryptor (cr-algo [_] "PBEWithMD5AndTripleDES") (decrypt [_ pkey data] (.decrypt ^StrongTextEncryptor (F pkey) (i/x->str data))) (encrypt [_ pkey data] (.encrypt ^StrongTextEncryptor (F pkey) (i/x->str data)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; java cryptor (defn- get-cipher ^Cipher [pkey mode ^String algo] (doto (Cipher/getInstance algo) (.init (int mode) (SecretKeySpec. (key->bits pkey algo) algo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- java-codec ^bytes [pkey data ^Cipher c] (when-some [p (i/x->bytes data)] (let [plen (alength p) baos (i/baos<>) out (byte-array (max c/BUF-SZ (.getOutputSize c plen))) n (.update c p 0 plen out 0)] (if (pos? n) (.write baos out 0 n)) (let [n2 (.doFinal c out 0)] (if (pos? n2) (.write baos out 0 n2))) (i/x->bytes baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- jcryptor-impl [pkey data algo mode] `(when ~data (c/test-cond "pkey != bytes" (bytes? ~pkey)) (ensure-key-size ~pkey ~algo) (java-codec ~pkey ~data (get-cipher ~pkey ~mode ~algo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn jcrypt<> "A Cryptor using Java's implementation." {:arglists '([])} [] (reify Cryptor ;;PBEWithMD5AndDES (decrypt [me pkey cipher] (jcryptor-impl pkey cipher (cr-algo me) Cipher/DECRYPT_MODE)) (cr-algo [_] t3-des) (encrypt [me pkey clear] (jcryptor-impl pkey clear (cr-algo me) Cipher/ENCRYPT_MODE)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn asym<> "A Cryptor using 1024 - 2048 bits RSA." {:arglists '([])} [] (reify Cryptor (cr-algo [_] "RSA/ECB/PKCS1Padding") (encrypt [me pubKey data] (when data (let [k (i/x->bytes pubKey) pk (-> (KeyFactory/getInstance "RSA") (.generatePublic (X509EncodedKeySpec. k))) cipher (doto (Cipher/getInstance (cr-algo me)) (.init Cipher/ENCRYPT_MODE ^Key pk))] (.doFinal cipher (i/x->bytes data))))) (decrypt [me prvKey data] (when data (let [k (i/x->bytes prvKey) pk (-> (KeyFactory/getInstance "RSA") (.generatePrivate (PKCS8EncodedKeySpec. k))) cipher (doto (Cipher/getInstance (cr-algo me)) (.init Cipher/DECRYPT_MODE ^Key pk))] (.doFinal cipher (i/x->bytes data))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BC cryptor (defn- bc-xxx ^bytes [pkey data algo mode] (when data (ensure-key-size pkey algo) (let [eng (condp = algo "Blowfish" (BlowfishEngine.) "DESede" (DESedeEngine.) "AES" (AESEngine.) "RSA" (RSAEngine.) (c/test-cond "no crypto engine" false)) cipher (doto (-> eng CBCBlockCipher. PaddedBufferedBlockCipher.) (.init mode (KeyParameter. (key->bits pkey algo)))) out (byte-array c/BUF-SZ) p (i/x->bytes data) baos (i/baos<>) c (.processBytes cipher p 0 (alength p) out 0)] (if (pos? c) (.write baos out 0 c)) (let [c2 (.doFinal cipher out 0)] (if (pos? c2) (.write baos out 0 c2))) (i/x->bytes baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bcastle<> "A Cryptor using BouncyCastle's implementation." {:arglists '([])} [] (reify Cryptor (encrypt [me pkey clear] (bc-xxx pkey clear (cr-algo me) true)) (cr-algo [_] t3-des) (decrypt [me pkey cipher] (bc-xxx pkey cipher (cr-algo me) false)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; passwords (defn- create-xxx ^String [^chars chArray len] (let [b Integer/MAX_VALUE r (u/rand<>) alen (alength chArray)] (cond (zero? len) "" (neg? len) nil :else (i/x->str (amap (char-array len) pos ret (aget chArray (mod (.nextInt r b) alen))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Password (strongly-hashed [_] "Get (string) hash value") (is-hash-valid? [_ targetHashed] "Check to match") (stringify [_] "Get as string") (hashed [_] "Get hash value") (pw-encoded [_] "Get encoded value") (pw-text [_] "Get clear text value")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- mkpwd [pwd pkey] (let [_pwd (i/x->chars pwd) _pkey (i/x->chars pkey)] (reify Password (strongly-hashed [me] (if-not (empty? _pwd) (->> (BCrypt/gensalt 12) (BCrypt/hashpw (stringify me))) "")) (hashed [me] (if-not (empty? _pwd) (->> (BCrypt/gensalt 10) (BCrypt/hashpw (stringify me))) "")) (is-hash-valid? [me pwdHashed] (BCrypt/checkpw (stringify me) pwdHashed)) (stringify [me] (i/x->str (pw-text me))) (pw-text [_] _pwd) (pw-encoded [me] (cond (nil? _pwd) nil (empty? _pwd) CZERO :else (i/x->chars (str pwd-pfx (encrypt (jasypt<>) _pkey (stringify me))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pwd<> "Create a password object." {:arglists '([pwd] [pwd pkey])} ([pwd] (pwd<> pwd nil)) ([pwd pkey] (let [s (i/x->str pwd) pk (i/x->chars (or pkey CKEY))] (if-not (some-> s (cs/starts-with? pwd-pfx)) (mkpwd pwd pk) (mkpwd (decrypt (jasypt<>) pk (subs s pwd-pfxlen)) pk))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn random-str "Generate random text." {:tag String :arglists '([len])} [len] (create-xxx s-ascii-chars len)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strong-pwd<> "Generate a strong password." {:arglists '([len])} [len] (pwd<> (i/x->chars (create-xxx s-pwd-chars len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
65070
;; 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.twisty.codec "Password Encoders & Decoders." (:require [clojure.string :as cs] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.basal.core :as c]) (:import [org.bouncycastle.crypto.params DESedeParameters KeyParameter] [org.bouncycastle.crypto.paddings PaddedBufferedBlockCipher] [java.security.spec PKCS8EncodedKeySpec X509EncodedKeySpec] [org.bouncycastle.crypto.generators DESedeKeyGenerator] [org.jasypt.encryption.pbe StandardPBEStringEncryptor] [org.bouncycastle.crypto KeyGenerationParameters] [org.apache.commons.codec.binary Base64] [javax.crypto.spec SecretKeySpec] [org.jasypt.util.text StrongTextEncryptor] [java.io ByteArrayOutputStream] [java.security Key KeyFactory SecureRandom] [javax.crypto Cipher] [org.mindrot.jbcrypt BCrypt] [org.bouncycastle.crypto.engines BlowfishEngine AESEngine RSAEngine DESedeEngine] [org.bouncycastle.crypto.modes CBCBlockCipher])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;; AES (128,256) ;; DES (8) ;; DESede (TripleDES - 8 x 3 = 24bytes -> 192 bits) ;; RSA 1024 + ;; Blowfish ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DO NOT change this string as it is used by the caesar.js. Make sure ;; you change both the front-end and back-end version of this string! (c/def- ^{:tag "[C"} VISCHS (i/x->chars (str " @N/\\Ri2}aP`(xeT4F3mt;8~%r0v:L5$+Z{'V)\"CKIc>z.*" "fJEwSU7juYg<klO&1?[h9=n,yoQGsW]BMHpXb6A|D#q^_d!-"))) (c/def- ^{:tag "[C"} CKEY (i/x->chars "ed8xwl2XukYfdgR2aAddrg0lqzQjFhbs")) (c/def- VISCHS-LEN (alength VISCHS)) (c/def- s-ascii-chars (-> (str "abcdefghijklmnopqrstuvqxyz1234567890" "-_ABCDEFGHIJKLMNOPQRSTUVWXYZ") u/shuffle i/x->chars)) (c/def- s-pwd-chars (-> (str "abcdefghijklmnopqrstuvqxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "`1234567890-_~!@#$%^&*()") u/shuffle i/x->chars)) (c/def- ^String pwd-pfx "crypt:") (c/def- pwd-pfxlen 6) (c/def- CZERO (char-array 0)) ;; default javax supports this ;; TripleDES (c/def- ^String t3-des "DESede") (c/def- ^String c-algo t3-des) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Cryptor (cr-algo [_] "Encryption algorithm used") (decrypt [_ pvkey data] "Decrypt some data") (encrypt [_ pukey data] "Encrypt some data")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- ensure-key-size "Key has enough bits?" ^bytes [^bytes kee algo] (let [bits (* 8 (alength kee))] (if (and (< bits 192) (c/eq? t3-des algo)) ;; 8x 3 = 24 bytes (u/throw-BadArg "TripleDES key length must be 192.")) (if (and (< bits 128) (c/eq? "AES" algo)) (u/throw-BadArg "AES key length must be 128 or 256.")) ;ok kee)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- key->bits "Sanitize the key, maybe chop length." ^bytes [^bytes pwd algo] (let [blen (alength pwd) bits (* 8 blen)] (cond (c/eq? "AES" algo) (cond (> bits 256) ;; 32 bytes (c/vargs Byte/TYPE (take 32 pwd)) ;; 128 => 16 bytes (and (> bits 128) (< bits 256)) (c/vargs Byte/TYPE (take 16 pwd)) :else pwd) (= algo t3-des) (if (> blen 24) ;; 24 bytes (c/vargs Byte/TYPE (take 24 pwd)) pwd) :else pwd))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; caesar cipher (c/defmacro- ident-ch "Get a character." [pos] `(aget VISCHS (int ~pos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- locate-ch "Locate a character." ^Integer [ch] (or (some #(if (= ^Character ch (aget VISCHS %1)) %1) (range VISCHS-LEN)) -1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slide-forward [delta cpos] (let [ptr (+ cpos delta)] (-> (if (>= ptr VISCHS-LEN) (- ptr VISCHS-LEN) ptr) ident-ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slide-back [delta cpos] (let [ptr (- cpos delta)] (-> (if (neg? ptr) (+ VISCHS-LEN ptr) ptr) ident-ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- shiftenc [shift delta cpos] (if (neg? shift) (slide-forward delta cpos) (slide-back delta cpos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- shiftdec [shift delta cpos] (if (neg? shift) (slide-back delta cpos) (slide-forward delta cpos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- caesar-amap-expr ^Character [^chars ca pos shiftFunc] (let [ch (aget ca pos) p (locate-ch ch)] (if (neg? p) ch (shiftFunc p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn caesar<> "Encrypt by character rotation." {:arglists '([])} [] (let [F (fn [shiftpos text func'] (if (or (c/nichts? text) (c/szero? shiftpos)) text (let [delta (mod (Math/abs (int shiftpos)) VISCHS-LEN) pf (partial func' shiftpos delta) ca (i/x->chars text)] (i/x->str (amap ca pos ret (caesar-amap-expr ca pos pf))))))] (reify Cryptor (encrypt [_ shiftpos text] (F shiftpos text shiftenc)) (cr-algo [_] "caesar") (decrypt [_ shiftpos text] (F shiftpos text shiftdec))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn jasypt<> "A Cryptor using Jasypt's implementation." {:arglists '([])} [] (let [F #(doto (StrongTextEncryptor.) (.setPasswordCharArray (i/x->chars %1)))] (reify Cryptor (cr-algo [_] "PBEWithMD5AndTripleDES") (decrypt [_ pkey data] (.decrypt ^StrongTextEncryptor (F pkey) (i/x->str data))) (encrypt [_ pkey data] (.encrypt ^StrongTextEncryptor (F pkey) (i/x->str data)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; java cryptor (defn- get-cipher ^Cipher [pkey mode ^String algo] (doto (Cipher/getInstance algo) (.init (int mode) (SecretKeySpec. (key->bits pkey algo) algo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- java-codec ^bytes [pkey data ^Cipher c] (when-some [p (i/x->bytes data)] (let [plen (alength p) baos (i/baos<>) out (byte-array (max c/BUF-SZ (.getOutputSize c plen))) n (.update c p 0 plen out 0)] (if (pos? n) (.write baos out 0 n)) (let [n2 (.doFinal c out 0)] (if (pos? n2) (.write baos out 0 n2))) (i/x->bytes baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- jcryptor-impl [pkey data algo mode] `(when ~data (c/test-cond "pkey != bytes" (bytes? ~pkey)) (ensure-key-size ~pkey ~algo) (java-codec ~pkey ~data (get-cipher ~pkey ~mode ~algo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn jcrypt<> "A Cryptor using Java's implementation." {:arglists '([])} [] (reify Cryptor ;;PBEWithMD5AndDES (decrypt [me pkey cipher] (jcryptor-impl pkey cipher (cr-algo me) Cipher/DECRYPT_MODE)) (cr-algo [_] t3-des) (encrypt [me pkey clear] (jcryptor-impl pkey clear (cr-algo me) Cipher/ENCRYPT_MODE)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn asym<> "A Cryptor using 1024 - 2048 bits RSA." {:arglists '([])} [] (reify Cryptor (cr-algo [_] "RSA/ECB/PKCS1Padding") (encrypt [me pubKey data] (when data (let [k (i/x->bytes pubKey) pk (-> (KeyFactory/getInstance "RSA") (.generatePublic (X509EncodedKeySpec. k))) cipher (doto (Cipher/getInstance (cr-algo me)) (.init Cipher/ENCRYPT_MODE ^Key pk))] (.doFinal cipher (i/x->bytes data))))) (decrypt [me prvKey data] (when data (let [k (i/x->bytes prvKey) pk (-> (KeyFactory/getInstance "RSA") (.generatePrivate (PKCS8EncodedKeySpec. k))) cipher (doto (Cipher/getInstance (cr-algo me)) (.init Cipher/DECRYPT_MODE ^Key pk))] (.doFinal cipher (i/x->bytes data))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BC cryptor (defn- bc-xxx ^bytes [pkey data algo mode] (when data (ensure-key-size pkey algo) (let [eng (condp = algo "Blowfish" (BlowfishEngine.) "DESede" (DESedeEngine.) "AES" (AESEngine.) "RSA" (RSAEngine.) (c/test-cond "no crypto engine" false)) cipher (doto (-> eng CBCBlockCipher. PaddedBufferedBlockCipher.) (.init mode (KeyParameter. (key->bits pkey algo)))) out (byte-array c/BUF-SZ) p (i/x->bytes data) baos (i/baos<>) c (.processBytes cipher p 0 (alength p) out 0)] (if (pos? c) (.write baos out 0 c)) (let [c2 (.doFinal cipher out 0)] (if (pos? c2) (.write baos out 0 c2))) (i/x->bytes baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bcastle<> "A Cryptor using BouncyCastle's implementation." {:arglists '([])} [] (reify Cryptor (encrypt [me pkey clear] (bc-xxx pkey clear (cr-algo me) true)) (cr-algo [_] t3-des) (decrypt [me pkey cipher] (bc-xxx pkey cipher (cr-algo me) false)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; passwords (defn- create-xxx ^String [^chars chArray len] (let [b Integer/MAX_VALUE r (u/rand<>) alen (alength chArray)] (cond (zero? len) "" (neg? len) nil :else (i/x->str (amap (char-array len) pos ret (aget chArray (mod (.nextInt r b) alen))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Password (strongly-hashed [_] "Get (string) hash value") (is-hash-valid? [_ targetHashed] "Check to match") (stringify [_] "Get as string") (hashed [_] "Get hash value") (pw-encoded [_] "Get encoded value") (pw-text [_] "Get clear text value")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- mkpwd [pwd pkey] (let [_pwd (i/x->chars pwd) _pkey (i/x->chars pkey)] (reify Password (strongly-hashed [me] (if-not (empty? _pwd) (->> (BCrypt/gensalt 12) (BCrypt/hashpw (stringify me))) "")) (hashed [me] (if-not (empty? _pwd) (->> (BCrypt/gensalt 10) (BCrypt/hashpw (stringify me))) "")) (is-hash-valid? [me pwdHashed] (BCrypt/checkpw (stringify me) pwdHashed)) (stringify [me] (i/x->str (pw-text me))) (pw-text [_] _pwd) (pw-encoded [me] (cond (nil? _pwd) nil (empty? _pwd) CZERO :else (i/x->chars (str pwd-pfx (encrypt (jasypt<>) _pkey (stringify me))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pwd<> "Create a password object." {:arglists '([pwd] [pwd pkey])} ([pwd] (pwd<> pwd nil)) ([pwd pkey] (let [s (i/x->str pwd) pk (i/x->chars (or pkey CKEY))] (if-not (some-> s (cs/starts-with? pwd-pfx)) (mkpwd pwd pk) (mkpwd (decrypt (jasypt<>) pk (subs s pwd-pfxlen)) pk))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn random-str "Generate random text." {:tag String :arglists '([len])} [len] (create-xxx s-ascii-chars len)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strong-pwd<> "Generate a strong password." {:arglists '([len])} [len] (pwd<> (i/x->chars (create-xxx s-pwd-chars len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;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.twisty.codec "Password Encoders & Decoders." (:require [clojure.string :as cs] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.basal.core :as c]) (:import [org.bouncycastle.crypto.params DESedeParameters KeyParameter] [org.bouncycastle.crypto.paddings PaddedBufferedBlockCipher] [java.security.spec PKCS8EncodedKeySpec X509EncodedKeySpec] [org.bouncycastle.crypto.generators DESedeKeyGenerator] [org.jasypt.encryption.pbe StandardPBEStringEncryptor] [org.bouncycastle.crypto KeyGenerationParameters] [org.apache.commons.codec.binary Base64] [javax.crypto.spec SecretKeySpec] [org.jasypt.util.text StrongTextEncryptor] [java.io ByteArrayOutputStream] [java.security Key KeyFactory SecureRandom] [javax.crypto Cipher] [org.mindrot.jbcrypt BCrypt] [org.bouncycastle.crypto.engines BlowfishEngine AESEngine RSAEngine DESedeEngine] [org.bouncycastle.crypto.modes CBCBlockCipher])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;; AES (128,256) ;; DES (8) ;; DESede (TripleDES - 8 x 3 = 24bytes -> 192 bits) ;; RSA 1024 + ;; Blowfish ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DO NOT change this string as it is used by the caesar.js. Make sure ;; you change both the front-end and back-end version of this string! (c/def- ^{:tag "[C"} VISCHS (i/x->chars (str " @N/\\Ri2}aP`(xeT4F3mt;8~%r0v:L5$+Z{'V)\"CKIc>z.*" "fJEwSU7juYg<klO&1?[h9=n,yoQGsW]BMHpXb6A|D#q^_d!-"))) (c/def- ^{:tag "[C"} CKEY (i/x->chars "ed8xwl2XukYfdgR2aAddrg0lqzQjFhbs")) (c/def- VISCHS-LEN (alength VISCHS)) (c/def- s-ascii-chars (-> (str "abcdefghijklmnopqrstuvqxyz1234567890" "-_ABCDEFGHIJKLMNOPQRSTUVWXYZ") u/shuffle i/x->chars)) (c/def- s-pwd-chars (-> (str "abcdefghijklmnopqrstuvqxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "`1234567890-_~!@#$%^&*()") u/shuffle i/x->chars)) (c/def- ^String pwd-pfx "crypt:") (c/def- pwd-pfxlen 6) (c/def- CZERO (char-array 0)) ;; default javax supports this ;; TripleDES (c/def- ^String t3-des "DESede") (c/def- ^String c-algo t3-des) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Cryptor (cr-algo [_] "Encryption algorithm used") (decrypt [_ pvkey data] "Decrypt some data") (encrypt [_ pukey data] "Encrypt some data")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- ensure-key-size "Key has enough bits?" ^bytes [^bytes kee algo] (let [bits (* 8 (alength kee))] (if (and (< bits 192) (c/eq? t3-des algo)) ;; 8x 3 = 24 bytes (u/throw-BadArg "TripleDES key length must be 192.")) (if (and (< bits 128) (c/eq? "AES" algo)) (u/throw-BadArg "AES key length must be 128 or 256.")) ;ok kee)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- key->bits "Sanitize the key, maybe chop length." ^bytes [^bytes pwd algo] (let [blen (alength pwd) bits (* 8 blen)] (cond (c/eq? "AES" algo) (cond (> bits 256) ;; 32 bytes (c/vargs Byte/TYPE (take 32 pwd)) ;; 128 => 16 bytes (and (> bits 128) (< bits 256)) (c/vargs Byte/TYPE (take 16 pwd)) :else pwd) (= algo t3-des) (if (> blen 24) ;; 24 bytes (c/vargs Byte/TYPE (take 24 pwd)) pwd) :else pwd))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; caesar cipher (c/defmacro- ident-ch "Get a character." [pos] `(aget VISCHS (int ~pos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- locate-ch "Locate a character." ^Integer [ch] (or (some #(if (= ^Character ch (aget VISCHS %1)) %1) (range VISCHS-LEN)) -1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slide-forward [delta cpos] (let [ptr (+ cpos delta)] (-> (if (>= ptr VISCHS-LEN) (- ptr VISCHS-LEN) ptr) ident-ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slide-back [delta cpos] (let [ptr (- cpos delta)] (-> (if (neg? ptr) (+ VISCHS-LEN ptr) ptr) ident-ch))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- shiftenc [shift delta cpos] (if (neg? shift) (slide-forward delta cpos) (slide-back delta cpos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- shiftdec [shift delta cpos] (if (neg? shift) (slide-back delta cpos) (slide-forward delta cpos))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- caesar-amap-expr ^Character [^chars ca pos shiftFunc] (let [ch (aget ca pos) p (locate-ch ch)] (if (neg? p) ch (shiftFunc p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn caesar<> "Encrypt by character rotation." {:arglists '([])} [] (let [F (fn [shiftpos text func'] (if (or (c/nichts? text) (c/szero? shiftpos)) text (let [delta (mod (Math/abs (int shiftpos)) VISCHS-LEN) pf (partial func' shiftpos delta) ca (i/x->chars text)] (i/x->str (amap ca pos ret (caesar-amap-expr ca pos pf))))))] (reify Cryptor (encrypt [_ shiftpos text] (F shiftpos text shiftenc)) (cr-algo [_] "caesar") (decrypt [_ shiftpos text] (F shiftpos text shiftdec))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn jasypt<> "A Cryptor using Jasypt's implementation." {:arglists '([])} [] (let [F #(doto (StrongTextEncryptor.) (.setPasswordCharArray (i/x->chars %1)))] (reify Cryptor (cr-algo [_] "PBEWithMD5AndTripleDES") (decrypt [_ pkey data] (.decrypt ^StrongTextEncryptor (F pkey) (i/x->str data))) (encrypt [_ pkey data] (.encrypt ^StrongTextEncryptor (F pkey) (i/x->str data)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; java cryptor (defn- get-cipher ^Cipher [pkey mode ^String algo] (doto (Cipher/getInstance algo) (.init (int mode) (SecretKeySpec. (key->bits pkey algo) algo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- java-codec ^bytes [pkey data ^Cipher c] (when-some [p (i/x->bytes data)] (let [plen (alength p) baos (i/baos<>) out (byte-array (max c/BUF-SZ (.getOutputSize c plen))) n (.update c p 0 plen out 0)] (if (pos? n) (.write baos out 0 n)) (let [n2 (.doFinal c out 0)] (if (pos? n2) (.write baos out 0 n2))) (i/x->bytes baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- jcryptor-impl [pkey data algo mode] `(when ~data (c/test-cond "pkey != bytes" (bytes? ~pkey)) (ensure-key-size ~pkey ~algo) (java-codec ~pkey ~data (get-cipher ~pkey ~mode ~algo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn jcrypt<> "A Cryptor using Java's implementation." {:arglists '([])} [] (reify Cryptor ;;PBEWithMD5AndDES (decrypt [me pkey cipher] (jcryptor-impl pkey cipher (cr-algo me) Cipher/DECRYPT_MODE)) (cr-algo [_] t3-des) (encrypt [me pkey clear] (jcryptor-impl pkey clear (cr-algo me) Cipher/ENCRYPT_MODE)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn asym<> "A Cryptor using 1024 - 2048 bits RSA." {:arglists '([])} [] (reify Cryptor (cr-algo [_] "RSA/ECB/PKCS1Padding") (encrypt [me pubKey data] (when data (let [k (i/x->bytes pubKey) pk (-> (KeyFactory/getInstance "RSA") (.generatePublic (X509EncodedKeySpec. k))) cipher (doto (Cipher/getInstance (cr-algo me)) (.init Cipher/ENCRYPT_MODE ^Key pk))] (.doFinal cipher (i/x->bytes data))))) (decrypt [me prvKey data] (when data (let [k (i/x->bytes prvKey) pk (-> (KeyFactory/getInstance "RSA") (.generatePrivate (PKCS8EncodedKeySpec. k))) cipher (doto (Cipher/getInstance (cr-algo me)) (.init Cipher/DECRYPT_MODE ^Key pk))] (.doFinal cipher (i/x->bytes data))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BC cryptor (defn- bc-xxx ^bytes [pkey data algo mode] (when data (ensure-key-size pkey algo) (let [eng (condp = algo "Blowfish" (BlowfishEngine.) "DESede" (DESedeEngine.) "AES" (AESEngine.) "RSA" (RSAEngine.) (c/test-cond "no crypto engine" false)) cipher (doto (-> eng CBCBlockCipher. PaddedBufferedBlockCipher.) (.init mode (KeyParameter. (key->bits pkey algo)))) out (byte-array c/BUF-SZ) p (i/x->bytes data) baos (i/baos<>) c (.processBytes cipher p 0 (alength p) out 0)] (if (pos? c) (.write baos out 0 c)) (let [c2 (.doFinal cipher out 0)] (if (pos? c2) (.write baos out 0 c2))) (i/x->bytes baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bcastle<> "A Cryptor using BouncyCastle's implementation." {:arglists '([])} [] (reify Cryptor (encrypt [me pkey clear] (bc-xxx pkey clear (cr-algo me) true)) (cr-algo [_] t3-des) (decrypt [me pkey cipher] (bc-xxx pkey cipher (cr-algo me) false)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; passwords (defn- create-xxx ^String [^chars chArray len] (let [b Integer/MAX_VALUE r (u/rand<>) alen (alength chArray)] (cond (zero? len) "" (neg? len) nil :else (i/x->str (amap (char-array len) pos ret (aget chArray (mod (.nextInt r b) alen))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol Password (strongly-hashed [_] "Get (string) hash value") (is-hash-valid? [_ targetHashed] "Check to match") (stringify [_] "Get as string") (hashed [_] "Get hash value") (pw-encoded [_] "Get encoded value") (pw-text [_] "Get clear text value")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- mkpwd [pwd pkey] (let [_pwd (i/x->chars pwd) _pkey (i/x->chars pkey)] (reify Password (strongly-hashed [me] (if-not (empty? _pwd) (->> (BCrypt/gensalt 12) (BCrypt/hashpw (stringify me))) "")) (hashed [me] (if-not (empty? _pwd) (->> (BCrypt/gensalt 10) (BCrypt/hashpw (stringify me))) "")) (is-hash-valid? [me pwdHashed] (BCrypt/checkpw (stringify me) pwdHashed)) (stringify [me] (i/x->str (pw-text me))) (pw-text [_] _pwd) (pw-encoded [me] (cond (nil? _pwd) nil (empty? _pwd) CZERO :else (i/x->chars (str pwd-pfx (encrypt (jasypt<>) _pkey (stringify me))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pwd<> "Create a password object." {:arglists '([pwd] [pwd pkey])} ([pwd] (pwd<> pwd nil)) ([pwd pkey] (let [s (i/x->str pwd) pk (i/x->chars (or pkey CKEY))] (if-not (some-> s (cs/starts-with? pwd-pfx)) (mkpwd pwd pk) (mkpwd (decrypt (jasypt<>) pk (subs s pwd-pfxlen)) pk))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn random-str "Generate random text." {:tag String :arglists '([len])} [len] (create-xxx s-ascii-chars len)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn strong-pwd<> "Generate a strong password." {:arglists '([len])} [len] (pwd<> (i/x->chars (create-xxx s-pwd-chars len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; ", "end": 31, "score": 0.9998766779899597, "start": 19, "tag": "NAME", "value": "Di Sera Luca" }, { "context": " Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; https://github.com/diseraluc", "end": 74, "score": 0.9999309182167053, "start": 53, "tag": "EMAIL", "value": "disera.luca@gmail.com" }, { "context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/", "end": 125, "score": 0.9996949434280396, "start": 115, "tag": "USERNAME", "value": "diseraluca" }, { "context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License", "end": 197, "score": 0.999532163143158, "start": 175, "tag": "USERNAME", "value": "luca-di-sera-200023167" } ]
pmal/test/pmal/backend/packages/packagemanagers/core_test.clj
diseraluca/pmal
0
;; Copyright 2020, Di Sera Luca ;; Contacts: disera.luca@gmail.com ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.backend.packages.packagemanagers.core-test (:require [clojure.test :refer :all] [pmal.backend.packages.packagemanagers.core :as pkgmanager] [pmal.backend.packages.packagemanagers.dpkg :as dpkg] [pmal.backend.packages.packagemanagers.pacman :as pacman] [mock.core :refer :all]) (:import (pmal.backend.packages.packagemanagers.dpkg dpkg)) (:import (pmal.backend.packages.packagemanagers.pacman pacman))) (deftest test-package-manager (do-with-mock (mock #'dpkg/available? (fn [] true)) (is (instance? dpkg (pkgmanager/package-manager ::pkgmanager/dpkg)) "Calling package-manager with the dpkg keyword returns a dpkg instance, when it is available.")) (do-with-mock (mock #'dpkg/available? (fn [] false)) (is (nil? (pkgmanager/package-manager ::pkgmanager/dpkg)) "Calling package-manager with the dpkg keyword returns nil when dpkg is not available.")) (do-with-mock (mock #'pacman/available? (fn [] true)) (is (instance? pacman (pkgmanager/package-manager ::pkgmanager/pacman)) "Calling package-manager with the pacman keyword returns a pacman instance, when it is available.")) (do-with-mock (mock #'pacman/available? (fn [] false)) (is (nil? (pkgmanager/package-manager ::pkgmanager/pacman)) "Calling package-manager with the pacman keyword returns nil when pacman is not available.")) (is (= nil (pkgmanager/package-manager :uknown-value)) "Calling package-manager with an unknown package manager keyword will return nil."))
63836
;; Copyright 2020, <NAME> ;; Contacts: <EMAIL> ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.backend.packages.packagemanagers.core-test (:require [clojure.test :refer :all] [pmal.backend.packages.packagemanagers.core :as pkgmanager] [pmal.backend.packages.packagemanagers.dpkg :as dpkg] [pmal.backend.packages.packagemanagers.pacman :as pacman] [mock.core :refer :all]) (:import (pmal.backend.packages.packagemanagers.dpkg dpkg)) (:import (pmal.backend.packages.packagemanagers.pacman pacman))) (deftest test-package-manager (do-with-mock (mock #'dpkg/available? (fn [] true)) (is (instance? dpkg (pkgmanager/package-manager ::pkgmanager/dpkg)) "Calling package-manager with the dpkg keyword returns a dpkg instance, when it is available.")) (do-with-mock (mock #'dpkg/available? (fn [] false)) (is (nil? (pkgmanager/package-manager ::pkgmanager/dpkg)) "Calling package-manager with the dpkg keyword returns nil when dpkg is not available.")) (do-with-mock (mock #'pacman/available? (fn [] true)) (is (instance? pacman (pkgmanager/package-manager ::pkgmanager/pacman)) "Calling package-manager with the pacman keyword returns a pacman instance, when it is available.")) (do-with-mock (mock #'pacman/available? (fn [] false)) (is (nil? (pkgmanager/package-manager ::pkgmanager/pacman)) "Calling package-manager with the pacman keyword returns nil when pacman is not available.")) (is (= nil (pkgmanager/package-manager :uknown-value)) "Calling package-manager with an unknown package manager keyword will return nil."))
true
;; Copyright 2020, PI:NAME:<NAME>END_PI ;; Contacts: PI:EMAIL:<EMAIL>END_PI ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.backend.packages.packagemanagers.core-test (:require [clojure.test :refer :all] [pmal.backend.packages.packagemanagers.core :as pkgmanager] [pmal.backend.packages.packagemanagers.dpkg :as dpkg] [pmal.backend.packages.packagemanagers.pacman :as pacman] [mock.core :refer :all]) (:import (pmal.backend.packages.packagemanagers.dpkg dpkg)) (:import (pmal.backend.packages.packagemanagers.pacman pacman))) (deftest test-package-manager (do-with-mock (mock #'dpkg/available? (fn [] true)) (is (instance? dpkg (pkgmanager/package-manager ::pkgmanager/dpkg)) "Calling package-manager with the dpkg keyword returns a dpkg instance, when it is available.")) (do-with-mock (mock #'dpkg/available? (fn [] false)) (is (nil? (pkgmanager/package-manager ::pkgmanager/dpkg)) "Calling package-manager with the dpkg keyword returns nil when dpkg is not available.")) (do-with-mock (mock #'pacman/available? (fn [] true)) (is (instance? pacman (pkgmanager/package-manager ::pkgmanager/pacman)) "Calling package-manager with the pacman keyword returns a pacman instance, when it is available.")) (do-with-mock (mock #'pacman/available? (fn [] false)) (is (nil? (pkgmanager/package-manager ::pkgmanager/pacman)) "Calling package-manager with the pacman keyword returns nil when pacman is not available.")) (is (= nil (pkgmanager/package-manager :uknown-value)) "Calling package-manager with an unknown package manager keyword will return nil."))
[ { "context": "(api-call :post \"/api/invitations/create\" {:name \"Katherine Johnson\"\n ", "end": 954, "score": 0.9995953440666199, "start": 937, "tag": "NAME", "value": "Katherine Johnson" }, { "context": " :email \"katherine.johnson@nasa.gov\"\n ", "end": 1050, "score": 0.9998987317085266, "start": 1024, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "key+ \"owner\"))]\n (is (= {:invitation/name \"Katherine Johnson\"\n :invitation/email \"katherine.joh", "end": 1877, "score": 0.9998880624771118, "start": 1860, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "erine Johnson\"\n :invitation/email \"katherine.johnson@nasa.gov\"\n :invitation/invited-by {:email \"", "end": 1940, "score": 0.9999237060546875, "start": 1914, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "\"\n :invitation/invited-by {:email \"owner@example.com\"\n :userid ", "end": 2007, "score": 0.9999189376831055, "start": 1990, "tag": "EMAIL", "value": "owner@example.com" }, { "context": "\n :userid \"owner\"\n :name \"O", "end": 2063, "score": 0.9748914837837219, "start": 2058, "tag": "USERNAME", "value": "owner" }, { "context": "))))\n (test-helpers/create-user! {:eppn \"katherine\" :mail \"katherine.johnson@nasa.gov\" :commonName \"", "end": 3103, "score": 0.7275133728981018, "start": 3094, "tag": "USERNAME", "value": "katherine" }, { "context": "st-helpers/create-user! {:eppn \"katherine\" :mail \"katherine.johnson@nasa.gov\" :commonName \"Katherine Johnson\"})\n\n (le", "end": 3138, "score": 0.9999168515205383, "start": 3112, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "\" :mail \"katherine.johnson@nasa.gov\" :commonName \"Katherine Johnson\"})\n\n (let [accepted-invitation (first (a", "end": 3170, "score": 0.999886155128479, "start": 3153, "tag": "NAME", "value": "Katherine Johnson" }, { "context": " \"owner\"))]\n (is (= {:invitation/name \"Katherine Johnson\"\n :invitation/email \"katherine", "end": 3347, "score": 0.9998852610588074, "start": 3330, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "e Johnson\"\n :invitation/email \"katherine.johnson@nasa.gov\"\n :invitation/invited-by {:ema", "end": 3414, "score": 0.9999244809150696, "start": 3388, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": " :invitation/invited-by {:email \"owner@example.com\"\n :use", "end": 3485, "score": 0.9999181628227234, "start": 3468, "tag": "EMAIL", "value": "owner@example.com" }, { "context": " :userid \"owner\"\n :nam", "end": 3545, "score": 0.974898636341095, "start": 3540, "tag": "USERNAME", "value": "owner" }, { "context": " :invitation/invited-user {:email \"katherine.johnson@nasa.gov\"\n :u", "end": 3686, "score": 0.9999262690544128, "start": 3660, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": " :userid \"katherine\"\n :n", "end": 3752, "score": 0.9992172718048096, "start": 3743, "tag": "USERNAME", "value": "katherine" }, { "context": " :name \"Katherine Johnson\"}\n :invitation/workflow {:work", "end": 3824, "score": 0.9998930096626282, "start": 3807, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "42\" \"owner\")\n (test-helpers/create-user! {:eppn \"katherine\" :mail \"katherine.johnson@nasa.gov\" :commonName \"", "end": 4560, "score": 0.9702991843223572, "start": 4551, "tag": "USERNAME", "value": "katherine" }, { "context": "st-helpers/create-user! {:eppn \"katherine\" :mail \"katherine.johnson@nasa.gov\" :commonName \"Katherine Johnson\"})\n (let [workfl", "end": 4595, "score": 0.999914288520813, "start": 4569, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "\" :mail \"katherine.johnson@nasa.gov\" :commonName \"Katherine Johnson\"})\n (let [workflow-id (test-helpers/create-workf", "end": 4627, "score": 0.9998811483383179, "start": 4610, "tag": "NAME", "value": "Katherine Johnson" }, { "context": " :name \"Katherine Johnson\"\n ", "end": 4979, "score": 0.9998717308044434, "start": 4962, "tag": "NAME", "value": "Katherine Johnson" }, { "context": " :email \"katherine.johnson@nasa.gov\"\n ", "end": 5087, "score": 0.9999087452888489, "start": 5061, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "ate\"\n {:name \"Katherine Johnson\"\n :email \"ka", "end": 5680, "score": 0.9998635053634644, "start": 5663, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "on\"\n :email \"katherine.johnson@nasa.gov\"\n :workflow-", "end": 5754, "score": 0.9999111294746399, "start": 5728, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "ate\"\n {:name \"Katherine Johnson\"\n :email \"ka", "end": 6400, "score": 0.999886155128479, "start": 6383, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "on\"\n :email \"katherine.johnson@nasa.gov\"\n :workflow-", "end": 6474, "score": 0.9999195337295532, "start": 6448, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "ate\"\n {:name \"Katherine Johnson\"\n :email \"ka", "end": 6879, "score": 0.9998834729194641, "start": 6862, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "on\"\n :email \"katherine.johnson@nasa.gov\"\n :workflow-", "end": 6953, "score": 0.9999217987060547, "start": 6927, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "api/invitations/create\"\n {:name \"Katherine Johnson\"\n :email \"katherine.johnson@nas", "end": 7316, "score": 0.9998832941055298, "start": 7299, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "me \"Katherine Johnson\"\n :email \"katherine.johnson@nasa.gov\"\n :workflow-id workflow-id}\n ", "end": 7371, "score": 0.9999139904975891, "start": 7345, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" }, { "context": "api/invitations/create\"\n {:name \"Katherine Johnson\"\n :email \"katherine.johnson@nas", "end": 7592, "score": 0.9998689889907837, "start": 7575, "tag": "NAME", "value": "Katherine Johnson" }, { "context": "me \"Katherine Johnson\"\n :email \"katherine.johnson@nasa.gov\"\n :workflow-id workflow-id}\n ", "end": 7647, "score": 0.9999216794967651, "start": 7621, "tag": "EMAIL", "value": "katherine.johnson@nasa.gov" } ]
test/clj/rems/api/test_invitations.clj
tjb/rems
31
(ns ^:integration rems.api.test-invitations (:require [clojure.test :refer :all] [rems.api.services.invitation :as invitation] [rems.api.testing :refer :all] [rems.db.applications] [rems.db.test-data :as test-data] [rems.db.test-data-helpers :as test-helpers] [rems.json] [rems.testing-util :refer [with-user]] [ring.mock.request :refer :all])) (use-fixtures :each api-fixture ;; TODO should this fixture have a name? (fn [f] (test-data/create-test-api-key!) (test-data/create-test-users-and-roles!) (f))) (deftest test-invitation-flow (let [workflow-id (test-helpers/create-workflow! {})] (testing "before invitation" (is (= [] (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner")))) (testing "create invitation" (let [body (api-call :post "/api/invitations/create" {:name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id} test-data/+test-api-key+ "owner")] (is (= {:success true} (dissoc body :invitation/id))))) (testing "after invitation" (is (= [] (api-call :get "/api/invitations?sent=false" nil test-data/+test-api-key+ "owner")) "invitation has already been sent") (is (= [] (api-call :get "/api/invitations?accepted=true" nil test-data/+test-api-key+ "owner")) "invitation has not been accepted") (let [invitation (first (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner")) invitation2 (first (api-call :get "/api/invitations?sent=true" nil test-data/+test-api-key+ "owner"))] (is (= {:invitation/name "Katherine Johnson" :invitation/email "katherine.johnson@nasa.gov" :invitation/invited-by {:email "owner@example.com" :userid "owner" :name "Owner"} :invitation/workflow {:workflow/id workflow-id}} (dissoc invitation :invitation/id ; always different from sequence :invitation/created ; should be checked in service :invitation/sent) (dissoc invitation2 :invitation/id ; always different from sequence :invitation/created ; should be checked in service :invitation/sent))) ; should be checked in service (testing "accepting" (let [token (:invitation/token (invitation/get-invitation-full (:invitation/id invitation)))] ; not available in API (is (= {:success true :invitation/workflow {:workflow/id workflow-id}} (api-call :post "/api/invitations/accept-invitation" {:token token} test-data/+test-api-key+ "katherine")))) (test-helpers/create-user! {:eppn "katherine" :mail "katherine.johnson@nasa.gov" :commonName "Katherine Johnson"}) (let [accepted-invitation (first (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner"))] (is (= {:invitation/name "Katherine Johnson" :invitation/email "katherine.johnson@nasa.gov" :invitation/invited-by {:email "owner@example.com" :userid "owner" :name "Owner"} :invitation/invited-user {:email "katherine.johnson@nasa.gov" :userid "katherine" :name "Katherine Johnson"} :invitation/workflow {:workflow/id workflow-id}} (dissoc accepted-invitation :invitation/id :invitation/created :invitation/sent :invitation/accepted))))))))) (deftest test-invitations-api-security (api-call :post "/api/organizations/create" {:organization/id "test-organization" :organization/name {:fi "Testiorganisaatio" :en "Test Organization"} :organization/short-name {:fi "ORG" :en "ORG"} :organization/owners [{:userid "organization-owner2"}] :organization/review-emails []} "42" "owner") (test-helpers/create-user! {:eppn "katherine" :mail "katherine.johnson@nasa.gov" :commonName "Katherine Johnson"}) (let [workflow-id (test-helpers/create-workflow! {:organization {:organization/id "test-organization"}}) invitation-id (:invitation/id (with-user "owner" (invitation/create-invitation! {:userid "owner" :name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id}))) token (:invitation/token (with-user "owner" (invitation/get-invitation-full invitation-id)))] (testing "without authentication" (testing "list" (let [response (api-response :get "/api/invitations")] (is (response-is-unauthorized? response)) (is (= "unauthorized" (read-body response))))) (testing "create" (let [response (api-response :post "/api/invitations/create" {:name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id})] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response))))) (testing "accept-invitation" (let [response (api-response :post (str "/api/invitations/accept-invitation?token=" token) nil)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "create" (testing "without owner role" (let [response (api-response :post "/api/invitations/create" {:name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id} "42" "alice")] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response))))) (testing "for an owner of wrong organization" (let [response (api-response :post "/api/invitations/create" {:name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id} "42" "organization-owner1")] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response))))) (testing "given owner role" (api-call :post "/api/invitations/create" {:name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id} "42" "owner")) (testing "given organization-owner role" (api-call :post "/api/invitations/create" {:name "Katherine Johnson" :email "katherine.johnson@nasa.gov" :workflow-id workflow-id} "42" "organization-owner2"))) (testing "accept-invitation" (let [response (api-response :post (str "/api/invitations/accept-invitation?token=" token) nil "42" "katherine")] (is (response-is-ok? response))))))
30171
(ns ^:integration rems.api.test-invitations (:require [clojure.test :refer :all] [rems.api.services.invitation :as invitation] [rems.api.testing :refer :all] [rems.db.applications] [rems.db.test-data :as test-data] [rems.db.test-data-helpers :as test-helpers] [rems.json] [rems.testing-util :refer [with-user]] [ring.mock.request :refer :all])) (use-fixtures :each api-fixture ;; TODO should this fixture have a name? (fn [f] (test-data/create-test-api-key!) (test-data/create-test-users-and-roles!) (f))) (deftest test-invitation-flow (let [workflow-id (test-helpers/create-workflow! {})] (testing "before invitation" (is (= [] (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner")))) (testing "create invitation" (let [body (api-call :post "/api/invitations/create" {:name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id} test-data/+test-api-key+ "owner")] (is (= {:success true} (dissoc body :invitation/id))))) (testing "after invitation" (is (= [] (api-call :get "/api/invitations?sent=false" nil test-data/+test-api-key+ "owner")) "invitation has already been sent") (is (= [] (api-call :get "/api/invitations?accepted=true" nil test-data/+test-api-key+ "owner")) "invitation has not been accepted") (let [invitation (first (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner")) invitation2 (first (api-call :get "/api/invitations?sent=true" nil test-data/+test-api-key+ "owner"))] (is (= {:invitation/name "<NAME>" :invitation/email "<EMAIL>" :invitation/invited-by {:email "<EMAIL>" :userid "owner" :name "Owner"} :invitation/workflow {:workflow/id workflow-id}} (dissoc invitation :invitation/id ; always different from sequence :invitation/created ; should be checked in service :invitation/sent) (dissoc invitation2 :invitation/id ; always different from sequence :invitation/created ; should be checked in service :invitation/sent))) ; should be checked in service (testing "accepting" (let [token (:invitation/token (invitation/get-invitation-full (:invitation/id invitation)))] ; not available in API (is (= {:success true :invitation/workflow {:workflow/id workflow-id}} (api-call :post "/api/invitations/accept-invitation" {:token token} test-data/+test-api-key+ "katherine")))) (test-helpers/create-user! {:eppn "katherine" :mail "<EMAIL>" :commonName "<NAME>"}) (let [accepted-invitation (first (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner"))] (is (= {:invitation/name "<NAME>" :invitation/email "<EMAIL>" :invitation/invited-by {:email "<EMAIL>" :userid "owner" :name "Owner"} :invitation/invited-user {:email "<EMAIL>" :userid "katherine" :name "<NAME>"} :invitation/workflow {:workflow/id workflow-id}} (dissoc accepted-invitation :invitation/id :invitation/created :invitation/sent :invitation/accepted))))))))) (deftest test-invitations-api-security (api-call :post "/api/organizations/create" {:organization/id "test-organization" :organization/name {:fi "Testiorganisaatio" :en "Test Organization"} :organization/short-name {:fi "ORG" :en "ORG"} :organization/owners [{:userid "organization-owner2"}] :organization/review-emails []} "42" "owner") (test-helpers/create-user! {:eppn "katherine" :mail "<EMAIL>" :commonName "<NAME>"}) (let [workflow-id (test-helpers/create-workflow! {:organization {:organization/id "test-organization"}}) invitation-id (:invitation/id (with-user "owner" (invitation/create-invitation! {:userid "owner" :name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id}))) token (:invitation/token (with-user "owner" (invitation/get-invitation-full invitation-id)))] (testing "without authentication" (testing "list" (let [response (api-response :get "/api/invitations")] (is (response-is-unauthorized? response)) (is (= "unauthorized" (read-body response))))) (testing "create" (let [response (api-response :post "/api/invitations/create" {:name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id})] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response))))) (testing "accept-invitation" (let [response (api-response :post (str "/api/invitations/accept-invitation?token=" token) nil)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "create" (testing "without owner role" (let [response (api-response :post "/api/invitations/create" {:name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id} "42" "alice")] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response))))) (testing "for an owner of wrong organization" (let [response (api-response :post "/api/invitations/create" {:name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id} "42" "organization-owner1")] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response))))) (testing "given owner role" (api-call :post "/api/invitations/create" {:name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id} "42" "owner")) (testing "given organization-owner role" (api-call :post "/api/invitations/create" {:name "<NAME>" :email "<EMAIL>" :workflow-id workflow-id} "42" "organization-owner2"))) (testing "accept-invitation" (let [response (api-response :post (str "/api/invitations/accept-invitation?token=" token) nil "42" "katherine")] (is (response-is-ok? response))))))
true
(ns ^:integration rems.api.test-invitations (:require [clojure.test :refer :all] [rems.api.services.invitation :as invitation] [rems.api.testing :refer :all] [rems.db.applications] [rems.db.test-data :as test-data] [rems.db.test-data-helpers :as test-helpers] [rems.json] [rems.testing-util :refer [with-user]] [ring.mock.request :refer :all])) (use-fixtures :each api-fixture ;; TODO should this fixture have a name? (fn [f] (test-data/create-test-api-key!) (test-data/create-test-users-and-roles!) (f))) (deftest test-invitation-flow (let [workflow-id (test-helpers/create-workflow! {})] (testing "before invitation" (is (= [] (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner")))) (testing "create invitation" (let [body (api-call :post "/api/invitations/create" {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id} test-data/+test-api-key+ "owner")] (is (= {:success true} (dissoc body :invitation/id))))) (testing "after invitation" (is (= [] (api-call :get "/api/invitations?sent=false" nil test-data/+test-api-key+ "owner")) "invitation has already been sent") (is (= [] (api-call :get "/api/invitations?accepted=true" nil test-data/+test-api-key+ "owner")) "invitation has not been accepted") (let [invitation (first (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner")) invitation2 (first (api-call :get "/api/invitations?sent=true" nil test-data/+test-api-key+ "owner"))] (is (= {:invitation/name "PI:NAME:<NAME>END_PI" :invitation/email "PI:EMAIL:<EMAIL>END_PI" :invitation/invited-by {:email "PI:EMAIL:<EMAIL>END_PI" :userid "owner" :name "Owner"} :invitation/workflow {:workflow/id workflow-id}} (dissoc invitation :invitation/id ; always different from sequence :invitation/created ; should be checked in service :invitation/sent) (dissoc invitation2 :invitation/id ; always different from sequence :invitation/created ; should be checked in service :invitation/sent))) ; should be checked in service (testing "accepting" (let [token (:invitation/token (invitation/get-invitation-full (:invitation/id invitation)))] ; not available in API (is (= {:success true :invitation/workflow {:workflow/id workflow-id}} (api-call :post "/api/invitations/accept-invitation" {:token token} test-data/+test-api-key+ "katherine")))) (test-helpers/create-user! {:eppn "katherine" :mail "PI:EMAIL:<EMAIL>END_PI" :commonName "PI:NAME:<NAME>END_PI"}) (let [accepted-invitation (first (api-call :get "/api/invitations" nil test-data/+test-api-key+ "owner"))] (is (= {:invitation/name "PI:NAME:<NAME>END_PI" :invitation/email "PI:EMAIL:<EMAIL>END_PI" :invitation/invited-by {:email "PI:EMAIL:<EMAIL>END_PI" :userid "owner" :name "Owner"} :invitation/invited-user {:email "PI:EMAIL:<EMAIL>END_PI" :userid "katherine" :name "PI:NAME:<NAME>END_PI"} :invitation/workflow {:workflow/id workflow-id}} (dissoc accepted-invitation :invitation/id :invitation/created :invitation/sent :invitation/accepted))))))))) (deftest test-invitations-api-security (api-call :post "/api/organizations/create" {:organization/id "test-organization" :organization/name {:fi "Testiorganisaatio" :en "Test Organization"} :organization/short-name {:fi "ORG" :en "ORG"} :organization/owners [{:userid "organization-owner2"}] :organization/review-emails []} "42" "owner") (test-helpers/create-user! {:eppn "katherine" :mail "PI:EMAIL:<EMAIL>END_PI" :commonName "PI:NAME:<NAME>END_PI"}) (let [workflow-id (test-helpers/create-workflow! {:organization {:organization/id "test-organization"}}) invitation-id (:invitation/id (with-user "owner" (invitation/create-invitation! {:userid "owner" :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id}))) token (:invitation/token (with-user "owner" (invitation/get-invitation-full invitation-id)))] (testing "without authentication" (testing "list" (let [response (api-response :get "/api/invitations")] (is (response-is-unauthorized? response)) (is (= "unauthorized" (read-body response))))) (testing "create" (let [response (api-response :post "/api/invitations/create" {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id})] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response))))) (testing "accept-invitation" (let [response (api-response :post (str "/api/invitations/accept-invitation?token=" token) nil)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "create" (testing "without owner role" (let [response (api-response :post "/api/invitations/create" {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id} "42" "alice")] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response))))) (testing "for an owner of wrong organization" (let [response (api-response :post "/api/invitations/create" {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id} "42" "organization-owner1")] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response))))) (testing "given owner role" (api-call :post "/api/invitations/create" {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id} "42" "owner")) (testing "given organization-owner role" (api-call :post "/api/invitations/create" {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :workflow-id workflow-id} "42" "organization-owner2"))) (testing "accept-invitation" (let [response (api-response :post (str "/api/invitations/accept-invitation?token=" token) nil "42" "katherine")] (is (response-is-ok? response))))))
[ { "context": " to closest xterm-256 colour.\n;;;;\n;;;; Written by Alex Vear (2021-02-14).\n;;;; Public domain. No rights rese", "end": 87, "score": 0.9998580813407898, "start": 78, "tag": "NAME", "value": "Alex Vear" } ]
2021/colours/colours.clj
axvr/codedump
1
;;;; Convert 24-bit colours to closest xterm-256 colour. ;;;; ;;;; Written by Alex Vear (2021-02-14). ;;;; Public domain. No rights reserved. (ns colours (:require [clojure.math.numeric-tower :as math])) (def xterm-colours {"000000" 16, "00005F" 17, "000087" 18, "0000AF" 19 "0000D7" 20, "0000FF" 21, "005F00" 22, "005F5F" 23 "005F87" 24, "005FAF" 25, "005FD7" 26, "005FFF" 27 "008700" 28, "00875F" 29, "008787" 30, "0087AF" 31 "0087D7" 32, "0087FF" 33, "00AF00" 34, "00AF5F" 35 "00AF87" 36, "00AFAF" 37, "00AFD7" 38, "00AFFF" 39 "00D700" 40, "00D75F" 41, "00D787" 42, "00D7AF" 43 "00D7D7" 44, "00D7FF" 45, "00FF00" 46, "00FF5F" 47 "00FF87" 48, "00FFAF" 49, "00FFD7" 50, "00FFFF" 51 "5F0000" 52, "5F005F" 53, "5F0087" 54, "5F00AF" 55 "5F00D7" 56, "5F00FF" 57, "5F5F00" 58, "5F5F5F" 59 "5F5F87" 60, "5F5FAF" 61, "5F5FD7" 62, "5F5FFF" 63 "5F8700" 64, "5F875F" 65, "5F8787" 66, "5F87AF" 67 "5F87D7" 68, "5F87FF" 69, "5FAF00" 70, "5FAF5F" 71 "5FAF87" 72, "5FAFAF" 73, "5FAFD7" 74, "5FAFFF" 75 "5FD700" 76, "5FD75F" 77, "5FD787" 78, "5FD7AF" 79 "5FD7D7" 80, "5FD7FF" 81, "5FFF00" 82, "5FFF5F" 83 "5FFF87" 84, "5FFFAF" 85, "5FFFD7" 86, "5FFFFF" 87 "870000" 88, "87005F" 89, "870087" 90, "8700AF" 91 "8700D7" 92, "8700FF" 93, "875F00" 94, "875F5F" 95 "875F87" 96, "875FAF" 97, "875FD7" 98, "875FFF" 99 "878700" 100, "87875F" 101, "878787" 102, "8787AF" 103 "8787D7" 104, "8787FF" 105, "87AF00" 106, "87AF5F" 107 "87AF87" 108, "87AFAF" 109, "87AFD7" 110, "87AFFF" 111 "87D700" 112, "87D75F" 113, "87D787" 114, "87D7AF" 115 "87D7D7" 116, "87D7FF" 117, "87FF00" 118, "87FF5F" 119 "87FF87" 120, "87FFAF" 121, "87FFD7" 122, "87FFFF" 123 "AF0000" 124, "AF005F" 125, "AF0087" 126, "AF00AF" 127 "AF00D7" 128, "AF00FF" 129, "AF5F00" 130, "AF5F5F" 131 "AF5F87" 132, "AF5FAF" 133, "AF5FD7" 134, "AF5FFF" 135 "AF8700" 136, "AF875F" 137, "AF8787" 138, "AF87AF" 139 "AF87D7" 140, "AF87FF" 141, "AFAF00" 142, "AFAF5F" 143 "AFAF87" 144, "AFAFAF" 145, "AFAFD7" 146, "AFAFFF" 147 "AFD700" 148, "AFD75F" 149, "AFD787" 150, "AFD7AF" 151 "AFD7D7" 152, "AFD7FF" 153, "AFFF00" 154, "AFFF5F" 155 "AFFF87" 156, "AFFFAF" 157, "AFFFD7" 158, "AFFFFF" 159 "D70000" 160, "D7005F" 161, "D70087" 162, "D700AF" 163 "D700D7" 164, "D700FF" 165, "D75F00" 166, "D75F5F" 167 "D75F87" 168, "D75FAF" 169, "D75FD7" 170, "D75FFF" 171 "D78700" 172, "D7875F" 173, "D78787" 174, "D787AF" 175 "D787D7" 176, "D787FF" 177, "D7AF00" 178, "D7AF5F" 179 "D7AF87" 180, "D7AFAF" 181, "D7AFD7" 182, "D7AFFF" 183 "D7D700" 184, "D7D75F" 185, "D7D787" 186, "D7D7AF" 187 "D7D7D7" 188, "D7D7FF" 189, "D7FF00" 190, "D7FF5F" 191 "D7FF87" 192, "D7FFAF" 193, "D7FFD7" 194, "D7FFFF" 195 "FF0000" 196, "FF005F" 197, "FF0087" 198, "FF00AF" 199 "FF00D7" 200, "FF00FF" 201, "FF5F00" 202, "FF5F5F" 203 "FF5F87" 204, "FF5FAF" 205, "FF5FD7" 206, "FF5FFF" 207 "FF8700" 208, "FF875F" 209, "FF8787" 210, "FF87AF" 211 "FF87D7" 212, "FF87FF" 213, "FFAF00" 214, "FFAF5F" 215 "FFAF87" 216, "FFAFAF" 217, "FFAFD7" 218, "FFAFFF" 219 "FFD700" 220, "FFD75F" 221, "FFD787" 222, "FFD7AF" 223 "FFD7D7" 224, "FFD7FF" 225, "FFFF00" 226, "FFFF5F" 227 "FFFF87" 228, "FFFFAF" 229, "FFFFD7" 230, "FFFFFF" 231 "080808" 232, "121212" 233, "1C1C1C" 234, "262626" 235 "303030" 236, "3A3A3A" 237, "444444" 238, "4E4E4E" 239 "585858" 240, "626262" 241, "6C6C6C" 242, "767676" 243 "808080" 244, "8A8A8A" 245, "949494" 246, "9E9E9E" 247 "A8A8A8" 248, "B2B2B2" 249, "BCBCBC" 250, "C6C6C6" 251 "D0D0D0" 252, "DADADA" 253, "E4E4E4" 254, "EEEEEE" 255}) (defn decode-hex-char "Convert hexadecimal character to its decimal equivalent." [char] (case char \0 0 \1 1 \2 2 \3 3 \4 4 \5 5 \6 6 \7 7 \8 8 \9 9 (\A \a) 10 (\B \b) 11 (\C \c) 12 (\D \d) 13 (\E \e) 14 (\F \f) 15 nil)) (defn hex->dec "Merge hexadecimal digits into a single decimal value." [digits] (->> digits reverse (map-indexed (fn [idx dgt] (* dgt (math/expt 16 idx)))) (reduce +))) ;;; TODO: use CIELAB colour space instead of HSL. (defn srgb->hsl "Convert sRGB values to HSL." ([hex] (->> hex (keep decode-hex-char) (partition 2) (map hex->dec) (map #(/ % 255)) ; Normalise from 0-255 -> 0-1. (apply srgb->hsl))) ([r g b] (let [x-max (max r g b) x-min (min r g b) chroma (- x-max x-min) lightness (/ (+ x-max x-min) 2) saturation (if (or (= lightness 0) (= lightness 1)) 0 (/ chroma (- 1 (math/abs (- (* 2 lightness) 1))))) hue (if (= chroma 0) 0 (let [h (* 60 (cond (= r x-max) (/ (- g b) chroma) (= g x-max) (+ 2 (/ (- b r) chroma)) :else (+ 4 (/ (- r g) chroma))))] (if (< h 0) (+ h 360) h)))] {:h hue :s (* saturation 100) :l (* lightness 100)}))) (defn euclidean-distance "Calculate Euclidean distance between points p and q in Euclidean space." [p q] (->> (map (fn [p1 q1] (math/expt (- p1 q1) 2)) p q) (reduce +) math/sqrt)) (defn apply-weights [{:keys [h s l]}] {:h (* h 10) :s (* s 7) :l (* l 1)}) (defn find-closest [colour table] (let [base (-> colour srgb->hsl apply-weights vals)] (first (sort-by :dist (map (fn [[rgb code]] {:dist (->> rgb srgb->hsl apply-weights vals (euclidean-distance base)) :code code :hex rgb}) table))))) (comment (use 'clojure.pprint) (pprint (find-closest "#88766F" xterm-colours)) ; FIXME: inaccurate result. (pprint (find-closest "#998B70" xterm-colours)) (pprint (find-closest "#EAB56B" xterm-colours)) (pprint (find-closest "#A74F4F" xterm-colours)) (pprint (find-closest "#858CA6" xterm-colours)) (pprint (find-closest "#94BACA" xterm-colours)) (pprint (find-closest "#96A8A1" xterm-colours)) (pprint (find-closest "#679D80" xterm-colours)) (pprint (find-closest "#C9C9C9" xterm-colours)) (pprint (find-closest "#666967" xterm-colours)) ; FIXME: inaccurate result. (pprint (find-closest "#222222" xterm-colours)) (pprint (find-closest "#2A2A2A" xterm-colours)) (pprint (find-closest "#343434" xterm-colours)) (pprint (find-closest "#1A1A1A" xterm-colours)) (pprint (find-closest "#4A4A4A" xterm-colours)) )
83229
;;;; Convert 24-bit colours to closest xterm-256 colour. ;;;; ;;;; Written by <NAME> (2021-02-14). ;;;; Public domain. No rights reserved. (ns colours (:require [clojure.math.numeric-tower :as math])) (def xterm-colours {"000000" 16, "00005F" 17, "000087" 18, "0000AF" 19 "0000D7" 20, "0000FF" 21, "005F00" 22, "005F5F" 23 "005F87" 24, "005FAF" 25, "005FD7" 26, "005FFF" 27 "008700" 28, "00875F" 29, "008787" 30, "0087AF" 31 "0087D7" 32, "0087FF" 33, "00AF00" 34, "00AF5F" 35 "00AF87" 36, "00AFAF" 37, "00AFD7" 38, "00AFFF" 39 "00D700" 40, "00D75F" 41, "00D787" 42, "00D7AF" 43 "00D7D7" 44, "00D7FF" 45, "00FF00" 46, "00FF5F" 47 "00FF87" 48, "00FFAF" 49, "00FFD7" 50, "00FFFF" 51 "5F0000" 52, "5F005F" 53, "5F0087" 54, "5F00AF" 55 "5F00D7" 56, "5F00FF" 57, "5F5F00" 58, "5F5F5F" 59 "5F5F87" 60, "5F5FAF" 61, "5F5FD7" 62, "5F5FFF" 63 "5F8700" 64, "5F875F" 65, "5F8787" 66, "5F87AF" 67 "5F87D7" 68, "5F87FF" 69, "5FAF00" 70, "5FAF5F" 71 "5FAF87" 72, "5FAFAF" 73, "5FAFD7" 74, "5FAFFF" 75 "5FD700" 76, "5FD75F" 77, "5FD787" 78, "5FD7AF" 79 "5FD7D7" 80, "5FD7FF" 81, "5FFF00" 82, "5FFF5F" 83 "5FFF87" 84, "5FFFAF" 85, "5FFFD7" 86, "5FFFFF" 87 "870000" 88, "87005F" 89, "870087" 90, "8700AF" 91 "8700D7" 92, "8700FF" 93, "875F00" 94, "875F5F" 95 "875F87" 96, "875FAF" 97, "875FD7" 98, "875FFF" 99 "878700" 100, "87875F" 101, "878787" 102, "8787AF" 103 "8787D7" 104, "8787FF" 105, "87AF00" 106, "87AF5F" 107 "87AF87" 108, "87AFAF" 109, "87AFD7" 110, "87AFFF" 111 "87D700" 112, "87D75F" 113, "87D787" 114, "87D7AF" 115 "87D7D7" 116, "87D7FF" 117, "87FF00" 118, "87FF5F" 119 "87FF87" 120, "87FFAF" 121, "87FFD7" 122, "87FFFF" 123 "AF0000" 124, "AF005F" 125, "AF0087" 126, "AF00AF" 127 "AF00D7" 128, "AF00FF" 129, "AF5F00" 130, "AF5F5F" 131 "AF5F87" 132, "AF5FAF" 133, "AF5FD7" 134, "AF5FFF" 135 "AF8700" 136, "AF875F" 137, "AF8787" 138, "AF87AF" 139 "AF87D7" 140, "AF87FF" 141, "AFAF00" 142, "AFAF5F" 143 "AFAF87" 144, "AFAFAF" 145, "AFAFD7" 146, "AFAFFF" 147 "AFD700" 148, "AFD75F" 149, "AFD787" 150, "AFD7AF" 151 "AFD7D7" 152, "AFD7FF" 153, "AFFF00" 154, "AFFF5F" 155 "AFFF87" 156, "AFFFAF" 157, "AFFFD7" 158, "AFFFFF" 159 "D70000" 160, "D7005F" 161, "D70087" 162, "D700AF" 163 "D700D7" 164, "D700FF" 165, "D75F00" 166, "D75F5F" 167 "D75F87" 168, "D75FAF" 169, "D75FD7" 170, "D75FFF" 171 "D78700" 172, "D7875F" 173, "D78787" 174, "D787AF" 175 "D787D7" 176, "D787FF" 177, "D7AF00" 178, "D7AF5F" 179 "D7AF87" 180, "D7AFAF" 181, "D7AFD7" 182, "D7AFFF" 183 "D7D700" 184, "D7D75F" 185, "D7D787" 186, "D7D7AF" 187 "D7D7D7" 188, "D7D7FF" 189, "D7FF00" 190, "D7FF5F" 191 "D7FF87" 192, "D7FFAF" 193, "D7FFD7" 194, "D7FFFF" 195 "FF0000" 196, "FF005F" 197, "FF0087" 198, "FF00AF" 199 "FF00D7" 200, "FF00FF" 201, "FF5F00" 202, "FF5F5F" 203 "FF5F87" 204, "FF5FAF" 205, "FF5FD7" 206, "FF5FFF" 207 "FF8700" 208, "FF875F" 209, "FF8787" 210, "FF87AF" 211 "FF87D7" 212, "FF87FF" 213, "FFAF00" 214, "FFAF5F" 215 "FFAF87" 216, "FFAFAF" 217, "FFAFD7" 218, "FFAFFF" 219 "FFD700" 220, "FFD75F" 221, "FFD787" 222, "FFD7AF" 223 "FFD7D7" 224, "FFD7FF" 225, "FFFF00" 226, "FFFF5F" 227 "FFFF87" 228, "FFFFAF" 229, "FFFFD7" 230, "FFFFFF" 231 "080808" 232, "121212" 233, "1C1C1C" 234, "262626" 235 "303030" 236, "3A3A3A" 237, "444444" 238, "4E4E4E" 239 "585858" 240, "626262" 241, "6C6C6C" 242, "767676" 243 "808080" 244, "8A8A8A" 245, "949494" 246, "9E9E9E" 247 "A8A8A8" 248, "B2B2B2" 249, "BCBCBC" 250, "C6C6C6" 251 "D0D0D0" 252, "DADADA" 253, "E4E4E4" 254, "EEEEEE" 255}) (defn decode-hex-char "Convert hexadecimal character to its decimal equivalent." [char] (case char \0 0 \1 1 \2 2 \3 3 \4 4 \5 5 \6 6 \7 7 \8 8 \9 9 (\A \a) 10 (\B \b) 11 (\C \c) 12 (\D \d) 13 (\E \e) 14 (\F \f) 15 nil)) (defn hex->dec "Merge hexadecimal digits into a single decimal value." [digits] (->> digits reverse (map-indexed (fn [idx dgt] (* dgt (math/expt 16 idx)))) (reduce +))) ;;; TODO: use CIELAB colour space instead of HSL. (defn srgb->hsl "Convert sRGB values to HSL." ([hex] (->> hex (keep decode-hex-char) (partition 2) (map hex->dec) (map #(/ % 255)) ; Normalise from 0-255 -> 0-1. (apply srgb->hsl))) ([r g b] (let [x-max (max r g b) x-min (min r g b) chroma (- x-max x-min) lightness (/ (+ x-max x-min) 2) saturation (if (or (= lightness 0) (= lightness 1)) 0 (/ chroma (- 1 (math/abs (- (* 2 lightness) 1))))) hue (if (= chroma 0) 0 (let [h (* 60 (cond (= r x-max) (/ (- g b) chroma) (= g x-max) (+ 2 (/ (- b r) chroma)) :else (+ 4 (/ (- r g) chroma))))] (if (< h 0) (+ h 360) h)))] {:h hue :s (* saturation 100) :l (* lightness 100)}))) (defn euclidean-distance "Calculate Euclidean distance between points p and q in Euclidean space." [p q] (->> (map (fn [p1 q1] (math/expt (- p1 q1) 2)) p q) (reduce +) math/sqrt)) (defn apply-weights [{:keys [h s l]}] {:h (* h 10) :s (* s 7) :l (* l 1)}) (defn find-closest [colour table] (let [base (-> colour srgb->hsl apply-weights vals)] (first (sort-by :dist (map (fn [[rgb code]] {:dist (->> rgb srgb->hsl apply-weights vals (euclidean-distance base)) :code code :hex rgb}) table))))) (comment (use 'clojure.pprint) (pprint (find-closest "#88766F" xterm-colours)) ; FIXME: inaccurate result. (pprint (find-closest "#998B70" xterm-colours)) (pprint (find-closest "#EAB56B" xterm-colours)) (pprint (find-closest "#A74F4F" xterm-colours)) (pprint (find-closest "#858CA6" xterm-colours)) (pprint (find-closest "#94BACA" xterm-colours)) (pprint (find-closest "#96A8A1" xterm-colours)) (pprint (find-closest "#679D80" xterm-colours)) (pprint (find-closest "#C9C9C9" xterm-colours)) (pprint (find-closest "#666967" xterm-colours)) ; FIXME: inaccurate result. (pprint (find-closest "#222222" xterm-colours)) (pprint (find-closest "#2A2A2A" xterm-colours)) (pprint (find-closest "#343434" xterm-colours)) (pprint (find-closest "#1A1A1A" xterm-colours)) (pprint (find-closest "#4A4A4A" xterm-colours)) )
true
;;;; Convert 24-bit colours to closest xterm-256 colour. ;;;; ;;;; Written by PI:NAME:<NAME>END_PI (2021-02-14). ;;;; Public domain. No rights reserved. (ns colours (:require [clojure.math.numeric-tower :as math])) (def xterm-colours {"000000" 16, "00005F" 17, "000087" 18, "0000AF" 19 "0000D7" 20, "0000FF" 21, "005F00" 22, "005F5F" 23 "005F87" 24, "005FAF" 25, "005FD7" 26, "005FFF" 27 "008700" 28, "00875F" 29, "008787" 30, "0087AF" 31 "0087D7" 32, "0087FF" 33, "00AF00" 34, "00AF5F" 35 "00AF87" 36, "00AFAF" 37, "00AFD7" 38, "00AFFF" 39 "00D700" 40, "00D75F" 41, "00D787" 42, "00D7AF" 43 "00D7D7" 44, "00D7FF" 45, "00FF00" 46, "00FF5F" 47 "00FF87" 48, "00FFAF" 49, "00FFD7" 50, "00FFFF" 51 "5F0000" 52, "5F005F" 53, "5F0087" 54, "5F00AF" 55 "5F00D7" 56, "5F00FF" 57, "5F5F00" 58, "5F5F5F" 59 "5F5F87" 60, "5F5FAF" 61, "5F5FD7" 62, "5F5FFF" 63 "5F8700" 64, "5F875F" 65, "5F8787" 66, "5F87AF" 67 "5F87D7" 68, "5F87FF" 69, "5FAF00" 70, "5FAF5F" 71 "5FAF87" 72, "5FAFAF" 73, "5FAFD7" 74, "5FAFFF" 75 "5FD700" 76, "5FD75F" 77, "5FD787" 78, "5FD7AF" 79 "5FD7D7" 80, "5FD7FF" 81, "5FFF00" 82, "5FFF5F" 83 "5FFF87" 84, "5FFFAF" 85, "5FFFD7" 86, "5FFFFF" 87 "870000" 88, "87005F" 89, "870087" 90, "8700AF" 91 "8700D7" 92, "8700FF" 93, "875F00" 94, "875F5F" 95 "875F87" 96, "875FAF" 97, "875FD7" 98, "875FFF" 99 "878700" 100, "87875F" 101, "878787" 102, "8787AF" 103 "8787D7" 104, "8787FF" 105, "87AF00" 106, "87AF5F" 107 "87AF87" 108, "87AFAF" 109, "87AFD7" 110, "87AFFF" 111 "87D700" 112, "87D75F" 113, "87D787" 114, "87D7AF" 115 "87D7D7" 116, "87D7FF" 117, "87FF00" 118, "87FF5F" 119 "87FF87" 120, "87FFAF" 121, "87FFD7" 122, "87FFFF" 123 "AF0000" 124, "AF005F" 125, "AF0087" 126, "AF00AF" 127 "AF00D7" 128, "AF00FF" 129, "AF5F00" 130, "AF5F5F" 131 "AF5F87" 132, "AF5FAF" 133, "AF5FD7" 134, "AF5FFF" 135 "AF8700" 136, "AF875F" 137, "AF8787" 138, "AF87AF" 139 "AF87D7" 140, "AF87FF" 141, "AFAF00" 142, "AFAF5F" 143 "AFAF87" 144, "AFAFAF" 145, "AFAFD7" 146, "AFAFFF" 147 "AFD700" 148, "AFD75F" 149, "AFD787" 150, "AFD7AF" 151 "AFD7D7" 152, "AFD7FF" 153, "AFFF00" 154, "AFFF5F" 155 "AFFF87" 156, "AFFFAF" 157, "AFFFD7" 158, "AFFFFF" 159 "D70000" 160, "D7005F" 161, "D70087" 162, "D700AF" 163 "D700D7" 164, "D700FF" 165, "D75F00" 166, "D75F5F" 167 "D75F87" 168, "D75FAF" 169, "D75FD7" 170, "D75FFF" 171 "D78700" 172, "D7875F" 173, "D78787" 174, "D787AF" 175 "D787D7" 176, "D787FF" 177, "D7AF00" 178, "D7AF5F" 179 "D7AF87" 180, "D7AFAF" 181, "D7AFD7" 182, "D7AFFF" 183 "D7D700" 184, "D7D75F" 185, "D7D787" 186, "D7D7AF" 187 "D7D7D7" 188, "D7D7FF" 189, "D7FF00" 190, "D7FF5F" 191 "D7FF87" 192, "D7FFAF" 193, "D7FFD7" 194, "D7FFFF" 195 "FF0000" 196, "FF005F" 197, "FF0087" 198, "FF00AF" 199 "FF00D7" 200, "FF00FF" 201, "FF5F00" 202, "FF5F5F" 203 "FF5F87" 204, "FF5FAF" 205, "FF5FD7" 206, "FF5FFF" 207 "FF8700" 208, "FF875F" 209, "FF8787" 210, "FF87AF" 211 "FF87D7" 212, "FF87FF" 213, "FFAF00" 214, "FFAF5F" 215 "FFAF87" 216, "FFAFAF" 217, "FFAFD7" 218, "FFAFFF" 219 "FFD700" 220, "FFD75F" 221, "FFD787" 222, "FFD7AF" 223 "FFD7D7" 224, "FFD7FF" 225, "FFFF00" 226, "FFFF5F" 227 "FFFF87" 228, "FFFFAF" 229, "FFFFD7" 230, "FFFFFF" 231 "080808" 232, "121212" 233, "1C1C1C" 234, "262626" 235 "303030" 236, "3A3A3A" 237, "444444" 238, "4E4E4E" 239 "585858" 240, "626262" 241, "6C6C6C" 242, "767676" 243 "808080" 244, "8A8A8A" 245, "949494" 246, "9E9E9E" 247 "A8A8A8" 248, "B2B2B2" 249, "BCBCBC" 250, "C6C6C6" 251 "D0D0D0" 252, "DADADA" 253, "E4E4E4" 254, "EEEEEE" 255}) (defn decode-hex-char "Convert hexadecimal character to its decimal equivalent." [char] (case char \0 0 \1 1 \2 2 \3 3 \4 4 \5 5 \6 6 \7 7 \8 8 \9 9 (\A \a) 10 (\B \b) 11 (\C \c) 12 (\D \d) 13 (\E \e) 14 (\F \f) 15 nil)) (defn hex->dec "Merge hexadecimal digits into a single decimal value." [digits] (->> digits reverse (map-indexed (fn [idx dgt] (* dgt (math/expt 16 idx)))) (reduce +))) ;;; TODO: use CIELAB colour space instead of HSL. (defn srgb->hsl "Convert sRGB values to HSL." ([hex] (->> hex (keep decode-hex-char) (partition 2) (map hex->dec) (map #(/ % 255)) ; Normalise from 0-255 -> 0-1. (apply srgb->hsl))) ([r g b] (let [x-max (max r g b) x-min (min r g b) chroma (- x-max x-min) lightness (/ (+ x-max x-min) 2) saturation (if (or (= lightness 0) (= lightness 1)) 0 (/ chroma (- 1 (math/abs (- (* 2 lightness) 1))))) hue (if (= chroma 0) 0 (let [h (* 60 (cond (= r x-max) (/ (- g b) chroma) (= g x-max) (+ 2 (/ (- b r) chroma)) :else (+ 4 (/ (- r g) chroma))))] (if (< h 0) (+ h 360) h)))] {:h hue :s (* saturation 100) :l (* lightness 100)}))) (defn euclidean-distance "Calculate Euclidean distance between points p and q in Euclidean space." [p q] (->> (map (fn [p1 q1] (math/expt (- p1 q1) 2)) p q) (reduce +) math/sqrt)) (defn apply-weights [{:keys [h s l]}] {:h (* h 10) :s (* s 7) :l (* l 1)}) (defn find-closest [colour table] (let [base (-> colour srgb->hsl apply-weights vals)] (first (sort-by :dist (map (fn [[rgb code]] {:dist (->> rgb srgb->hsl apply-weights vals (euclidean-distance base)) :code code :hex rgb}) table))))) (comment (use 'clojure.pprint) (pprint (find-closest "#88766F" xterm-colours)) ; FIXME: inaccurate result. (pprint (find-closest "#998B70" xterm-colours)) (pprint (find-closest "#EAB56B" xterm-colours)) (pprint (find-closest "#A74F4F" xterm-colours)) (pprint (find-closest "#858CA6" xterm-colours)) (pprint (find-closest "#94BACA" xterm-colours)) (pprint (find-closest "#96A8A1" xterm-colours)) (pprint (find-closest "#679D80" xterm-colours)) (pprint (find-closest "#C9C9C9" xterm-colours)) (pprint (find-closest "#666967" xterm-colours)) ; FIXME: inaccurate result. (pprint (find-closest "#222222" xterm-colours)) (pprint (find-closest "#2A2A2A" xterm-colours)) (pprint (find-closest "#343434" xterm-colours)) (pprint (find-closest "#1A1A1A" xterm-colours)) (pprint (find-closest "#4A4A4A" xterm-colours)) )
[ { "context": "ation\n; Kombinatorische Logik\n; Copyright (c) 2021 Burkhardt Renz, THM. All rights reserved.\n\n(ns pres.cl\n (:requi", "end": 97, "score": 0.999861478805542, "start": 83, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/pres/cl.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Präsentation ; Kombinatorische Logik ; Copyright (c) 2021 Burkhardt Renz, THM. All rights reserved. (ns pres.cl (:require [lwb.cl :refer :all] [lwb.cl.repl :refer :all])) ; I.1 Syntax ; 1. Kombinatoren werden repräsentiert als Symbole beginnend ; mit einem Großbuchstaben, z.B. S, K, I. ; 2. Variablen werden repräsentiert durch Symbole beginnend ; mit einem Kleinbuchstaben, z.B. x, y. ; 3. Funktionsapplikation wird repräsentiert durch eine Liste ; mit zwei Elementen, z.B. ((K x) y). ; 4. Ein Term wird durch einen Vektor dargestellt, in einem Term ; kann man die Klammern weglassen entsprechend der Konvention ; dass Funktionsapplikation linksassoziativ ist, z.B. ; [K x y], [S x y z], [(((S x) y) z)]. (wff? '[S K K]) ; => true (wff? '[S I I (S I I)]) ; => true (wff? '[S (S x y z) (S x y z) z]) ; => true (wff? '[(S) K]) ; => false ; -------------------------------------------------------------- ; I.2 Definition der Kombinatoren ; Kombinatoren sind nicht eingebaut, sondern werden definiert: (def-combinator '[I x] '[x]) (def-combinator '[K x y] '[x]) (def-combinator '[S x y z] '[x z (y z)]) (show-combinators) ; --- Defined combinators -------- ; I := [I x] -> [x] ; K := [K x y] -> [x] ; S := [S x y z] -> [x z (y z)] ; -------------------------------- ; -------------------------------------------------------------- ; I.3 Interaktive Session (session '[S (K (S I)) K a b]) (red :S) (red :K) (red :S) (red :I) (red :K) ; Wir haben a und b vertauscht ; -------------------------------------------------------------- ; I.4 Reduktion (one-step-red '[S (S x y z) b c] :S) ; => [S x y z c (b c)] (one-step-red '[S (S x y z) b c] :S 2) ; => [S (x z (y z)) b c] ; -------------------------------------------------------------- ; I.5 Expansion (one-step-exp '[x z (y z) c (b c)] :S) ; => [S (x z (y z)) b c] (one-step-exp '[x z (y z) c (b c)] :S 2) ; => [S x y z c (b c)] (one-step-exp '[x] :K) ; => [K x _0] ; -------------------------------------------------------------- ; II.1 Interessante Beispiele (weak-reduce '[S (S x y z) (S x y z) z]) ; => [x z (y z) z (x z (y z) z)] (weak-reduce '[S (S x y z) (S x y z) z] {:trace true}) ; Immer die erste Möglichkeit der Reduktion (weak-reduce '[S I I (S I I)]) ; gibt einen sehr langen Ausdruck, warum? (meta (weak-reduce '[S I I (S I I)])) ;{:reduced ((I (I (I (I ((S I) I))))) (I (I (I (I (I (I (I (I (I (I (I (I (I ((S I) I))))))))))))))), ; :no-steps 100, ; :cycle :unknown, ; :overrun true} ; Es gibt aber auch eine ganz andere Möglichkeit (session '[S I I (S I I)]) (red :S) (red :I) (red :I) ; => [S I I (S I I)] ein Zyklus (weak-reduce '[S I I (S I I)] {:limit 3 :trace true}) ; In Zeile 2 wird mit :S reduziert, nicht mit :I wie oben ; Zwei Kombinatoren, gleicher Effekt (weak-reduce '[S K K x]) (weak-reduce '[I x]) ; I = S K K im Sinne der extensionalen Gleichheit ; Zwei Kombinatoren in Normalform (weak-reduce '[S K K]) (weak-reduce '[S K S]) ; aber (weak-reduce '[S K K x]) ; => [x] (weak-reduce '[S K S x]) ; => [x] ; S K K = S K S im Sinne der extensionalen Gleichheit ; -------------------------------------------------------------- ; II.2 Normalform (weak-reduce '[S (S x y z) (S x y z) z]) ; => [x z (y z) z (x z (y z) z)] ; -------------------------------------------------------------- ; II.3 Church-Rosser (session '[S (S x y z) (S x y z) z]) (red* :S [1 1 1]) (session '[S (S x y z) (S x y z) z]) (red* :S [3 2 1]) ; und alle weiteren 4 Möglichkeiten führen zum ; gleichen Term ; -------------------------------------------------------------- ; II.4 Currys Fixpunkt-Kombinator ;; Curry's fixed point combinator (session '[S (B W B) (B W B) x]) (red :S) (red :B) (red :B) (red :W) (red :B) (exp :B 3) (exp :B 3) (exp :S) ; => [x (S (B W B) (B W B) x)] ; -------------------------------------------------------------- ; II.5 Bracket Abstraction ; Gesucht ein Kombinator, der zwei Argumente vertauscht (abstract '[x y] '[y x]) ; => [S (K (S I)) K] ; Probe mit a und b (weak-reduce (conj (abstract '[x y] '[y x]) 'a 'b)) ; => [b a] ; -------------------------------------------------------------- ; III Symullyans Rätsel interaktiv lösen (def-combinatory-birds) (show-combinators) ; Aufgabe 1 aus Kapitel 11 von Smullyans Buch ; Given B then the composition law holds (session '[(B f g) x]) (red :B) ; => [f (g x)] i.e. [B f g] composes f with g. ; Let's use this fact (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x) i.e. B M L is a sage bird ; Alle Rätsel, die man interaktiv lösen kann ; auf github: src/lwb/cl/examples/smullyan.clj ; -------------------------------------------------------------- ; IV.1 Boolesche Werte und Operatoren der Aussagenlogik ; Definition Wahrheitswerte (def True '[K]) (def False '[K I]) (defn to-boolean [term] (let [red (weak-reduce (conj term 't 'f))] (cond (= red '[t]) 'True (= red '[f]) 'False :else nil))) ; Definition von not (def Not '[S (S I (K (K I))) (K K)]) (defn Not' [term] (to-boolean (weak-reduce (comb-concat Not term)))) ; Wahrheitstafel von not (Not' True) (Not' False) ; Definition von and (def And '[S S K]) (defn And' [term1 term2] (to-boolean (weak-reduce (comb-concat And term1 term2)))) ; Wahrheitstafel von and (And' True True) (And' True False) (And' False True) (And' False False) ; -------------------------------------------------------------- ; IV.2 Natürliche Zahlen: Church-Numerale ; Null (def Zero '[K I]) ; Nachfolger-Kombinator (def Succ '[S B]) ; Nachfolger-Funktion (defn succ "The successor of the given numeral. Pre: `term` is a numeral." [term] (comb-concat Succ term)) ; Numeral (defn Num "Defines Church numeral for `i`." [i] (cond (neg? i) nil (>= i 0) (loop [current 0 result Zero] (if (= current i) result (recur (inc current) (succ result)))))) (Num 0) (Num 1) (Num 2) (defn to-num "The given term is transformed to numeral or nil if it's not a numeral." [term] (let [red (weak-reduce (conj term 'f 'x) {:limit 1000}) nof (count (filter #(= 'f %) (flatten red)))] (when (= red (weak-reduce (conj (Num nof) 'f 'x))) (list 'Num nof)))) ; Addition (def Add '[S I (K (S B))]) (defn add "Adds two numerals." [term1 term2] (comb-concat Add term1 term2)) (add (Num 1) (Num 2)) (to-num (add (Num 1) (Num 2))) ; => (Num 3) ; -------------------------------------------------------------- ; V. Das Titelbild von Bimbós Monographie (session '[S (S x y z)(S x y z) z]) (red :S 2) (red :S 1) (red :S 1) ; --- Current session ----------------------------- ; 1: [S (S x y z) (S x y z) z] [:given] ; 2: [S (x z (y z)) (S x y z) z] [:red :S 2] ; 3: [x z (y z) z (S x y z z)] [:red :S 1] ; 4: [x z (y z) z (x z (y z) z)] [:red :S 1] ; ------------------------------------------------- (session '[S (S x y z)(S x y z) z]) (red* :S [2 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [1 1 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [1 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [3 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [3 1 1])
3650
; lwb Logic WorkBench -- Präsentation ; Kombinatorische Logik ; Copyright (c) 2021 <NAME>, THM. All rights reserved. (ns pres.cl (:require [lwb.cl :refer :all] [lwb.cl.repl :refer :all])) ; I.1 Syntax ; 1. Kombinatoren werden repräsentiert als Symbole beginnend ; mit einem Großbuchstaben, z.B. S, K, I. ; 2. Variablen werden repräsentiert durch Symbole beginnend ; mit einem Kleinbuchstaben, z.B. x, y. ; 3. Funktionsapplikation wird repräsentiert durch eine Liste ; mit zwei Elementen, z.B. ((K x) y). ; 4. Ein Term wird durch einen Vektor dargestellt, in einem Term ; kann man die Klammern weglassen entsprechend der Konvention ; dass Funktionsapplikation linksassoziativ ist, z.B. ; [K x y], [S x y z], [(((S x) y) z)]. (wff? '[S K K]) ; => true (wff? '[S I I (S I I)]) ; => true (wff? '[S (S x y z) (S x y z) z]) ; => true (wff? '[(S) K]) ; => false ; -------------------------------------------------------------- ; I.2 Definition der Kombinatoren ; Kombinatoren sind nicht eingebaut, sondern werden definiert: (def-combinator '[I x] '[x]) (def-combinator '[K x y] '[x]) (def-combinator '[S x y z] '[x z (y z)]) (show-combinators) ; --- Defined combinators -------- ; I := [I x] -> [x] ; K := [K x y] -> [x] ; S := [S x y z] -> [x z (y z)] ; -------------------------------- ; -------------------------------------------------------------- ; I.3 Interaktive Session (session '[S (K (S I)) K a b]) (red :S) (red :K) (red :S) (red :I) (red :K) ; Wir haben a und b vertauscht ; -------------------------------------------------------------- ; I.4 Reduktion (one-step-red '[S (S x y z) b c] :S) ; => [S x y z c (b c)] (one-step-red '[S (S x y z) b c] :S 2) ; => [S (x z (y z)) b c] ; -------------------------------------------------------------- ; I.5 Expansion (one-step-exp '[x z (y z) c (b c)] :S) ; => [S (x z (y z)) b c] (one-step-exp '[x z (y z) c (b c)] :S 2) ; => [S x y z c (b c)] (one-step-exp '[x] :K) ; => [K x _0] ; -------------------------------------------------------------- ; II.1 Interessante Beispiele (weak-reduce '[S (S x y z) (S x y z) z]) ; => [x z (y z) z (x z (y z) z)] (weak-reduce '[S (S x y z) (S x y z) z] {:trace true}) ; Immer die erste Möglichkeit der Reduktion (weak-reduce '[S I I (S I I)]) ; gibt einen sehr langen Ausdruck, warum? (meta (weak-reduce '[S I I (S I I)])) ;{:reduced ((I (I (I (I ((S I) I))))) (I (I (I (I (I (I (I (I (I (I (I (I (I ((S I) I))))))))))))))), ; :no-steps 100, ; :cycle :unknown, ; :overrun true} ; Es gibt aber auch eine ganz andere Möglichkeit (session '[S I I (S I I)]) (red :S) (red :I) (red :I) ; => [S I I (S I I)] ein Zyklus (weak-reduce '[S I I (S I I)] {:limit 3 :trace true}) ; In Zeile 2 wird mit :S reduziert, nicht mit :I wie oben ; Zwei Kombinatoren, gleicher Effekt (weak-reduce '[S K K x]) (weak-reduce '[I x]) ; I = S K K im Sinne der extensionalen Gleichheit ; Zwei Kombinatoren in Normalform (weak-reduce '[S K K]) (weak-reduce '[S K S]) ; aber (weak-reduce '[S K K x]) ; => [x] (weak-reduce '[S K S x]) ; => [x] ; S K K = S K S im Sinne der extensionalen Gleichheit ; -------------------------------------------------------------- ; II.2 Normalform (weak-reduce '[S (S x y z) (S x y z) z]) ; => [x z (y z) z (x z (y z) z)] ; -------------------------------------------------------------- ; II.3 Church-Rosser (session '[S (S x y z) (S x y z) z]) (red* :S [1 1 1]) (session '[S (S x y z) (S x y z) z]) (red* :S [3 2 1]) ; und alle weiteren 4 Möglichkeiten führen zum ; gleichen Term ; -------------------------------------------------------------- ; II.4 Currys Fixpunkt-Kombinator ;; Curry's fixed point combinator (session '[S (B W B) (B W B) x]) (red :S) (red :B) (red :B) (red :W) (red :B) (exp :B 3) (exp :B 3) (exp :S) ; => [x (S (B W B) (B W B) x)] ; -------------------------------------------------------------- ; II.5 Bracket Abstraction ; Gesucht ein Kombinator, der zwei Argumente vertauscht (abstract '[x y] '[y x]) ; => [S (K (S I)) K] ; Probe mit a und b (weak-reduce (conj (abstract '[x y] '[y x]) 'a 'b)) ; => [b a] ; -------------------------------------------------------------- ; III Symullyans Rätsel interaktiv lösen (def-combinatory-birds) (show-combinators) ; Aufgabe 1 aus Kapitel 11 von Smullyans Buch ; Given B then the composition law holds (session '[(B f g) x]) (red :B) ; => [f (g x)] i.e. [B f g] composes f with g. ; Let's use this fact (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x) i.e. B M L is a sage bird ; Alle Rätsel, die man interaktiv lösen kann ; auf github: src/lwb/cl/examples/smullyan.clj ; -------------------------------------------------------------- ; IV.1 Boolesche Werte und Operatoren der Aussagenlogik ; Definition Wahrheitswerte (def True '[K]) (def False '[K I]) (defn to-boolean [term] (let [red (weak-reduce (conj term 't 'f))] (cond (= red '[t]) 'True (= red '[f]) 'False :else nil))) ; Definition von not (def Not '[S (S I (K (K I))) (K K)]) (defn Not' [term] (to-boolean (weak-reduce (comb-concat Not term)))) ; Wahrheitstafel von not (Not' True) (Not' False) ; Definition von and (def And '[S S K]) (defn And' [term1 term2] (to-boolean (weak-reduce (comb-concat And term1 term2)))) ; Wahrheitstafel von and (And' True True) (And' True False) (And' False True) (And' False False) ; -------------------------------------------------------------- ; IV.2 Natürliche Zahlen: Church-Numerale ; Null (def Zero '[K I]) ; Nachfolger-Kombinator (def Succ '[S B]) ; Nachfolger-Funktion (defn succ "The successor of the given numeral. Pre: `term` is a numeral." [term] (comb-concat Succ term)) ; Numeral (defn Num "Defines Church numeral for `i`." [i] (cond (neg? i) nil (>= i 0) (loop [current 0 result Zero] (if (= current i) result (recur (inc current) (succ result)))))) (Num 0) (Num 1) (Num 2) (defn to-num "The given term is transformed to numeral or nil if it's not a numeral." [term] (let [red (weak-reduce (conj term 'f 'x) {:limit 1000}) nof (count (filter #(= 'f %) (flatten red)))] (when (= red (weak-reduce (conj (Num nof) 'f 'x))) (list 'Num nof)))) ; Addition (def Add '[S I (K (S B))]) (defn add "Adds two numerals." [term1 term2] (comb-concat Add term1 term2)) (add (Num 1) (Num 2)) (to-num (add (Num 1) (Num 2))) ; => (Num 3) ; -------------------------------------------------------------- ; V. Das Titelbild von Bimbós Monographie (session '[S (S x y z)(S x y z) z]) (red :S 2) (red :S 1) (red :S 1) ; --- Current session ----------------------------- ; 1: [S (S x y z) (S x y z) z] [:given] ; 2: [S (x z (y z)) (S x y z) z] [:red :S 2] ; 3: [x z (y z) z (S x y z z)] [:red :S 1] ; 4: [x z (y z) z (x z (y z) z)] [:red :S 1] ; ------------------------------------------------- (session '[S (S x y z)(S x y z) z]) (red* :S [2 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [1 1 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [1 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [3 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [3 1 1])
true
; lwb Logic WorkBench -- Präsentation ; Kombinatorische Logik ; Copyright (c) 2021 PI:NAME:<NAME>END_PI, THM. All rights reserved. (ns pres.cl (:require [lwb.cl :refer :all] [lwb.cl.repl :refer :all])) ; I.1 Syntax ; 1. Kombinatoren werden repräsentiert als Symbole beginnend ; mit einem Großbuchstaben, z.B. S, K, I. ; 2. Variablen werden repräsentiert durch Symbole beginnend ; mit einem Kleinbuchstaben, z.B. x, y. ; 3. Funktionsapplikation wird repräsentiert durch eine Liste ; mit zwei Elementen, z.B. ((K x) y). ; 4. Ein Term wird durch einen Vektor dargestellt, in einem Term ; kann man die Klammern weglassen entsprechend der Konvention ; dass Funktionsapplikation linksassoziativ ist, z.B. ; [K x y], [S x y z], [(((S x) y) z)]. (wff? '[S K K]) ; => true (wff? '[S I I (S I I)]) ; => true (wff? '[S (S x y z) (S x y z) z]) ; => true (wff? '[(S) K]) ; => false ; -------------------------------------------------------------- ; I.2 Definition der Kombinatoren ; Kombinatoren sind nicht eingebaut, sondern werden definiert: (def-combinator '[I x] '[x]) (def-combinator '[K x y] '[x]) (def-combinator '[S x y z] '[x z (y z)]) (show-combinators) ; --- Defined combinators -------- ; I := [I x] -> [x] ; K := [K x y] -> [x] ; S := [S x y z] -> [x z (y z)] ; -------------------------------- ; -------------------------------------------------------------- ; I.3 Interaktive Session (session '[S (K (S I)) K a b]) (red :S) (red :K) (red :S) (red :I) (red :K) ; Wir haben a und b vertauscht ; -------------------------------------------------------------- ; I.4 Reduktion (one-step-red '[S (S x y z) b c] :S) ; => [S x y z c (b c)] (one-step-red '[S (S x y z) b c] :S 2) ; => [S (x z (y z)) b c] ; -------------------------------------------------------------- ; I.5 Expansion (one-step-exp '[x z (y z) c (b c)] :S) ; => [S (x z (y z)) b c] (one-step-exp '[x z (y z) c (b c)] :S 2) ; => [S x y z c (b c)] (one-step-exp '[x] :K) ; => [K x _0] ; -------------------------------------------------------------- ; II.1 Interessante Beispiele (weak-reduce '[S (S x y z) (S x y z) z]) ; => [x z (y z) z (x z (y z) z)] (weak-reduce '[S (S x y z) (S x y z) z] {:trace true}) ; Immer die erste Möglichkeit der Reduktion (weak-reduce '[S I I (S I I)]) ; gibt einen sehr langen Ausdruck, warum? (meta (weak-reduce '[S I I (S I I)])) ;{:reduced ((I (I (I (I ((S I) I))))) (I (I (I (I (I (I (I (I (I (I (I (I (I ((S I) I))))))))))))))), ; :no-steps 100, ; :cycle :unknown, ; :overrun true} ; Es gibt aber auch eine ganz andere Möglichkeit (session '[S I I (S I I)]) (red :S) (red :I) (red :I) ; => [S I I (S I I)] ein Zyklus (weak-reduce '[S I I (S I I)] {:limit 3 :trace true}) ; In Zeile 2 wird mit :S reduziert, nicht mit :I wie oben ; Zwei Kombinatoren, gleicher Effekt (weak-reduce '[S K K x]) (weak-reduce '[I x]) ; I = S K K im Sinne der extensionalen Gleichheit ; Zwei Kombinatoren in Normalform (weak-reduce '[S K K]) (weak-reduce '[S K S]) ; aber (weak-reduce '[S K K x]) ; => [x] (weak-reduce '[S K S x]) ; => [x] ; S K K = S K S im Sinne der extensionalen Gleichheit ; -------------------------------------------------------------- ; II.2 Normalform (weak-reduce '[S (S x y z) (S x y z) z]) ; => [x z (y z) z (x z (y z) z)] ; -------------------------------------------------------------- ; II.3 Church-Rosser (session '[S (S x y z) (S x y z) z]) (red* :S [1 1 1]) (session '[S (S x y z) (S x y z) z]) (red* :S [3 2 1]) ; und alle weiteren 4 Möglichkeiten führen zum ; gleichen Term ; -------------------------------------------------------------- ; II.4 Currys Fixpunkt-Kombinator ;; Curry's fixed point combinator (session '[S (B W B) (B W B) x]) (red :S) (red :B) (red :B) (red :W) (red :B) (exp :B 3) (exp :B 3) (exp :S) ; => [x (S (B W B) (B W B) x)] ; -------------------------------------------------------------- ; II.5 Bracket Abstraction ; Gesucht ein Kombinator, der zwei Argumente vertauscht (abstract '[x y] '[y x]) ; => [S (K (S I)) K] ; Probe mit a und b (weak-reduce (conj (abstract '[x y] '[y x]) 'a 'b)) ; => [b a] ; -------------------------------------------------------------- ; III Symullyans Rätsel interaktiv lösen (def-combinatory-birds) (show-combinators) ; Aufgabe 1 aus Kapitel 11 von Smullyans Buch ; Given B then the composition law holds (session '[(B f g) x]) (red :B) ; => [f (g x)] i.e. [B f g] composes f with g. ; Let's use this fact (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x) i.e. B M L is a sage bird ; Alle Rätsel, die man interaktiv lösen kann ; auf github: src/lwb/cl/examples/smullyan.clj ; -------------------------------------------------------------- ; IV.1 Boolesche Werte und Operatoren der Aussagenlogik ; Definition Wahrheitswerte (def True '[K]) (def False '[K I]) (defn to-boolean [term] (let [red (weak-reduce (conj term 't 'f))] (cond (= red '[t]) 'True (= red '[f]) 'False :else nil))) ; Definition von not (def Not '[S (S I (K (K I))) (K K)]) (defn Not' [term] (to-boolean (weak-reduce (comb-concat Not term)))) ; Wahrheitstafel von not (Not' True) (Not' False) ; Definition von and (def And '[S S K]) (defn And' [term1 term2] (to-boolean (weak-reduce (comb-concat And term1 term2)))) ; Wahrheitstafel von and (And' True True) (And' True False) (And' False True) (And' False False) ; -------------------------------------------------------------- ; IV.2 Natürliche Zahlen: Church-Numerale ; Null (def Zero '[K I]) ; Nachfolger-Kombinator (def Succ '[S B]) ; Nachfolger-Funktion (defn succ "The successor of the given numeral. Pre: `term` is a numeral." [term] (comb-concat Succ term)) ; Numeral (defn Num "Defines Church numeral for `i`." [i] (cond (neg? i) nil (>= i 0) (loop [current 0 result Zero] (if (= current i) result (recur (inc current) (succ result)))))) (Num 0) (Num 1) (Num 2) (defn to-num "The given term is transformed to numeral or nil if it's not a numeral." [term] (let [red (weak-reduce (conj term 'f 'x) {:limit 1000}) nof (count (filter #(= 'f %) (flatten red)))] (when (= red (weak-reduce (conj (Num nof) 'f 'x))) (list 'Num nof)))) ; Addition (def Add '[S I (K (S B))]) (defn add "Adds two numerals." [term1 term2] (comb-concat Add term1 term2)) (add (Num 1) (Num 2)) (to-num (add (Num 1) (Num 2))) ; => (Num 3) ; -------------------------------------------------------------- ; V. Das Titelbild von Bimbós Monographie (session '[S (S x y z)(S x y z) z]) (red :S 2) (red :S 1) (red :S 1) ; --- Current session ----------------------------- ; 1: [S (S x y z) (S x y z) z] [:given] ; 2: [S (x z (y z)) (S x y z) z] [:red :S 2] ; 3: [x z (y z) z (S x y z z)] [:red :S 1] ; 4: [x z (y z) z (x z (y z) z)] [:red :S 1] ; ------------------------------------------------- (session '[S (S x y z)(S x y z) z]) (red* :S [2 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [1 1 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [1 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [3 2 1]) (session '[S (S x y z)(S x y z) z]) (red* :S [3 1 1])
[ { "context": "ields\" :since \"now\" :until \"now\"}}\n token \"token\"\n out-dir *tmpdir*]\n (println *tmpdir*)", "end": 2298, "score": 0.5284016728401184, "start": 2293, "tag": "KEY", "value": "token" } ]
test/keboola/facebook/extractor/query_test.clj
keboola/ex-facebook-graph-api
40
(ns keboola.facebook.extractor.query-test (:require [keboola.facebook.extractor.query :as sut] [keboola.test-utils.core :as test-utils] [clojure.java.io :as io] [keboola.facebook.api.request-test :refer [media-posted-before-error-response]] [clojure.test :refer :all]) (:use clj-http.fake)) (def ^:dynamic *tmpdir* "") (defn setup-tmpdir [f] (binding [*tmpdir* (test-utils/mk-tmp-dir! "exfbtestquery")] (f) (test-utils/recursive-delete *tmpdir*))) (deftest test-query-contains-insights? (is (not (sut/query-contains-insights? {}))) (is (not (sut/query-contains-insights? {:fields "asasd"}))) (is (not (sut/query-contains-insights? {:fields "asasd" :path "asdfff"}))) (is (not (sut/query-contains-insights? {:fields "" :path nil}))) (is (not (sut/query-contains-insights? {:fields nil :path nil}))) (is (not (sut/query-contains-insights? {:fields nil :path ""}))) (is (sut/query-contains-insights? {:fields nil :path "insights"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path "insights"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path "feed"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path nil})) (is (sut/query-contains-insights? {:fields nil :path "insights"}))) (deftest test-query-path-feed? (is (not (sut/query-path-feed? {}))) (is (not (sut/query-path-feed? {:path "ratings" :fields "feed"}))) (is (sut/query-path-feed? {:path "feed" :fields "insights"})) (is (sut/query-path-feed? {:path "me/feed" :fields "insights"}))) (deftest test-query-need-userinfo? (is (not (sut/query-need-userinfo? {}))) (is (not (sut/query-need-userinfo? {:path "ratings" :fields "feed"}))) (is (sut/query-need-userinfo? {:path "likes" :fields "insights"})) (is (sut/query-need-userinfo? {:path "" :fields "likes"})) (is (sut/query-need-userinfo? {:path "me/feed" :fields "from"}))) (defn empty-dir? [path] (let [file (io/file path)] (assert (.exists file)) (assert (.isDirectory file)) (-> file .list empty?))) (deftest test-media-posted-before-error-response-query (let [query {:name "mediatest" :version "v2.11" :query {:path "media" :ids "123" :fields "fields" :since "now" :until "now"}} token "token" out-dir *tmpdir*] (println *tmpdir*) (with-global-fake-routes-in-isolation { "https://graph.facebook.com/v2.11/media?path=media&ids=123&fields=fields&since=now&until=now&access_token=token" (fn [req] media-posted-before-error-response)} (sut/run-nested-query token out-dir query) (is (empty-dir? *tmpdir*))))) (use-fixtures :once setup-tmpdir)
9864
(ns keboola.facebook.extractor.query-test (:require [keboola.facebook.extractor.query :as sut] [keboola.test-utils.core :as test-utils] [clojure.java.io :as io] [keboola.facebook.api.request-test :refer [media-posted-before-error-response]] [clojure.test :refer :all]) (:use clj-http.fake)) (def ^:dynamic *tmpdir* "") (defn setup-tmpdir [f] (binding [*tmpdir* (test-utils/mk-tmp-dir! "exfbtestquery")] (f) (test-utils/recursive-delete *tmpdir*))) (deftest test-query-contains-insights? (is (not (sut/query-contains-insights? {}))) (is (not (sut/query-contains-insights? {:fields "asasd"}))) (is (not (sut/query-contains-insights? {:fields "asasd" :path "asdfff"}))) (is (not (sut/query-contains-insights? {:fields "" :path nil}))) (is (not (sut/query-contains-insights? {:fields nil :path nil}))) (is (not (sut/query-contains-insights? {:fields nil :path ""}))) (is (sut/query-contains-insights? {:fields nil :path "insights"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path "insights"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path "feed"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path nil})) (is (sut/query-contains-insights? {:fields nil :path "insights"}))) (deftest test-query-path-feed? (is (not (sut/query-path-feed? {}))) (is (not (sut/query-path-feed? {:path "ratings" :fields "feed"}))) (is (sut/query-path-feed? {:path "feed" :fields "insights"})) (is (sut/query-path-feed? {:path "me/feed" :fields "insights"}))) (deftest test-query-need-userinfo? (is (not (sut/query-need-userinfo? {}))) (is (not (sut/query-need-userinfo? {:path "ratings" :fields "feed"}))) (is (sut/query-need-userinfo? {:path "likes" :fields "insights"})) (is (sut/query-need-userinfo? {:path "" :fields "likes"})) (is (sut/query-need-userinfo? {:path "me/feed" :fields "from"}))) (defn empty-dir? [path] (let [file (io/file path)] (assert (.exists file)) (assert (.isDirectory file)) (-> file .list empty?))) (deftest test-media-posted-before-error-response-query (let [query {:name "mediatest" :version "v2.11" :query {:path "media" :ids "123" :fields "fields" :since "now" :until "now"}} token "<KEY>" out-dir *tmpdir*] (println *tmpdir*) (with-global-fake-routes-in-isolation { "https://graph.facebook.com/v2.11/media?path=media&ids=123&fields=fields&since=now&until=now&access_token=token" (fn [req] media-posted-before-error-response)} (sut/run-nested-query token out-dir query) (is (empty-dir? *tmpdir*))))) (use-fixtures :once setup-tmpdir)
true
(ns keboola.facebook.extractor.query-test (:require [keboola.facebook.extractor.query :as sut] [keboola.test-utils.core :as test-utils] [clojure.java.io :as io] [keboola.facebook.api.request-test :refer [media-posted-before-error-response]] [clojure.test :refer :all]) (:use clj-http.fake)) (def ^:dynamic *tmpdir* "") (defn setup-tmpdir [f] (binding [*tmpdir* (test-utils/mk-tmp-dir! "exfbtestquery")] (f) (test-utils/recursive-delete *tmpdir*))) (deftest test-query-contains-insights? (is (not (sut/query-contains-insights? {}))) (is (not (sut/query-contains-insights? {:fields "asasd"}))) (is (not (sut/query-contains-insights? {:fields "asasd" :path "asdfff"}))) (is (not (sut/query-contains-insights? {:fields "" :path nil}))) (is (not (sut/query-contains-insights? {:fields nil :path nil}))) (is (not (sut/query-contains-insights? {:fields nil :path ""}))) (is (sut/query-contains-insights? {:fields nil :path "insights"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path "insights"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path "feed"})) (is (sut/query-contains-insights? {:fields "asdasdasd,insights" :path nil})) (is (sut/query-contains-insights? {:fields nil :path "insights"}))) (deftest test-query-path-feed? (is (not (sut/query-path-feed? {}))) (is (not (sut/query-path-feed? {:path "ratings" :fields "feed"}))) (is (sut/query-path-feed? {:path "feed" :fields "insights"})) (is (sut/query-path-feed? {:path "me/feed" :fields "insights"}))) (deftest test-query-need-userinfo? (is (not (sut/query-need-userinfo? {}))) (is (not (sut/query-need-userinfo? {:path "ratings" :fields "feed"}))) (is (sut/query-need-userinfo? {:path "likes" :fields "insights"})) (is (sut/query-need-userinfo? {:path "" :fields "likes"})) (is (sut/query-need-userinfo? {:path "me/feed" :fields "from"}))) (defn empty-dir? [path] (let [file (io/file path)] (assert (.exists file)) (assert (.isDirectory file)) (-> file .list empty?))) (deftest test-media-posted-before-error-response-query (let [query {:name "mediatest" :version "v2.11" :query {:path "media" :ids "123" :fields "fields" :since "now" :until "now"}} token "PI:KEY:<KEY>END_PI" out-dir *tmpdir*] (println *tmpdir*) (with-global-fake-routes-in-isolation { "https://graph.facebook.com/v2.11/media?path=media&ids=123&fields=fields&since=now&until=now&access_token=token" (fn [req] media-posted-before-error-response)} (sut/run-nested-query token out-dir query) (is (empty-dir? *tmpdir*))))) (use-fixtures :once setup-tmpdir)
[ { "context": " :body (edn->json {:message \"I have a dream - Martin Luther King, Jr.\"})} \n response))))))\n", "end": 744, "score": 0.9997578859329224, "start": 726, "tag": "NAME", "value": "Martin Luther King" } ]
test/integration/integration/health_test.clj
eduardoeof/clojure-service
0
(ns integration.health-test (:require [clojure.test :refer :all] [matcher-combinators.test :refer [match?]] [clojure-service.component :as component] [integration.util.http :refer [http-get edn->json]])) (def components (atom nil)) (defn fixtures-once [test-case] (reset! components (component/create-and-start)) (test-case) (reset! components nil)) (use-fixtures :once fixtures-once) (deftest health-test (testing "when GET /api/health endpoint is requested" (let [response (http-get "/api/health" @components)] (testing "then it should return 200 and a message" (is (match? {:status 200 :body (edn->json {:message "I have a dream - Martin Luther King, Jr."})} response))))))
76771
(ns integration.health-test (:require [clojure.test :refer :all] [matcher-combinators.test :refer [match?]] [clojure-service.component :as component] [integration.util.http :refer [http-get edn->json]])) (def components (atom nil)) (defn fixtures-once [test-case] (reset! components (component/create-and-start)) (test-case) (reset! components nil)) (use-fixtures :once fixtures-once) (deftest health-test (testing "when GET /api/health endpoint is requested" (let [response (http-get "/api/health" @components)] (testing "then it should return 200 and a message" (is (match? {:status 200 :body (edn->json {:message "I have a dream - <NAME>, Jr."})} response))))))
true
(ns integration.health-test (:require [clojure.test :refer :all] [matcher-combinators.test :refer [match?]] [clojure-service.component :as component] [integration.util.http :refer [http-get edn->json]])) (def components (atom nil)) (defn fixtures-once [test-case] (reset! components (component/create-and-start)) (test-case) (reset! components nil)) (use-fixtures :once fixtures-once) (deftest health-test (testing "when GET /api/health endpoint is requested" (let [response (http-get "/api/health" @components)] (testing "then it should return 200 and a message" (is (match? {:status 200 :body (edn->json {:message "I have a dream - PI:NAME:<NAME>END_PI, Jr."})} response))))))
[ { "context": "sword]\n \"TODO: Test, goog.async\"\n (let [username username\n password password\n authentication-", "end": 315, "score": 0.9937187433242798, "start": 307, "tag": "USERNAME", "value": "username" }, { "context": ".async\"\n (let [username username\n password password\n authentication-data {:Username username :", "end": 341, "score": 0.9930446743965149, "start": 333, "tag": "PASSWORD", "value": "password" }, { "context": "rd password\n authentication-data {:Username username :Password password}\n authentication-detail", "end": 389, "score": 0.9851083159446716, "start": 381, "tag": "USERNAME", "value": "username" }, { "context": " authentication-data {:Username username :Password password}\n authentication-details (new js/AmazonCog", "end": 408, "score": 0.9961841702461243, "start": 400, "tag": "PASSWORD", "value": "password" }, { "context": " (clj->js pool-data))\n user-data {:Username username :Pool user-pool}\n cognito-user (new js/Ama", "end": 733, "score": 0.990166962146759, "start": 725, "tag": "USERNAME", "value": "username" } ]
src/aws_services/core.cljs
theopcode/aws-services-cognito
0
(ns aws-services.core (:require [cljsjs.aws-sdk-js] [aws.amazon-cognito])) (defonce config (atom {})) (def empty-data {:region nil :identity-pool-id nil :user-pool-id nil :client-id nil }) (defn ^:export sign-in [username password] "TODO: Test, goog.async" (let [username username password password authentication-data {:Username username :Password password} authentication-details (new js/AmazonCognitoIdentity.AuthenticationDetails (clj->js authentication-data)) pool-data {:UserPoolId (:user-pool-id @config) :ClientId (:client-id @config)} user-pool (new js/AmazonCognitoIdentity.CognitoUserPool (clj->js pool-data)) user-data {:Username username :Pool user-pool} cognito-user (new js/AmazonCognitoIdentity.CognitoUser (clj->js user-data))] (.authenticateUser cognito-user authentication-details (clj->js { :onSuccess (fn [results] (js/console.log "results" results) (js/console.log "accessToken" (.getJwtToken (.getAccessToken results))) (js/console.log "idToken" (.-jwtToken (.-idToken results))) ) :onFailure (fn [error] (js/console.log "onFailure" error)) })))) (defn- set-config [user-conf] "TODO: Test" (let [user-conf (merge empty-data user-conf) {:keys [region identity-pool-id user-pool-id client-id] :as required } user-conf] (if (some nil? (vals required)) (let [missing (remove nil? (flatten (filterv (fn [[k v]] (nil? v)) required)))] (throw (js/Error. (str "The following values are required: " (clojure.string/join ", " missing))))) (do (swap! config assoc :region region) (swap! config assoc :identity-pool-id identity-pool-id) (swap! config assoc :user-pool-id user-pool-id) (swap! config assoc :client-id client-id))))) (defn- set-aws-basic [{:keys [region identity-pool-id] :or {:region nil :identity-pool-id nil}}] "TODO: Test" (let [region region identity-pool-id identity-pool-id identity-credential-args { :IdentityPoolId identity-pool-id } cognito-identity-credentials (new js/AWS.CognitoIdentityCredentials (clj->js identity-credential-args)) place-holder {:accessKeyId "anything" :secretAccessKey "anything"}] (set! (.-region (.-config js/AWS)) region) (set! (.-credentials (.-config js/AWS)) cognito-identity-credentials) (.update (.-config js/AWS) (clj->js place-holder)))) (defn ^:init init [user-conf] (set-config user-conf) (set-aws-basic @config))
118595
(ns aws-services.core (:require [cljsjs.aws-sdk-js] [aws.amazon-cognito])) (defonce config (atom {})) (def empty-data {:region nil :identity-pool-id nil :user-pool-id nil :client-id nil }) (defn ^:export sign-in [username password] "TODO: Test, goog.async" (let [username username password <PASSWORD> authentication-data {:Username username :Password <PASSWORD>} authentication-details (new js/AmazonCognitoIdentity.AuthenticationDetails (clj->js authentication-data)) pool-data {:UserPoolId (:user-pool-id @config) :ClientId (:client-id @config)} user-pool (new js/AmazonCognitoIdentity.CognitoUserPool (clj->js pool-data)) user-data {:Username username :Pool user-pool} cognito-user (new js/AmazonCognitoIdentity.CognitoUser (clj->js user-data))] (.authenticateUser cognito-user authentication-details (clj->js { :onSuccess (fn [results] (js/console.log "results" results) (js/console.log "accessToken" (.getJwtToken (.getAccessToken results))) (js/console.log "idToken" (.-jwtToken (.-idToken results))) ) :onFailure (fn [error] (js/console.log "onFailure" error)) })))) (defn- set-config [user-conf] "TODO: Test" (let [user-conf (merge empty-data user-conf) {:keys [region identity-pool-id user-pool-id client-id] :as required } user-conf] (if (some nil? (vals required)) (let [missing (remove nil? (flatten (filterv (fn [[k v]] (nil? v)) required)))] (throw (js/Error. (str "The following values are required: " (clojure.string/join ", " missing))))) (do (swap! config assoc :region region) (swap! config assoc :identity-pool-id identity-pool-id) (swap! config assoc :user-pool-id user-pool-id) (swap! config assoc :client-id client-id))))) (defn- set-aws-basic [{:keys [region identity-pool-id] :or {:region nil :identity-pool-id nil}}] "TODO: Test" (let [region region identity-pool-id identity-pool-id identity-credential-args { :IdentityPoolId identity-pool-id } cognito-identity-credentials (new js/AWS.CognitoIdentityCredentials (clj->js identity-credential-args)) place-holder {:accessKeyId "anything" :secretAccessKey "anything"}] (set! (.-region (.-config js/AWS)) region) (set! (.-credentials (.-config js/AWS)) cognito-identity-credentials) (.update (.-config js/AWS) (clj->js place-holder)))) (defn ^:init init [user-conf] (set-config user-conf) (set-aws-basic @config))
true
(ns aws-services.core (:require [cljsjs.aws-sdk-js] [aws.amazon-cognito])) (defonce config (atom {})) (def empty-data {:region nil :identity-pool-id nil :user-pool-id nil :client-id nil }) (defn ^:export sign-in [username password] "TODO: Test, goog.async" (let [username username password PI:PASSWORD:<PASSWORD>END_PI authentication-data {:Username username :Password PI:PASSWORD:<PASSWORD>END_PI} authentication-details (new js/AmazonCognitoIdentity.AuthenticationDetails (clj->js authentication-data)) pool-data {:UserPoolId (:user-pool-id @config) :ClientId (:client-id @config)} user-pool (new js/AmazonCognitoIdentity.CognitoUserPool (clj->js pool-data)) user-data {:Username username :Pool user-pool} cognito-user (new js/AmazonCognitoIdentity.CognitoUser (clj->js user-data))] (.authenticateUser cognito-user authentication-details (clj->js { :onSuccess (fn [results] (js/console.log "results" results) (js/console.log "accessToken" (.getJwtToken (.getAccessToken results))) (js/console.log "idToken" (.-jwtToken (.-idToken results))) ) :onFailure (fn [error] (js/console.log "onFailure" error)) })))) (defn- set-config [user-conf] "TODO: Test" (let [user-conf (merge empty-data user-conf) {:keys [region identity-pool-id user-pool-id client-id] :as required } user-conf] (if (some nil? (vals required)) (let [missing (remove nil? (flatten (filterv (fn [[k v]] (nil? v)) required)))] (throw (js/Error. (str "The following values are required: " (clojure.string/join ", " missing))))) (do (swap! config assoc :region region) (swap! config assoc :identity-pool-id identity-pool-id) (swap! config assoc :user-pool-id user-pool-id) (swap! config assoc :client-id client-id))))) (defn- set-aws-basic [{:keys [region identity-pool-id] :or {:region nil :identity-pool-id nil}}] "TODO: Test" (let [region region identity-pool-id identity-pool-id identity-credential-args { :IdentityPoolId identity-pool-id } cognito-identity-credentials (new js/AWS.CognitoIdentityCredentials (clj->js identity-credential-args)) place-holder {:accessKeyId "anything" :secretAccessKey "anything"}] (set! (.-region (.-config js/AWS)) region) (set! (.-credentials (.-config js/AWS)) cognito-identity-credentials) (.update (.-config js/AWS) (clj->js place-holder)))) (defn ^:init init [user-conf] (set-config user-conf) (set-aws-basic @config))
[ { "context": "n [subs]\n (let [key (keyword (gensym \"beicon\"))]\n (when emit-current-value? ", "end": 5701, "score": 0.5743555426597595, "start": 5699, "tag": "KEY", "value": "be" } ]
src/beicon/core.cljs
funcool/beicon
151
(ns beicon.core (:refer-clojure :exclude [true? map filter reduce merge repeat first last mapcat repeatedly zip dedupe drop take take-while map-indexed concat empty delay range throw do trampoline subs flatten]) (:require [beicon.impl.rxjs] [beicon.impl.rxjs-operators] [cljs.core :as c])) (def rx js/rxjsMain) (def rxop js/rxjsOperators) (def ^:const Observable (.-Observable ^js rx)) (def ^:const Subject (.-Subject ^js rx)) (def ^:const BehaviorSubject (.-BehaviorSubject ^js rx)) (def ^:const Subscriber (.-Subscriber ^js rx)) (def ^:const Observer (.-Subscriber ^js rx)) (def ^:const Disposable (.-Subscription ^js rx)) (def ^:const Scheduler (.-Scheduler ^js rx)) ;; --- Interop Helpers (declare subject?) (defn to-observable "Coerce a object to an observable instance." [ob] (assert (subject? ob) "`ob` should be a Subject instance") (.asObservable ^js ob)) (def ^:private noop (constantly nil)) (defn pipe ([ob f] (.pipe ob f)) ([ob f1 f2] (.pipe ob f1 f2)) ([ob f1 f2 f3] (.pipe ob f1 f2 f3)) ([ob f1 f2 f3 f4] (.pipe ob f1 f2 f3 f4)) ([ob f1 f2 f3 f4 & rest] (let [pipe' (.-pipe ob)] (apply pipe' ob f1 f2 f4 rest)))) ;; --- Predicates (extend-type BehaviorSubject IDeref (-deref [self] (.getValue ^js self))) (defn observable? "Return true if `ob` is a instance of Rx.Observable." [ob] (instance? Observable ob)) (defn disposable? "Check if the provided object is disposable (jvm) or subscription (js)." [v] (instance? Disposable v)) (defn scheduler? "Check if the provided value is Scheduler instance." [v] (instance? Scheduler v)) (defn subject? "Check if the provided value is Subject instance." [b] (instance? Subject b)) ;; --- Observables Constructor (defn create "Creates an observable sequence from a specified subscribe method implementation." [sf] {:pre [(fn? sf)]} (.create ^js Observable (fn [subs] (try (sf subs) (catch :default e (.error subs e)))))) ;; --- Observable Subscription (defprotocol ISubscriber "Backpressure aware subscriber abstraction." (-on-init [_ s] "Subscription initialization hook.") (-on-next [_ s value] "Subscription data notification hook.") (-on-error [_ error] "Subscription error notification hook.") (-on-end [_] "Subscription termination notification hook.")) (defprotocol IDisposable (-dispose [_] "dispose resources.")) (defn dispose! "Dispose resources acquired by the subscription." [v] (-dispose v)) ;; Alias (def unsub! dispose!) (def cancel! dispose!) (defn- wrap-disposable [disposable] (specify! disposable IFn (-invoke ([this] (-dispose this))) IDisposable (-dispose [this] (.unsubscribe this)))) (defn subscribe-with "Subscribes an observer or subscriber to the observable sequence." [ob observer] {:pre [(subject? observer)]} (wrap-disposable (.subscribe ob observer))) (defn subscribe "Subscribes an observer to the observable sequence." ([ob nf] (subscribe ob nf nil nil)) ([ob nf ef] (subscribe ob nf ef nil)) ([ob nf ef cf] (let [observer (.create ^js Subscriber (if (fn? nf) nf noop) (if (fn? ef) ef noop) (if (fn? cf) cf noop))] (wrap-disposable (.subscribe ob observer))))) (defn subs "A specialized version of `subscribe` with inverted arguments." ([nf ob] (subscribe ob nf nil nil)) ([nf ef ob] (subscribe ob nf ef nil)) ([nf ef cf ob] (subscribe ob nf ef cf))) ;; Alias (def sub! subscribe) (defn on-value "Subscribes a function to invoke for each element in the observable sequence." [ob f] (subscribe ob f nil nil)) (def on-next "A semantic alias for `on-value`." on-value) (defn on-error "Subscribes a function to invoke upon exceptional termination of the observable sequence." [ob f] (subscribe ob nil f nil)) (defn on-end "Subscribes a function to invoke upon graceful termination of the observable sequence." [ob f] (subscribe ob nil nil f)) (def on-complete "A semantic alias for `on-end`." on-end) ;; --- Bus / Subject (defn subject "Subject that, once an Observer has subscribed, emits all subsequently observed items to the subscriber." [] (Subject.)) (defn behavior-subject "Bus that emits the most recent item it has observed and all subsequent observed items to each subscribed Observer." [v] (BehaviorSubject. v)) (defn push! "Pushes the given value to the bus stream." [b v] (.next ^js b v)) (defn error! "Pushes the given error to the bus stream." [b e] (.error ^js b e)) (defn end! "Ends the given bus stream." [b] (.complete ^js b)) ;; --- Observable Factory Helpers (defn range "Generates an observable sequence that repeats the given element." ([b] (range 0 b)) ([a b] (.range rx a b))) (defn publish "Create a connectable (hot) observable from other observable." [ob] (.publish ob)) (defn share "Returns an observable sequence that shares a single subscription to the underlying sequence." [ob] (pipe ob (.share ^js rxop))) (defn connect! "Connect the connectable observable." [ob] (.connect ob)) (defn from "Creates an observable from js arrays, clojurescript collections, and promise instance." [v] (if (nil? v) (.empty rx) (.from rx v))) (defn from-atom ([atm] (from-atom atm nil)) ([atm {:keys [emit-current-value?] :or {emit-current-value? false}}] (create (fn [subs] (let [key (keyword (gensym "beicon"))] (when emit-current-value? (push! subs @atm)) (add-watch atm key (fn [_ _ _ val] (push! subs val))) (fn [] (remove-watch atm key))))))) (defn from-event "Creates an Observable by attaching an event listener to an event target" [et ev] (.fromEvent rx et ev)) (defn empty "Returns an observable sequence that is already in end state." [] (.empty rx)) (defn if-empty "Emits a given value if the source Observable completes without emitting any next value, otherwise mirrors the source Observable." [default ob] (pipe ob (.defaultIfEmpty ^js rxop default))) ;; Alias (def default-if-empty if-empty) (defn throw [e] (.throwError rx e)) ;; Alias (def error throw) (defn fjoin "Runs all observable sequences in parallel and collect their last elements." [& items] (let [[selector items] (if (ifn? (c/first items)) [(c/first items) (rest items)] [vector items]) items (if (vector? items) items (into [] items))] (apply (.-forkJoin rx) (conj items selector)))) ;; Alias (def fork-join fjoin) (defn of "Converts arguments to an observable sequence." ([a] (.of rx a)) ([a b] (.of rx a b)) ([a b c] (.of rx a b c)) ([a b c d] (.of rx a b c d)) ([a b c d e] (.of rx a b c d e)) ([a b c d e f] (.of rx a b c d e f)) ([a b c d e f & more] (apply (.-of rx) a b c d e f more))) (defn- disposable-atom [ref disposable] (specify! ref IFn (-invoke ([this] (-dispose this))) IDisposable (-dispose [_] (.unsubscribe disposable)))) (defn to-atom "Materialize the observable sequence into an atom." ([ob] (let [a (atom nil)] (to-atom ob a))) ([ob a] (let [disposable (on-value ob #(reset! a %))] (disposable-atom a disposable))) ([ob a f] (let [disposable (on-value ob #(swap! a f %))] (disposable-atom a disposable)))) ;; --- Observable Transformations (defn race "Create an observable that surfaces any of the given sequences, whichever reacted first." ([a b] (.race rx a b)) ([a b & more] (apply (.-race rx) a b more))) (defn zip "Merges the specified observable sequences or Promises (cljs) into one observable sequence." [& items] (let [zip-fn (unchecked-get rx "zip")] (apply zip-fn items))) (defn concat "Concatenates all of the specified observable sequences, as long as the previous observable sequence terminated successfully." [& more] (let [concat-fn (unchecked-get rx "concat")] (apply concat-fn (c/filter some? more)))) (defn merge "Merges all the observable sequences and Promises into a single observable sequence." [& more] (let [merge-fn (unchecked-get rx "merge")] (apply merge-fn (c/filter some? more)))) (defn merge-all "Merges an observable sequence of observable sequences into an observable sequence." ([ob] (pipe ob (.mergeAll ^js rxop))) ([^number concurrency ob] (pipe ob (.mergeAll ^js rxop concurrency)))) (defn filter "Filters the elements of an observable sequence based on a predicate." [f ob] (pipe ob (.filter ^js rxop #(boolean (f %))))) (defn map "Apply a function to each element of an observable sequence." [f ob] (pipe ob (.map ^js rxop #(f %)))) (defn map-indexed [f ob] (pipe ob (.map ^js rxop #(f %2 %1)))) (defn merge-map "Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences or Promises or array/iterable into one observable sequence. In other languages is called: flatMap or mergeMap." [f ob] (pipe ob (.flatMap ^js rxop #(f %)))) (defn switch-map [f obj] (pipe obj (.switchMap ^js rxop #(f %)))) ;; Aliases (def fmap merge-map) (def flat-map merge-map) (defn mapcat "Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences or Promises or array/iterable into one observable sequence." [f ob] (pipe ob (.concatMap ^js rxop #(f %)))) (defn mapcat-indexed [f ob] (pipe ob (.concatMap ^js rxop #(f %2 %1)))) (defn concat-all [ob] (pipe ob (.concatAll ^js rxop))) (defn skip "Bypasses a specified number of elements in an observable sequence and then returns the remaining elements." [n ob] (pipe ob (.skip ^js rxop (int n)))) (defn skip-while "Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements." [f ob] (pipe ob (.skipWhile ^js rxop #(boolean (f %))))) (defn skip-until "Returns the values from the source observable sequence only after the other observable sequence produces a value." [pob ob] (pipe ob (.skipUntil ^js rxop pob))) (defn skip-last "Skip a specified number of values before the completion of an observable." [n ob] (.pipe ob (.skipLast ^js rxop (int n)))) (defn take "Bypasses a specified number of elements in an observable sequence and then returns the remaining elements." [n ob] (pipe ob (.take ^js rxop n))) (defn first "Return an observable that only has the first value of the provided observable. You can optionally pass a predicate and default value." ([ob] (pipe ob (.first ^js rxop))) ([f ob] (pipe ob (.first ^js rxop #(boolean (f %))))) ([f default ob] (pipe ob (.first ^js rxop #(boolean (f %)) default)))) (defn last "Return an observable that only has the last value of the provided observable. You can optionally pass a predicate and default value." ([ob] (pipe ob (.last ^js rxop))) ([f ob] (pipe ob (.last ^js rxop #(boolean (f %))))) ([f default ob] (pipe ob (.last ^js rxop #(boolean (f %)) default)))) (defn take-while "Returns elements from an observable sequence as long as a specified predicate returns true." [f ob] (pipe ob (.takeWhile ^js rxop #(boolean (f %))))) (defn take-until "Returns the values from the source observable sequence until the other observable sequence or Promise produces a value." [other ob] (pipe ob (.takeUntil ^js rxop other))) (defn reduce "Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence." ([f ob] (pipe ob (.reduce ^js rxop #(f %1 %2)))) ([f seed ob] (pipe ob (.reduce ^js rxop #(f %1 %2) seed)))) (defn scan "Applies an accumulator function over an observable sequence and returns each intermediate result. Same as reduce but with intermediate results" ([f ob] (pipe ob (.scan ^js rxop #(f %1 %2)))) ([f seed ob] (pipe ob (.scan ^js rxop #(f %1 %2) seed)))) (defn merge-scan "Applies an accumulator function over the source Observable where the accumulator function itself returns an Observable, then each intermediate Observable returned is merged into the output Observable." [f seed ob] (let [merge-scan-fn (unchecked-get rxop "mergeScan")] (pipe ob (merge-scan-fn #(f %1 %2) seed)))) (defn expand "Recursively projects each source value to an Observable which is merged in the output Observable." [f ob] (pipe ob (.expand ^js rxop f))) (defn with-latest "Merges the specified observable sequences into one observable sequence by using the selector function only when the source observable sequence (the instance) produces an element." {:deprecated true} [f other source] (pipe source (.withLatestFrom ^js rxop other f))) (defn with-latest-from "Merges the specified observable sequences into one observable sequence by using the selector function only when the source observable sequence (the instance) produces an element." ([other source] (let [wlf (.-withLatestFrom ^js rxop) cmb (cond (observable? other) (wlf other) (array? other) (.apply wlf nil other) (sequential? other) (apply wlf other) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))] (pipe source cmb))) ([o1 o2 source] (pipe source (.withLatestFrom ^js rxop o1 o2))) ([o1 o2 o3 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3))) ([o1 o2 o3 o4 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4))) ([o1 o2 o3 o4 o5 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4 o5))) ([o1 o2 o3 o4 o5 o6 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4 o5 o6)))) (defn combine-latest "Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables (constructor)." ([obs] (cond (array? obs) (.combineLatest rx obs) (sequential? obs) (.combineLatest rx (into-array obs)) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))) ([o1 o2] (.combineLatest rx o1 o2)) ([o1 o2 o3] (.combineLatest rx o1 o2 o3)) ([o1 o2 o3 o4] (.combineLatest rx o1 o2 o3 o4)) ([o1 o2 o3 o4 & other] (combine-latest (into-array (into [o1 o2 o3 o4] other))))) (defn combine-latest-with "Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables (operator)." [other ob] (pipe ob (.combineLatestWith ^js rxop other))) (defn catch "Continues an observable sequence that is terminated by an exception with the next observable sequence." ([handler ob] (pipe ob (.catchError ^js rxop (fn [error source] (let [value (handler error source)] (if (observable? value) value (empty))))))) ([pred handler ob] (catch (fn [value] (if (pred value) (handler value) (throw value))) ob))) (defn tap "Invokes an action for each element in the observable sequence." ([f ob] (pipe ob (.tap ^js rxop f))) ([f g ob] (pipe ob (.tap ^js rxop f g))) ([f g e ob] (pipe ob (.tap ^js rxop f g e)))) ;; Aliases (def do tap) (defn log "Print all values passed through the given observable sequence." ([ob] (tap #(println %) ob)) ([prefix ob] (tap #(println prefix (str %)) ob))) (defn pr-log "Print all values passed through the given observable sequence using pr-str." ([ob] (tap #(println (pr-str %)) ob)) ([prefix ob] (tap #(println prefix (pr-str %)) ob))) (defn throttle "Returns an observable sequence that emits only the first item emitted by the source Observable during sequential time windows of a specified duration." ([ms ob] (pipe ob (.throttleTime ^js rxop ms))) ([ms config ob] (let [{:keys [leading trailing] :or {leading true trailing false}} config] (pipe ob (.throttleTime ^js rxop ms #js {:leading leading :trailing trailing}))))) (defn debounce "Emits an item from the source Observable after a particular timespan has passed without the Observable omitting any other items." [ms ob] (pipe ob (.debounceTime ^js rxop ms))) (defn sample "Samples the observable sequence at each interval." [ms ob] (pipe ob (.sampleTime ^js rxop ms))) (defn sample-when "Samples the observable sequence at each interval." [other ob] (pipe ob (.sample ^js rxop other))) (defn ignore "Ignores all elements in an observable sequence leaving only the termination messages." [ob] (pipe ob (.ignoreElements ^js rxop))) (defn finalize "Returns an Observable that mirrors the source Observable, but will call a specified function when the source terminates on complete or error." [f ob] (pipe ob (.finalize ^js rxop #(f)))) (defn dedupe "Returns an observable sequence that contains only distinct contiguous elements." ([ob] (dedupe identity ob)) ([f ob] (pipe ob (.distinctUntilChanged ^js rxop identical? f)))) (defn dedupe' "Returns an observable sequence that contains only d istinct elements. Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large." ([ob] (pipe ob (.distinct ^js rxop identical?))) ([f ob] (pipe ob (.distinct ^js rxop identical? f)))) (defn buffer "Projects each element of an observable sequence into zero or more buffers which are produced based on element count information." ([n ob] (pipe ob (.bufferCount ^js rxop n))) ([n skip ob] (pipe ob (.bufferCount ^js rxop n skip)))) (defn buffer-time "Buffers the source Observable values for a specific time period." ([ms ob] (pipe ob (.bufferTime ^js rxop ms))) ([ms start ob] (pipe ob (.bufferTime ^js rxop ms start))) ([ms start max ob] (pipe ob (.bufferTime ^js rxop ms start max)))) (defn buffer-until "Buffers the source Observable values until notifier emits." [notifier ob] (pipe ob (.buffer ^js rxop notifier))) (defn retry "Given an optional number of retries and an observable, repeats the source observable the specified number of times or until it terminates. If no number of retries is given, it will be retried indefinitely." ([ob] (pipe ob (.retry ^js rxop))) ([n ob] (pipe ob (.retry ^js rxop ^long n)))) (defn transform "Transform the observable sequence using transducers." [xform ob] (when-not (observable? ob) (throw (ex-info "Only observables are supported" {}))) (letfn [(subs-step [subs] (fn ([r] (end! subs) r) ([_ input] (push! subs input) input)))] (create (fn [subs] (let [xsubs (xform (subs-step subs)) step (fn [input] (let [v (xsubs nil input)] (when (reduced? v) (xsubs @v)))) disposable (on-value ob step)] (on-complete ob #(do (xsubs nil) (end! subs))) (fn [] (dispose! disposable))))))) (defn timer "Returns an observable sequence that produces a value after `ms` has elapsed and then after each period." ([delay] (.timer rx delay)) ([delay period] (.timer rx delay period))) (defn timeout "Returns the source observable sequence or the other observable sequence if dueTime elapses." ([ms ob] (pipe ob (.timeout ^js rxop ms))) ([ms other ob] (pipe ob (.timeoutWith ^js rxop ms other)))) (defn delay "Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved." [ms ob] (pipe ob (.delay ^js rxop ms))) (defn delay-emit "Time shift the observable but also increase the relative time between emisions." [ms ob] (mapcat #(delay ms (of %)) ob)) (defn delay-when "Time shifts the observable sequence based on a subscription delay and a delay selector function for each element." ([sf ob] (pipe ob (.delayWhen ^js rxop sf))) ([sd sf ob] (pipe ob (.delayWhen ^js rxop sf sd)))) (defn delay-at-least "Time shifts at least `ms` milisseconds." [ms ob] (pipe ob (fn [source] (->> source (combine-latest-with (timer ms)) (map c/first))))) (defn interval "Returns an observable sequence that produces a value after each period." [ms] (.interval rx ms)) (defn flatten "Just like clojure collections flatten but for rx streams. Given a stream off collections will emit every value separately" [ob] (pipe ob (.concatMap ^js rxop identity))) (defn concat-reduce "Like reduce but accepts a function that returns a stream. Will use as value for the next step in the reduce the last valued emited by the stream in the function." [f seed ob] (let [current-acc (volatile! seed)] (->> (concat (of seed) (->> ob (mapcat #(f @current-acc %)) (tap #(vreset! current-acc %)))) (last)))) ;; --- Schedulers (defn scheduler "Get the scheduler instance by type. The posible types are: `:asap`, `:async`, `:queue`. Old `:trampoline` type is renamed as `:queue` and is deprecated." [type] (case type :asap (.-asapScheduler rx) :async (.-asyncScheduler rx) :queue (.-queueScheduler rx) :af (.-animationFrameScheduler rx) :animation-frame (.-animationFrameScheduler rx))) (defn observe-on [schd ob] (cond (scheduler? schd) (pipe ob (.observeOn ^js rxop schd)) (keyword? schd) (pipe ob (.observeOn ^js rxop (scheduler schd))) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))) (defn subscribe-on [schd ob] (cond (scheduler? schd) (pipe ob (.subscribeOn ^js rxop schd)) (keyword? schd) (pipe ob (.subscribeOn ^js rxop (scheduler schd))) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument}))))
121430
(ns beicon.core (:refer-clojure :exclude [true? map filter reduce merge repeat first last mapcat repeatedly zip dedupe drop take take-while map-indexed concat empty delay range throw do trampoline subs flatten]) (:require [beicon.impl.rxjs] [beicon.impl.rxjs-operators] [cljs.core :as c])) (def rx js/rxjsMain) (def rxop js/rxjsOperators) (def ^:const Observable (.-Observable ^js rx)) (def ^:const Subject (.-Subject ^js rx)) (def ^:const BehaviorSubject (.-BehaviorSubject ^js rx)) (def ^:const Subscriber (.-Subscriber ^js rx)) (def ^:const Observer (.-Subscriber ^js rx)) (def ^:const Disposable (.-Subscription ^js rx)) (def ^:const Scheduler (.-Scheduler ^js rx)) ;; --- Interop Helpers (declare subject?) (defn to-observable "Coerce a object to an observable instance." [ob] (assert (subject? ob) "`ob` should be a Subject instance") (.asObservable ^js ob)) (def ^:private noop (constantly nil)) (defn pipe ([ob f] (.pipe ob f)) ([ob f1 f2] (.pipe ob f1 f2)) ([ob f1 f2 f3] (.pipe ob f1 f2 f3)) ([ob f1 f2 f3 f4] (.pipe ob f1 f2 f3 f4)) ([ob f1 f2 f3 f4 & rest] (let [pipe' (.-pipe ob)] (apply pipe' ob f1 f2 f4 rest)))) ;; --- Predicates (extend-type BehaviorSubject IDeref (-deref [self] (.getValue ^js self))) (defn observable? "Return true if `ob` is a instance of Rx.Observable." [ob] (instance? Observable ob)) (defn disposable? "Check if the provided object is disposable (jvm) or subscription (js)." [v] (instance? Disposable v)) (defn scheduler? "Check if the provided value is Scheduler instance." [v] (instance? Scheduler v)) (defn subject? "Check if the provided value is Subject instance." [b] (instance? Subject b)) ;; --- Observables Constructor (defn create "Creates an observable sequence from a specified subscribe method implementation." [sf] {:pre [(fn? sf)]} (.create ^js Observable (fn [subs] (try (sf subs) (catch :default e (.error subs e)))))) ;; --- Observable Subscription (defprotocol ISubscriber "Backpressure aware subscriber abstraction." (-on-init [_ s] "Subscription initialization hook.") (-on-next [_ s value] "Subscription data notification hook.") (-on-error [_ error] "Subscription error notification hook.") (-on-end [_] "Subscription termination notification hook.")) (defprotocol IDisposable (-dispose [_] "dispose resources.")) (defn dispose! "Dispose resources acquired by the subscription." [v] (-dispose v)) ;; Alias (def unsub! dispose!) (def cancel! dispose!) (defn- wrap-disposable [disposable] (specify! disposable IFn (-invoke ([this] (-dispose this))) IDisposable (-dispose [this] (.unsubscribe this)))) (defn subscribe-with "Subscribes an observer or subscriber to the observable sequence." [ob observer] {:pre [(subject? observer)]} (wrap-disposable (.subscribe ob observer))) (defn subscribe "Subscribes an observer to the observable sequence." ([ob nf] (subscribe ob nf nil nil)) ([ob nf ef] (subscribe ob nf ef nil)) ([ob nf ef cf] (let [observer (.create ^js Subscriber (if (fn? nf) nf noop) (if (fn? ef) ef noop) (if (fn? cf) cf noop))] (wrap-disposable (.subscribe ob observer))))) (defn subs "A specialized version of `subscribe` with inverted arguments." ([nf ob] (subscribe ob nf nil nil)) ([nf ef ob] (subscribe ob nf ef nil)) ([nf ef cf ob] (subscribe ob nf ef cf))) ;; Alias (def sub! subscribe) (defn on-value "Subscribes a function to invoke for each element in the observable sequence." [ob f] (subscribe ob f nil nil)) (def on-next "A semantic alias for `on-value`." on-value) (defn on-error "Subscribes a function to invoke upon exceptional termination of the observable sequence." [ob f] (subscribe ob nil f nil)) (defn on-end "Subscribes a function to invoke upon graceful termination of the observable sequence." [ob f] (subscribe ob nil nil f)) (def on-complete "A semantic alias for `on-end`." on-end) ;; --- Bus / Subject (defn subject "Subject that, once an Observer has subscribed, emits all subsequently observed items to the subscriber." [] (Subject.)) (defn behavior-subject "Bus that emits the most recent item it has observed and all subsequent observed items to each subscribed Observer." [v] (BehaviorSubject. v)) (defn push! "Pushes the given value to the bus stream." [b v] (.next ^js b v)) (defn error! "Pushes the given error to the bus stream." [b e] (.error ^js b e)) (defn end! "Ends the given bus stream." [b] (.complete ^js b)) ;; --- Observable Factory Helpers (defn range "Generates an observable sequence that repeats the given element." ([b] (range 0 b)) ([a b] (.range rx a b))) (defn publish "Create a connectable (hot) observable from other observable." [ob] (.publish ob)) (defn share "Returns an observable sequence that shares a single subscription to the underlying sequence." [ob] (pipe ob (.share ^js rxop))) (defn connect! "Connect the connectable observable." [ob] (.connect ob)) (defn from "Creates an observable from js arrays, clojurescript collections, and promise instance." [v] (if (nil? v) (.empty rx) (.from rx v))) (defn from-atom ([atm] (from-atom atm nil)) ([atm {:keys [emit-current-value?] :or {emit-current-value? false}}] (create (fn [subs] (let [key (keyword (gensym "<KEY>icon"))] (when emit-current-value? (push! subs @atm)) (add-watch atm key (fn [_ _ _ val] (push! subs val))) (fn [] (remove-watch atm key))))))) (defn from-event "Creates an Observable by attaching an event listener to an event target" [et ev] (.fromEvent rx et ev)) (defn empty "Returns an observable sequence that is already in end state." [] (.empty rx)) (defn if-empty "Emits a given value if the source Observable completes without emitting any next value, otherwise mirrors the source Observable." [default ob] (pipe ob (.defaultIfEmpty ^js rxop default))) ;; Alias (def default-if-empty if-empty) (defn throw [e] (.throwError rx e)) ;; Alias (def error throw) (defn fjoin "Runs all observable sequences in parallel and collect their last elements." [& items] (let [[selector items] (if (ifn? (c/first items)) [(c/first items) (rest items)] [vector items]) items (if (vector? items) items (into [] items))] (apply (.-forkJoin rx) (conj items selector)))) ;; Alias (def fork-join fjoin) (defn of "Converts arguments to an observable sequence." ([a] (.of rx a)) ([a b] (.of rx a b)) ([a b c] (.of rx a b c)) ([a b c d] (.of rx a b c d)) ([a b c d e] (.of rx a b c d e)) ([a b c d e f] (.of rx a b c d e f)) ([a b c d e f & more] (apply (.-of rx) a b c d e f more))) (defn- disposable-atom [ref disposable] (specify! ref IFn (-invoke ([this] (-dispose this))) IDisposable (-dispose [_] (.unsubscribe disposable)))) (defn to-atom "Materialize the observable sequence into an atom." ([ob] (let [a (atom nil)] (to-atom ob a))) ([ob a] (let [disposable (on-value ob #(reset! a %))] (disposable-atom a disposable))) ([ob a f] (let [disposable (on-value ob #(swap! a f %))] (disposable-atom a disposable)))) ;; --- Observable Transformations (defn race "Create an observable that surfaces any of the given sequences, whichever reacted first." ([a b] (.race rx a b)) ([a b & more] (apply (.-race rx) a b more))) (defn zip "Merges the specified observable sequences or Promises (cljs) into one observable sequence." [& items] (let [zip-fn (unchecked-get rx "zip")] (apply zip-fn items))) (defn concat "Concatenates all of the specified observable sequences, as long as the previous observable sequence terminated successfully." [& more] (let [concat-fn (unchecked-get rx "concat")] (apply concat-fn (c/filter some? more)))) (defn merge "Merges all the observable sequences and Promises into a single observable sequence." [& more] (let [merge-fn (unchecked-get rx "merge")] (apply merge-fn (c/filter some? more)))) (defn merge-all "Merges an observable sequence of observable sequences into an observable sequence." ([ob] (pipe ob (.mergeAll ^js rxop))) ([^number concurrency ob] (pipe ob (.mergeAll ^js rxop concurrency)))) (defn filter "Filters the elements of an observable sequence based on a predicate." [f ob] (pipe ob (.filter ^js rxop #(boolean (f %))))) (defn map "Apply a function to each element of an observable sequence." [f ob] (pipe ob (.map ^js rxop #(f %)))) (defn map-indexed [f ob] (pipe ob (.map ^js rxop #(f %2 %1)))) (defn merge-map "Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences or Promises or array/iterable into one observable sequence. In other languages is called: flatMap or mergeMap." [f ob] (pipe ob (.flatMap ^js rxop #(f %)))) (defn switch-map [f obj] (pipe obj (.switchMap ^js rxop #(f %)))) ;; Aliases (def fmap merge-map) (def flat-map merge-map) (defn mapcat "Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences or Promises or array/iterable into one observable sequence." [f ob] (pipe ob (.concatMap ^js rxop #(f %)))) (defn mapcat-indexed [f ob] (pipe ob (.concatMap ^js rxop #(f %2 %1)))) (defn concat-all [ob] (pipe ob (.concatAll ^js rxop))) (defn skip "Bypasses a specified number of elements in an observable sequence and then returns the remaining elements." [n ob] (pipe ob (.skip ^js rxop (int n)))) (defn skip-while "Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements." [f ob] (pipe ob (.skipWhile ^js rxop #(boolean (f %))))) (defn skip-until "Returns the values from the source observable sequence only after the other observable sequence produces a value." [pob ob] (pipe ob (.skipUntil ^js rxop pob))) (defn skip-last "Skip a specified number of values before the completion of an observable." [n ob] (.pipe ob (.skipLast ^js rxop (int n)))) (defn take "Bypasses a specified number of elements in an observable sequence and then returns the remaining elements." [n ob] (pipe ob (.take ^js rxop n))) (defn first "Return an observable that only has the first value of the provided observable. You can optionally pass a predicate and default value." ([ob] (pipe ob (.first ^js rxop))) ([f ob] (pipe ob (.first ^js rxop #(boolean (f %))))) ([f default ob] (pipe ob (.first ^js rxop #(boolean (f %)) default)))) (defn last "Return an observable that only has the last value of the provided observable. You can optionally pass a predicate and default value." ([ob] (pipe ob (.last ^js rxop))) ([f ob] (pipe ob (.last ^js rxop #(boolean (f %))))) ([f default ob] (pipe ob (.last ^js rxop #(boolean (f %)) default)))) (defn take-while "Returns elements from an observable sequence as long as a specified predicate returns true." [f ob] (pipe ob (.takeWhile ^js rxop #(boolean (f %))))) (defn take-until "Returns the values from the source observable sequence until the other observable sequence or Promise produces a value." [other ob] (pipe ob (.takeUntil ^js rxop other))) (defn reduce "Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence." ([f ob] (pipe ob (.reduce ^js rxop #(f %1 %2)))) ([f seed ob] (pipe ob (.reduce ^js rxop #(f %1 %2) seed)))) (defn scan "Applies an accumulator function over an observable sequence and returns each intermediate result. Same as reduce but with intermediate results" ([f ob] (pipe ob (.scan ^js rxop #(f %1 %2)))) ([f seed ob] (pipe ob (.scan ^js rxop #(f %1 %2) seed)))) (defn merge-scan "Applies an accumulator function over the source Observable where the accumulator function itself returns an Observable, then each intermediate Observable returned is merged into the output Observable." [f seed ob] (let [merge-scan-fn (unchecked-get rxop "mergeScan")] (pipe ob (merge-scan-fn #(f %1 %2) seed)))) (defn expand "Recursively projects each source value to an Observable which is merged in the output Observable." [f ob] (pipe ob (.expand ^js rxop f))) (defn with-latest "Merges the specified observable sequences into one observable sequence by using the selector function only when the source observable sequence (the instance) produces an element." {:deprecated true} [f other source] (pipe source (.withLatestFrom ^js rxop other f))) (defn with-latest-from "Merges the specified observable sequences into one observable sequence by using the selector function only when the source observable sequence (the instance) produces an element." ([other source] (let [wlf (.-withLatestFrom ^js rxop) cmb (cond (observable? other) (wlf other) (array? other) (.apply wlf nil other) (sequential? other) (apply wlf other) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))] (pipe source cmb))) ([o1 o2 source] (pipe source (.withLatestFrom ^js rxop o1 o2))) ([o1 o2 o3 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3))) ([o1 o2 o3 o4 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4))) ([o1 o2 o3 o4 o5 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4 o5))) ([o1 o2 o3 o4 o5 o6 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4 o5 o6)))) (defn combine-latest "Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables (constructor)." ([obs] (cond (array? obs) (.combineLatest rx obs) (sequential? obs) (.combineLatest rx (into-array obs)) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))) ([o1 o2] (.combineLatest rx o1 o2)) ([o1 o2 o3] (.combineLatest rx o1 o2 o3)) ([o1 o2 o3 o4] (.combineLatest rx o1 o2 o3 o4)) ([o1 o2 o3 o4 & other] (combine-latest (into-array (into [o1 o2 o3 o4] other))))) (defn combine-latest-with "Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables (operator)." [other ob] (pipe ob (.combineLatestWith ^js rxop other))) (defn catch "Continues an observable sequence that is terminated by an exception with the next observable sequence." ([handler ob] (pipe ob (.catchError ^js rxop (fn [error source] (let [value (handler error source)] (if (observable? value) value (empty))))))) ([pred handler ob] (catch (fn [value] (if (pred value) (handler value) (throw value))) ob))) (defn tap "Invokes an action for each element in the observable sequence." ([f ob] (pipe ob (.tap ^js rxop f))) ([f g ob] (pipe ob (.tap ^js rxop f g))) ([f g e ob] (pipe ob (.tap ^js rxop f g e)))) ;; Aliases (def do tap) (defn log "Print all values passed through the given observable sequence." ([ob] (tap #(println %) ob)) ([prefix ob] (tap #(println prefix (str %)) ob))) (defn pr-log "Print all values passed through the given observable sequence using pr-str." ([ob] (tap #(println (pr-str %)) ob)) ([prefix ob] (tap #(println prefix (pr-str %)) ob))) (defn throttle "Returns an observable sequence that emits only the first item emitted by the source Observable during sequential time windows of a specified duration." ([ms ob] (pipe ob (.throttleTime ^js rxop ms))) ([ms config ob] (let [{:keys [leading trailing] :or {leading true trailing false}} config] (pipe ob (.throttleTime ^js rxop ms #js {:leading leading :trailing trailing}))))) (defn debounce "Emits an item from the source Observable after a particular timespan has passed without the Observable omitting any other items." [ms ob] (pipe ob (.debounceTime ^js rxop ms))) (defn sample "Samples the observable sequence at each interval." [ms ob] (pipe ob (.sampleTime ^js rxop ms))) (defn sample-when "Samples the observable sequence at each interval." [other ob] (pipe ob (.sample ^js rxop other))) (defn ignore "Ignores all elements in an observable sequence leaving only the termination messages." [ob] (pipe ob (.ignoreElements ^js rxop))) (defn finalize "Returns an Observable that mirrors the source Observable, but will call a specified function when the source terminates on complete or error." [f ob] (pipe ob (.finalize ^js rxop #(f)))) (defn dedupe "Returns an observable sequence that contains only distinct contiguous elements." ([ob] (dedupe identity ob)) ([f ob] (pipe ob (.distinctUntilChanged ^js rxop identical? f)))) (defn dedupe' "Returns an observable sequence that contains only d istinct elements. Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large." ([ob] (pipe ob (.distinct ^js rxop identical?))) ([f ob] (pipe ob (.distinct ^js rxop identical? f)))) (defn buffer "Projects each element of an observable sequence into zero or more buffers which are produced based on element count information." ([n ob] (pipe ob (.bufferCount ^js rxop n))) ([n skip ob] (pipe ob (.bufferCount ^js rxop n skip)))) (defn buffer-time "Buffers the source Observable values for a specific time period." ([ms ob] (pipe ob (.bufferTime ^js rxop ms))) ([ms start ob] (pipe ob (.bufferTime ^js rxop ms start))) ([ms start max ob] (pipe ob (.bufferTime ^js rxop ms start max)))) (defn buffer-until "Buffers the source Observable values until notifier emits." [notifier ob] (pipe ob (.buffer ^js rxop notifier))) (defn retry "Given an optional number of retries and an observable, repeats the source observable the specified number of times or until it terminates. If no number of retries is given, it will be retried indefinitely." ([ob] (pipe ob (.retry ^js rxop))) ([n ob] (pipe ob (.retry ^js rxop ^long n)))) (defn transform "Transform the observable sequence using transducers." [xform ob] (when-not (observable? ob) (throw (ex-info "Only observables are supported" {}))) (letfn [(subs-step [subs] (fn ([r] (end! subs) r) ([_ input] (push! subs input) input)))] (create (fn [subs] (let [xsubs (xform (subs-step subs)) step (fn [input] (let [v (xsubs nil input)] (when (reduced? v) (xsubs @v)))) disposable (on-value ob step)] (on-complete ob #(do (xsubs nil) (end! subs))) (fn [] (dispose! disposable))))))) (defn timer "Returns an observable sequence that produces a value after `ms` has elapsed and then after each period." ([delay] (.timer rx delay)) ([delay period] (.timer rx delay period))) (defn timeout "Returns the source observable sequence or the other observable sequence if dueTime elapses." ([ms ob] (pipe ob (.timeout ^js rxop ms))) ([ms other ob] (pipe ob (.timeoutWith ^js rxop ms other)))) (defn delay "Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved." [ms ob] (pipe ob (.delay ^js rxop ms))) (defn delay-emit "Time shift the observable but also increase the relative time between emisions." [ms ob] (mapcat #(delay ms (of %)) ob)) (defn delay-when "Time shifts the observable sequence based on a subscription delay and a delay selector function for each element." ([sf ob] (pipe ob (.delayWhen ^js rxop sf))) ([sd sf ob] (pipe ob (.delayWhen ^js rxop sf sd)))) (defn delay-at-least "Time shifts at least `ms` milisseconds." [ms ob] (pipe ob (fn [source] (->> source (combine-latest-with (timer ms)) (map c/first))))) (defn interval "Returns an observable sequence that produces a value after each period." [ms] (.interval rx ms)) (defn flatten "Just like clojure collections flatten but for rx streams. Given a stream off collections will emit every value separately" [ob] (pipe ob (.concatMap ^js rxop identity))) (defn concat-reduce "Like reduce but accepts a function that returns a stream. Will use as value for the next step in the reduce the last valued emited by the stream in the function." [f seed ob] (let [current-acc (volatile! seed)] (->> (concat (of seed) (->> ob (mapcat #(f @current-acc %)) (tap #(vreset! current-acc %)))) (last)))) ;; --- Schedulers (defn scheduler "Get the scheduler instance by type. The posible types are: `:asap`, `:async`, `:queue`. Old `:trampoline` type is renamed as `:queue` and is deprecated." [type] (case type :asap (.-asapScheduler rx) :async (.-asyncScheduler rx) :queue (.-queueScheduler rx) :af (.-animationFrameScheduler rx) :animation-frame (.-animationFrameScheduler rx))) (defn observe-on [schd ob] (cond (scheduler? schd) (pipe ob (.observeOn ^js rxop schd)) (keyword? schd) (pipe ob (.observeOn ^js rxop (scheduler schd))) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))) (defn subscribe-on [schd ob] (cond (scheduler? schd) (pipe ob (.subscribeOn ^js rxop schd)) (keyword? schd) (pipe ob (.subscribeOn ^js rxop (scheduler schd))) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument}))))
true
(ns beicon.core (:refer-clojure :exclude [true? map filter reduce merge repeat first last mapcat repeatedly zip dedupe drop take take-while map-indexed concat empty delay range throw do trampoline subs flatten]) (:require [beicon.impl.rxjs] [beicon.impl.rxjs-operators] [cljs.core :as c])) (def rx js/rxjsMain) (def rxop js/rxjsOperators) (def ^:const Observable (.-Observable ^js rx)) (def ^:const Subject (.-Subject ^js rx)) (def ^:const BehaviorSubject (.-BehaviorSubject ^js rx)) (def ^:const Subscriber (.-Subscriber ^js rx)) (def ^:const Observer (.-Subscriber ^js rx)) (def ^:const Disposable (.-Subscription ^js rx)) (def ^:const Scheduler (.-Scheduler ^js rx)) ;; --- Interop Helpers (declare subject?) (defn to-observable "Coerce a object to an observable instance." [ob] (assert (subject? ob) "`ob` should be a Subject instance") (.asObservable ^js ob)) (def ^:private noop (constantly nil)) (defn pipe ([ob f] (.pipe ob f)) ([ob f1 f2] (.pipe ob f1 f2)) ([ob f1 f2 f3] (.pipe ob f1 f2 f3)) ([ob f1 f2 f3 f4] (.pipe ob f1 f2 f3 f4)) ([ob f1 f2 f3 f4 & rest] (let [pipe' (.-pipe ob)] (apply pipe' ob f1 f2 f4 rest)))) ;; --- Predicates (extend-type BehaviorSubject IDeref (-deref [self] (.getValue ^js self))) (defn observable? "Return true if `ob` is a instance of Rx.Observable." [ob] (instance? Observable ob)) (defn disposable? "Check if the provided object is disposable (jvm) or subscription (js)." [v] (instance? Disposable v)) (defn scheduler? "Check if the provided value is Scheduler instance." [v] (instance? Scheduler v)) (defn subject? "Check if the provided value is Subject instance." [b] (instance? Subject b)) ;; --- Observables Constructor (defn create "Creates an observable sequence from a specified subscribe method implementation." [sf] {:pre [(fn? sf)]} (.create ^js Observable (fn [subs] (try (sf subs) (catch :default e (.error subs e)))))) ;; --- Observable Subscription (defprotocol ISubscriber "Backpressure aware subscriber abstraction." (-on-init [_ s] "Subscription initialization hook.") (-on-next [_ s value] "Subscription data notification hook.") (-on-error [_ error] "Subscription error notification hook.") (-on-end [_] "Subscription termination notification hook.")) (defprotocol IDisposable (-dispose [_] "dispose resources.")) (defn dispose! "Dispose resources acquired by the subscription." [v] (-dispose v)) ;; Alias (def unsub! dispose!) (def cancel! dispose!) (defn- wrap-disposable [disposable] (specify! disposable IFn (-invoke ([this] (-dispose this))) IDisposable (-dispose [this] (.unsubscribe this)))) (defn subscribe-with "Subscribes an observer or subscriber to the observable sequence." [ob observer] {:pre [(subject? observer)]} (wrap-disposable (.subscribe ob observer))) (defn subscribe "Subscribes an observer to the observable sequence." ([ob nf] (subscribe ob nf nil nil)) ([ob nf ef] (subscribe ob nf ef nil)) ([ob nf ef cf] (let [observer (.create ^js Subscriber (if (fn? nf) nf noop) (if (fn? ef) ef noop) (if (fn? cf) cf noop))] (wrap-disposable (.subscribe ob observer))))) (defn subs "A specialized version of `subscribe` with inverted arguments." ([nf ob] (subscribe ob nf nil nil)) ([nf ef ob] (subscribe ob nf ef nil)) ([nf ef cf ob] (subscribe ob nf ef cf))) ;; Alias (def sub! subscribe) (defn on-value "Subscribes a function to invoke for each element in the observable sequence." [ob f] (subscribe ob f nil nil)) (def on-next "A semantic alias for `on-value`." on-value) (defn on-error "Subscribes a function to invoke upon exceptional termination of the observable sequence." [ob f] (subscribe ob nil f nil)) (defn on-end "Subscribes a function to invoke upon graceful termination of the observable sequence." [ob f] (subscribe ob nil nil f)) (def on-complete "A semantic alias for `on-end`." on-end) ;; --- Bus / Subject (defn subject "Subject that, once an Observer has subscribed, emits all subsequently observed items to the subscriber." [] (Subject.)) (defn behavior-subject "Bus that emits the most recent item it has observed and all subsequent observed items to each subscribed Observer." [v] (BehaviorSubject. v)) (defn push! "Pushes the given value to the bus stream." [b v] (.next ^js b v)) (defn error! "Pushes the given error to the bus stream." [b e] (.error ^js b e)) (defn end! "Ends the given bus stream." [b] (.complete ^js b)) ;; --- Observable Factory Helpers (defn range "Generates an observable sequence that repeats the given element." ([b] (range 0 b)) ([a b] (.range rx a b))) (defn publish "Create a connectable (hot) observable from other observable." [ob] (.publish ob)) (defn share "Returns an observable sequence that shares a single subscription to the underlying sequence." [ob] (pipe ob (.share ^js rxop))) (defn connect! "Connect the connectable observable." [ob] (.connect ob)) (defn from "Creates an observable from js arrays, clojurescript collections, and promise instance." [v] (if (nil? v) (.empty rx) (.from rx v))) (defn from-atom ([atm] (from-atom atm nil)) ([atm {:keys [emit-current-value?] :or {emit-current-value? false}}] (create (fn [subs] (let [key (keyword (gensym "PI:KEY:<KEY>END_PIicon"))] (when emit-current-value? (push! subs @atm)) (add-watch atm key (fn [_ _ _ val] (push! subs val))) (fn [] (remove-watch atm key))))))) (defn from-event "Creates an Observable by attaching an event listener to an event target" [et ev] (.fromEvent rx et ev)) (defn empty "Returns an observable sequence that is already in end state." [] (.empty rx)) (defn if-empty "Emits a given value if the source Observable completes without emitting any next value, otherwise mirrors the source Observable." [default ob] (pipe ob (.defaultIfEmpty ^js rxop default))) ;; Alias (def default-if-empty if-empty) (defn throw [e] (.throwError rx e)) ;; Alias (def error throw) (defn fjoin "Runs all observable sequences in parallel and collect their last elements." [& items] (let [[selector items] (if (ifn? (c/first items)) [(c/first items) (rest items)] [vector items]) items (if (vector? items) items (into [] items))] (apply (.-forkJoin rx) (conj items selector)))) ;; Alias (def fork-join fjoin) (defn of "Converts arguments to an observable sequence." ([a] (.of rx a)) ([a b] (.of rx a b)) ([a b c] (.of rx a b c)) ([a b c d] (.of rx a b c d)) ([a b c d e] (.of rx a b c d e)) ([a b c d e f] (.of rx a b c d e f)) ([a b c d e f & more] (apply (.-of rx) a b c d e f more))) (defn- disposable-atom [ref disposable] (specify! ref IFn (-invoke ([this] (-dispose this))) IDisposable (-dispose [_] (.unsubscribe disposable)))) (defn to-atom "Materialize the observable sequence into an atom." ([ob] (let [a (atom nil)] (to-atom ob a))) ([ob a] (let [disposable (on-value ob #(reset! a %))] (disposable-atom a disposable))) ([ob a f] (let [disposable (on-value ob #(swap! a f %))] (disposable-atom a disposable)))) ;; --- Observable Transformations (defn race "Create an observable that surfaces any of the given sequences, whichever reacted first." ([a b] (.race rx a b)) ([a b & more] (apply (.-race rx) a b more))) (defn zip "Merges the specified observable sequences or Promises (cljs) into one observable sequence." [& items] (let [zip-fn (unchecked-get rx "zip")] (apply zip-fn items))) (defn concat "Concatenates all of the specified observable sequences, as long as the previous observable sequence terminated successfully." [& more] (let [concat-fn (unchecked-get rx "concat")] (apply concat-fn (c/filter some? more)))) (defn merge "Merges all the observable sequences and Promises into a single observable sequence." [& more] (let [merge-fn (unchecked-get rx "merge")] (apply merge-fn (c/filter some? more)))) (defn merge-all "Merges an observable sequence of observable sequences into an observable sequence." ([ob] (pipe ob (.mergeAll ^js rxop))) ([^number concurrency ob] (pipe ob (.mergeAll ^js rxop concurrency)))) (defn filter "Filters the elements of an observable sequence based on a predicate." [f ob] (pipe ob (.filter ^js rxop #(boolean (f %))))) (defn map "Apply a function to each element of an observable sequence." [f ob] (pipe ob (.map ^js rxop #(f %)))) (defn map-indexed [f ob] (pipe ob (.map ^js rxop #(f %2 %1)))) (defn merge-map "Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences or Promises or array/iterable into one observable sequence. In other languages is called: flatMap or mergeMap." [f ob] (pipe ob (.flatMap ^js rxop #(f %)))) (defn switch-map [f obj] (pipe obj (.switchMap ^js rxop #(f %)))) ;; Aliases (def fmap merge-map) (def flat-map merge-map) (defn mapcat "Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences or Promises or array/iterable into one observable sequence." [f ob] (pipe ob (.concatMap ^js rxop #(f %)))) (defn mapcat-indexed [f ob] (pipe ob (.concatMap ^js rxop #(f %2 %1)))) (defn concat-all [ob] (pipe ob (.concatAll ^js rxop))) (defn skip "Bypasses a specified number of elements in an observable sequence and then returns the remaining elements." [n ob] (pipe ob (.skip ^js rxop (int n)))) (defn skip-while "Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements." [f ob] (pipe ob (.skipWhile ^js rxop #(boolean (f %))))) (defn skip-until "Returns the values from the source observable sequence only after the other observable sequence produces a value." [pob ob] (pipe ob (.skipUntil ^js rxop pob))) (defn skip-last "Skip a specified number of values before the completion of an observable." [n ob] (.pipe ob (.skipLast ^js rxop (int n)))) (defn take "Bypasses a specified number of elements in an observable sequence and then returns the remaining elements." [n ob] (pipe ob (.take ^js rxop n))) (defn first "Return an observable that only has the first value of the provided observable. You can optionally pass a predicate and default value." ([ob] (pipe ob (.first ^js rxop))) ([f ob] (pipe ob (.first ^js rxop #(boolean (f %))))) ([f default ob] (pipe ob (.first ^js rxop #(boolean (f %)) default)))) (defn last "Return an observable that only has the last value of the provided observable. You can optionally pass a predicate and default value." ([ob] (pipe ob (.last ^js rxop))) ([f ob] (pipe ob (.last ^js rxop #(boolean (f %))))) ([f default ob] (pipe ob (.last ^js rxop #(boolean (f %)) default)))) (defn take-while "Returns elements from an observable sequence as long as a specified predicate returns true." [f ob] (pipe ob (.takeWhile ^js rxop #(boolean (f %))))) (defn take-until "Returns the values from the source observable sequence until the other observable sequence or Promise produces a value." [other ob] (pipe ob (.takeUntil ^js rxop other))) (defn reduce "Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence." ([f ob] (pipe ob (.reduce ^js rxop #(f %1 %2)))) ([f seed ob] (pipe ob (.reduce ^js rxop #(f %1 %2) seed)))) (defn scan "Applies an accumulator function over an observable sequence and returns each intermediate result. Same as reduce but with intermediate results" ([f ob] (pipe ob (.scan ^js rxop #(f %1 %2)))) ([f seed ob] (pipe ob (.scan ^js rxop #(f %1 %2) seed)))) (defn merge-scan "Applies an accumulator function over the source Observable where the accumulator function itself returns an Observable, then each intermediate Observable returned is merged into the output Observable." [f seed ob] (let [merge-scan-fn (unchecked-get rxop "mergeScan")] (pipe ob (merge-scan-fn #(f %1 %2) seed)))) (defn expand "Recursively projects each source value to an Observable which is merged in the output Observable." [f ob] (pipe ob (.expand ^js rxop f))) (defn with-latest "Merges the specified observable sequences into one observable sequence by using the selector function only when the source observable sequence (the instance) produces an element." {:deprecated true} [f other source] (pipe source (.withLatestFrom ^js rxop other f))) (defn with-latest-from "Merges the specified observable sequences into one observable sequence by using the selector function only when the source observable sequence (the instance) produces an element." ([other source] (let [wlf (.-withLatestFrom ^js rxop) cmb (cond (observable? other) (wlf other) (array? other) (.apply wlf nil other) (sequential? other) (apply wlf other) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))] (pipe source cmb))) ([o1 o2 source] (pipe source (.withLatestFrom ^js rxop o1 o2))) ([o1 o2 o3 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3))) ([o1 o2 o3 o4 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4))) ([o1 o2 o3 o4 o5 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4 o5))) ([o1 o2 o3 o4 o5 o6 source] (pipe source (.withLatestFrom ^js rxop o1 o2 o3 o4 o5 o6)))) (defn combine-latest "Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables (constructor)." ([obs] (cond (array? obs) (.combineLatest rx obs) (sequential? obs) (.combineLatest rx (into-array obs)) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))) ([o1 o2] (.combineLatest rx o1 o2)) ([o1 o2 o3] (.combineLatest rx o1 o2 o3)) ([o1 o2 o3 o4] (.combineLatest rx o1 o2 o3 o4)) ([o1 o2 o3 o4 & other] (combine-latest (into-array (into [o1 o2 o3 o4] other))))) (defn combine-latest-with "Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables (operator)." [other ob] (pipe ob (.combineLatestWith ^js rxop other))) (defn catch "Continues an observable sequence that is terminated by an exception with the next observable sequence." ([handler ob] (pipe ob (.catchError ^js rxop (fn [error source] (let [value (handler error source)] (if (observable? value) value (empty))))))) ([pred handler ob] (catch (fn [value] (if (pred value) (handler value) (throw value))) ob))) (defn tap "Invokes an action for each element in the observable sequence." ([f ob] (pipe ob (.tap ^js rxop f))) ([f g ob] (pipe ob (.tap ^js rxop f g))) ([f g e ob] (pipe ob (.tap ^js rxop f g e)))) ;; Aliases (def do tap) (defn log "Print all values passed through the given observable sequence." ([ob] (tap #(println %) ob)) ([prefix ob] (tap #(println prefix (str %)) ob))) (defn pr-log "Print all values passed through the given observable sequence using pr-str." ([ob] (tap #(println (pr-str %)) ob)) ([prefix ob] (tap #(println prefix (pr-str %)) ob))) (defn throttle "Returns an observable sequence that emits only the first item emitted by the source Observable during sequential time windows of a specified duration." ([ms ob] (pipe ob (.throttleTime ^js rxop ms))) ([ms config ob] (let [{:keys [leading trailing] :or {leading true trailing false}} config] (pipe ob (.throttleTime ^js rxop ms #js {:leading leading :trailing trailing}))))) (defn debounce "Emits an item from the source Observable after a particular timespan has passed without the Observable omitting any other items." [ms ob] (pipe ob (.debounceTime ^js rxop ms))) (defn sample "Samples the observable sequence at each interval." [ms ob] (pipe ob (.sampleTime ^js rxop ms))) (defn sample-when "Samples the observable sequence at each interval." [other ob] (pipe ob (.sample ^js rxop other))) (defn ignore "Ignores all elements in an observable sequence leaving only the termination messages." [ob] (pipe ob (.ignoreElements ^js rxop))) (defn finalize "Returns an Observable that mirrors the source Observable, but will call a specified function when the source terminates on complete or error." [f ob] (pipe ob (.finalize ^js rxop #(f)))) (defn dedupe "Returns an observable sequence that contains only distinct contiguous elements." ([ob] (dedupe identity ob)) ([f ob] (pipe ob (.distinctUntilChanged ^js rxop identical? f)))) (defn dedupe' "Returns an observable sequence that contains only d istinct elements. Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large." ([ob] (pipe ob (.distinct ^js rxop identical?))) ([f ob] (pipe ob (.distinct ^js rxop identical? f)))) (defn buffer "Projects each element of an observable sequence into zero or more buffers which are produced based on element count information." ([n ob] (pipe ob (.bufferCount ^js rxop n))) ([n skip ob] (pipe ob (.bufferCount ^js rxop n skip)))) (defn buffer-time "Buffers the source Observable values for a specific time period." ([ms ob] (pipe ob (.bufferTime ^js rxop ms))) ([ms start ob] (pipe ob (.bufferTime ^js rxop ms start))) ([ms start max ob] (pipe ob (.bufferTime ^js rxop ms start max)))) (defn buffer-until "Buffers the source Observable values until notifier emits." [notifier ob] (pipe ob (.buffer ^js rxop notifier))) (defn retry "Given an optional number of retries and an observable, repeats the source observable the specified number of times or until it terminates. If no number of retries is given, it will be retried indefinitely." ([ob] (pipe ob (.retry ^js rxop))) ([n ob] (pipe ob (.retry ^js rxop ^long n)))) (defn transform "Transform the observable sequence using transducers." [xform ob] (when-not (observable? ob) (throw (ex-info "Only observables are supported" {}))) (letfn [(subs-step [subs] (fn ([r] (end! subs) r) ([_ input] (push! subs input) input)))] (create (fn [subs] (let [xsubs (xform (subs-step subs)) step (fn [input] (let [v (xsubs nil input)] (when (reduced? v) (xsubs @v)))) disposable (on-value ob step)] (on-complete ob #(do (xsubs nil) (end! subs))) (fn [] (dispose! disposable))))))) (defn timer "Returns an observable sequence that produces a value after `ms` has elapsed and then after each period." ([delay] (.timer rx delay)) ([delay period] (.timer rx delay period))) (defn timeout "Returns the source observable sequence or the other observable sequence if dueTime elapses." ([ms ob] (pipe ob (.timeout ^js rxop ms))) ([ms other ob] (pipe ob (.timeoutWith ^js rxop ms other)))) (defn delay "Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved." [ms ob] (pipe ob (.delay ^js rxop ms))) (defn delay-emit "Time shift the observable but also increase the relative time between emisions." [ms ob] (mapcat #(delay ms (of %)) ob)) (defn delay-when "Time shifts the observable sequence based on a subscription delay and a delay selector function for each element." ([sf ob] (pipe ob (.delayWhen ^js rxop sf))) ([sd sf ob] (pipe ob (.delayWhen ^js rxop sf sd)))) (defn delay-at-least "Time shifts at least `ms` milisseconds." [ms ob] (pipe ob (fn [source] (->> source (combine-latest-with (timer ms)) (map c/first))))) (defn interval "Returns an observable sequence that produces a value after each period." [ms] (.interval rx ms)) (defn flatten "Just like clojure collections flatten but for rx streams. Given a stream off collections will emit every value separately" [ob] (pipe ob (.concatMap ^js rxop identity))) (defn concat-reduce "Like reduce but accepts a function that returns a stream. Will use as value for the next step in the reduce the last valued emited by the stream in the function." [f seed ob] (let [current-acc (volatile! seed)] (->> (concat (of seed) (->> ob (mapcat #(f @current-acc %)) (tap #(vreset! current-acc %)))) (last)))) ;; --- Schedulers (defn scheduler "Get the scheduler instance by type. The posible types are: `:asap`, `:async`, `:queue`. Old `:trampoline` type is renamed as `:queue` and is deprecated." [type] (case type :asap (.-asapScheduler rx) :async (.-asyncScheduler rx) :queue (.-queueScheduler rx) :af (.-animationFrameScheduler rx) :animation-frame (.-animationFrameScheduler rx))) (defn observe-on [schd ob] (cond (scheduler? schd) (pipe ob (.observeOn ^js rxop schd)) (keyword? schd) (pipe ob (.observeOn ^js rxop (scheduler schd))) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument})))) (defn subscribe-on [schd ob] (cond (scheduler? schd) (pipe ob (.subscribeOn ^js rxop schd)) (keyword? schd) (pipe ob (.subscribeOn ^js rxop (scheduler schd))) :else (throw (ex-info "Invalid argument" {:type ::invalid-argument}))))
[ { "context": "e uri))\n stage (<?? S (create-stage! \"mail:your@email.com\" peer))]\n (<?? S (start peer))\n ;; NOTE: yo", "end": 709, "score": 0.9994716644287109, "start": 695, "tag": "EMAIL", "value": "your@email.com" } ]
src/clj/pinkgorilla/replikativ.clj
agilecreativity/gorilla-notebook
1
(ns pinkgorilla.replikativ (:require ;; [replikativ.peer :refer [server-peer]] ;; [replikativ.stage :refer [create-stage! connect!]] ;; [kabel.peer :refer [start stop]] ;; [konserve.memory :refer [new-mem-store]] ;; [konserve.filestore :refer [new-fs-store]] ;; [superv.async :refer [<?? S]] ;; core.async error handling [clojure.core.async :refer [chan] :as async] [taoensso.timbre :as timbre] )) (def uri "ws://0.0.0.0:31744") #_(defn start-replikativ [] (let [_ (timbre/set-level! :info) store (<?? S #_(new-mem-store) (new-fs-store "/tmp/chat42-store")) peer (<?? S (server-peer S store uri)) stage (<?? S (create-stage! "mail:your@email.com" peer))] (<?? S (start peer)) ;; NOTE: you do not need to connect to the test net, but you can :) ;(connect! stage "ws://replikativ.io:8888") (println "Your chat42 replikativ server peer is up and running! :)" uri) ;; HACK blocking main termination ;(<?? S (chan)) )) (comment (require '[taoensso.timbre :as timbre]) (timbre/set-level! :info) (stop peer) (start-replikativ) )
14624
(ns pinkgorilla.replikativ (:require ;; [replikativ.peer :refer [server-peer]] ;; [replikativ.stage :refer [create-stage! connect!]] ;; [kabel.peer :refer [start stop]] ;; [konserve.memory :refer [new-mem-store]] ;; [konserve.filestore :refer [new-fs-store]] ;; [superv.async :refer [<?? S]] ;; core.async error handling [clojure.core.async :refer [chan] :as async] [taoensso.timbre :as timbre] )) (def uri "ws://0.0.0.0:31744") #_(defn start-replikativ [] (let [_ (timbre/set-level! :info) store (<?? S #_(new-mem-store) (new-fs-store "/tmp/chat42-store")) peer (<?? S (server-peer S store uri)) stage (<?? S (create-stage! "mail:<EMAIL>" peer))] (<?? S (start peer)) ;; NOTE: you do not need to connect to the test net, but you can :) ;(connect! stage "ws://replikativ.io:8888") (println "Your chat42 replikativ server peer is up and running! :)" uri) ;; HACK blocking main termination ;(<?? S (chan)) )) (comment (require '[taoensso.timbre :as timbre]) (timbre/set-level! :info) (stop peer) (start-replikativ) )
true
(ns pinkgorilla.replikativ (:require ;; [replikativ.peer :refer [server-peer]] ;; [replikativ.stage :refer [create-stage! connect!]] ;; [kabel.peer :refer [start stop]] ;; [konserve.memory :refer [new-mem-store]] ;; [konserve.filestore :refer [new-fs-store]] ;; [superv.async :refer [<?? S]] ;; core.async error handling [clojure.core.async :refer [chan] :as async] [taoensso.timbre :as timbre] )) (def uri "ws://0.0.0.0:31744") #_(defn start-replikativ [] (let [_ (timbre/set-level! :info) store (<?? S #_(new-mem-store) (new-fs-store "/tmp/chat42-store")) peer (<?? S (server-peer S store uri)) stage (<?? S (create-stage! "mail:PI:EMAIL:<EMAIL>END_PI" peer))] (<?? S (start peer)) ;; NOTE: you do not need to connect to the test net, but you can :) ;(connect! stage "ws://replikativ.io:8888") (println "Your chat42 replikativ server peer is up and running! :)" uri) ;; HACK blocking main termination ;(<?? S (chan)) )) (comment (require '[taoensso.timbre :as timbre]) (timbre/set-level! :info) (stop peer) (start-replikativ) )
[ { "context": "oken (atom \"\"))\n(def auth-url \"https://github.com/login/oauth/authorize?client_id=3056f749c2e91ce4d780&sc", "end": 380, "score": 0.7819816470146179, "start": 375, "tag": "USERNAME", "value": "login" }, { "context": "\")\n\n(def id \"3056f749c2e91ce4d780\")\n(def secret \"a94c6cac3ba9a2f13b4c112a762169bc18bfd7a1\")\n(def scope \"repo admin:org delete_repo\")\n\n;; PO", "end": 545, "score": 0.9994101524353027, "start": 505, "tag": "KEY", "value": "a94c6cac3ba9a2f13b4c112a762169bc18bfd7a1" }, { "context": "xtract-code url)\n url \"https://github.com/login/oauth/access_token\"\n ]\n (go (let [resp", "end": 1035, "score": 0.8242290616035461, "start": 1030, "tag": "USERNAME", "value": "login" } ]
src/main/main.cljs
zamansky/clojurescript-electron-oauth-test
0
(ns main.main (:require ["electron" :refer [app BrowserWindow crashReporter ipcMain ]] [cljs.core.async :refer (chan put! <! >! go go-loop timeout)] [cljs-http.client :as http] [ajax.core :refer [GET POST]] )) (def main-window (atom nil)) (def auth-window (atom nil)) (def token (atom "")) (def auth-url "https://github.com/login/oauth/authorize?client_id=3056f749c2e91ce4d780&scope=admin:org delete_repo") (def id "3056f749c2e91ce4d780") (def secret "a94c6cac3ba9a2f13b4c112a762169bc18bfd7a1") (def scope "repo admin:org delete_repo") ;; POST https://github.com/login/oauth/access_token ;; client_id ;; client_secret ;; code ;; Accept: application/json (defn extract-code [url] (second (re-matches #".*code=([0-9a-f]+).*" url)) ) (defn extract-token [url] (second (re-matches #".*token=([0-9a-f]+).*" url))) (.on ipcMain "get-token" #(.reply %1 "token" @token) ) (defn get-token [url] (let [code (extract-code url) url "https://github.com/login/oauth/access_token" ] (go (let [response (<! (http/get url {:query-params {"client_id" id "client_secret" secret "code" code } :headers {"Accept" "application/json"} })) ] (reset! token (extract-token (:body response))) (prn @token) (.loadURL @auth-window (str "file://" js/__dirname "/public/index.html")) ;;(GET url {:params {:client_id id :client_secret secret :code code} ;; :handler handler ;; }) )))) (defn init-browser [] (reset! auth-window (BrowserWindow. (clj->js {:width 1200 :height 1200 :webPreferences {:nodeIntegration true} ;;"node-integration" false ;;"web-security" false }))) ;;(.show @auth-window) (.catch (.loadURL @auth-window auth-url) (fn [x] (prn (get-token (.toString (js->clj x)))) ;;(.log js/console x)) )) ;;(.webContents.on @auth-window "did-fail-load" #(.log js/console (.sender.history %))) (.on @auth-window "load" #(prn %1)) (.on @auth-window "closed" #(reset! main-window nil)) (.webContents.on @auth-window "will-navigate" #(do (prn %1 %2 ) ( get-token %2)))) ;; webView.getSettings().setJavaScriptEnabled(true); ;; authWindow.webContents.on('will-navigate', function (event, newUrl) { ;; console.log(newUrl); (defn main [] ; CrashReporter can just be omitted (.start crashReporter (clj->js {:companyName "MyAwesomeCompany" :productName "MyAwesomeApp" :submitURL "https://example.com/submit-url" :autoSubmit false})) (.on app "window-all-closed" #(when-not (= js/process.platform "darwin") (.quit app))) (.on app "ready" init-browser))
80293
(ns main.main (:require ["electron" :refer [app BrowserWindow crashReporter ipcMain ]] [cljs.core.async :refer (chan put! <! >! go go-loop timeout)] [cljs-http.client :as http] [ajax.core :refer [GET POST]] )) (def main-window (atom nil)) (def auth-window (atom nil)) (def token (atom "")) (def auth-url "https://github.com/login/oauth/authorize?client_id=3056f749c2e91ce4d780&scope=admin:org delete_repo") (def id "3056f749c2e91ce4d780") (def secret "<KEY>") (def scope "repo admin:org delete_repo") ;; POST https://github.com/login/oauth/access_token ;; client_id ;; client_secret ;; code ;; Accept: application/json (defn extract-code [url] (second (re-matches #".*code=([0-9a-f]+).*" url)) ) (defn extract-token [url] (second (re-matches #".*token=([0-9a-f]+).*" url))) (.on ipcMain "get-token" #(.reply %1 "token" @token) ) (defn get-token [url] (let [code (extract-code url) url "https://github.com/login/oauth/access_token" ] (go (let [response (<! (http/get url {:query-params {"client_id" id "client_secret" secret "code" code } :headers {"Accept" "application/json"} })) ] (reset! token (extract-token (:body response))) (prn @token) (.loadURL @auth-window (str "file://" js/__dirname "/public/index.html")) ;;(GET url {:params {:client_id id :client_secret secret :code code} ;; :handler handler ;; }) )))) (defn init-browser [] (reset! auth-window (BrowserWindow. (clj->js {:width 1200 :height 1200 :webPreferences {:nodeIntegration true} ;;"node-integration" false ;;"web-security" false }))) ;;(.show @auth-window) (.catch (.loadURL @auth-window auth-url) (fn [x] (prn (get-token (.toString (js->clj x)))) ;;(.log js/console x)) )) ;;(.webContents.on @auth-window "did-fail-load" #(.log js/console (.sender.history %))) (.on @auth-window "load" #(prn %1)) (.on @auth-window "closed" #(reset! main-window nil)) (.webContents.on @auth-window "will-navigate" #(do (prn %1 %2 ) ( get-token %2)))) ;; webView.getSettings().setJavaScriptEnabled(true); ;; authWindow.webContents.on('will-navigate', function (event, newUrl) { ;; console.log(newUrl); (defn main [] ; CrashReporter can just be omitted (.start crashReporter (clj->js {:companyName "MyAwesomeCompany" :productName "MyAwesomeApp" :submitURL "https://example.com/submit-url" :autoSubmit false})) (.on app "window-all-closed" #(when-not (= js/process.platform "darwin") (.quit app))) (.on app "ready" init-browser))
true
(ns main.main (:require ["electron" :refer [app BrowserWindow crashReporter ipcMain ]] [cljs.core.async :refer (chan put! <! >! go go-loop timeout)] [cljs-http.client :as http] [ajax.core :refer [GET POST]] )) (def main-window (atom nil)) (def auth-window (atom nil)) (def token (atom "")) (def auth-url "https://github.com/login/oauth/authorize?client_id=3056f749c2e91ce4d780&scope=admin:org delete_repo") (def id "3056f749c2e91ce4d780") (def secret "PI:KEY:<KEY>END_PI") (def scope "repo admin:org delete_repo") ;; POST https://github.com/login/oauth/access_token ;; client_id ;; client_secret ;; code ;; Accept: application/json (defn extract-code [url] (second (re-matches #".*code=([0-9a-f]+).*" url)) ) (defn extract-token [url] (second (re-matches #".*token=([0-9a-f]+).*" url))) (.on ipcMain "get-token" #(.reply %1 "token" @token) ) (defn get-token [url] (let [code (extract-code url) url "https://github.com/login/oauth/access_token" ] (go (let [response (<! (http/get url {:query-params {"client_id" id "client_secret" secret "code" code } :headers {"Accept" "application/json"} })) ] (reset! token (extract-token (:body response))) (prn @token) (.loadURL @auth-window (str "file://" js/__dirname "/public/index.html")) ;;(GET url {:params {:client_id id :client_secret secret :code code} ;; :handler handler ;; }) )))) (defn init-browser [] (reset! auth-window (BrowserWindow. (clj->js {:width 1200 :height 1200 :webPreferences {:nodeIntegration true} ;;"node-integration" false ;;"web-security" false }))) ;;(.show @auth-window) (.catch (.loadURL @auth-window auth-url) (fn [x] (prn (get-token (.toString (js->clj x)))) ;;(.log js/console x)) )) ;;(.webContents.on @auth-window "did-fail-load" #(.log js/console (.sender.history %))) (.on @auth-window "load" #(prn %1)) (.on @auth-window "closed" #(reset! main-window nil)) (.webContents.on @auth-window "will-navigate" #(do (prn %1 %2 ) ( get-token %2)))) ;; webView.getSettings().setJavaScriptEnabled(true); ;; authWindow.webContents.on('will-navigate', function (event, newUrl) { ;; console.log(newUrl); (defn main [] ; CrashReporter can just be omitted (.start crashReporter (clj->js {:companyName "MyAwesomeCompany" :productName "MyAwesomeApp" :submitURL "https://example.com/submit-url" :autoSubmit false})) (.on app "window-all-closed" #(when-not (= js/process.platform "darwin") (.quit app))) (.on app "ready" init-browser))
[ { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Copyright:: Copyright (c)", "end": 25, "score": 0.999851405620575, "start": 15, "tag": "NAME", "value": "Adam Jacob" }, { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Copyright:: Copyright (c) 2011 Opscode, Inc.", "end": 44, "score": 0.9999306201934814, "start": 28, "tag": "EMAIL", "value": "adam@opscode.com" } ]
config/software/gecode.clj
racker/omnibus
2
;; ;; Author:: Adam Jacob (<adam@opscode.com>) ;; Copyright:: Copyright (c) 2011 Opscode, Inc. ;; License:: Apache License, Version 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. ;; (let [env (if (= 0 (get (clojure.java.shell/sh "test" "-f" "/usr/bin/gcc44") :exit)) { "CC" "gcc44" "CXX" "g++44" } { })] (software "gecode" :source "gecode-3.7.1" :steps [ {:command "./configure" :env env :args [ "--prefix=/opt/opscode/embedded" "--disable-doc-dot" "--disable-doc-search" "--disable-doc-tagfile" "--disable-doc-chm" "--disable-doc-docset" "--disable-qt" "--disable-examples" ]} {:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib"} :command "make"} {:command "make" :args [ "install" ]} ]))
6296
;; ;; Author:: <NAME> (<<EMAIL>>) ;; Copyright:: Copyright (c) 2011 Opscode, Inc. ;; License:: Apache License, Version 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. ;; (let [env (if (= 0 (get (clojure.java.shell/sh "test" "-f" "/usr/bin/gcc44") :exit)) { "CC" "gcc44" "CXX" "g++44" } { })] (software "gecode" :source "gecode-3.7.1" :steps [ {:command "./configure" :env env :args [ "--prefix=/opt/opscode/embedded" "--disable-doc-dot" "--disable-doc-search" "--disable-doc-tagfile" "--disable-doc-chm" "--disable-doc-docset" "--disable-qt" "--disable-examples" ]} {:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib"} :command "make"} {:command "make" :args [ "install" ]} ]))
true
;; ;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>) ;; Copyright:: Copyright (c) 2011 Opscode, Inc. ;; License:: Apache License, Version 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. ;; (let [env (if (= 0 (get (clojure.java.shell/sh "test" "-f" "/usr/bin/gcc44") :exit)) { "CC" "gcc44" "CXX" "g++44" } { })] (software "gecode" :source "gecode-3.7.1" :steps [ {:command "./configure" :env env :args [ "--prefix=/opt/opscode/embedded" "--disable-doc-dot" "--disable-doc-search" "--disable-doc-tagfile" "--disable-doc-chm" "--disable-doc-docset" "--disable-qt" "--disable-examples" ]} {:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib"} :command "make"} {:command "make" :args [ "install" ]} ]))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-03-16\"\n :doc \"Tests for zana.da", "end": 105, "score": 0.9998740553855896, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/zana/test/defs/data/oempty.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-03-16" :doc "Tests for zana.data.enum." } zana.test.defs.data.oempty (:require [zana.api :as z])) ;;------------------------------------------------------------------------------ (z/define-ordered-enum OEmpty []) ;;------------------------------------------------------------------------------
3216
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-03-16" :doc "Tests for zana.data.enum." } zana.test.defs.data.oempty (:require [zana.api :as z])) ;;------------------------------------------------------------------------------ (z/define-ordered-enum OEmpty []) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-03-16" :doc "Tests for zana.data.enum." } zana.test.defs.data.oempty (:require [zana.api :as z])) ;;------------------------------------------------------------------------------ (z/define-ordered-enum OEmpty []) ;;------------------------------------------------------------------------------
[ { "context": "\n (def q\n '{:find [e]\n :where [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]})\n ;; e", "end": 476, "score": 0.9998331069946289, "start": 468, "tag": "NAME", "value": "Malcolma" }, { "context": "[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]})\n ;; end::query-at-t-q1[]\n )\n\n(t/deftest te", "end": 514, "score": 0.9996261596679688, "start": 508, "tag": "NAME", "value": "Sparks" }, { "context": "[:crux.tx/put\n {:crux.db/id :malcolm :name \"Malcolm\" :last-name \"Sparks\"}\n #inst \"1986-10-22\"]]", "end": 724, "score": 0.9998369812965393, "start": 717, "tag": "NAME", "value": "Malcolm" }, { "context": "{:crux.db/id :malcolm :name \"Malcolm\" :last-name \"Sparks\"}\n #inst \"1986-10-22\"]])\n ;; end::query-", "end": 744, "score": 0.9995675086975098, "start": 738, "tag": "NAME", "value": "Sparks" }, { "context": "[:crux.tx/put\n {:crux.db/id :malcolm :name \"Malcolma\" :last-name \"Sparks\"}\n #inst \"1986-10-24\"]]", "end": 927, "score": 0.999847948551178, "start": 919, "tag": "NAME", "value": "Malcolma" }, { "context": ":crux.db/id :malcolm :name \"Malcolma\" :last-name \"Sparks\"}\n #inst \"1986-10-24\"]])\n ;; end::query-", "end": 947, "score": 0.9997200965881348, "start": 941, "tag": "NAME", "value": "Sparks" }, { "context": "et [q '{:find [e]\n :where [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}", "end": 1094, "score": 0.9998511672019958, "start": 1086, "tag": "NAME", "value": "Malcolma" }, { "context": " \"Malcolma\"]\n [e :last-name \"Sparks\"]]}]\n (t/is (= #{}\n ;; tag::qu", "end": 1140, "score": 0.9997108578681946, "start": 1134, "tag": "NAME", "value": "Sparks" }, { "context": "uery-input[]\n [{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :p", "end": 1645, "score": 0.999731183052063, "start": 1641, "tag": "NAME", "value": "Ivan" }, { "context": ".db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n ", "end": 1671, "score": 0.9996817708015442, "start": 1665, "tag": "NAME", "value": "Ivanov" }, { "context": "e \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :s", "end": 1716, "score": 0.9997249841690063, "start": 1712, "tag": "NAME", "value": "Petr" }, { "context": ".db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n ", "end": 1742, "score": 0.9992142915725708, "start": 1736, "tag": "NAME", "value": "Petrov" }, { "context": " \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}])\n ;; end::query-inp", "end": 1789, "score": 0.9997419118881226, "start": 1784, "tag": "NAME", "value": "Smith" }, { "context": "b/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}])\n ;; end::query-input[]\n )\n\n (let [node *", "end": 1814, "score": 0.9997697472572327, "start": 1809, "tag": "NAME", "value": "Smith" }, { "context": " [p1 :name \"Smith\"]]})]\n (doseq [tuple (iterator-seq res)]\n ", "end": 2325, "score": 0.9997290372848511, "start": 2320, "tag": "NAME", "value": "Smith" }, { "context": "ps\n ;; tag::query-input[]\n [{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n ", "end": 2587, "score": 0.7019186615943909, "start": 2585, "tag": "NAME", "value": "an" }, { "context": "uery-input[]\n [{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :p", "end": 2605, "score": 0.9997118711471558, "start": 2601, "tag": "NAME", "value": "Ivan" }, { "context": ".db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n ", "end": 2631, "score": 0.999699056148529, "start": 2625, "tag": "NAME", "value": "Ivanov" }, { "context": "e \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :s", "end": 2676, "score": 0.9997295141220093, "start": 2672, "tag": "NAME", "value": "Petr" }, { "context": ".db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n ", "end": 2702, "score": 0.9995734691619873, "start": 2696, "tag": "NAME", "value": "Petrov" }, { "context": " \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n ;; end::query-inp", "end": 2749, "score": 0.9997397065162659, "start": 2744, "tag": "NAME", "value": "Smith" }, { "context": "b/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n ;; end::query-input[]\n ))\n\n (let [node", "end": 2774, "score": 0.9997859001159668, "start": 2769, "tag": "NAME", "value": "Smith" }, { "context": "p1 :last-name n]\n [p1 :name \"Smith\"]]})\n ;; end::basic-query[]\n ", "end": 3156, "score": 0.9997695088386536, "start": 3151, "tag": "NAME", "value": "Smith" }, { "context": " :where [[e :name first-name]]}\n \"Ivan\")\n ;; end::query-with-arguments1[]\n ", "end": 3542, "score": 0.9997072219848633, "start": 3538, "tag": "NAME", "value": "Ivan" }, { "context": " :where [[e :name first-name]]}\n [\"Ivan\" \"Petr\"])\n ;; end::query-with-arguments", "end": 3950, "score": 0.9996975660324097, "start": 3946, "tag": "NAME", "value": "Ivan" }, { "context": "here [[e :name first-name]]}\n [\"Ivan\" \"Petr\"])\n ;; end::query-with-arguments2[]\n ", "end": 3957, "score": 0.9997541904449463, "start": 3953, "tag": "NAME", "value": "Petr" }, { "context": " [e :last-name last-name]]}\n [\"Ivan\" \"Ivanov\"])\n ;; end::query-with-argumen", "end": 4411, "score": 0.9996570348739624, "start": 4407, "tag": "NAME", "value": "Ivan" }, { "context": " [e :last-name last-name]]}\n [\"Ivan\" \"Ivanov\"])\n ;; end::query-with-arguments3[]\n ", "end": 4420, "score": 0.9995134472846985, "start": 4414, "tag": "NAME", "value": "Ivanov" }, { "context": " [e :last-name last-name]]}\n [[\"Petr\" \"Petrov\"]\n [\"Smith\" \"Smith\"]])\n ", "end": 4886, "score": 0.9998171329498291, "start": 4882, "tag": "NAME", "value": "Petr" }, { "context": " [e :last-name last-name]]}\n [[\"Petr\" \"Petrov\"]\n [\"Smith\" \"Smith\"]])\n ;; ", "end": 4895, "score": 0.9570574760437012, "start": 4889, "tag": "NAME", "value": "Petrov" }, { "context": "]]}\n [[\"Petr\" \"Petrov\"]\n [\"Smith\" \"Smith\"]])\n ;; end::query-with-argumen", "end": 4918, "score": 0.9998452663421631, "start": 4913, "tag": "NAME", "value": "Smith" }, { "context": " [[\"Petr\" \"Petrov\"]\n [\"Smith\" \"Smith\"]])\n ;; end::query-with-arguments4[]\n ", "end": 4926, "score": 0.9997686743736267, "start": 4921, "tag": "NAME", "value": "Smith" }, { "context": " ;; tag::join-d[]\n [{:crux.db/id :ivan :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n {:cr", "end": 7646, "score": 0.9208805561065674, "start": 7642, "tag": "NAME", "value": "Ivan" }, { "context": "ivan :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei\"}\n ", "end": 7684, "score": 0.9098975658416748, "start": 7680, "tag": "NAME", "value": "Petr" }, { "context": "tr :name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei\"}\n {:crux.db/id :denis-a :name \"Denis\"}\n ", "end": 7725, "score": 0.7930499315261841, "start": 7720, "tag": "NAME", "value": "Serge" }, { "context": ":name \"Sergei\"}\n {:crux.db/id :denis-a :name \"Denis\"}\n {:crux.db/id :denis-b :name \"Denis\"}]\n ", "end": 7768, "score": 0.8772152662277222, "start": 7763, "tag": "NAME", "value": "Denis" }, { "context": " :name \"Denis\"}\n {:crux.db/id :denis-b :name \"Denis\"}]\n ;; end::join-d[]\n ))\n\n (let [node *api", "end": 7810, "score": 0.9313939809799194, "start": 7805, "tag": "NAME", "value": "Denis" }, { "context": "; tag::join2-d[]\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :", "end": 8523, "score": 0.9997653961181641, "start": 8519, "tag": "NAME", "value": "Ivan" }, { "context": " [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :name \"Petr\" :follows", "end": 8543, "score": 0.9997759461402893, "start": 8537, "tag": "NAME", "value": "Ivanov" }, { "context": "t-name \"Ivanov\"}\n {:crux.db/id :petr :name \"Petr\" :follows #{\"Ivanov\"}}]\n ;; end::join2-d[]\n ", "end": 8583, "score": 0.9997189044952393, "start": 8579, "tag": "NAME", "value": "Petr" }, { "context": " {:crux.db/id :petr :name \"Petr\" :follows #{\"Ivanov\"}}]\n ;; end::join2-d[]\n ))\n\n (t/is (", "end": 8603, "score": 0.9988346099853516, "start": 8597, "tag": "NAME", "value": "Ivanov" }, { "context": " [e2 :follows l]\n [e :name \"Ivan\"]]})\n ;; end::join2-q[]\n ))))", "end": 8949, "score": 0.9997336864471436, "start": 8945, "tag": "NAME", "value": "Ivan" }, { "context": "/maps->tx-ops\n [{:crux.db/id :ivan :user/name \"Ivan\" :user/id 1 :user/profession :doctor}\n {:crux", "end": 9105, "score": 0.9996852874755859, "start": 9101, "tag": "NAME", "value": "Ivan" }, { "context": "on :doctor}\n {:crux.db/id :sergei :user/name \"Sergei\" :user/id 2 :user/profession :lawyer}\n {:crux", "end": 9188, "score": 0.9993386268615723, "start": 9182, "tag": "NAME", "value": "Sergei" }, { "context": "sion :lawyer}\n {:crux.db/id :petr :user/name \"Petr\" :user/id 3 :user/profession :doctor}\n {:crux", "end": 9267, "score": 0.9996951818466187, "start": 9263, "tag": "NAME", "value": "Petr" }, { "context": " ;; tag::eql-query-1-r[]\n #{[1 \"Ivan\" :doctor] [2 \"Sergei\" :lawyer], [3 \"Petr\" :doctor", "end": 9505, "score": 0.9996896982192993, "start": 9501, "tag": "NAME", "value": "Ivan" }, { "context": "l-query-1-r[]\n #{[1 \"Ivan\" :doctor] [2 \"Sergei\" :lawyer], [3 \"Petr\" :doctor]}\n ;; end:", "end": 9526, "score": 0.9988920092582703, "start": 9520, "tag": "NAME", "value": "Sergei" }, { "context": " #{[1 \"Ivan\" :doctor] [2 \"Sergei\" :lawyer], [3 \"Petr\" :doctor]}\n ;; end::eql-query-1-r[]\n\n ", "end": 9546, "score": 0.9995094537734985, "start": 9542, "tag": "NAME", "value": "Petr" }, { "context": "; tag::eql-query-2-r[]\n #{[{:user/name \"Ivan\" :user/profession :doctor}]\n [{:user/", "end": 10031, "score": 0.9997791051864624, "start": 10027, "tag": "NAME", "value": "Ivan" }, { "context": "r/profession :doctor}]\n [{:user/name \"Sergei\" :user/profession :lawyer}]\n [{:user/", "end": 10093, "score": 0.9995853304862976, "start": 10087, "tag": "NAME", "value": "Sergei" }, { "context": "r/profession :lawyer}]\n [{:user/name \"Petr\" :user/profession :doctor}]}\n ;; end::e", "end": 10153, "score": 0.9994128942489624, "start": 10149, "tag": "NAME", "value": "Petr" }, { "context": " ;; tag::eql-query-3-r[]\n #{[1 \"Ivan\" \"Doctor\"] [2 \"Sergei\" \"Lawyer\"] [3 \"Petr\" \"Docto", "end": 10569, "score": 0.9996873140335083, "start": 10565, "tag": "NAME", "value": "Ivan" }, { "context": "-query-3-r[]\n #{[1 \"Ivan\" \"Doctor\"] [2 \"Sergei\" \"Lawyer\"] [3 \"Petr\" \"Doctor\"]}\n ;; end", "end": 10591, "score": 0.9957736134529114, "start": 10585, "tag": "NAME", "value": "Sergei" }, { "context": "; tag::eql-query-4-r[]\n #{[{:user/name \"Ivan\" :user/profession {:profession/name \"Doctor\"}}]\n ", "end": 11172, "score": 0.9997682571411133, "start": 11168, "tag": "NAME", "value": "Ivan" }, { "context": "ssion/name \"Doctor\"}}]\n [{:user/name \"Sergei\" :user/profession {:profession/name \"Lawyer\"}}]\n ", "end": 11254, "score": 0.9995871186256409, "start": 11248, "tag": "NAME", "value": "Sergei" }, { "context": "ssion/name \"Lawyer\"}}]\n [{:user/name \"Petr\" :user/profession {:profession/name \"Doctor\"}}]}\n", "end": 11334, "score": 0.9952765703201294, "start": 11330, "tag": "NAME", "value": "Petr" }, { "context": " :user/_profession [{:user/id 1 :user/name \"Ivan\"},\n {:user/id 3 ", "end": 11873, "score": 0.9996182322502136, "start": 11869, "tag": "NAME", "value": "Ivan" }, { "context": " {:user/id 3 :user/name \"Petr\"}]}]\n [{:profession/name \"Lawyer\"\n ", "end": 11939, "score": 0.9998021125793457, "start": 11935, "tag": "NAME", "value": "Petr" }, { "context": " :user/_profession [{:user/id 2 :user/name \"Sergei\"}]}]}\n ;; end::eql-query-5-r[]\n\n ", "end": 12050, "score": 0.9997882843017578, "start": 12044, "tag": "NAME", "value": "Sergei" }, { "context": " #{[{:crux.db/id :ivan :user/id 1, :user/name \"Ivan\", :user/profession :doctor}]}\n ;; end::", "end": 12494, "score": 0.9994484186172485, "start": 12490, "tag": "NAME", "value": "Ivan" }, { "context": "]\n\n ;; tag::eql-project-r[]\n ;; => {:user/name \"Ivan\", :user/profession :doctor}\n ;; end::eql-project", "end": 13054, "score": 0.999380350112915, "start": 13050, "tag": "NAME", "value": "Ivan" }, { "context": "; tag::eql-project-many-r[]\n ;; => [{:user/name \"Ivan\", :user/profession :doctor},\n ;; {:user/name", "end": 13345, "score": 0.9997437000274658, "start": 13341, "tag": "NAME", "value": "Ivan" }, { "context": " :user/profession :doctor},\n ;; {:user/name \"Sergei\", :user/profession :lawyer}]\n ;; end::eql-projec", "end": 13403, "score": 0.9997859597206116, "start": 13397, "tag": "NAME", "value": "Sergei" }, { "context": "/maps->tx-ops\n [{:crux.db/id :ivan :user/name \"Ivan\" :user/id 1 :user/profession :doctor}\n {:crux", "end": 13581, "score": 0.9997351169586182, "start": 13577, "tag": "NAME", "value": "Ivan" }, { "context": "on :doctor}\n {:crux.db/id :sergei :user/name \"Sergei\" :user/id 2 :user/profession :lawyer}\n {:crux", "end": 13664, "score": 0.9997732043266296, "start": 13658, "tag": "NAME", "value": "Sergei" }, { "context": "sion :lawyer}\n {:crux.db/id :petr :user/name \"Petr\" :user/id 3 :user/profession :doctor}\n {:crux", "end": 13743, "score": 0.9997648000717163, "start": 13739, "tag": "NAME", "value": "Petr" }, { "context": " ;; tag::return-maps-r[]\n #{{:name \"Ivan\", :profession \"Doctor\"}}\n ;; end::retur", "end": 13985, "score": 0.9996213912963867, "start": 13981, "tag": "NAME", "value": "Ivan" }, { "context": ":not-data[]\n [{:crux.db/id :petr-ivanov :name \"Petr\" :last-name \"Ivanov\"} ;; <1>\n {:crux.db/id :i", "end": 18209, "score": 0.9998308420181274, "start": 18205, "tag": "NAME", "value": "Petr" }, { "context": ":crux.db/id :petr-ivanov :name \"Petr\" :last-name \"Ivanov\"} ;; <1>\n {:crux.db/id :ivan-ivanov :name \"Iv", "end": 18229, "score": 0.9997437596321106, "start": 18223, "tag": "NAME", "value": "Ivanov" }, { "context": "ov\"} ;; <1>\n {:crux.db/id :ivan-ivanov :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :ivan-pet", "end": 18281, "score": 0.9998291730880737, "start": 18277, "tag": "NAME", "value": "Ivan" }, { "context": ":crux.db/id :ivan-ivanov :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :ivan-petrov :name \"Ivan\" :la", "end": 18301, "score": 0.99980229139328, "start": 18295, "tag": "NAME", "value": "Ivanov" }, { "context": "e \"Ivanov\"}\n {:crux.db/id :ivan-petrov :name \"Ivan\" :last-name \"Petrov\"}\n {:crux.db/id :petr-pet", "end": 18346, "score": 0.9998183846473694, "start": 18342, "tag": "NAME", "value": "Ivan" }, { "context": ":crux.db/id :ivan-petrov :name \"Ivan\" :last-name \"Petrov\"}\n {:crux.db/id :petr-petrov :name \"Petr\" :la", "end": 18366, "score": 0.9989906549453735, "start": 18360, "tag": "NAME", "value": "Petrov" }, { "context": "e \"Petrov\"}\n {:crux.db/id :petr-petrov :name \"Petr\" :last-name \"Petrov\"}]\n ;; end::not-data[]\n ", "end": 18411, "score": 0.9998232126235962, "start": 18407, "tag": "NAME", "value": "Petr" }, { "context": ":crux.db/id :petr-petrov :name \"Petr\" :last-name \"Petrov\"}]\n ;; end::not-data[]\n ))\n\n (let [node *a", "end": 18431, "score": 0.9993883967399597, "start": 18425, "tag": "NAME", "value": "Petrov" }, { "context": "[[e :name name]\n [e :name \"Ivan\"]\n (not [e :last-name \"Iva", "end": 18670, "score": 0.9997950792312622, "start": 18666, "tag": "NAME", "value": "Ivan" }, { "context": "van\"]\n (not [e :last-name \"Ivanov\"])]})\n ))\n\n (t/is (=\n ;;", "end": 18723, "score": 0.9996892809867859, "start": 18717, "tag": "NAME", "value": "Ivanov" }, { "context": ".db/id]\n (not [e :last-name \"Ivanov\"] ;;<2>\n [e :name \"Ivan", "end": 19067, "score": 0.9997407793998718, "start": 19061, "tag": "NAME", "value": "Ivanov" }, { "context": "anov\"] ;;<2>\n [e :name \"Ivan\"])]})\n ;; end::not-2[]\n ))\n\n ", "end": 19117, "score": 0.9997454881668091, "start": 19113, "tag": "NAME", "value": "Ivan" }, { "context": "or-data[]\n [{:crux.db/id :ivan-ivanov-1 :name \"Ivan\" :last-name \"Ivanov\" :sex :male} ;;<1>\n {:cru", "end": 19585, "score": 0.9997884035110474, "start": 19581, "tag": "NAME", "value": "Ivan" }, { "context": "rux.db/id :ivan-ivanov-1 :name \"Ivan\" :last-name \"Ivanov\" :sex :male} ;;<1>\n {:crux.db/id :ivan-ivanov", "end": 19605, "score": 0.9997221827507019, "start": 19599, "tag": "NAME", "value": "Ivanov" }, { "context": "le} ;;<1>\n {:crux.db/id :ivan-ivanov-2 :name \"Ivan\" :last-name \"Ivanov\" :sex :male}\n {:crux.db/i", "end": 19669, "score": 0.9998093843460083, "start": 19665, "tag": "NAME", "value": "Ivan" }, { "context": "rux.db/id :ivan-ivanov-2 :name \"Ivan\" :last-name \"Ivanov\" :sex :male}\n {:crux.db/id :ivan-ivanovtov-1 ", "end": 19689, "score": 0.9997236728668213, "start": 19683, "tag": "NAME", "value": "Ivanov" }, { "context": ":male}\n {:crux.db/id :ivan-ivanovtov-1 :name \"Ivan\" :last-name \"Ivannotov\" :sex :male}\n {:crux.d", "end": 19750, "score": 0.9997894763946533, "start": 19746, "tag": "NAME", "value": "Ivan" }, { "context": ".db/id :ivan-ivanovtov-1 :name \"Ivan\" :last-name \"Ivannotov\" :sex :male}\n {:crux.db/id :ivanova :name \"Iv", "end": 19773, "score": 0.9997234344482422, "start": 19764, "tag": "NAME", "value": "Ivannotov" }, { "context": "name \"Ivannotov\" :sex :male}\n {:crux.db/id :ivanova :name \"Ivanova\" :last-name \"Ivanov\" :sex :female}", "end": 19813, "score": 0.8354073762893677, "start": 19808, "tag": "NAME", "value": "anova" }, { "context": "ov\" :sex :male}\n {:crux.db/id :ivanova :name \"Ivanova\" :last-name \"Ivanov\" :sex :female}\n {:crux.db", "end": 19828, "score": 0.9997034072875977, "start": 19821, "tag": "NAME", "value": "Ivanova" }, { "context": "{:crux.db/id :ivanova :name \"Ivanova\" :last-name \"Ivanov\" :sex :female}\n {:crux.db/id :bob :name \"Bob\"", "end": 19848, "score": 0.9997377395629883, "start": 19842, "tag": "NAME", "value": "Ivanov" }, { "context": "anov\" :sex :female}\n {:crux.db/id :bob :name \"Bob\" :last-name \"Controlguy\"}]\n ;; end::or-data[]\n", "end": 19897, "score": 0.9998258948326111, "start": 19894, "tag": "NAME", "value": "Bob" }, { "context": "e}\n {:crux.db/id :bob :name \"Bob\" :last-name \"Controlguy\"}]\n ;; end::or-data[]\n ))\n\n (let [node *ap", "end": 19921, "score": 0.9995653629302979, "start": 19911, "tag": "NAME", "value": "Controlguy" }, { "context": "e [[e :name name]\n [e :name \"Ivan\"]\n (or [e :last-name \"Ivanov", "end": 20294, "score": 0.9997091293334961, "start": 20290, "tag": "NAME", "value": "Ivan" }, { "context": " \"Ivan\"]\n (or [e :last-name \"Ivanov\"]\n [e :last-name \"Ivanno", "end": 20344, "score": 0.9997296333312988, "start": 20338, "tag": "NAME", "value": "Ivanov" }, { "context": "Ivanov\"]\n [e :last-name \"Ivannotov\"])]})\n ;; end::or-1[]\n ))\n\n ", "end": 20397, "score": 0.9997190833091736, "start": 20388, "tag": "NAME", "value": "Ivannotov" }, { "context": "or-1[]\n ))\n\n (t/is (=\n #{[\"Ivan\"] [\"Ivanova\"]}\n ;; tag::or-2[]\n ", "end": 20477, "score": 0.9636718034744263, "start": 20473, "tag": "NAME", "value": "Ivan" }, { "context": " ))\n\n (t/is (=\n #{[\"Ivan\"] [\"Ivanova\"]}\n ;; tag::or-2[]\n (crux/q\n ", "end": 20489, "score": 0.9995561242103577, "start": 20482, "tag": "NAME", "value": "Ivanova" }, { "context": "x :male]\n [e :name \"Ivan\"]))]})\n ;; end::or-2[]\n ))\n\n ", "end": 20763, "score": 0.9996005296707153, "start": 20759, "tag": "NAME", "value": "Ivan" }, { "context": " [?p2]\n :where [(or (and [?p2 :name \"Petr\"]\n [?p2 :sex :femal", "end": 20992, "score": 0.9997038841247559, "start": 20988, "tag": "NAME", "value": "Petr" }, { "context": ")\n (and [?p2 :last-name \"Ivanov\"]\n [?p2 :sex :male]", "end": 21100, "score": 0.9997105598449707, "start": 21094, "tag": "NAME", "value": "Ivanov" }, { "context": "x\n (fix/maps->tx-ops [{:crux.db/id :ivan :name \"Ivan\"}\n {:crux.db/id :petr :name ", "end": 21271, "score": 0.9986301064491272, "start": 21267, "tag": "NAME", "value": "Ivan" }, { "context": "}\n {:crux.db/id :petr :name \"Petr\"}\n {:crux.db/id :sergei :nam", "end": 21326, "score": 0.9985086917877197, "start": 21322, "tag": "NAME", "value": "Petr" }, { "context": " {:crux.db/id :sergei :name \"Sergei\"}]))\n\n (let [node *api*]\n (t/is (= #{[\"Ivan\"]", "end": 21385, "score": 0.9998496174812317, "start": 21379, "tag": "NAME", "value": "Sergei" }, { "context": "Sergei\"}]))\n\n (let [node *api*]\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (crux/q\n ", "end": 21433, "score": 0.9998010396957397, "start": 21429, "tag": "NAME", "value": "Ivan" }, { "context": "))\n\n (let [node *api*]\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (crux/q\n ", "end": 21442, "score": 0.9998253583908081, "start": 21438, "tag": "NAME", "value": "Petr" }, { "context": "t [node *api*]\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (crux/q\n (crux/db no", "end": 21453, "score": 0.9998356699943542, "start": 21447, "tag": "NAME", "value": "Sergei" }, { "context": "g::not-join-data[]\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"} ;;<1>\n {:crux.db/id :pe", "end": 21715, "score": 0.9997758269309998, "start": 21711, "tag": "NAME", "value": "Ivan" }, { "context": "\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"} ;;<1>\n {:crux.db/id :petr :name \"Petr\" :las", "end": 21735, "score": 0.9997648596763611, "start": 21729, "tag": "NAME", "value": "Ivanov" }, { "context": "me \"Ivanov\"} ;;<1>\n {:crux.db/id :petr :name \"Petr\" :last-name \"Petrov\"}\n {:crux.db/id :sergei :", "end": 21779, "score": 0.9997869729995728, "start": 21775, "tag": "NAME", "value": "Petr" }, { "context": "\n {:crux.db/id :petr :name \"Petr\" :last-name \"Petrov\"}\n {:crux.db/id :sergei :name \"Sergei\" :last-", "end": 21799, "score": 0.9995718002319336, "start": 21793, "tag": "NAME", "value": "Petrov" }, { "context": "t-name \"Petrov\"}\n {:crux.db/id :sergei :name \"Sergei\" :last-name \"Sergei\"}]\n ;; end::not-join-data[", "end": 21841, "score": 0.9998276829719543, "start": 21835, "tag": "NAME", "value": "Sergei" }, { "context": " {:crux.db/id :sergei :name \"Sergei\" :last-name \"Sergei\"}]\n ;; end::not-join-data[]\n ))\n\n (let [no", "end": 21861, "score": 0.999758243560791, "start": 21855, "tag": "NAME", "value": "Sergei" }, { "context": " (fix/maps->tx-ops\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivan\"}]))\n\n (let [node *api*]\n (", "end": 22467, "score": 0.9997674226760864, "start": 22463, "tag": "NAME", "value": "Ivan" }, { "context": "\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivan\"}]))\n\n (let [node *api*]\n (t/is (= #{[:ivan]}", "end": 22485, "score": 0.99980229139328, "start": 22481, "tag": "NAME", "value": "Ivan" }, { "context": "name]]\n :in [name]}\n \"Ivan\") ;;<3>\n ;; end::anatomy[]\n ", "end": 22823, "score": 0.9996762871742249, "start": 22819, "tag": "NAME", "value": "Ivan" }, { "context": " end::anatomy[]\n ))\n\n (t/is (= #{[\"Ivan\"]}\n ;; tag::triple[]\n (cr", "end": 22901, "score": 0.962064266204834, "start": 22897, "tag": "NAME", "value": "Ivan" }, { "context": " '{:find [p]\n :where [[p :name \"Ivan\"]]}) ;;<2>\n ;; end::triple-2[]\n ", "end": 23490, "score": 0.9997062683105469, "start": 23486, "tag": "NAME", "value": "Ivan" }, { "context": "ag::or-join-data[]\n [{:crux.db/id :ivan :name \"Ivan\" :age 12} ;;<1>\n {:crux.db/id :petr :name \"Pe", "end": 23941, "score": 0.9996510744094849, "start": 23937, "tag": "NAME", "value": "Ivan" }, { "context": "an\" :age 12} ;;<1>\n {:crux.db/id :petr :name \"Petr\" :age 15}\n {:crux.db/id :sergei :name \"Sergei", "end": 23993, "score": 0.9994711875915527, "start": 23989, "tag": "NAME", "value": "Petr" }, { "context": " \"Petr\" :age 15}\n {:crux.db/id :sergei :name \"Sergei\" :age 19}]\n ;; end::or-join-data[]\n ))\n\n (", "end": 24043, "score": 0.9996671676635742, "start": 24037, "tag": "NAME", "value": "Sergei" }, { "context": " a 18)])\n [p :name \"Ivan\"])]})\n ;; end::or-join[]\n )))", "end": 24549, "score": 0.9996732473373413, "start": 24545, "tag": "NAME", "value": "Ivan" }, { "context": " tag::range-data[]\n [{:crux.db/id :ivan :name \"Ivan\" :age 12} ;;<1>\n {:crux.db/id :petr :name \"Pe", "end": 24728, "score": 0.9996505379676819, "start": 24724, "tag": "NAME", "value": "Ivan" }, { "context": "an\" :age 12} ;;<1>\n {:crux.db/id :petr :name \"Petr\" :age 15}\n {:crux.db/id :sergei :name \"Sergei", "end": 24780, "score": 0.9994316697120667, "start": 24776, "tag": "NAME", "value": "Petr" }, { "context": " \"Petr\" :age 15}\n {:crux.db/id :sergei :name \"Sergei\" :age 19}]\n ;; end::range-data[]\n ))\n\n (le", "end": 24830, "score": 0.9997029304504395, "start": 24824, "tag": "NAME", "value": "Sergei" } ]
docs/reference/modules/ROOT/examples/test/crux/docs/examples/query_test.clj
cmgrote/crux
0
(ns crux.docs.examples.query-test (:require [clojure.test :as t] [crux.api :as crux] [crux.fixtures :as fix :refer [*api*]] [user :as user])) (def ^:dynamic *storage-dir*) (defn with-storage-dir [f] (fix/with-tmp-dirs [storage-dir] (binding [*storage-dir* storage-dir] (f)))) (t/use-fixtures :each fix/with-node with-storage-dir) (comment ;; tag::query-at-t-q1[] (def q '{:find [e] :where [[e :name "Malcolma"] [e :last-name "Sparks"]]}) ;; end::query-at-t-q1[] ) (t/deftest test-queries-at-time (let [node *api*] ;; tag::query-at-t-d1[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :malcolm :name "Malcolm" :last-name "Sparks"} #inst "1986-10-22"]]) ;; end::query-at-t-d1[] ;; tag::query-at-t-d2[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :malcolm :name "Malcolma" :last-name "Sparks"} #inst "1986-10-24"]]) ;; end::query-at-t-d2[] (crux/sync node) (let [q '{:find [e] :where [[e :name "Malcolma"] [e :last-name "Sparks"]]}] (t/is (= #{} ;; tag::query-at-t-q1-q[] (crux/q (crux/db node #inst "1986-10-23") q) ;; end::query-at-t-q1-q[] )) (t/is (= #{[:malcolm]} ;; tag::query-at-t-q2-q[] (crux/q (crux/db node) q) ;; end::query-at-t-q2-q[] ))))) (t/deftest test-streaming-queries (fix/submit+await-tx (fix/maps->tx-ops ;; tag::query-input[] [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"} {:crux.db/id :petr :name "Petr" :last-name "Petrov"} {:crux.db/id :smith :name "Smith" :last-name "Smith"}]) ;; end::query-input[] ) (let [node *api* !results (atom []) ;; so that it's 'prn' in the example but we can still test it. ;; cheeky. prn #(swap! !results conj %)] ;; tag::streaming-query[] (with-open [res (crux/open-q (crux/db node) '{:find [p1] :where [[p1 :name n] [p1 :last-name n] [p1 :name "Smith"]]})] (doseq [tuple (iterator-seq res)] (prn tuple))) ;; end::streaming-query[] (t/is (= [[:smith]] @!results)))) (t/deftest test-basic-queries (fix/submit+await-tx (fix/maps->tx-ops ;; tag::query-input[] [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"} {:crux.db/id :petr :name "Petr" :last-name "Petrov"} {:crux.db/id :smith :name "Smith" :last-name "Smith"}] ;; end::query-input[] )) (let [node *api*] (t/is (= ;; tag::basic-query-r[] #{[:smith]} ;; end::basic-query-r[] ;; tag::basic-query[] (crux/q (crux/db node) '{:find [p1] :where [[p1 :name n] [p1 :last-name n] [p1 :name "Smith"]]}) ;; end::basic-query[] )) (t/is (= ;; tag::query-with-arguments1-r[] #{[:ivan]} ;; end::query-with-arguments1-r[] ;; tag::query-with-arguments1[] (crux/q (crux/db node) '{:find [e] :in [first-name] :where [[e :name first-name]]} "Ivan") ;; end::query-with-arguments1[] )) (t/is (= ;; tag::query-with-arguments2-r[] #{[:ivan] [:petr]} ;; end::query-with-arguments2-r[] ;; tag::query-with-arguments2[] (crux/q (crux/db node) '{:find [e] :in [[first-name ...]] :where [[e :name first-name]]} ["Ivan" "Petr"]) ;; end::query-with-arguments2[] )) (t/is (= ;; tag::query-with-arguments3-r[] #{[:ivan]} ;; end::query-with-arguments3-r[] ;; tag::query-with-arguments3[] (crux/q (crux/db node) '{:find [e] :in [[first-name last-name]] :where [[e :name first-name] [e :last-name last-name]]} ["Ivan" "Ivanov"]) ;; end::query-with-arguments3[] )) (t/is (= ;; tag::query-with-arguments4-r[] #{[:petr] [:smith]} ;; end::query-with-arguments4-r[] ;; tag::query-with-arguments4[] (crux/q (crux/db node) '{:find [e] :in [[[first-name last-name]]] :where [[e :name first-name] [e :last-name last-name]]} [["Petr" "Petrov"] ["Smith" "Smith"]]) ;; end::query-with-arguments4[] )) (t/is (= ;; tag::query-with-arguments5-r[] #{[22]} ;; end::query-with-arguments5-r[] ;; tag::query-with-arguments5[] (crux/q (crux/db node) '{:find [age] :in [[age ...]] :where [[(> age 21)]]} [21 22]) ;; end::query-with-arguments5[] )) (t/is (= ;; tag::sub-query-example-1-r[] #{[[[4]]]} ;; end::sub-query-example-1-r[] ;; tag::sub-query-example-1[] (crux/q (crux/db node) '{:find [x] :where [[(q {:find [y] :where [[(identity 2) x] [(+ x 2) y]]}) x]]}) ;; end::sub-query-example-1[] )) (t/is (= ;; tag::sub-query-example-2-r[] #{[4]} ;; end::sub-query-example-2-r[] ;; tag::sub-query-example-2[] (crux/q (crux/db node) '{:find [x] :where [[(q {:find [y] :where [[(identity 2) x] [(+ x 2) y]]}) [[x]]]]}) ;; end::sub-query-example-2[] )) (t/is (= ;; tag::sub-query-example-3-r[] #{[2 4 8]} ;; end::sub-query-example-3-r[] ;; tag::sub-query-example-3[] (crux/q (crux/db node) '{:find [x y z] :where [[(q {:find [x y] :where [[(identity 2) x] [(+ x 2) y]]}) [[x y]]] [(* x y) z]]}) ;; end::sub-query-example-3[] )))) (t/deftest test-aggregates (let [node *api*] (t/is (= ;; tag::query-aggregates-r[] #{[6 1 3 4 2]} ;; end::query-aggregates-r[] ;; tag::query-aggregates[] (crux/q (crux/db node) '{:find [(sum ?heads) (min ?heads) (max ?heads) (count ?heads) (count-distinct ?heads)] :where [[(identity [["Cerberus" 3] ["Medusa" 1] ["Cyclops" 1] ["Chimera" 1]]) [[?monster ?heads]]]]}) ;; end::query-aggregates[] )))) (t/deftest test-join-1 (fix/submit+await-tx (fix/maps->tx-ops ;; tag::join-d[] [{:crux.db/id :ivan :name "Ivan"} {:crux.db/id :petr :name "Petr"} {:crux.db/id :sergei :name "Sergei"} {:crux.db/id :denis-a :name "Denis"} {:crux.db/id :denis-b :name "Denis"}] ;; end::join-d[] )) (let [node *api*] (t/is (= ;; tag::join-r[] #{[:ivan :ivan] [:petr :petr] [:sergei :sergei] [:denis-a :denis-a] [:denis-b :denis-b] [:denis-a :denis-b] [:denis-b :denis-a]} ;; end::join-r[] ;; tag::join-q[] (crux/q (crux/db node) '{:find [p1 p2] :where [[p1 :name n] [p2 :name n]]}) ;; end::join-q[] )))) (t/deftest test-join-2 (let [node *api*] (fix/submit+await-tx (fix/maps->tx-ops ;; tag::join2-d[] [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"} {:crux.db/id :petr :name "Petr" :follows #{"Ivanov"}}] ;; end::join2-d[] )) (t/is (= ;; tag::join2-r[] #{[:petr]} ;; end::join2-r[] ;; tag::join2-q[] (crux/q (crux/db node) '{:find [e2] :where [[e :last-name l] [e2 :follows l] [e :name "Ivan"]]}) ;; end::join2-q[] )))) (t/deftest test-eql (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :user/name "Ivan" :user/id 1 :user/profession :doctor} {:crux.db/id :sergei :user/name "Sergei" :user/id 2 :user/profession :lawyer} {:crux.db/id :petr :user/name "Petr" :user/id 3 :user/profession :doctor} {:crux.db/id :doctor :profession/name "Doctor"} {:crux.db/id :lawyer :profession/name "Lawyer"}])) (let [node *api*] (t/is (= ;; tag::eql-query-1-r[] #{[1 "Ivan" :doctor] [2 "Sergei" :lawyer], [3 "Petr" :doctor]} ;; end::eql-query-1-r[] ;; tag::eql-query-1[] ;; with just 'query': (crux/q (crux/db node) '{:find [?uid ?name ?profession] :where [[?user :user/id ?uid] [?user :user/name ?name] [?user :user/profession ?profession]]}) ;; end::eql-query-1[] )) (t/is (= ;; tag::eql-query-2-r[] #{[{:user/name "Ivan" :user/profession :doctor}] [{:user/name "Sergei" :user/profession :lawyer}] [{:user/name "Petr" :user/profession :doctor}]} ;; end::eql-query-2-r[] ;; tag::eql-query-2[] ;; using `eql/project`: (crux/q (crux/db node) '{:find [(eql/project ?user [:user/name :user/profession])] :where [[?user :user/id ?uid]]}) ;; end::eql-query-2[] )) (t/is (= ;; tag::eql-query-3-r[] #{[1 "Ivan" "Doctor"] [2 "Sergei" "Lawyer"] [3 "Petr" "Doctor"]} ;; end::eql-query-3-r[] ;; tag::eql-query-3[] ;; with just 'query': (crux/q (crux/db node) '{:find [?uid ?name ?profession-name] :where [[?user :user/id ?uid] [?user :user/name ?name] [?user :user/profession ?profession] [?profession :profession/name ?profession-name]]}) ;; end::eql-query-3[] )) (t/is (= ;; tag::eql-query-4-r[] #{[{:user/name "Ivan" :user/profession {:profession/name "Doctor"}}] [{:user/name "Sergei" :user/profession {:profession/name "Lawyer"}}] [{:user/name "Petr" :user/profession {:profession/name "Doctor"}}]} ;; end::eql-query-4-r[] ;; tag::eql-query-4[] ;; using `eql/project`: (crux/q (crux/db node) '{:find [(eql/project ?user [:user/name {:user/profession [:profession/name]}])] :where [[?user :user/id ?uid]]}) ;; end::eql-query-4[] )) (t/is (= ;; tag::eql-query-5-r[] #{[{:profession/name "Doctor" :user/_profession [{:user/id 1 :user/name "Ivan"}, {:user/id 3 :user/name "Petr"}]}] [{:profession/name "Lawyer" :user/_profession [{:user/id 2 :user/name "Sergei"}]}]} ;; end::eql-query-5-r[] ;; tag::eql-query-5[] (crux/q (crux/db node) '{:find [(eql/project ?profession [:profession/name {:user/_profession [:user/id :user/name]}])] :where [[?profession :profession/name]]}) ;; end::eql-query-5[] )) (t/is (= ;; tag::eql-query-6-r[] #{[{:crux.db/id :ivan :user/id 1, :user/name "Ivan", :user/profession :doctor}]} ;; end::eql-query-6-r[] ;; tag::eql-query-6[] (crux/q (crux/db node) '{:find [(eql/project ?user [*])] :where [[?user :user/id 1]]}) ;; end::eql-query-6[] )))) (comment ;; TODO resurrected from git history, need to be tested though ;; tag::eql-project[] ;; using `project`: (crux/project (crux/db node) [:user/name :user/profession] :ivan) ;; end::eql-project[] ;; tag::eql-project-r[] ;; => {:user/name "Ivan", :user/profession :doctor} ;; end::eql-project-r[] ;; tag::eql-project-many[] ;; using `project-many`: (crux/project-many (crux/db node) [:user/name :user/profession] [:ivan :sergei]) ;; end::eql-project-many[] ;; tag::eql-project-many-r[] ;; => [{:user/name "Ivan", :user/profession :doctor}, ;; {:user/name "Sergei", :user/profession :lawyer}] ;; end::eql-project-many-r[] ) (t/deftest test-return-maps (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :user/name "Ivan" :user/id 1 :user/profession :doctor} {:crux.db/id :sergei :user/name "Sergei" :user/id 2 :user/profession :lawyer} {:crux.db/id :petr :user/name "Petr" :user/id 3 :user/profession :doctor} {:crux.db/id :doctor :profession/name "Doctor"} {:crux.db/id :lawyer :profession/name "Lawyer"}])) (let [node *api*] (t/is (= ;; tag::return-maps-r[] #{{:name "Ivan", :profession "Doctor"}} ;; end::return-maps-r[] ;; tag::return-maps[] (crux/q (crux/db node) '{:find [?name ?profession-name] :keys [name profession] :where [[?user :user/id 1] [?user :user/name ?name] [?user :user/profession ?profession] [?profession :profession/name ?profession-name]]}) ;; end::return-maps[] )))) (t/deftest test-order-and-pagination (let [node *api* data (for [i (range 200)] {:crux.db/id i :condition/time (if (even? i) (quot i 4) (- (quot i 4))) :condition/device-id i :condition/temperature :temp :condition/humidity :hum}) conv (partial map #(vec [(:condition/time %) (:condition/device-id %) :temp :hum]))] (fix/submit+await-tx (fix/maps->tx-ops data)) (t/is (= (->> data (sort-by :condition/device-id <) (sort-by :condition/time >) conv) ;; tag::order-and-pagination-1[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[time :desc] [device-id :asc]]}) ;; end::order-and-pagination-1[] )) (t/is (= (->> data (sort-by :condition/device-id <) (drop 90) (take 10) conv) ;; tag::order-and-pagination-2[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[device-id :asc]] :limit 10 :offset 90}) ;; end::order-and-pagination-2[] )) (t/is (= (->> data (sort-by :condition/device-id <) (drop 150) (take 10) conv) ;; tag::order-and-pagination-3[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [(>= device-id my-offset)] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[device-id :asc]] :limit 10 :args [{my-offset 150}]}) ;; end::order-and-pagination-3[] )))) (t/deftest test-rules (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :follow :petr :age 19} {:crux.db/id :petr :follow :sergei :age 25} {:crux.db/id :sergei :age 3}])) (let [node *api*] (t/is (= #{[:ivan] [:petr]} ;; tag::rules-1[] (crux/q (crux/db node) '{:find [p] :where [(adult? p)] ;;<1> :rules [[(adult? p) ;;<2> [p :age a] ;;<3> [(>= a 18)]]]}) ;; end::rules-1[] )) (t/is (= #{[:petr] [:sergei]} ;; tag::rules-2[] (crux/q (crux/db node) '{:find [?e2] :where [(follow ?e1 ?e2)] :args [{?e1 :ivan}] :rules [[(follow ?e1 ?e2) [?e1 :follow ?e2]] [(follow ?e1 ?e2) [?e1 :follow ?t] (follow ?t ?e2)]]} ) ;; end::rules-2[] )))) (t/deftest test-not (fix/submit+await-tx (fix/maps->tx-ops ;; tag::not-data[] [{:crux.db/id :petr-ivanov :name "Petr" :last-name "Ivanov"} ;; <1> {:crux.db/id :ivan-ivanov :name "Ivan" :last-name "Ivanov"} {:crux.db/id :ivan-petrov :name "Ivan" :last-name "Petrov"} {:crux.db/id :petr-petrov :name "Petr" :last-name "Petrov"}] ;; end::not-data[] )) (let [node *api*] (t/is (= #{[:ivan-petrov]} (crux/q (crux/db node) '{:find [e] :where [[e :name name] [e :name "Ivan"] (not [e :last-name "Ivanov"])]}) )) (t/is (= ;; tag::not-2-r[] #{[:petr-ivanov] [:petr-petrov] [:ivan-petrov]} ;;<3> ;; end::not-2-r[] ;; tag::not-2[] (crux/q (crux/db node) '{:find [e] :where [[e :crux.db/id] (not [e :last-name "Ivanov"] ;;<2> [e :name "Ivan"])]}) ;; end::not-2[] )) (t/is (= #{[:ivan-ivanov] [:petr-ivanov]} (crux/q (crux/db node) '{:find [e] :where [[e :name name] [:ivan-petrov :last-name i-name] (not [e :last-name i-name])]}) )))) (t/deftest test-or (fix/submit+await-tx (fix/maps->tx-ops ;; tag::or-data[] [{:crux.db/id :ivan-ivanov-1 :name "Ivan" :last-name "Ivanov" :sex :male} ;;<1> {:crux.db/id :ivan-ivanov-2 :name "Ivan" :last-name "Ivanov" :sex :male} {:crux.db/id :ivan-ivanovtov-1 :name "Ivan" :last-name "Ivannotov" :sex :male} {:crux.db/id :ivanova :name "Ivanova" :last-name "Ivanov" :sex :female} {:crux.db/id :bob :name "Bob" :last-name "Controlguy"}] ;; end::or-data[] )) (let [node *api*] (t/is (= ;; tag::or-1-r[] #{[:ivan-ivanov-1] [:ivan-ivanov-2] [:ivan-ivanovtov-1]} ;;<3> ;; end::or-1-r[] ;; tag::or-1[] (crux/q (crux/db node) '{:find [e] ;;<2> :where [[e :name name] [e :name "Ivan"] (or [e :last-name "Ivanov"] [e :last-name "Ivannotov"])]}) ;; end::or-1[] )) (t/is (= #{["Ivan"] ["Ivanova"]} ;; tag::or-2[] (crux/q (crux/db node) '{:find [name] :where [[e :name name] (or [e :sex :female] (and [e :sex :male] [e :name "Ivan"]))]}) ;; end::or-2[] )) (t/is (= #{[:ivan-ivanov-1] [:ivan-ivanov-2]} (crux/q (crux/db node) '{:find [?p2] :where [(or (and [?p2 :name "Petr"] [?p2 :sex :female]) (and [?p2 :last-name "Ivanov"] [?p2 :sex :male]))]}) )))) (t/deftest test-blanks (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :name "Ivan"} {:crux.db/id :petr :name "Petr"} {:crux.db/id :sergei :name "Sergei"}])) (let [node *api*] (t/is (= #{["Ivan"] ["Petr"] ["Sergei"]} (crux/q (crux/db node) '{:find [name] :where [[_ :name name]]}))))) (t/deftest test-not-join (fix/submit+await-tx (fix/maps->tx-ops ;; tag::not-join-data[] [{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"} ;;<1> {:crux.db/id :petr :name "Petr" :last-name "Petrov"} {:crux.db/id :sergei :name "Sergei" :last-name "Sergei"}] ;; end::not-join-data[] )) (let [node *api*] (t/is (= ;; tag::not-join-r[] #{[:ivan] [:petr]} ;;<4> ;; end::not-join-r[] ;; tag::not-join[] (crux/q (crux/db node) '{:find [e] :where [[e :crux.db/id] (not-join [e] ;;<2> [e :last-name n] ;;<3> [e :name n])]}) ;; end::not-join[] )))) (t/deftest test-generic (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :name "Ivan" :last-name "Ivan"}])) (let [node *api*] (t/is (= #{[:ivan]} ;; tag::anatomy[] (crux/q (crux/db node) ;;<1> '{:find [p1] ;;<2> :where [[p1 :name n] [p1 :last-name n] [p1 :name name]] :in [name]} "Ivan") ;;<3> ;; end::anatomy[] )) (t/is (= #{["Ivan"]} ;; tag::triple[] (crux/q (crux/db node) '{:find [n] :where [[p :last-name n]]}) ;; end::triple[] )) (t/is (= #{[:ivan]} ;; tag::double[] (crux/q (crux/db node) '{:find [p] :where [[p :name]]}) ;;<1> ;; end::double[] )) (t/is (= #{[:ivan]} ;; tag::triple-2[] (crux/q (crux/db node) '{:find [p] :where [[p :name "Ivan"]]}) ;;<2> ;; end::triple-2[] )) (t/is (= #{[:ivan]} ;; tag::triple-3[] (crux/q (crux/db node) '{:find [p] :where [[q :name n] [p :last-name n]]}) ;;<3> ;; end::triple-3[] )))) (t/deftest test-or-join (fix/submit+await-tx (fix/maps->tx-ops ;; tag::or-join-data[] [{:crux.db/id :ivan :name "Ivan" :age 12} ;;<1> {:crux.db/id :petr :name "Petr" :age 15} {:crux.db/id :sergei :name "Sergei" :age 19}] ;; end::or-join-data[] )) (let [node *api*] (t/is (= ;; tag::or-join-r[] #{[:ivan] [:sergei]} ;;<4> ;; end::or-join-r[] ;; tag::or-join[] (crux/q (crux/db node) '{:find [p] :where [[p :crux.db/id] (or-join [p] ;;<2> (and [p :age a] ;;<3> [(>= a 18)]) [p :name "Ivan"])]}) ;; end::or-join[] )))) (t/deftest test-range (fix/submit+await-tx (fix/maps->tx-ops ;; tag::range-data[] [{:crux.db/id :ivan :name "Ivan" :age 12} ;;<1> {:crux.db/id :petr :name "Petr" :age 15} {:crux.db/id :sergei :name "Sergei" :age 19}] ;; end::range-data[] )) (let [node *api*] (t/is (= #{[:sergei]} ;; tag::range-1[] (crux/q (crux/db node) '{:find [p] ;;<1> :where [[p :age a] [(> a 18)]]}) ;; end::range-1[] )) (t/is (= #{[:petr] [:sergei]} ;; tag::range-2[] (crux/q (crux/db node) '{:find [p] ;;<2> :where [[p :age a] [q :age b] [(> a b)]]}) ;; end::range-2[] )) (t/is (= #{[:ivan] [:petr]} ;; tag::range-3[] (crux/q (crux/db node) '{:find [p] ;;<3> :where [[p :age a] [(> 18 a)]]}) ;; end::range-3[] )) (t/is (= ;; tag::query-with-pred-1-r[] #{[:petr] [:sergei]} ;; end::query-with-pred-1-r[] ;; tag::query-with-pred-1[] (crux/q (crux/db node) '{:find [p] :where [[p :age age] [(odd? age)]]}) ;; end::query-with-pred-1[] )) )) (t/deftest test-full-results (fix/submit+await-tx (fix/maps->tx-ops ;; tag::full-results-data[] [{:crux.db/id :foo :bar :baz}] ;; end::full-results-data[] )) (let [node *api*] (t/is (= ;; tag::full-results-1-r[] #{[:foo]} ;; end::full-results-1-r[] ;; tag::full-results-1[] (crux/q (crux/db node) '{:find [p] :where [[p :bar :baz]]}) ;; end::full-results-1[] )) (t/is (= ;; tag::full-results-2-r[] #{[{:crux.db/id :foo :bar :baz}]} ;; end::full-results-2-r[] ;; tag::full-results-2[] (crux/q (crux/db node) '{:find [p] :where [[p :bar :baz]] :full-results? true}) ;; end::full-results-2[] ))))
111298
(ns crux.docs.examples.query-test (:require [clojure.test :as t] [crux.api :as crux] [crux.fixtures :as fix :refer [*api*]] [user :as user])) (def ^:dynamic *storage-dir*) (defn with-storage-dir [f] (fix/with-tmp-dirs [storage-dir] (binding [*storage-dir* storage-dir] (f)))) (t/use-fixtures :each fix/with-node with-storage-dir) (comment ;; tag::query-at-t-q1[] (def q '{:find [e] :where [[e :name "<NAME>"] [e :last-name "<NAME>"]]}) ;; end::query-at-t-q1[] ) (t/deftest test-queries-at-time (let [node *api*] ;; tag::query-at-t-d1[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :malcolm :name "<NAME>" :last-name "<NAME>"} #inst "1986-10-22"]]) ;; end::query-at-t-d1[] ;; tag::query-at-t-d2[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :malcolm :name "<NAME>" :last-name "<NAME>"} #inst "1986-10-24"]]) ;; end::query-at-t-d2[] (crux/sync node) (let [q '{:find [e] :where [[e :name "<NAME>"] [e :last-name "<NAME>"]]}] (t/is (= #{} ;; tag::query-at-t-q1-q[] (crux/q (crux/db node #inst "1986-10-23") q) ;; end::query-at-t-q1-q[] )) (t/is (= #{[:malcolm]} ;; tag::query-at-t-q2-q[] (crux/q (crux/db node) q) ;; end::query-at-t-q2-q[] ))))) (t/deftest test-streaming-queries (fix/submit+await-tx (fix/maps->tx-ops ;; tag::query-input[] [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :petr :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :smith :name "<NAME>" :last-name "<NAME>"}]) ;; end::query-input[] ) (let [node *api* !results (atom []) ;; so that it's 'prn' in the example but we can still test it. ;; cheeky. prn #(swap! !results conj %)] ;; tag::streaming-query[] (with-open [res (crux/open-q (crux/db node) '{:find [p1] :where [[p1 :name n] [p1 :last-name n] [p1 :name "<NAME>"]]})] (doseq [tuple (iterator-seq res)] (prn tuple))) ;; end::streaming-query[] (t/is (= [[:smith]] @!results)))) (t/deftest test-basic-queries (fix/submit+await-tx (fix/maps->tx-ops ;; tag::query-input[] [{:crux.db/id :iv<NAME> :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :petr :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :smith :name "<NAME>" :last-name "<NAME>"}] ;; end::query-input[] )) (let [node *api*] (t/is (= ;; tag::basic-query-r[] #{[:smith]} ;; end::basic-query-r[] ;; tag::basic-query[] (crux/q (crux/db node) '{:find [p1] :where [[p1 :name n] [p1 :last-name n] [p1 :name "<NAME>"]]}) ;; end::basic-query[] )) (t/is (= ;; tag::query-with-arguments1-r[] #{[:ivan]} ;; end::query-with-arguments1-r[] ;; tag::query-with-arguments1[] (crux/q (crux/db node) '{:find [e] :in [first-name] :where [[e :name first-name]]} "<NAME>") ;; end::query-with-arguments1[] )) (t/is (= ;; tag::query-with-arguments2-r[] #{[:ivan] [:petr]} ;; end::query-with-arguments2-r[] ;; tag::query-with-arguments2[] (crux/q (crux/db node) '{:find [e] :in [[first-name ...]] :where [[e :name first-name]]} ["<NAME>" "<NAME>"]) ;; end::query-with-arguments2[] )) (t/is (= ;; tag::query-with-arguments3-r[] #{[:ivan]} ;; end::query-with-arguments3-r[] ;; tag::query-with-arguments3[] (crux/q (crux/db node) '{:find [e] :in [[first-name last-name]] :where [[e :name first-name] [e :last-name last-name]]} ["<NAME>" "<NAME>"]) ;; end::query-with-arguments3[] )) (t/is (= ;; tag::query-with-arguments4-r[] #{[:petr] [:smith]} ;; end::query-with-arguments4-r[] ;; tag::query-with-arguments4[] (crux/q (crux/db node) '{:find [e] :in [[[first-name last-name]]] :where [[e :name first-name] [e :last-name last-name]]} [["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"]]) ;; end::query-with-arguments4[] )) (t/is (= ;; tag::query-with-arguments5-r[] #{[22]} ;; end::query-with-arguments5-r[] ;; tag::query-with-arguments5[] (crux/q (crux/db node) '{:find [age] :in [[age ...]] :where [[(> age 21)]]} [21 22]) ;; end::query-with-arguments5[] )) (t/is (= ;; tag::sub-query-example-1-r[] #{[[[4]]]} ;; end::sub-query-example-1-r[] ;; tag::sub-query-example-1[] (crux/q (crux/db node) '{:find [x] :where [[(q {:find [y] :where [[(identity 2) x] [(+ x 2) y]]}) x]]}) ;; end::sub-query-example-1[] )) (t/is (= ;; tag::sub-query-example-2-r[] #{[4]} ;; end::sub-query-example-2-r[] ;; tag::sub-query-example-2[] (crux/q (crux/db node) '{:find [x] :where [[(q {:find [y] :where [[(identity 2) x] [(+ x 2) y]]}) [[x]]]]}) ;; end::sub-query-example-2[] )) (t/is (= ;; tag::sub-query-example-3-r[] #{[2 4 8]} ;; end::sub-query-example-3-r[] ;; tag::sub-query-example-3[] (crux/q (crux/db node) '{:find [x y z] :where [[(q {:find [x y] :where [[(identity 2) x] [(+ x 2) y]]}) [[x y]]] [(* x y) z]]}) ;; end::sub-query-example-3[] )))) (t/deftest test-aggregates (let [node *api*] (t/is (= ;; tag::query-aggregates-r[] #{[6 1 3 4 2]} ;; end::query-aggregates-r[] ;; tag::query-aggregates[] (crux/q (crux/db node) '{:find [(sum ?heads) (min ?heads) (max ?heads) (count ?heads) (count-distinct ?heads)] :where [[(identity [["Cerberus" 3] ["Medusa" 1] ["Cyclops" 1] ["Chimera" 1]]) [[?monster ?heads]]]]}) ;; end::query-aggregates[] )))) (t/deftest test-join-1 (fix/submit+await-tx (fix/maps->tx-ops ;; tag::join-d[] [{:crux.db/id :ivan :name "<NAME>"} {:crux.db/id :petr :name "<NAME>"} {:crux.db/id :sergei :name "<NAME>i"} {:crux.db/id :denis-a :name "<NAME>"} {:crux.db/id :denis-b :name "<NAME>"}] ;; end::join-d[] )) (let [node *api*] (t/is (= ;; tag::join-r[] #{[:ivan :ivan] [:petr :petr] [:sergei :sergei] [:denis-a :denis-a] [:denis-b :denis-b] [:denis-a :denis-b] [:denis-b :denis-a]} ;; end::join-r[] ;; tag::join-q[] (crux/q (crux/db node) '{:find [p1 p2] :where [[p1 :name n] [p2 :name n]]}) ;; end::join-q[] )))) (t/deftest test-join-2 (let [node *api*] (fix/submit+await-tx (fix/maps->tx-ops ;; tag::join2-d[] [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :petr :name "<NAME>" :follows #{"<NAME>"}}] ;; end::join2-d[] )) (t/is (= ;; tag::join2-r[] #{[:petr]} ;; end::join2-r[] ;; tag::join2-q[] (crux/q (crux/db node) '{:find [e2] :where [[e :last-name l] [e2 :follows l] [e :name "<NAME>"]]}) ;; end::join2-q[] )))) (t/deftest test-eql (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :user/name "<NAME>" :user/id 1 :user/profession :doctor} {:crux.db/id :sergei :user/name "<NAME>" :user/id 2 :user/profession :lawyer} {:crux.db/id :petr :user/name "<NAME>" :user/id 3 :user/profession :doctor} {:crux.db/id :doctor :profession/name "Doctor"} {:crux.db/id :lawyer :profession/name "Lawyer"}])) (let [node *api*] (t/is (= ;; tag::eql-query-1-r[] #{[1 "<NAME>" :doctor] [2 "<NAME>" :lawyer], [3 "<NAME>" :doctor]} ;; end::eql-query-1-r[] ;; tag::eql-query-1[] ;; with just 'query': (crux/q (crux/db node) '{:find [?uid ?name ?profession] :where [[?user :user/id ?uid] [?user :user/name ?name] [?user :user/profession ?profession]]}) ;; end::eql-query-1[] )) (t/is (= ;; tag::eql-query-2-r[] #{[{:user/name "<NAME>" :user/profession :doctor}] [{:user/name "<NAME>" :user/profession :lawyer}] [{:user/name "<NAME>" :user/profession :doctor}]} ;; end::eql-query-2-r[] ;; tag::eql-query-2[] ;; using `eql/project`: (crux/q (crux/db node) '{:find [(eql/project ?user [:user/name :user/profession])] :where [[?user :user/id ?uid]]}) ;; end::eql-query-2[] )) (t/is (= ;; tag::eql-query-3-r[] #{[1 "<NAME>" "Doctor"] [2 "<NAME>" "Lawyer"] [3 "Petr" "Doctor"]} ;; end::eql-query-3-r[] ;; tag::eql-query-3[] ;; with just 'query': (crux/q (crux/db node) '{:find [?uid ?name ?profession-name] :where [[?user :user/id ?uid] [?user :user/name ?name] [?user :user/profession ?profession] [?profession :profession/name ?profession-name]]}) ;; end::eql-query-3[] )) (t/is (= ;; tag::eql-query-4-r[] #{[{:user/name "<NAME>" :user/profession {:profession/name "Doctor"}}] [{:user/name "<NAME>" :user/profession {:profession/name "Lawyer"}}] [{:user/name "<NAME>" :user/profession {:profession/name "Doctor"}}]} ;; end::eql-query-4-r[] ;; tag::eql-query-4[] ;; using `eql/project`: (crux/q (crux/db node) '{:find [(eql/project ?user [:user/name {:user/profession [:profession/name]}])] :where [[?user :user/id ?uid]]}) ;; end::eql-query-4[] )) (t/is (= ;; tag::eql-query-5-r[] #{[{:profession/name "Doctor" :user/_profession [{:user/id 1 :user/name "<NAME>"}, {:user/id 3 :user/name "<NAME>"}]}] [{:profession/name "Lawyer" :user/_profession [{:user/id 2 :user/name "<NAME>"}]}]} ;; end::eql-query-5-r[] ;; tag::eql-query-5[] (crux/q (crux/db node) '{:find [(eql/project ?profession [:profession/name {:user/_profession [:user/id :user/name]}])] :where [[?profession :profession/name]]}) ;; end::eql-query-5[] )) (t/is (= ;; tag::eql-query-6-r[] #{[{:crux.db/id :ivan :user/id 1, :user/name "<NAME>", :user/profession :doctor}]} ;; end::eql-query-6-r[] ;; tag::eql-query-6[] (crux/q (crux/db node) '{:find [(eql/project ?user [*])] :where [[?user :user/id 1]]}) ;; end::eql-query-6[] )))) (comment ;; TODO resurrected from git history, need to be tested though ;; tag::eql-project[] ;; using `project`: (crux/project (crux/db node) [:user/name :user/profession] :ivan) ;; end::eql-project[] ;; tag::eql-project-r[] ;; => {:user/name "<NAME>", :user/profession :doctor} ;; end::eql-project-r[] ;; tag::eql-project-many[] ;; using `project-many`: (crux/project-many (crux/db node) [:user/name :user/profession] [:ivan :sergei]) ;; end::eql-project-many[] ;; tag::eql-project-many-r[] ;; => [{:user/name "<NAME>", :user/profession :doctor}, ;; {:user/name "<NAME>", :user/profession :lawyer}] ;; end::eql-project-many-r[] ) (t/deftest test-return-maps (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :user/name "<NAME>" :user/id 1 :user/profession :doctor} {:crux.db/id :sergei :user/name "<NAME>" :user/id 2 :user/profession :lawyer} {:crux.db/id :petr :user/name "<NAME>" :user/id 3 :user/profession :doctor} {:crux.db/id :doctor :profession/name "Doctor"} {:crux.db/id :lawyer :profession/name "Lawyer"}])) (let [node *api*] (t/is (= ;; tag::return-maps-r[] #{{:name "<NAME>", :profession "Doctor"}} ;; end::return-maps-r[] ;; tag::return-maps[] (crux/q (crux/db node) '{:find [?name ?profession-name] :keys [name profession] :where [[?user :user/id 1] [?user :user/name ?name] [?user :user/profession ?profession] [?profession :profession/name ?profession-name]]}) ;; end::return-maps[] )))) (t/deftest test-order-and-pagination (let [node *api* data (for [i (range 200)] {:crux.db/id i :condition/time (if (even? i) (quot i 4) (- (quot i 4))) :condition/device-id i :condition/temperature :temp :condition/humidity :hum}) conv (partial map #(vec [(:condition/time %) (:condition/device-id %) :temp :hum]))] (fix/submit+await-tx (fix/maps->tx-ops data)) (t/is (= (->> data (sort-by :condition/device-id <) (sort-by :condition/time >) conv) ;; tag::order-and-pagination-1[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[time :desc] [device-id :asc]]}) ;; end::order-and-pagination-1[] )) (t/is (= (->> data (sort-by :condition/device-id <) (drop 90) (take 10) conv) ;; tag::order-and-pagination-2[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[device-id :asc]] :limit 10 :offset 90}) ;; end::order-and-pagination-2[] )) (t/is (= (->> data (sort-by :condition/device-id <) (drop 150) (take 10) conv) ;; tag::order-and-pagination-3[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [(>= device-id my-offset)] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[device-id :asc]] :limit 10 :args [{my-offset 150}]}) ;; end::order-and-pagination-3[] )))) (t/deftest test-rules (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :follow :petr :age 19} {:crux.db/id :petr :follow :sergei :age 25} {:crux.db/id :sergei :age 3}])) (let [node *api*] (t/is (= #{[:ivan] [:petr]} ;; tag::rules-1[] (crux/q (crux/db node) '{:find [p] :where [(adult? p)] ;;<1> :rules [[(adult? p) ;;<2> [p :age a] ;;<3> [(>= a 18)]]]}) ;; end::rules-1[] )) (t/is (= #{[:petr] [:sergei]} ;; tag::rules-2[] (crux/q (crux/db node) '{:find [?e2] :where [(follow ?e1 ?e2)] :args [{?e1 :ivan}] :rules [[(follow ?e1 ?e2) [?e1 :follow ?e2]] [(follow ?e1 ?e2) [?e1 :follow ?t] (follow ?t ?e2)]]} ) ;; end::rules-2[] )))) (t/deftest test-not (fix/submit+await-tx (fix/maps->tx-ops ;; tag::not-data[] [{:crux.db/id :petr-ivanov :name "<NAME>" :last-name "<NAME>"} ;; <1> {:crux.db/id :ivan-ivanov :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :ivan-petrov :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :petr-petrov :name "<NAME>" :last-name "<NAME>"}] ;; end::not-data[] )) (let [node *api*] (t/is (= #{[:ivan-petrov]} (crux/q (crux/db node) '{:find [e] :where [[e :name name] [e :name "<NAME>"] (not [e :last-name "<NAME>"])]}) )) (t/is (= ;; tag::not-2-r[] #{[:petr-ivanov] [:petr-petrov] [:ivan-petrov]} ;;<3> ;; end::not-2-r[] ;; tag::not-2[] (crux/q (crux/db node) '{:find [e] :where [[e :crux.db/id] (not [e :last-name "<NAME>"] ;;<2> [e :name "<NAME>"])]}) ;; end::not-2[] )) (t/is (= #{[:ivan-ivanov] [:petr-ivanov]} (crux/q (crux/db node) '{:find [e] :where [[e :name name] [:ivan-petrov :last-name i-name] (not [e :last-name i-name])]}) )))) (t/deftest test-or (fix/submit+await-tx (fix/maps->tx-ops ;; tag::or-data[] [{:crux.db/id :ivan-ivanov-1 :name "<NAME>" :last-name "<NAME>" :sex :male} ;;<1> {:crux.db/id :ivan-ivanov-2 :name "<NAME>" :last-name "<NAME>" :sex :male} {:crux.db/id :ivan-ivanovtov-1 :name "<NAME>" :last-name "<NAME>" :sex :male} {:crux.db/id :iv<NAME> :name "<NAME>" :last-name "<NAME>" :sex :female} {:crux.db/id :bob :name "<NAME>" :last-name "<NAME>"}] ;; end::or-data[] )) (let [node *api*] (t/is (= ;; tag::or-1-r[] #{[:ivan-ivanov-1] [:ivan-ivanov-2] [:ivan-ivanovtov-1]} ;;<3> ;; end::or-1-r[] ;; tag::or-1[] (crux/q (crux/db node) '{:find [e] ;;<2> :where [[e :name name] [e :name "<NAME>"] (or [e :last-name "<NAME>"] [e :last-name "<NAME>"])]}) ;; end::or-1[] )) (t/is (= #{["<NAME>"] ["<NAME>"]} ;; tag::or-2[] (crux/q (crux/db node) '{:find [name] :where [[e :name name] (or [e :sex :female] (and [e :sex :male] [e :name "<NAME>"]))]}) ;; end::or-2[] )) (t/is (= #{[:ivan-ivanov-1] [:ivan-ivanov-2]} (crux/q (crux/db node) '{:find [?p2] :where [(or (and [?p2 :name "<NAME>"] [?p2 :sex :female]) (and [?p2 :last-name "<NAME>"] [?p2 :sex :male]))]}) )))) (t/deftest test-blanks (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :name "<NAME>"} {:crux.db/id :petr :name "<NAME>"} {:crux.db/id :sergei :name "<NAME>"}])) (let [node *api*] (t/is (= #{["<NAME>"] ["<NAME>"] ["<NAME>"]} (crux/q (crux/db node) '{:find [name] :where [[_ :name name]]}))))) (t/deftest test-not-join (fix/submit+await-tx (fix/maps->tx-ops ;; tag::not-join-data[] [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"} ;;<1> {:crux.db/id :petr :name "<NAME>" :last-name "<NAME>"} {:crux.db/id :sergei :name "<NAME>" :last-name "<NAME>"}] ;; end::not-join-data[] )) (let [node *api*] (t/is (= ;; tag::not-join-r[] #{[:ivan] [:petr]} ;;<4> ;; end::not-join-r[] ;; tag::not-join[] (crux/q (crux/db node) '{:find [e] :where [[e :crux.db/id] (not-join [e] ;;<2> [e :last-name n] ;;<3> [e :name n])]}) ;; end::not-join[] )))) (t/deftest test-generic (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"}])) (let [node *api*] (t/is (= #{[:ivan]} ;; tag::anatomy[] (crux/q (crux/db node) ;;<1> '{:find [p1] ;;<2> :where [[p1 :name n] [p1 :last-name n] [p1 :name name]] :in [name]} "<NAME>") ;;<3> ;; end::anatomy[] )) (t/is (= #{["<NAME>"]} ;; tag::triple[] (crux/q (crux/db node) '{:find [n] :where [[p :last-name n]]}) ;; end::triple[] )) (t/is (= #{[:ivan]} ;; tag::double[] (crux/q (crux/db node) '{:find [p] :where [[p :name]]}) ;;<1> ;; end::double[] )) (t/is (= #{[:ivan]} ;; tag::triple-2[] (crux/q (crux/db node) '{:find [p] :where [[p :name "<NAME>"]]}) ;;<2> ;; end::triple-2[] )) (t/is (= #{[:ivan]} ;; tag::triple-3[] (crux/q (crux/db node) '{:find [p] :where [[q :name n] [p :last-name n]]}) ;;<3> ;; end::triple-3[] )))) (t/deftest test-or-join (fix/submit+await-tx (fix/maps->tx-ops ;; tag::or-join-data[] [{:crux.db/id :ivan :name "<NAME>" :age 12} ;;<1> {:crux.db/id :petr :name "<NAME>" :age 15} {:crux.db/id :sergei :name "<NAME>" :age 19}] ;; end::or-join-data[] )) (let [node *api*] (t/is (= ;; tag::or-join-r[] #{[:ivan] [:sergei]} ;;<4> ;; end::or-join-r[] ;; tag::or-join[] (crux/q (crux/db node) '{:find [p] :where [[p :crux.db/id] (or-join [p] ;;<2> (and [p :age a] ;;<3> [(>= a 18)]) [p :name "<NAME>"])]}) ;; end::or-join[] )))) (t/deftest test-range (fix/submit+await-tx (fix/maps->tx-ops ;; tag::range-data[] [{:crux.db/id :ivan :name "<NAME>" :age 12} ;;<1> {:crux.db/id :petr :name "<NAME>" :age 15} {:crux.db/id :sergei :name "<NAME>" :age 19}] ;; end::range-data[] )) (let [node *api*] (t/is (= #{[:sergei]} ;; tag::range-1[] (crux/q (crux/db node) '{:find [p] ;;<1> :where [[p :age a] [(> a 18)]]}) ;; end::range-1[] )) (t/is (= #{[:petr] [:sergei]} ;; tag::range-2[] (crux/q (crux/db node) '{:find [p] ;;<2> :where [[p :age a] [q :age b] [(> a b)]]}) ;; end::range-2[] )) (t/is (= #{[:ivan] [:petr]} ;; tag::range-3[] (crux/q (crux/db node) '{:find [p] ;;<3> :where [[p :age a] [(> 18 a)]]}) ;; end::range-3[] )) (t/is (= ;; tag::query-with-pred-1-r[] #{[:petr] [:sergei]} ;; end::query-with-pred-1-r[] ;; tag::query-with-pred-1[] (crux/q (crux/db node) '{:find [p] :where [[p :age age] [(odd? age)]]}) ;; end::query-with-pred-1[] )) )) (t/deftest test-full-results (fix/submit+await-tx (fix/maps->tx-ops ;; tag::full-results-data[] [{:crux.db/id :foo :bar :baz}] ;; end::full-results-data[] )) (let [node *api*] (t/is (= ;; tag::full-results-1-r[] #{[:foo]} ;; end::full-results-1-r[] ;; tag::full-results-1[] (crux/q (crux/db node) '{:find [p] :where [[p :bar :baz]]}) ;; end::full-results-1[] )) (t/is (= ;; tag::full-results-2-r[] #{[{:crux.db/id :foo :bar :baz}]} ;; end::full-results-2-r[] ;; tag::full-results-2[] (crux/q (crux/db node) '{:find [p] :where [[p :bar :baz]] :full-results? true}) ;; end::full-results-2[] ))))
true
(ns crux.docs.examples.query-test (:require [clojure.test :as t] [crux.api :as crux] [crux.fixtures :as fix :refer [*api*]] [user :as user])) (def ^:dynamic *storage-dir*) (defn with-storage-dir [f] (fix/with-tmp-dirs [storage-dir] (binding [*storage-dir* storage-dir] (f)))) (t/use-fixtures :each fix/with-node with-storage-dir) (comment ;; tag::query-at-t-q1[] (def q '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"] [e :last-name "PI:NAME:<NAME>END_PI"]]}) ;; end::query-at-t-q1[] ) (t/deftest test-queries-at-time (let [node *api*] ;; tag::query-at-t-d1[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :malcolm :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} #inst "1986-10-22"]]) ;; end::query-at-t-d1[] ;; tag::query-at-t-d2[] (crux/submit-tx node [[:crux.tx/put {:crux.db/id :malcolm :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} #inst "1986-10-24"]]) ;; end::query-at-t-d2[] (crux/sync node) (let [q '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"] [e :last-name "PI:NAME:<NAME>END_PI"]]}] (t/is (= #{} ;; tag::query-at-t-q1-q[] (crux/q (crux/db node #inst "1986-10-23") q) ;; end::query-at-t-q1-q[] )) (t/is (= #{[:malcolm]} ;; tag::query-at-t-q2-q[] (crux/q (crux/db node) q) ;; end::query-at-t-q2-q[] ))))) (t/deftest test-streaming-queries (fix/submit+await-tx (fix/maps->tx-ops ;; tag::query-input[] [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :smith :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]) ;; end::query-input[] ) (let [node *api* !results (atom []) ;; so that it's 'prn' in the example but we can still test it. ;; cheeky. prn #(swap! !results conj %)] ;; tag::streaming-query[] (with-open [res (crux/open-q (crux/db node) '{:find [p1] :where [[p1 :name n] [p1 :last-name n] [p1 :name "PI:NAME:<NAME>END_PI"]]})] (doseq [tuple (iterator-seq res)] (prn tuple))) ;; end::streaming-query[] (t/is (= [[:smith]] @!results)))) (t/deftest test-basic-queries (fix/submit+await-tx (fix/maps->tx-ops ;; tag::query-input[] [{:crux.db/id :ivPI:NAME:<NAME>END_PI :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :smith :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}] ;; end::query-input[] )) (let [node *api*] (t/is (= ;; tag::basic-query-r[] #{[:smith]} ;; end::basic-query-r[] ;; tag::basic-query[] (crux/q (crux/db node) '{:find [p1] :where [[p1 :name n] [p1 :last-name n] [p1 :name "PI:NAME:<NAME>END_PI"]]}) ;; end::basic-query[] )) (t/is (= ;; tag::query-with-arguments1-r[] #{[:ivan]} ;; end::query-with-arguments1-r[] ;; tag::query-with-arguments1[] (crux/q (crux/db node) '{:find [e] :in [first-name] :where [[e :name first-name]]} "PI:NAME:<NAME>END_PI") ;; end::query-with-arguments1[] )) (t/is (= ;; tag::query-with-arguments2-r[] #{[:ivan] [:petr]} ;; end::query-with-arguments2-r[] ;; tag::query-with-arguments2[] (crux/q (crux/db node) '{:find [e] :in [[first-name ...]] :where [[e :name first-name]]} ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ;; end::query-with-arguments2[] )) (t/is (= ;; tag::query-with-arguments3-r[] #{[:ivan]} ;; end::query-with-arguments3-r[] ;; tag::query-with-arguments3[] (crux/q (crux/db node) '{:find [e] :in [[first-name last-name]] :where [[e :name first-name] [e :last-name last-name]]} ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ;; end::query-with-arguments3[] )) (t/is (= ;; tag::query-with-arguments4-r[] #{[:petr] [:smith]} ;; end::query-with-arguments4-r[] ;; tag::query-with-arguments4[] (crux/q (crux/db node) '{:find [e] :in [[[first-name last-name]]] :where [[e :name first-name] [e :last-name last-name]]} [["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]]) ;; end::query-with-arguments4[] )) (t/is (= ;; tag::query-with-arguments5-r[] #{[22]} ;; end::query-with-arguments5-r[] ;; tag::query-with-arguments5[] (crux/q (crux/db node) '{:find [age] :in [[age ...]] :where [[(> age 21)]]} [21 22]) ;; end::query-with-arguments5[] )) (t/is (= ;; tag::sub-query-example-1-r[] #{[[[4]]]} ;; end::sub-query-example-1-r[] ;; tag::sub-query-example-1[] (crux/q (crux/db node) '{:find [x] :where [[(q {:find [y] :where [[(identity 2) x] [(+ x 2) y]]}) x]]}) ;; end::sub-query-example-1[] )) (t/is (= ;; tag::sub-query-example-2-r[] #{[4]} ;; end::sub-query-example-2-r[] ;; tag::sub-query-example-2[] (crux/q (crux/db node) '{:find [x] :where [[(q {:find [y] :where [[(identity 2) x] [(+ x 2) y]]}) [[x]]]]}) ;; end::sub-query-example-2[] )) (t/is (= ;; tag::sub-query-example-3-r[] #{[2 4 8]} ;; end::sub-query-example-3-r[] ;; tag::sub-query-example-3[] (crux/q (crux/db node) '{:find [x y z] :where [[(q {:find [x y] :where [[(identity 2) x] [(+ x 2) y]]}) [[x y]]] [(* x y) z]]}) ;; end::sub-query-example-3[] )))) (t/deftest test-aggregates (let [node *api*] (t/is (= ;; tag::query-aggregates-r[] #{[6 1 3 4 2]} ;; end::query-aggregates-r[] ;; tag::query-aggregates[] (crux/q (crux/db node) '{:find [(sum ?heads) (min ?heads) (max ?heads) (count ?heads) (count-distinct ?heads)] :where [[(identity [["Cerberus" 3] ["Medusa" 1] ["Cyclops" 1] ["Chimera" 1]]) [[?monster ?heads]]]]}) ;; end::query-aggregates[] )))) (t/deftest test-join-1 (fix/submit+await-tx (fix/maps->tx-ops ;; tag::join-d[] [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI"} {:crux.db/id :sergei :name "PI:NAME:<NAME>END_PIi"} {:crux.db/id :denis-a :name "PI:NAME:<NAME>END_PI"} {:crux.db/id :denis-b :name "PI:NAME:<NAME>END_PI"}] ;; end::join-d[] )) (let [node *api*] (t/is (= ;; tag::join-r[] #{[:ivan :ivan] [:petr :petr] [:sergei :sergei] [:denis-a :denis-a] [:denis-b :denis-b] [:denis-a :denis-b] [:denis-b :denis-a]} ;; end::join-r[] ;; tag::join-q[] (crux/q (crux/db node) '{:find [p1 p2] :where [[p1 :name n] [p2 :name n]]}) ;; end::join-q[] )))) (t/deftest test-join-2 (let [node *api*] (fix/submit+await-tx (fix/maps->tx-ops ;; tag::join2-d[] [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :follows #{"PI:NAME:<NAME>END_PI"}}] ;; end::join2-d[] )) (t/is (= ;; tag::join2-r[] #{[:petr]} ;; end::join2-r[] ;; tag::join2-q[] (crux/q (crux/db node) '{:find [e2] :where [[e :last-name l] [e2 :follows l] [e :name "PI:NAME:<NAME>END_PI"]]}) ;; end::join2-q[] )))) (t/deftest test-eql (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :user/name "PI:NAME:<NAME>END_PI" :user/id 1 :user/profession :doctor} {:crux.db/id :sergei :user/name "PI:NAME:<NAME>END_PI" :user/id 2 :user/profession :lawyer} {:crux.db/id :petr :user/name "PI:NAME:<NAME>END_PI" :user/id 3 :user/profession :doctor} {:crux.db/id :doctor :profession/name "Doctor"} {:crux.db/id :lawyer :profession/name "Lawyer"}])) (let [node *api*] (t/is (= ;; tag::eql-query-1-r[] #{[1 "PI:NAME:<NAME>END_PI" :doctor] [2 "PI:NAME:<NAME>END_PI" :lawyer], [3 "PI:NAME:<NAME>END_PI" :doctor]} ;; end::eql-query-1-r[] ;; tag::eql-query-1[] ;; with just 'query': (crux/q (crux/db node) '{:find [?uid ?name ?profession] :where [[?user :user/id ?uid] [?user :user/name ?name] [?user :user/profession ?profession]]}) ;; end::eql-query-1[] )) (t/is (= ;; tag::eql-query-2-r[] #{[{:user/name "PI:NAME:<NAME>END_PI" :user/profession :doctor}] [{:user/name "PI:NAME:<NAME>END_PI" :user/profession :lawyer}] [{:user/name "PI:NAME:<NAME>END_PI" :user/profession :doctor}]} ;; end::eql-query-2-r[] ;; tag::eql-query-2[] ;; using `eql/project`: (crux/q (crux/db node) '{:find [(eql/project ?user [:user/name :user/profession])] :where [[?user :user/id ?uid]]}) ;; end::eql-query-2[] )) (t/is (= ;; tag::eql-query-3-r[] #{[1 "PI:NAME:<NAME>END_PI" "Doctor"] [2 "PI:NAME:<NAME>END_PI" "Lawyer"] [3 "Petr" "Doctor"]} ;; end::eql-query-3-r[] ;; tag::eql-query-3[] ;; with just 'query': (crux/q (crux/db node) '{:find [?uid ?name ?profession-name] :where [[?user :user/id ?uid] [?user :user/name ?name] [?user :user/profession ?profession] [?profession :profession/name ?profession-name]]}) ;; end::eql-query-3[] )) (t/is (= ;; tag::eql-query-4-r[] #{[{:user/name "PI:NAME:<NAME>END_PI" :user/profession {:profession/name "Doctor"}}] [{:user/name "PI:NAME:<NAME>END_PI" :user/profession {:profession/name "Lawyer"}}] [{:user/name "PI:NAME:<NAME>END_PI" :user/profession {:profession/name "Doctor"}}]} ;; end::eql-query-4-r[] ;; tag::eql-query-4[] ;; using `eql/project`: (crux/q (crux/db node) '{:find [(eql/project ?user [:user/name {:user/profession [:profession/name]}])] :where [[?user :user/id ?uid]]}) ;; end::eql-query-4[] )) (t/is (= ;; tag::eql-query-5-r[] #{[{:profession/name "Doctor" :user/_profession [{:user/id 1 :user/name "PI:NAME:<NAME>END_PI"}, {:user/id 3 :user/name "PI:NAME:<NAME>END_PI"}]}] [{:profession/name "Lawyer" :user/_profession [{:user/id 2 :user/name "PI:NAME:<NAME>END_PI"}]}]} ;; end::eql-query-5-r[] ;; tag::eql-query-5[] (crux/q (crux/db node) '{:find [(eql/project ?profession [:profession/name {:user/_profession [:user/id :user/name]}])] :where [[?profession :profession/name]]}) ;; end::eql-query-5[] )) (t/is (= ;; tag::eql-query-6-r[] #{[{:crux.db/id :ivan :user/id 1, :user/name "PI:NAME:<NAME>END_PI", :user/profession :doctor}]} ;; end::eql-query-6-r[] ;; tag::eql-query-6[] (crux/q (crux/db node) '{:find [(eql/project ?user [*])] :where [[?user :user/id 1]]}) ;; end::eql-query-6[] )))) (comment ;; TODO resurrected from git history, need to be tested though ;; tag::eql-project[] ;; using `project`: (crux/project (crux/db node) [:user/name :user/profession] :ivan) ;; end::eql-project[] ;; tag::eql-project-r[] ;; => {:user/name "PI:NAME:<NAME>END_PI", :user/profession :doctor} ;; end::eql-project-r[] ;; tag::eql-project-many[] ;; using `project-many`: (crux/project-many (crux/db node) [:user/name :user/profession] [:ivan :sergei]) ;; end::eql-project-many[] ;; tag::eql-project-many-r[] ;; => [{:user/name "PI:NAME:<NAME>END_PI", :user/profession :doctor}, ;; {:user/name "PI:NAME:<NAME>END_PI", :user/profession :lawyer}] ;; end::eql-project-many-r[] ) (t/deftest test-return-maps (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :user/name "PI:NAME:<NAME>END_PI" :user/id 1 :user/profession :doctor} {:crux.db/id :sergei :user/name "PI:NAME:<NAME>END_PI" :user/id 2 :user/profession :lawyer} {:crux.db/id :petr :user/name "PI:NAME:<NAME>END_PI" :user/id 3 :user/profession :doctor} {:crux.db/id :doctor :profession/name "Doctor"} {:crux.db/id :lawyer :profession/name "Lawyer"}])) (let [node *api*] (t/is (= ;; tag::return-maps-r[] #{{:name "PI:NAME:<NAME>END_PI", :profession "Doctor"}} ;; end::return-maps-r[] ;; tag::return-maps[] (crux/q (crux/db node) '{:find [?name ?profession-name] :keys [name profession] :where [[?user :user/id 1] [?user :user/name ?name] [?user :user/profession ?profession] [?profession :profession/name ?profession-name]]}) ;; end::return-maps[] )))) (t/deftest test-order-and-pagination (let [node *api* data (for [i (range 200)] {:crux.db/id i :condition/time (if (even? i) (quot i 4) (- (quot i 4))) :condition/device-id i :condition/temperature :temp :condition/humidity :hum}) conv (partial map #(vec [(:condition/time %) (:condition/device-id %) :temp :hum]))] (fix/submit+await-tx (fix/maps->tx-ops data)) (t/is (= (->> data (sort-by :condition/device-id <) (sort-by :condition/time >) conv) ;; tag::order-and-pagination-1[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[time :desc] [device-id :asc]]}) ;; end::order-and-pagination-1[] )) (t/is (= (->> data (sort-by :condition/device-id <) (drop 90) (take 10) conv) ;; tag::order-and-pagination-2[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[device-id :asc]] :limit 10 :offset 90}) ;; end::order-and-pagination-2[] )) (t/is (= (->> data (sort-by :condition/device-id <) (drop 150) (take 10) conv) ;; tag::order-and-pagination-3[] (crux/q (crux/db node) '{:find [time device-id temperature humidity] :where [[c :condition/time time] [c :condition/device-id device-id] [(>= device-id my-offset)] [c :condition/temperature temperature] [c :condition/humidity humidity]] :order-by [[device-id :asc]] :limit 10 :args [{my-offset 150}]}) ;; end::order-and-pagination-3[] )))) (t/deftest test-rules (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :follow :petr :age 19} {:crux.db/id :petr :follow :sergei :age 25} {:crux.db/id :sergei :age 3}])) (let [node *api*] (t/is (= #{[:ivan] [:petr]} ;; tag::rules-1[] (crux/q (crux/db node) '{:find [p] :where [(adult? p)] ;;<1> :rules [[(adult? p) ;;<2> [p :age a] ;;<3> [(>= a 18)]]]}) ;; end::rules-1[] )) (t/is (= #{[:petr] [:sergei]} ;; tag::rules-2[] (crux/q (crux/db node) '{:find [?e2] :where [(follow ?e1 ?e2)] :args [{?e1 :ivan}] :rules [[(follow ?e1 ?e2) [?e1 :follow ?e2]] [(follow ?e1 ?e2) [?e1 :follow ?t] (follow ?t ?e2)]]} ) ;; end::rules-2[] )))) (t/deftest test-not (fix/submit+await-tx (fix/maps->tx-ops ;; tag::not-data[] [{:crux.db/id :petr-ivanov :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} ;; <1> {:crux.db/id :ivan-ivanov :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :ivan-petrov :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :petr-petrov :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}] ;; end::not-data[] )) (let [node *api*] (t/is (= #{[:ivan-petrov]} (crux/q (crux/db node) '{:find [e] :where [[e :name name] [e :name "PI:NAME:<NAME>END_PI"] (not [e :last-name "PI:NAME:<NAME>END_PI"])]}) )) (t/is (= ;; tag::not-2-r[] #{[:petr-ivanov] [:petr-petrov] [:ivan-petrov]} ;;<3> ;; end::not-2-r[] ;; tag::not-2[] (crux/q (crux/db node) '{:find [e] :where [[e :crux.db/id] (not [e :last-name "PI:NAME:<NAME>END_PI"] ;;<2> [e :name "PI:NAME:<NAME>END_PI"])]}) ;; end::not-2[] )) (t/is (= #{[:ivan-ivanov] [:petr-ivanov]} (crux/q (crux/db node) '{:find [e] :where [[e :name name] [:ivan-petrov :last-name i-name] (not [e :last-name i-name])]}) )))) (t/deftest test-or (fix/submit+await-tx (fix/maps->tx-ops ;; tag::or-data[] [{:crux.db/id :ivan-ivanov-1 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male} ;;<1> {:crux.db/id :ivan-ivanov-2 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male} {:crux.db/id :ivan-ivanovtov-1 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male} {:crux.db/id :ivPI:NAME:<NAME>END_PI :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :female} {:crux.db/id :bob :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}] ;; end::or-data[] )) (let [node *api*] (t/is (= ;; tag::or-1-r[] #{[:ivan-ivanov-1] [:ivan-ivanov-2] [:ivan-ivanovtov-1]} ;;<3> ;; end::or-1-r[] ;; tag::or-1[] (crux/q (crux/db node) '{:find [e] ;;<2> :where [[e :name name] [e :name "PI:NAME:<NAME>END_PI"] (or [e :last-name "PI:NAME:<NAME>END_PI"] [e :last-name "PI:NAME:<NAME>END_PI"])]}) ;; end::or-1[] )) (t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]} ;; tag::or-2[] (crux/q (crux/db node) '{:find [name] :where [[e :name name] (or [e :sex :female] (and [e :sex :male] [e :name "PI:NAME:<NAME>END_PI"]))]}) ;; end::or-2[] )) (t/is (= #{[:ivan-ivanov-1] [:ivan-ivanov-2]} (crux/q (crux/db node) '{:find [?p2] :where [(or (and [?p2 :name "PI:NAME:<NAME>END_PI"] [?p2 :sex :female]) (and [?p2 :last-name "PI:NAME:<NAME>END_PI"] [?p2 :sex :male]))]}) )))) (t/deftest test-blanks (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI"} {:crux.db/id :sergei :name "PI:NAME:<NAME>END_PI"}])) (let [node *api*] (t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]} (crux/q (crux/db node) '{:find [name] :where [[_ :name name]]}))))) (t/deftest test-not-join (fix/submit+await-tx (fix/maps->tx-ops ;; tag::not-join-data[] [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} ;;<1> {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} {:crux.db/id :sergei :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}] ;; end::not-join-data[] )) (let [node *api*] (t/is (= ;; tag::not-join-r[] #{[:ivan] [:petr]} ;;<4> ;; end::not-join-r[] ;; tag::not-join[] (crux/q (crux/db node) '{:find [e] :where [[e :crux.db/id] (not-join [e] ;;<2> [e :last-name n] ;;<3> [e :name n])]}) ;; end::not-join[] )))) (t/deftest test-generic (fix/submit+await-tx (fix/maps->tx-ops [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])) (let [node *api*] (t/is (= #{[:ivan]} ;; tag::anatomy[] (crux/q (crux/db node) ;;<1> '{:find [p1] ;;<2> :where [[p1 :name n] [p1 :last-name n] [p1 :name name]] :in [name]} "PI:NAME:<NAME>END_PI") ;;<3> ;; end::anatomy[] )) (t/is (= #{["PI:NAME:<NAME>END_PI"]} ;; tag::triple[] (crux/q (crux/db node) '{:find [n] :where [[p :last-name n]]}) ;; end::triple[] )) (t/is (= #{[:ivan]} ;; tag::double[] (crux/q (crux/db node) '{:find [p] :where [[p :name]]}) ;;<1> ;; end::double[] )) (t/is (= #{[:ivan]} ;; tag::triple-2[] (crux/q (crux/db node) '{:find [p] :where [[p :name "PI:NAME:<NAME>END_PI"]]}) ;;<2> ;; end::triple-2[] )) (t/is (= #{[:ivan]} ;; tag::triple-3[] (crux/q (crux/db node) '{:find [p] :where [[q :name n] [p :last-name n]]}) ;;<3> ;; end::triple-3[] )))) (t/deftest test-or-join (fix/submit+await-tx (fix/maps->tx-ops ;; tag::or-join-data[] [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :age 12} ;;<1> {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :age 15} {:crux.db/id :sergei :name "PI:NAME:<NAME>END_PI" :age 19}] ;; end::or-join-data[] )) (let [node *api*] (t/is (= ;; tag::or-join-r[] #{[:ivan] [:sergei]} ;;<4> ;; end::or-join-r[] ;; tag::or-join[] (crux/q (crux/db node) '{:find [p] :where [[p :crux.db/id] (or-join [p] ;;<2> (and [p :age a] ;;<3> [(>= a 18)]) [p :name "PI:NAME:<NAME>END_PI"])]}) ;; end::or-join[] )))) (t/deftest test-range (fix/submit+await-tx (fix/maps->tx-ops ;; tag::range-data[] [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :age 12} ;;<1> {:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :age 15} {:crux.db/id :sergei :name "PI:NAME:<NAME>END_PI" :age 19}] ;; end::range-data[] )) (let [node *api*] (t/is (= #{[:sergei]} ;; tag::range-1[] (crux/q (crux/db node) '{:find [p] ;;<1> :where [[p :age a] [(> a 18)]]}) ;; end::range-1[] )) (t/is (= #{[:petr] [:sergei]} ;; tag::range-2[] (crux/q (crux/db node) '{:find [p] ;;<2> :where [[p :age a] [q :age b] [(> a b)]]}) ;; end::range-2[] )) (t/is (= #{[:ivan] [:petr]} ;; tag::range-3[] (crux/q (crux/db node) '{:find [p] ;;<3> :where [[p :age a] [(> 18 a)]]}) ;; end::range-3[] )) (t/is (= ;; tag::query-with-pred-1-r[] #{[:petr] [:sergei]} ;; end::query-with-pred-1-r[] ;; tag::query-with-pred-1[] (crux/q (crux/db node) '{:find [p] :where [[p :age age] [(odd? age)]]}) ;; end::query-with-pred-1[] )) )) (t/deftest test-full-results (fix/submit+await-tx (fix/maps->tx-ops ;; tag::full-results-data[] [{:crux.db/id :foo :bar :baz}] ;; end::full-results-data[] )) (let [node *api*] (t/is (= ;; tag::full-results-1-r[] #{[:foo]} ;; end::full-results-1-r[] ;; tag::full-results-1[] (crux/q (crux/db node) '{:find [p] :where [[p :bar :baz]]}) ;; end::full-results-1[] )) (t/is (= ;; tag::full-results-2-r[] #{[{:crux.db/id :foo :bar :baz}]} ;; end::full-results-2-r[] ;; tag::full-results-2[] (crux/q (crux/db node) '{:find [p] :where [[p :bar :baz]] :full-results? true}) ;; end::full-results-2[] ))))
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.9997344017028809, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
src/ambages/selectors.clj
rm-hull/twspi
4
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 Richard Hull ;; ;; 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 ambages.selectors "Selectors and constructor functions (which are only there for readability) built from CARs, CDRs and CONSes." (:refer-clojure :exclude [assoc]) (:require [ambages.primitives :refer :all])) (defn lvl "selector: extract level from molec" [x] (if (seq? x) (car x))) (defn xpr "selector: extract prolog expression" [x] (if (seq? x) (cadr x))) (defn molec "constructor: a `molec` is a tuple of (level,prolog_exp), where level is used to discriminate variables at different levels in the proof tree." [x y] (list x y)) ; Clojure doesn't properly implement the semantics of cons-cells ; so just use a list. The knock-on effect is that bond must ; call cadr rather than cdr (defn bind [x y e] (cons (list x y) e)) (defn bond [x e] (cadr (or (assoc x e) '(nil)))) (defn but-first-goal [x] (cons (cdar x) (cdr x)))
11270
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 <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 ambages.selectors "Selectors and constructor functions (which are only there for readability) built from CARs, CDRs and CONSes." (:refer-clojure :exclude [assoc]) (:require [ambages.primitives :refer :all])) (defn lvl "selector: extract level from molec" [x] (if (seq? x) (car x))) (defn xpr "selector: extract prolog expression" [x] (if (seq? x) (cadr x))) (defn molec "constructor: a `molec` is a tuple of (level,prolog_exp), where level is used to discriminate variables at different levels in the proof tree." [x y] (list x y)) ; Clojure doesn't properly implement the semantics of cons-cells ; so just use a list. The knock-on effect is that bond must ; call cadr rather than cdr (defn bind [x y e] (cons (list x y) e)) (defn bond [x e] (cadr (or (assoc x e) '(nil)))) (defn but-first-goal [x] (cons (cdar x) (cdr x)))
true
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 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 ambages.selectors "Selectors and constructor functions (which are only there for readability) built from CARs, CDRs and CONSes." (:refer-clojure :exclude [assoc]) (:require [ambages.primitives :refer :all])) (defn lvl "selector: extract level from molec" [x] (if (seq? x) (car x))) (defn xpr "selector: extract prolog expression" [x] (if (seq? x) (cadr x))) (defn molec "constructor: a `molec` is a tuple of (level,prolog_exp), where level is used to discriminate variables at different levels in the proof tree." [x y] (list x y)) ; Clojure doesn't properly implement the semantics of cons-cells ; so just use a list. The knock-on effect is that bond must ; call cadr rather than cdr (defn bind [x y e] (cons (list x y) e)) (defn bond [x e] (cadr (or (assoc x e) '(nil)))) (defn but-first-goal [x] (cons (cdar x) (cdr x)))
[ { "context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day14a\n (:r", "end": 39, "score": 0.9996466040611267, "start": 21, "tag": "NAME", "value": "Mikołaj Kuranowski" } ]
src/day14a.clj
MKuranowski/AdventOfCode2020
0
; Copyright (c) 2021 Mikołaj Kuranowski ; SPDX-License-Identifier: WTFPL (ns day14a (:require [core] [clojure.string])) (defn get-ones-mask [str-mask] (Long/parseLong (clojure.string/replace str-mask #"X" "0") 2)) (defn get-zeros-mask [str-mask] (Long/parseLong (clojure.string/replace str-mask #"X" "1") 2)) (defn apply-mask-to-value "Applies the ones-mask and zeros-mask to the value. The ones-mask should be a number with ones whenever a one appeared in the AOC mask, and the zeros-mask should be a number with ones whenever anything other than a zero apperead." [value ones-mask zeros-mask] (bit-and (bit-or value ones-mask) zeros-mask)) (defn exec-prog [all-instructions] (loop [instructions all-instructions ones-mask 0 zeros-mask 0 mem {}] (if-let [instruction (first instructions)] (if-let [[_ new-mask] (re-matches #"mask = ([01X]+)" instruction)] (recur (rest instructions) (get-ones-mask new-mask) (get-zeros-mask new-mask) mem) (if-let [[_ loc val] (re-matches #"mem\[(\d+)\] = (\d+)" instruction)] (recur (rest instructions) ones-mask zeros-mask (assoc mem loc (apply-mask-to-value (Long/parseLong val 10) ones-mask zeros-mask))) (throw (Exception. (str "Unknown instruction: " instruction))))) (apply + (vals mem))))) (defn -main [filename] (->> filename core/lines-from-file exec-prog prn))
88551
; Copyright (c) 2021 <NAME> ; SPDX-License-Identifier: WTFPL (ns day14a (:require [core] [clojure.string])) (defn get-ones-mask [str-mask] (Long/parseLong (clojure.string/replace str-mask #"X" "0") 2)) (defn get-zeros-mask [str-mask] (Long/parseLong (clojure.string/replace str-mask #"X" "1") 2)) (defn apply-mask-to-value "Applies the ones-mask and zeros-mask to the value. The ones-mask should be a number with ones whenever a one appeared in the AOC mask, and the zeros-mask should be a number with ones whenever anything other than a zero apperead." [value ones-mask zeros-mask] (bit-and (bit-or value ones-mask) zeros-mask)) (defn exec-prog [all-instructions] (loop [instructions all-instructions ones-mask 0 zeros-mask 0 mem {}] (if-let [instruction (first instructions)] (if-let [[_ new-mask] (re-matches #"mask = ([01X]+)" instruction)] (recur (rest instructions) (get-ones-mask new-mask) (get-zeros-mask new-mask) mem) (if-let [[_ loc val] (re-matches #"mem\[(\d+)\] = (\d+)" instruction)] (recur (rest instructions) ones-mask zeros-mask (assoc mem loc (apply-mask-to-value (Long/parseLong val 10) ones-mask zeros-mask))) (throw (Exception. (str "Unknown instruction: " instruction))))) (apply + (vals mem))))) (defn -main [filename] (->> filename core/lines-from-file exec-prog prn))
true
; Copyright (c) 2021 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: WTFPL (ns day14a (:require [core] [clojure.string])) (defn get-ones-mask [str-mask] (Long/parseLong (clojure.string/replace str-mask #"X" "0") 2)) (defn get-zeros-mask [str-mask] (Long/parseLong (clojure.string/replace str-mask #"X" "1") 2)) (defn apply-mask-to-value "Applies the ones-mask and zeros-mask to the value. The ones-mask should be a number with ones whenever a one appeared in the AOC mask, and the zeros-mask should be a number with ones whenever anything other than a zero apperead." [value ones-mask zeros-mask] (bit-and (bit-or value ones-mask) zeros-mask)) (defn exec-prog [all-instructions] (loop [instructions all-instructions ones-mask 0 zeros-mask 0 mem {}] (if-let [instruction (first instructions)] (if-let [[_ new-mask] (re-matches #"mask = ([01X]+)" instruction)] (recur (rest instructions) (get-ones-mask new-mask) (get-zeros-mask new-mask) mem) (if-let [[_ loc val] (re-matches #"mem\[(\d+)\] = (\d+)" instruction)] (recur (rest instructions) ones-mask zeros-mask (assoc mem loc (apply-mask-to-value (Long/parseLong val 10) ones-mask zeros-mask))) (throw (Exception. (str "Unknown instruction: " instruction))))) (apply + (vals mem))))) (defn -main [filename] (->> filename core/lines-from-file exec-prog prn))
[ { "context": "input-text stonecutter-register-first-name-input \"Journey\")\n (wd/input-text stonecutter-register-last-name", "end": 1046, "score": 0.9112247228622437, "start": 1039, "tag": "NAME", "value": "Journey" }, { "context": "/input-text stonecutter-register-last-name-input \"Test\")\n (wd/input-text stonecutter-register-password-", "end": 1108, "score": 0.9896240830421448, "start": 1104, "tag": "NAME", "value": "Test" }, { "context": "d/input-text stonecutter-register-password-input \"password123!!!\")\n (wd/click stonecutter-register-create-profile-b", "end": 1176, "score": 0.9993641972541809, "start": 1165, "tag": "PASSWORD", "value": "password123" } ]
test/stonecutter/browser/common.clj
d-cent/stonecutter
39
(ns stonecutter.browser.common (:require [clj-webdriver.taxi :as wd])) ;; COMMON (def stonecutter-index-page-body ".func--index-page") (def stonecutter-user-list-page-body ".func--admin-user-list-page") (def stonecutter-accept-invite-page-body ".func--accept-invite-page") (def stonecutter-sign-in-email-input ".func--sign-in-email__input") (def stonecutter-sign-in-password-input ".func--sign-in-password__input") (def stonecutter-sign-in-button ".func--sign-in__button") (def stonecutter-register-first-name-input ".func--registration-first-name__input") (def stonecutter-register-last-name-input ".func--registration-last-name__input") (def stonecutter-register-email-input ".func--registration-email__input") (def stonecutter-register-password-input ".func--registration-password__input") (def stonecutter-register-create-profile-button ".func--create-profile__button") (def stonecutter-trust-toggle ".clj--user-item__toggle") (defn input-register-credentials-and-submit [] (wd/input-text stonecutter-register-first-name-input "Journey") (wd/input-text stonecutter-register-last-name-input "Test") (wd/input-text stonecutter-register-password-input "password123!!!") (wd/click stonecutter-register-create-profile-button)) (defn wait-for-selector [selector] (try (wd/wait-until #(not (empty? (wd/css-finder selector))) 5000) (catch Exception e (prn (str ">>>>>>>>>> Selector could not be found: " selector)) (prn "========== PAGE SOURCE ==========") (prn (wd/page-source)) (prn "========== END PAGE SOURCE ==========") (throw e)))) (def localhost "localhost:5439") (defn accept-invite [id] (str localhost "/accept-invite/" id)) (def user-list-page (str localhost "/admin/users")) ;;______________
57991
(ns stonecutter.browser.common (:require [clj-webdriver.taxi :as wd])) ;; COMMON (def stonecutter-index-page-body ".func--index-page") (def stonecutter-user-list-page-body ".func--admin-user-list-page") (def stonecutter-accept-invite-page-body ".func--accept-invite-page") (def stonecutter-sign-in-email-input ".func--sign-in-email__input") (def stonecutter-sign-in-password-input ".func--sign-in-password__input") (def stonecutter-sign-in-button ".func--sign-in__button") (def stonecutter-register-first-name-input ".func--registration-first-name__input") (def stonecutter-register-last-name-input ".func--registration-last-name__input") (def stonecutter-register-email-input ".func--registration-email__input") (def stonecutter-register-password-input ".func--registration-password__input") (def stonecutter-register-create-profile-button ".func--create-profile__button") (def stonecutter-trust-toggle ".clj--user-item__toggle") (defn input-register-credentials-and-submit [] (wd/input-text stonecutter-register-first-name-input "<NAME>") (wd/input-text stonecutter-register-last-name-input "<NAME>") (wd/input-text stonecutter-register-password-input "<PASSWORD>!!!") (wd/click stonecutter-register-create-profile-button)) (defn wait-for-selector [selector] (try (wd/wait-until #(not (empty? (wd/css-finder selector))) 5000) (catch Exception e (prn (str ">>>>>>>>>> Selector could not be found: " selector)) (prn "========== PAGE SOURCE ==========") (prn (wd/page-source)) (prn "========== END PAGE SOURCE ==========") (throw e)))) (def localhost "localhost:5439") (defn accept-invite [id] (str localhost "/accept-invite/" id)) (def user-list-page (str localhost "/admin/users")) ;;______________
true
(ns stonecutter.browser.common (:require [clj-webdriver.taxi :as wd])) ;; COMMON (def stonecutter-index-page-body ".func--index-page") (def stonecutter-user-list-page-body ".func--admin-user-list-page") (def stonecutter-accept-invite-page-body ".func--accept-invite-page") (def stonecutter-sign-in-email-input ".func--sign-in-email__input") (def stonecutter-sign-in-password-input ".func--sign-in-password__input") (def stonecutter-sign-in-button ".func--sign-in__button") (def stonecutter-register-first-name-input ".func--registration-first-name__input") (def stonecutter-register-last-name-input ".func--registration-last-name__input") (def stonecutter-register-email-input ".func--registration-email__input") (def stonecutter-register-password-input ".func--registration-password__input") (def stonecutter-register-create-profile-button ".func--create-profile__button") (def stonecutter-trust-toggle ".clj--user-item__toggle") (defn input-register-credentials-and-submit [] (wd/input-text stonecutter-register-first-name-input "PI:NAME:<NAME>END_PI") (wd/input-text stonecutter-register-last-name-input "PI:NAME:<NAME>END_PI") (wd/input-text stonecutter-register-password-input "PI:PASSWORD:<PASSWORD>END_PI!!!") (wd/click stonecutter-register-create-profile-button)) (defn wait-for-selector [selector] (try (wd/wait-until #(not (empty? (wd/css-finder selector))) 5000) (catch Exception e (prn (str ">>>>>>>>>> Selector could not be found: " selector)) (prn "========== PAGE SOURCE ==========") (prn (wd/page-source)) (prn "========== END PAGE SOURCE ==========") (throw e)))) (def localhost "localhost:5439") (defn accept-invite [id] (str localhost "/accept-invite/" id)) (def user-list-page (str localhost "/admin/users")) ;;______________
[ { "context": "ents\\\".\"\n [opts]\n (let [opts (merge {:username \"root\"\n :password \"root\"\n ", "end": 3671, "score": 0.9569136500358582, "start": 3667, "tag": "USERNAME", "value": "root" }, { "context": "{:username \"root\"\n :password \"root\"\n :series :service}\n ", "end": 3709, "score": 0.999539852142334, "start": 3705, "tag": "PASSWORD", "value": "root" }, { "context": "\"\n :db \\\"my_db\\\"\n :user \\\"riemann\\\"\n :password \\\"secret\\\"})\n\n General ", "end": 6923, "score": 0.9881270527839661, "start": 6916, "tag": "USERNAME", "value": "riemann" }, { "context": " :user \\\"riemann\\\"\n :password \\\"secret\\\"})\n\n General Options:\n\n `:version` Vers", "end": 6957, "score": 0.9994707107543945, "start": 6951, "tag": "PASSWORD", "value": "secret" } ]
test/conflicts/mined/riemann-00f03eeec6306383b3074bf7ce6146bef7443c8b-5a4726d2d04892373cf1c698b6ec58f3311736b/B.clj
nazrhom/vcs-clojure
3
(ns riemann.influxdb "Forwards events to InfluxDB. Supports both 0.8 and 0.9 APIs." (:require [capacitor.core :as capacitor] [cheshire.core :as json] [clj-http.client :as http] [clojure.set :as set] [clojure.string :as str] [riemann.common :refer [unix-to-iso8601]])) ;; ## Helper Functions (def special-fields "A set of event fields in Riemann with special handling logic." #{:host :service :time :metric :tags :ttl}) (defn replace-disallowed-9 [field] (str/escape field {\space "\\ ", \= "\\=", \, "\\,"})) (defn kv-encode-9 [kv] (clojure.string/join "," (map (fn [[key value]] (if (instance? String value) (str (replace-disallowed-9 key) "=" (str "\"" (str/escape value {\" "\\\""}) "\"")) (str (replace-disallowed-9 key) "=" (clojure.pprint/cl-format nil "~F" value)))) kv))) (defn lineprotocol-encode-9 [event] (let [encoded_fields (kv-encode-9 (get event "fields")) encoded_tags (kv-encode-9 (get event "tags"))] (str (replace-disallowed-9 (get event "measurement")) "," encoded_tags " " encoded_fields " " (get event "time")))) (defn event-tags "Generates a map of InfluxDB tags from a Riemann event. Any fields in the event which are named in `tag-fields` will be converted to a string key/value entry in the tag map." [tag-fields event] (->> (select-keys event tag-fields) (map #(vector (name (key %)) (str (val %)))) (into {}))) (defn event-fields "Generates a map of InfluxDB fields from a Riemann event. The event's `metric` is converted to the `value` field, and any additional event fields which are not standard Riemann properties or in `tag-fields` will also be present." [tag-fields event] (let [ignored-fields (set/union special-fields tag-fields)] (-> event (->> (remove (comp ignored-fields key)) (remove #(nil? (val %))) (map #(vector (name (key %)) (val %))) (into {})) (assoc "value" (:metric event))))) ;; ## InfluxDB 0.8 (defn event->point-8 "Transform a Riemann event to an InfluxDB point, or nil if the event is missing a metric or service." [event] (when (and (:metric event) (:service event)) (merge {:name (:service event) :host (or (:host event) "") :time (:time event) :value (:metric event)} (apply dissoc event special-fields)))) (defn events->points-8 "Takes a series fn that finds the series for a given event, and a sequence of events, and emits a map of series names to vectors of points for that series." [series-fn events] (persistent! (reduce (fn [m event] (let [series (or (series-fn event) "riemann-events") point (event->point-8 event)] (if point (assoc! m series (conj (get m series []) point)) m))) (transient {}) events))) (defn influxdb-8 "Returns a function which accepts an event, or sequence of events, and sends it to InfluxDB. Compatible with the 0.8.x series. ; For giving series name as the concatenation of :host and :service fields ; with dot separator. (influxdb-8 {:host \"play.influxdb.org\" :port 8086 :series #(str (:host %) \".\" (:service %))}) 0.8 Options: :name Name of the metric which is same as the series name. :series Function which takes an event and returns the InfluxDB series name to use. Defaults to :service. If this function returns nil, series names default to \"riemann-events\"." [opts] (let [opts (merge {:username "root" :password "root" :series :service} opts) series (:series opts) client (capacitor/make-client opts)] (fn stream [events] (let [events (if (sequential? events) events (list events)) points (events->points-8 series events)] (when-not (empty? points) (doseq [[series points] points] (capacitor/post-points client series "s" points))))))) ;; ## InfluxDB 0.9 (defn event->point-9 "Converts a Riemann event into an InfluxDB point if it has a time, service, and metric." [tag-fields event] (when (and (:time event) (:service event) (:metric event)) {"measurement" (:service event) "time" (long (:time event)) "tags" (event-tags tag-fields event) "fields" (event-fields tag-fields event)})) (defn events->points-9 "Converts a collection of Riemann events into InfluxDB points. Events which map to nil are removed from the final collection. Also filter out NaNs that influxdb can't deal with currently." [tag-fields events] (filter (fn [p] (not-any? (fn [v] (and (instance? Number (val v)) (Double/isNaN (val v)))) (get p "fields"))) (remove nil? (map (partial event->point-9 tag-fields) events)))) (defn influxdb-9 "Returns a function which accepts an event, or sequence of events, and writes them to InfluxDB. Compatible with the 0.9.x series. (influxdb-9 {:host \"influxdb.example.com\" :db \"my_db\" :retention \"raw\" :tag-fields #{:host :sys :env}}) 0.9 Options: `:retention` Name of retention policy to use. (optional) `:tag-fields` A set of event fields to map into InfluxDB series tags. (default: `#{:host}`) `:tags` A common map of tags to apply to all points. (optional) `:timeout` HTTP timeout in milliseconds. (default: `5000`)" [opts] (let [write-url (str (cond-> (format "%s://%s:%s/write?db=%s&precision=s" (:scheme opts) (:host opts) (:port opts) (:db opts)) (:retention opts) (str "&rp=" (:retention opts)))) http-opts (cond-> {:socket-timeout (:timeout opts 5000) ; ms :conn-timeout (:timeout opts 5000) ; ms ;:debug true :debug-body true :content-type "text/plain"} (:username opts) (assoc :basic-auth [(:username opts) (:password opts)])) tag-fields (:tag-fields opts #{:host})] (fn stream [events] (let [events (if (sequential? events) events (list events)) points (events->points-9 tag-fields events)] (http/post write-url (assoc http-opts :body (->> points (map lineprotocol-encode-9) (clojure.string/join "\n")))))))) ;; ## Stream Construction (defn influxdb "Returns a function which accepts an event, or sequence of events, and writes them to InfluxDB as a batch of measurement points. For performance, you should wrap this stream with `batch` or an asynchronous queue. (influxdb {:host \"influxdb.example.com\" :db \"my_db\" :user \"riemann\" :password \"secret\"}) General Options: `:version` Version of InfluxDB client to use. Should be one of `:0.8` or `:0.9`. (default: `:0.8`) `:db` Name of the database to write to. (default: `\"riemann\"`) `:scheme` URL scheme for endpoint. (default: `\"http\"`) `:host` Hostname to write points to. (default: `\"localhost\"`) `:port` API port number. (default: `8086`) `:username` Database user to authenticate as. (optional) `:password` Password to authenticate with. (optional) See `influxdb-8` and `influxdb-9` for version-specific options." [opts] (let [opts (merge {:version :0.8 :db "riemann" :scheme "http" :host "localhost" :port 8086} opts)] (case (:version opts) :0.8 (influxdb-8 opts) :0.9 (influxdb-9 opts))))
100926
(ns riemann.influxdb "Forwards events to InfluxDB. Supports both 0.8 and 0.9 APIs." (:require [capacitor.core :as capacitor] [cheshire.core :as json] [clj-http.client :as http] [clojure.set :as set] [clojure.string :as str] [riemann.common :refer [unix-to-iso8601]])) ;; ## Helper Functions (def special-fields "A set of event fields in Riemann with special handling logic." #{:host :service :time :metric :tags :ttl}) (defn replace-disallowed-9 [field] (str/escape field {\space "\\ ", \= "\\=", \, "\\,"})) (defn kv-encode-9 [kv] (clojure.string/join "," (map (fn [[key value]] (if (instance? String value) (str (replace-disallowed-9 key) "=" (str "\"" (str/escape value {\" "\\\""}) "\"")) (str (replace-disallowed-9 key) "=" (clojure.pprint/cl-format nil "~F" value)))) kv))) (defn lineprotocol-encode-9 [event] (let [encoded_fields (kv-encode-9 (get event "fields")) encoded_tags (kv-encode-9 (get event "tags"))] (str (replace-disallowed-9 (get event "measurement")) "," encoded_tags " " encoded_fields " " (get event "time")))) (defn event-tags "Generates a map of InfluxDB tags from a Riemann event. Any fields in the event which are named in `tag-fields` will be converted to a string key/value entry in the tag map." [tag-fields event] (->> (select-keys event tag-fields) (map #(vector (name (key %)) (str (val %)))) (into {}))) (defn event-fields "Generates a map of InfluxDB fields from a Riemann event. The event's `metric` is converted to the `value` field, and any additional event fields which are not standard Riemann properties or in `tag-fields` will also be present." [tag-fields event] (let [ignored-fields (set/union special-fields tag-fields)] (-> event (->> (remove (comp ignored-fields key)) (remove #(nil? (val %))) (map #(vector (name (key %)) (val %))) (into {})) (assoc "value" (:metric event))))) ;; ## InfluxDB 0.8 (defn event->point-8 "Transform a Riemann event to an InfluxDB point, or nil if the event is missing a metric or service." [event] (when (and (:metric event) (:service event)) (merge {:name (:service event) :host (or (:host event) "") :time (:time event) :value (:metric event)} (apply dissoc event special-fields)))) (defn events->points-8 "Takes a series fn that finds the series for a given event, and a sequence of events, and emits a map of series names to vectors of points for that series." [series-fn events] (persistent! (reduce (fn [m event] (let [series (or (series-fn event) "riemann-events") point (event->point-8 event)] (if point (assoc! m series (conj (get m series []) point)) m))) (transient {}) events))) (defn influxdb-8 "Returns a function which accepts an event, or sequence of events, and sends it to InfluxDB. Compatible with the 0.8.x series. ; For giving series name as the concatenation of :host and :service fields ; with dot separator. (influxdb-8 {:host \"play.influxdb.org\" :port 8086 :series #(str (:host %) \".\" (:service %))}) 0.8 Options: :name Name of the metric which is same as the series name. :series Function which takes an event and returns the InfluxDB series name to use. Defaults to :service. If this function returns nil, series names default to \"riemann-events\"." [opts] (let [opts (merge {:username "root" :password "<PASSWORD>" :series :service} opts) series (:series opts) client (capacitor/make-client opts)] (fn stream [events] (let [events (if (sequential? events) events (list events)) points (events->points-8 series events)] (when-not (empty? points) (doseq [[series points] points] (capacitor/post-points client series "s" points))))))) ;; ## InfluxDB 0.9 (defn event->point-9 "Converts a Riemann event into an InfluxDB point if it has a time, service, and metric." [tag-fields event] (when (and (:time event) (:service event) (:metric event)) {"measurement" (:service event) "time" (long (:time event)) "tags" (event-tags tag-fields event) "fields" (event-fields tag-fields event)})) (defn events->points-9 "Converts a collection of Riemann events into InfluxDB points. Events which map to nil are removed from the final collection. Also filter out NaNs that influxdb can't deal with currently." [tag-fields events] (filter (fn [p] (not-any? (fn [v] (and (instance? Number (val v)) (Double/isNaN (val v)))) (get p "fields"))) (remove nil? (map (partial event->point-9 tag-fields) events)))) (defn influxdb-9 "Returns a function which accepts an event, or sequence of events, and writes them to InfluxDB. Compatible with the 0.9.x series. (influxdb-9 {:host \"influxdb.example.com\" :db \"my_db\" :retention \"raw\" :tag-fields #{:host :sys :env}}) 0.9 Options: `:retention` Name of retention policy to use. (optional) `:tag-fields` A set of event fields to map into InfluxDB series tags. (default: `#{:host}`) `:tags` A common map of tags to apply to all points. (optional) `:timeout` HTTP timeout in milliseconds. (default: `5000`)" [opts] (let [write-url (str (cond-> (format "%s://%s:%s/write?db=%s&precision=s" (:scheme opts) (:host opts) (:port opts) (:db opts)) (:retention opts) (str "&rp=" (:retention opts)))) http-opts (cond-> {:socket-timeout (:timeout opts 5000) ; ms :conn-timeout (:timeout opts 5000) ; ms ;:debug true :debug-body true :content-type "text/plain"} (:username opts) (assoc :basic-auth [(:username opts) (:password opts)])) tag-fields (:tag-fields opts #{:host})] (fn stream [events] (let [events (if (sequential? events) events (list events)) points (events->points-9 tag-fields events)] (http/post write-url (assoc http-opts :body (->> points (map lineprotocol-encode-9) (clojure.string/join "\n")))))))) ;; ## Stream Construction (defn influxdb "Returns a function which accepts an event, or sequence of events, and writes them to InfluxDB as a batch of measurement points. For performance, you should wrap this stream with `batch` or an asynchronous queue. (influxdb {:host \"influxdb.example.com\" :db \"my_db\" :user \"riemann\" :password \"<PASSWORD>\"}) General Options: `:version` Version of InfluxDB client to use. Should be one of `:0.8` or `:0.9`. (default: `:0.8`) `:db` Name of the database to write to. (default: `\"riemann\"`) `:scheme` URL scheme for endpoint. (default: `\"http\"`) `:host` Hostname to write points to. (default: `\"localhost\"`) `:port` API port number. (default: `8086`) `:username` Database user to authenticate as. (optional) `:password` Password to authenticate with. (optional) See `influxdb-8` and `influxdb-9` for version-specific options." [opts] (let [opts (merge {:version :0.8 :db "riemann" :scheme "http" :host "localhost" :port 8086} opts)] (case (:version opts) :0.8 (influxdb-8 opts) :0.9 (influxdb-9 opts))))
true
(ns riemann.influxdb "Forwards events to InfluxDB. Supports both 0.8 and 0.9 APIs." (:require [capacitor.core :as capacitor] [cheshire.core :as json] [clj-http.client :as http] [clojure.set :as set] [clojure.string :as str] [riemann.common :refer [unix-to-iso8601]])) ;; ## Helper Functions (def special-fields "A set of event fields in Riemann with special handling logic." #{:host :service :time :metric :tags :ttl}) (defn replace-disallowed-9 [field] (str/escape field {\space "\\ ", \= "\\=", \, "\\,"})) (defn kv-encode-9 [kv] (clojure.string/join "," (map (fn [[key value]] (if (instance? String value) (str (replace-disallowed-9 key) "=" (str "\"" (str/escape value {\" "\\\""}) "\"")) (str (replace-disallowed-9 key) "=" (clojure.pprint/cl-format nil "~F" value)))) kv))) (defn lineprotocol-encode-9 [event] (let [encoded_fields (kv-encode-9 (get event "fields")) encoded_tags (kv-encode-9 (get event "tags"))] (str (replace-disallowed-9 (get event "measurement")) "," encoded_tags " " encoded_fields " " (get event "time")))) (defn event-tags "Generates a map of InfluxDB tags from a Riemann event. Any fields in the event which are named in `tag-fields` will be converted to a string key/value entry in the tag map." [tag-fields event] (->> (select-keys event tag-fields) (map #(vector (name (key %)) (str (val %)))) (into {}))) (defn event-fields "Generates a map of InfluxDB fields from a Riemann event. The event's `metric` is converted to the `value` field, and any additional event fields which are not standard Riemann properties or in `tag-fields` will also be present." [tag-fields event] (let [ignored-fields (set/union special-fields tag-fields)] (-> event (->> (remove (comp ignored-fields key)) (remove #(nil? (val %))) (map #(vector (name (key %)) (val %))) (into {})) (assoc "value" (:metric event))))) ;; ## InfluxDB 0.8 (defn event->point-8 "Transform a Riemann event to an InfluxDB point, or nil if the event is missing a metric or service." [event] (when (and (:metric event) (:service event)) (merge {:name (:service event) :host (or (:host event) "") :time (:time event) :value (:metric event)} (apply dissoc event special-fields)))) (defn events->points-8 "Takes a series fn that finds the series for a given event, and a sequence of events, and emits a map of series names to vectors of points for that series." [series-fn events] (persistent! (reduce (fn [m event] (let [series (or (series-fn event) "riemann-events") point (event->point-8 event)] (if point (assoc! m series (conj (get m series []) point)) m))) (transient {}) events))) (defn influxdb-8 "Returns a function which accepts an event, or sequence of events, and sends it to InfluxDB. Compatible with the 0.8.x series. ; For giving series name as the concatenation of :host and :service fields ; with dot separator. (influxdb-8 {:host \"play.influxdb.org\" :port 8086 :series #(str (:host %) \".\" (:service %))}) 0.8 Options: :name Name of the metric which is same as the series name. :series Function which takes an event and returns the InfluxDB series name to use. Defaults to :service. If this function returns nil, series names default to \"riemann-events\"." [opts] (let [opts (merge {:username "root" :password "PI:PASSWORD:<PASSWORD>END_PI" :series :service} opts) series (:series opts) client (capacitor/make-client opts)] (fn stream [events] (let [events (if (sequential? events) events (list events)) points (events->points-8 series events)] (when-not (empty? points) (doseq [[series points] points] (capacitor/post-points client series "s" points))))))) ;; ## InfluxDB 0.9 (defn event->point-9 "Converts a Riemann event into an InfluxDB point if it has a time, service, and metric." [tag-fields event] (when (and (:time event) (:service event) (:metric event)) {"measurement" (:service event) "time" (long (:time event)) "tags" (event-tags tag-fields event) "fields" (event-fields tag-fields event)})) (defn events->points-9 "Converts a collection of Riemann events into InfluxDB points. Events which map to nil are removed from the final collection. Also filter out NaNs that influxdb can't deal with currently." [tag-fields events] (filter (fn [p] (not-any? (fn [v] (and (instance? Number (val v)) (Double/isNaN (val v)))) (get p "fields"))) (remove nil? (map (partial event->point-9 tag-fields) events)))) (defn influxdb-9 "Returns a function which accepts an event, or sequence of events, and writes them to InfluxDB. Compatible with the 0.9.x series. (influxdb-9 {:host \"influxdb.example.com\" :db \"my_db\" :retention \"raw\" :tag-fields #{:host :sys :env}}) 0.9 Options: `:retention` Name of retention policy to use. (optional) `:tag-fields` A set of event fields to map into InfluxDB series tags. (default: `#{:host}`) `:tags` A common map of tags to apply to all points. (optional) `:timeout` HTTP timeout in milliseconds. (default: `5000`)" [opts] (let [write-url (str (cond-> (format "%s://%s:%s/write?db=%s&precision=s" (:scheme opts) (:host opts) (:port opts) (:db opts)) (:retention opts) (str "&rp=" (:retention opts)))) http-opts (cond-> {:socket-timeout (:timeout opts 5000) ; ms :conn-timeout (:timeout opts 5000) ; ms ;:debug true :debug-body true :content-type "text/plain"} (:username opts) (assoc :basic-auth [(:username opts) (:password opts)])) tag-fields (:tag-fields opts #{:host})] (fn stream [events] (let [events (if (sequential? events) events (list events)) points (events->points-9 tag-fields events)] (http/post write-url (assoc http-opts :body (->> points (map lineprotocol-encode-9) (clojure.string/join "\n")))))))) ;; ## Stream Construction (defn influxdb "Returns a function which accepts an event, or sequence of events, and writes them to InfluxDB as a batch of measurement points. For performance, you should wrap this stream with `batch` or an asynchronous queue. (influxdb {:host \"influxdb.example.com\" :db \"my_db\" :user \"riemann\" :password \"PI:PASSWORD:<PASSWORD>END_PI\"}) General Options: `:version` Version of InfluxDB client to use. Should be one of `:0.8` or `:0.9`. (default: `:0.8`) `:db` Name of the database to write to. (default: `\"riemann\"`) `:scheme` URL scheme for endpoint. (default: `\"http\"`) `:host` Hostname to write points to. (default: `\"localhost\"`) `:port` API port number. (default: `8086`) `:username` Database user to authenticate as. (optional) `:password` Password to authenticate with. (optional) See `influxdb-8` and `influxdb-9` for version-specific options." [opts] (let [opts (merge {:version :0.8 :db "riemann" :scheme "http" :host "localhost" :port 8086} opts)] (case (:version opts) :0.8 (influxdb-8 opts) :0.9 (influxdb-9 opts))))
[ { "context": ";\n; Copyright 2020-2021 AppsFlyer\n;\n; Licensed under the Apache License, Version 2.", "end": 33, "score": 0.990562915802002, "start": 24, "tag": "USERNAME", "value": "AppsFlyer" }, { "context": "nk)\n(s/def ::basic-auth-options (s/map-of #{\"id\" \"password\"} ::not-blank))\n(s/def ::query-params (s/every st", "end": 6447, "score": 0.7479339241981506, "start": 6439, "tag": "PASSWORD", "value": "password" } ]
src/main/clojure/com/appsflyer/donkey/donkey_spec.clj
yaronel/donkey-1
274
; ; Copyright 2020-2021 AppsFlyer ; ; 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.appsflyer.donkey.donkey-spec (:require [clojure.spec.alpha :as s] [clojure.string]) (:import (com.codahale.metrics MetricRegistry) (io.vertx.core.impl.cpu CpuCoreSensor))) ;; ------- Predicates ------- ;; (s/def ::int>=0 (s/and int? #(<= 0 %))) (s/def ::strings (s/coll-of string?)) (s/def ::not-blank (s/and string? (comp not clojure.string/blank?))) ;; ------- Donkey Specification ------- ;; (s/def ::metrics-prefix string?) (s/def ::metric-registry #(instance? MetricRegistry %)) (s/def ::worker-threads #(s/int-in-range? 1 500 %)) (s/def ::event-loops #(s/int-in-range? 1 (* 2 (CpuCoreSensor/availableProcessors)) %)) (s/def ::debug boolean?) (s/def ::donkey-config (s/keys :opt-un [::metrics-prefix ::metric-registry ::worker-threads ::event-loops ::debug])) (s/def ::handler fn?) (s/def ::handlers (s/coll-of ::handler)) (s/def ::method #{:get :post :put :delete :options :head :trace :connect :patch}) (s/def ::keep-alive boolean?) ;; ------- Middleware Specification ------- ;; (s/def ::middleware ::handlers) ;; ------- Route Specification ------- ;; (s/def ::path string?) (s/def ::methods (s/coll-of ::method)) (s/def ::consumes ::strings) (s/def ::produces ::strings) (s/def ::handler-mode #{:blocking :non-blocking}) (s/def ::match-type #{:simple :regex}) (s/def :server/route (s/keys :req-un [::handler] :opt-un [::path ::methods ::consumes ::produces ::handler-mode ::match-type ::middleware])) ;; ------- Resources Specification ------- ;; (s/def ::resources-root ::not-blank) (s/def ::index-page ::not-blank) (s/def ::enable-caching boolean?) (s/def ::max-age-seconds ::int>=0) (s/def ::local-cache-duration-seconds pos-int?) (s/def ::local-cache-size pos-int?) (s/def :resources/route (s/keys :req-un [::path] :opt-un [::produces])) (s/def :resources/routes (s/coll-of :resources/route :distinct true :min-count 1)) (s/def ::resources (s/keys :req-un [:resources/routes] :opt-un [::resources-root ::index-page ::enable-caching ::max-age-seconds ::local-cache-duration-seconds ::local-cache-size])) ;; ------- Server Specification ------- ;; (s/def ::instances #(s/int-in-range? 1 500 %)) (s/def ::port #(s/int-in-range? 1 65536 %)) (s/def ::compression boolean?) (s/def ::decompression boolean?) (s/def ::host ::not-blank) (s/def ::date-header boolean?) (s/def ::content-type-header boolean?) (s/def ::server-header boolean?) (s/def ::tcp-no-delay boolean?) (s/def ::tcp-quick-ack boolean?) (s/def ::tcp-fast-open boolean?) (s/def ::socket-linger-seconds ::int>=0) (s/def ::accept-backlog pos-int?) (s/def ::idle-timeout-seconds ::int>=0) (s/def :server/routes (s/coll-of :server/route :distinct true :min-count 1)) (s/def ::error-handlers (s/map-of #(s/int-in-range? 400 600 %) fn?)) (s/def ::server-config (s/keys :req-un [::port (or :server/routes ::resources)] :opt-un [::error-handlers ::instances ::middleware ::compression ::decompression ::host ::date-header ::content-type-header ::server-header ::tcp-no-delay ::tcp-quick-ack ::tcp-fast-open ::socket-linger-seconds ::accept-backlog ::keep-alive ::idle-timeout-seconds])) ;; ------- Client Specification ------- ;; (s/def ::keep-alive-timeout-seconds pos-int?) (s/def ::connect-timeout-seconds pos-int?) (s/def ::follow-redirects boolean?) (s/def ::max-redirects pos-int?) (s/def ::default-port ::port) (s/def ::default-host ::host) (s/def ::user-agent string?) (s/def ::enable-user-agent boolean?) (s/def ::proxy-type #{:http :sock4 :sock5}) (s/def ::proxy-options (s/keys :req-un [::host ::port ::proxy-type])) (s/def ::force-sni boolean?) (s/def ::ssl boolean?) (s/def ::client-config (s/keys :opt-un [::compression ::default-host ::default-port ::force-sni ::keep-alive ::keep-alive-timeout-seconds ::connect-timeout-seconds ::idle-timeout-seconds ::follow-redirects ::max-redirects ::user-agent ::enable-user-agent ::proxy-options ::ssl])) ;; ------- Client Request Specification ------- ;; (s/def ::uri ::not-blank) (s/def ::bearer-token ::not-blank) (s/def ::basic-auth-options (s/map-of #{"id" "password"} ::not-blank)) (s/def ::query-params (s/every string? :kind map?)) (s/def ::headers (s/every string? :kind map?)) (s/def ::client-request (s/keys :req-un [::method] :opt-un [::uri ::host ::port ::idle-timeout-seconds ::bearer-token ::basic-auth-options ::query-params ::headers]))
105764
; ; Copyright 2020-2021 AppsFlyer ; ; 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.appsflyer.donkey.donkey-spec (:require [clojure.spec.alpha :as s] [clojure.string]) (:import (com.codahale.metrics MetricRegistry) (io.vertx.core.impl.cpu CpuCoreSensor))) ;; ------- Predicates ------- ;; (s/def ::int>=0 (s/and int? #(<= 0 %))) (s/def ::strings (s/coll-of string?)) (s/def ::not-blank (s/and string? (comp not clojure.string/blank?))) ;; ------- Donkey Specification ------- ;; (s/def ::metrics-prefix string?) (s/def ::metric-registry #(instance? MetricRegistry %)) (s/def ::worker-threads #(s/int-in-range? 1 500 %)) (s/def ::event-loops #(s/int-in-range? 1 (* 2 (CpuCoreSensor/availableProcessors)) %)) (s/def ::debug boolean?) (s/def ::donkey-config (s/keys :opt-un [::metrics-prefix ::metric-registry ::worker-threads ::event-loops ::debug])) (s/def ::handler fn?) (s/def ::handlers (s/coll-of ::handler)) (s/def ::method #{:get :post :put :delete :options :head :trace :connect :patch}) (s/def ::keep-alive boolean?) ;; ------- Middleware Specification ------- ;; (s/def ::middleware ::handlers) ;; ------- Route Specification ------- ;; (s/def ::path string?) (s/def ::methods (s/coll-of ::method)) (s/def ::consumes ::strings) (s/def ::produces ::strings) (s/def ::handler-mode #{:blocking :non-blocking}) (s/def ::match-type #{:simple :regex}) (s/def :server/route (s/keys :req-un [::handler] :opt-un [::path ::methods ::consumes ::produces ::handler-mode ::match-type ::middleware])) ;; ------- Resources Specification ------- ;; (s/def ::resources-root ::not-blank) (s/def ::index-page ::not-blank) (s/def ::enable-caching boolean?) (s/def ::max-age-seconds ::int>=0) (s/def ::local-cache-duration-seconds pos-int?) (s/def ::local-cache-size pos-int?) (s/def :resources/route (s/keys :req-un [::path] :opt-un [::produces])) (s/def :resources/routes (s/coll-of :resources/route :distinct true :min-count 1)) (s/def ::resources (s/keys :req-un [:resources/routes] :opt-un [::resources-root ::index-page ::enable-caching ::max-age-seconds ::local-cache-duration-seconds ::local-cache-size])) ;; ------- Server Specification ------- ;; (s/def ::instances #(s/int-in-range? 1 500 %)) (s/def ::port #(s/int-in-range? 1 65536 %)) (s/def ::compression boolean?) (s/def ::decompression boolean?) (s/def ::host ::not-blank) (s/def ::date-header boolean?) (s/def ::content-type-header boolean?) (s/def ::server-header boolean?) (s/def ::tcp-no-delay boolean?) (s/def ::tcp-quick-ack boolean?) (s/def ::tcp-fast-open boolean?) (s/def ::socket-linger-seconds ::int>=0) (s/def ::accept-backlog pos-int?) (s/def ::idle-timeout-seconds ::int>=0) (s/def :server/routes (s/coll-of :server/route :distinct true :min-count 1)) (s/def ::error-handlers (s/map-of #(s/int-in-range? 400 600 %) fn?)) (s/def ::server-config (s/keys :req-un [::port (or :server/routes ::resources)] :opt-un [::error-handlers ::instances ::middleware ::compression ::decompression ::host ::date-header ::content-type-header ::server-header ::tcp-no-delay ::tcp-quick-ack ::tcp-fast-open ::socket-linger-seconds ::accept-backlog ::keep-alive ::idle-timeout-seconds])) ;; ------- Client Specification ------- ;; (s/def ::keep-alive-timeout-seconds pos-int?) (s/def ::connect-timeout-seconds pos-int?) (s/def ::follow-redirects boolean?) (s/def ::max-redirects pos-int?) (s/def ::default-port ::port) (s/def ::default-host ::host) (s/def ::user-agent string?) (s/def ::enable-user-agent boolean?) (s/def ::proxy-type #{:http :sock4 :sock5}) (s/def ::proxy-options (s/keys :req-un [::host ::port ::proxy-type])) (s/def ::force-sni boolean?) (s/def ::ssl boolean?) (s/def ::client-config (s/keys :opt-un [::compression ::default-host ::default-port ::force-sni ::keep-alive ::keep-alive-timeout-seconds ::connect-timeout-seconds ::idle-timeout-seconds ::follow-redirects ::max-redirects ::user-agent ::enable-user-agent ::proxy-options ::ssl])) ;; ------- Client Request Specification ------- ;; (s/def ::uri ::not-blank) (s/def ::bearer-token ::not-blank) (s/def ::basic-auth-options (s/map-of #{"id" "<PASSWORD>"} ::not-blank)) (s/def ::query-params (s/every string? :kind map?)) (s/def ::headers (s/every string? :kind map?)) (s/def ::client-request (s/keys :req-un [::method] :opt-un [::uri ::host ::port ::idle-timeout-seconds ::bearer-token ::basic-auth-options ::query-params ::headers]))
true
; ; Copyright 2020-2021 AppsFlyer ; ; 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.appsflyer.donkey.donkey-spec (:require [clojure.spec.alpha :as s] [clojure.string]) (:import (com.codahale.metrics MetricRegistry) (io.vertx.core.impl.cpu CpuCoreSensor))) ;; ------- Predicates ------- ;; (s/def ::int>=0 (s/and int? #(<= 0 %))) (s/def ::strings (s/coll-of string?)) (s/def ::not-blank (s/and string? (comp not clojure.string/blank?))) ;; ------- Donkey Specification ------- ;; (s/def ::metrics-prefix string?) (s/def ::metric-registry #(instance? MetricRegistry %)) (s/def ::worker-threads #(s/int-in-range? 1 500 %)) (s/def ::event-loops #(s/int-in-range? 1 (* 2 (CpuCoreSensor/availableProcessors)) %)) (s/def ::debug boolean?) (s/def ::donkey-config (s/keys :opt-un [::metrics-prefix ::metric-registry ::worker-threads ::event-loops ::debug])) (s/def ::handler fn?) (s/def ::handlers (s/coll-of ::handler)) (s/def ::method #{:get :post :put :delete :options :head :trace :connect :patch}) (s/def ::keep-alive boolean?) ;; ------- Middleware Specification ------- ;; (s/def ::middleware ::handlers) ;; ------- Route Specification ------- ;; (s/def ::path string?) (s/def ::methods (s/coll-of ::method)) (s/def ::consumes ::strings) (s/def ::produces ::strings) (s/def ::handler-mode #{:blocking :non-blocking}) (s/def ::match-type #{:simple :regex}) (s/def :server/route (s/keys :req-un [::handler] :opt-un [::path ::methods ::consumes ::produces ::handler-mode ::match-type ::middleware])) ;; ------- Resources Specification ------- ;; (s/def ::resources-root ::not-blank) (s/def ::index-page ::not-blank) (s/def ::enable-caching boolean?) (s/def ::max-age-seconds ::int>=0) (s/def ::local-cache-duration-seconds pos-int?) (s/def ::local-cache-size pos-int?) (s/def :resources/route (s/keys :req-un [::path] :opt-un [::produces])) (s/def :resources/routes (s/coll-of :resources/route :distinct true :min-count 1)) (s/def ::resources (s/keys :req-un [:resources/routes] :opt-un [::resources-root ::index-page ::enable-caching ::max-age-seconds ::local-cache-duration-seconds ::local-cache-size])) ;; ------- Server Specification ------- ;; (s/def ::instances #(s/int-in-range? 1 500 %)) (s/def ::port #(s/int-in-range? 1 65536 %)) (s/def ::compression boolean?) (s/def ::decompression boolean?) (s/def ::host ::not-blank) (s/def ::date-header boolean?) (s/def ::content-type-header boolean?) (s/def ::server-header boolean?) (s/def ::tcp-no-delay boolean?) (s/def ::tcp-quick-ack boolean?) (s/def ::tcp-fast-open boolean?) (s/def ::socket-linger-seconds ::int>=0) (s/def ::accept-backlog pos-int?) (s/def ::idle-timeout-seconds ::int>=0) (s/def :server/routes (s/coll-of :server/route :distinct true :min-count 1)) (s/def ::error-handlers (s/map-of #(s/int-in-range? 400 600 %) fn?)) (s/def ::server-config (s/keys :req-un [::port (or :server/routes ::resources)] :opt-un [::error-handlers ::instances ::middleware ::compression ::decompression ::host ::date-header ::content-type-header ::server-header ::tcp-no-delay ::tcp-quick-ack ::tcp-fast-open ::socket-linger-seconds ::accept-backlog ::keep-alive ::idle-timeout-seconds])) ;; ------- Client Specification ------- ;; (s/def ::keep-alive-timeout-seconds pos-int?) (s/def ::connect-timeout-seconds pos-int?) (s/def ::follow-redirects boolean?) (s/def ::max-redirects pos-int?) (s/def ::default-port ::port) (s/def ::default-host ::host) (s/def ::user-agent string?) (s/def ::enable-user-agent boolean?) (s/def ::proxy-type #{:http :sock4 :sock5}) (s/def ::proxy-options (s/keys :req-un [::host ::port ::proxy-type])) (s/def ::force-sni boolean?) (s/def ::ssl boolean?) (s/def ::client-config (s/keys :opt-un [::compression ::default-host ::default-port ::force-sni ::keep-alive ::keep-alive-timeout-seconds ::connect-timeout-seconds ::idle-timeout-seconds ::follow-redirects ::max-redirects ::user-agent ::enable-user-agent ::proxy-options ::ssl])) ;; ------- Client Request Specification ------- ;; (s/def ::uri ::not-blank) (s/def ::bearer-token ::not-blank) (s/def ::basic-auth-options (s/map-of #{"id" "PI:PASSWORD:<PASSWORD>END_PI"} ::not-blank)) (s/def ::query-params (s/every string? :kind map?)) (s/def ::headers (s/every string? :kind map?)) (s/def ::client-request (s/keys :req-un [::method] :opt-un [::uri ::host ::port ::idle-timeout-seconds ::bearer-token ::basic-auth-options ::query-params ::headers]))
[ { "context": " \"https://github.com/kixus/reduce-clj\"\n :scm { :url ", "end": 250, "score": 0.9951303601264954, "start": 245, "tag": "USERNAME", "value": "kixus" }, { "context": " { :url \"https://github.com/kixus/reduce-clj\"\n :name", "end": 340, "score": 0.9958696961402893, "start": 335, "tag": "USERNAME", "value": "kixus" }, { "context": " :signing { :gpg-key \"56BA7F7E\" ;; check with \"gpg --fingerprint 56BA7F7E\"\n ", "end": 1454, "score": 0.9921891093254089, "start": 1446, "tag": "KEY", "value": "56BA7F7E" }, { "context": " \"56BA7F7E\" ;; check with \"gpg --fingerprint 56BA7F7E\"\n }\n :pom-addition ", "end": 1499, "score": 0.8994612693786621, "start": 1491, "tag": "KEY", "value": "56BA7F7E" }, { "context": " [:name \"Rajesh Krishnan\"]\n ", "end": 1716, "score": 0.9998818039894104, "start": 1701, "tag": "NAME", "value": "Rajesh Krishnan" }, { "context": " [:url \"https://github.com/kixus\"]\n ", "end": 1824, "score": 0.9977849125862122, "start": 1819, "tag": "USERNAME", "value": "kixus" }, { "context": " [:email \"raj.dev.github@pub.dom.st\"]\n ", "end": 1933, "score": 0.999915599822998, "start": 1908, "tag": "EMAIL", "value": "raj.dev.github@pub.dom.st" } ]
project.clj
kixus/clj-rdc
0
(defproject kixus/reduce "0.1.3" :description "Generalized multi-dimensional reduce functions in Clojure." :url "https://github.com/kixus/reduce-clj" :scm { :url "https://github.com/kixus/reduce-clj" :name "git" } :license { :url "http://opensource.org/licenses/BSD-3-Clause" :name "BSD 3-Clause License" } :dependencies [ [org.clojure/clojure "1.6.0"] ] :profiles { :dev [ ;; :dependencies [ ;; ] ;; :plugins [ ;; ] ] } :repositories { ;; "sonatype" "https://oss.sonatype.org/content/repositories/releases/" } :deploy-repositories [ ["clojars" {:creds :gpg}] ] :signing { :gpg-key "56BA7F7E" ;; check with "gpg --fingerprint 56BA7F7E" } :pom-addition [ :developers [:developer [:id "kixus"] [:name "Rajesh Krishnan"] [:url "https://github.com/kixus"] [:email "raj.dev.github@pub.dom.st"] [:timezone "America/Los_Angeles"] [:properties [:clojars "https://clojars.org/groups/kixus"] ] ] ] :target-path "out/tgt" :source-paths ["app/src"] :resource-paths ["app/res" "tst/res"] :test-paths ["tst/src"] :jvm-opts ["-Xmx4g"] )
17253
(defproject kixus/reduce "0.1.3" :description "Generalized multi-dimensional reduce functions in Clojure." :url "https://github.com/kixus/reduce-clj" :scm { :url "https://github.com/kixus/reduce-clj" :name "git" } :license { :url "http://opensource.org/licenses/BSD-3-Clause" :name "BSD 3-Clause License" } :dependencies [ [org.clojure/clojure "1.6.0"] ] :profiles { :dev [ ;; :dependencies [ ;; ] ;; :plugins [ ;; ] ] } :repositories { ;; "sonatype" "https://oss.sonatype.org/content/repositories/releases/" } :deploy-repositories [ ["clojars" {:creds :gpg}] ] :signing { :gpg-key "<KEY>" ;; check with "gpg --fingerprint <KEY>" } :pom-addition [ :developers [:developer [:id "kixus"] [:name "<NAME>"] [:url "https://github.com/kixus"] [:email "<EMAIL>"] [:timezone "America/Los_Angeles"] [:properties [:clojars "https://clojars.org/groups/kixus"] ] ] ] :target-path "out/tgt" :source-paths ["app/src"] :resource-paths ["app/res" "tst/res"] :test-paths ["tst/src"] :jvm-opts ["-Xmx4g"] )
true
(defproject kixus/reduce "0.1.3" :description "Generalized multi-dimensional reduce functions in Clojure." :url "https://github.com/kixus/reduce-clj" :scm { :url "https://github.com/kixus/reduce-clj" :name "git" } :license { :url "http://opensource.org/licenses/BSD-3-Clause" :name "BSD 3-Clause License" } :dependencies [ [org.clojure/clojure "1.6.0"] ] :profiles { :dev [ ;; :dependencies [ ;; ] ;; :plugins [ ;; ] ] } :repositories { ;; "sonatype" "https://oss.sonatype.org/content/repositories/releases/" } :deploy-repositories [ ["clojars" {:creds :gpg}] ] :signing { :gpg-key "PI:KEY:<KEY>END_PI" ;; check with "gpg --fingerprint PI:KEY:<KEY>END_PI" } :pom-addition [ :developers [:developer [:id "kixus"] [:name "PI:NAME:<NAME>END_PI"] [:url "https://github.com/kixus"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:timezone "America/Los_Angeles"] [:properties [:clojars "https://clojars.org/groups/kixus"] ] ] ] :target-path "out/tgt" :source-paths ["app/src"] :resource-paths ["app/res" "tst/res"] :test-paths ["tst/src"] :jvm-opts ["-Xmx4g"] )
[ { "context": "a-stuff \n {\n {\n \"id\": 1,\n \"first_name\": \"Verne\",\n \"last_name\": \"Oganesian\",\n \"email\": \"vog", "end": 91, "score": 0.9997501969337463, "start": 86, "tag": "NAME", "value": "Verne" }, { "context": ": 1,\n \"first_name\": \"Verne\",\n \"last_name\": \"Oganesian\",\n \"email\": \"voganesian0@newyorker.com\",\n \"", "end": 121, "score": 0.9997504353523254, "start": 112, "tag": "NAME", "value": "Oganesian" }, { "context": "rne\",\n \"last_name\": \"Oganesian\",\n \"email\": \"voganesian0@newyorker.com\",\n \"gender\": \"Male\",\n \"ip_address\": \"206.44", "end": 163, "score": 0.999933660030365, "start": 138, "tag": "EMAIL", "value": "voganesian0@newyorker.com" }, { "context": "er.com\",\n \"gender\": \"Male\",\n \"ip_address\": \"206.44.174.25\"\n }, \n {\n \"id\": 2,\n \"first_name\": \"Hil", "end": 220, "score": 0.9997433423995972, "start": 207, "tag": "IP_ADDRESS", "value": "206.44.174.25" }, { "context": ".25\"\n }, \n {\n \"id\": 2,\n \"first_name\": \"Hildagard\",\n \"last_name\": \"Dunnion\",\n \"email\": \"hdunn", "end": 276, "score": 0.9997711181640625, "start": 267, "tag": "NAME", "value": "Hildagard" }, { "context": "\n \"first_name\": \"Hildagard\",\n \"last_name\": \"Dunnion\",\n \"email\": \"hdunnion1@slideshare.net\",\n \"g", "end": 304, "score": 0.9982632994651794, "start": 297, "tag": "NAME", "value": "Dunnion" }, { "context": "agard\",\n \"last_name\": \"Dunnion\",\n \"email\": \"hdunnion1@slideshare.net\",\n \"gender\": \"Female\",\n \"ip_address\": \"79.8", "end": 345, "score": 0.9999324083328247, "start": 321, "tag": "EMAIL", "value": "hdunnion1@slideshare.net" }, { "context": ".net\",\n \"gender\": \"Female\",\n \"ip_address\": \"79.89.58.25\"\n }, \n {\n \"id\": 3,\n \"first_name\": \"Bal", "end": 402, "score": 0.9997308254241943, "start": 391, "tag": "IP_ADDRESS", "value": "79.89.58.25" }, { "context": ".25\"\n }, \n {\n \"id\": 3,\n \"first_name\": \"Bald\",\n \"last_name\": \"Knoton\",\n \"email\": \"bknoto", "end": 453, "score": 0.9997224807739258, "start": 449, "tag": "NAME", "value": "Bald" }, { "context": "\": 3,\n \"first_name\": \"Bald\",\n \"last_name\": \"Knoton\",\n \"email\": \"bknoton2@geocities.jp\",\n \"gend", "end": 480, "score": 0.9987006187438965, "start": 474, "tag": "NAME", "value": "Knoton" }, { "context": " \"Bald\",\n \"last_name\": \"Knoton\",\n \"email\": \"bknoton2@geocities.jp\",\n \"gender\": \"Male\",\n \"ip_address\": \"41.119", "end": 518, "score": 0.9999241828918457, "start": 497, "tag": "EMAIL", "value": "bknoton2@geocities.jp" }, { "context": "ies.jp\",\n \"gender\": \"Male\",\n \"ip_address\": \"41.119.138.48\"\n }, \n {\n \"id\": 4,\n \"first_name\": \"Art", "end": 575, "score": 0.9997259378433228, "start": 562, "tag": "IP_ADDRESS", "value": "41.119.138.48" }, { "context": ".48\"\n }, \n {\n \"id\": 4,\n \"first_name\": \"Artur\",\n \"last_name\": \"Winsom\",\n \"email\": \"awinso", "end": 627, "score": 0.9997031688690186, "start": 622, "tag": "NAME", "value": "Artur" }, { "context": ": 4,\n \"first_name\": \"Artur\",\n \"last_name\": \"Winsom\",\n \"email\": \"awinsom3@nbcnews.com\",\n \"gende", "end": 654, "score": 0.999682605266571, "start": 648, "tag": "NAME", "value": "Winsom" }, { "context": "\"Artur\",\n \"last_name\": \"Winsom\",\n \"email\": \"awinsom3@nbcnews.com\",\n \"gender\": \"Male\",\n \"ip_address\": \"54.215", "end": 691, "score": 0.9999273419380188, "start": 671, "tag": "EMAIL", "value": "awinsom3@nbcnews.com" }, { "context": "ws.com\",\n \"gender\": \"Male\",\n \"ip_address\": \"54.215.145.9\"\n }, \n {\n \"id\": 5,\n \"first_name\": \"Jaq", "end": 747, "score": 0.9997264742851257, "start": 735, "tag": "IP_ADDRESS", "value": "54.215.145.9" }, { "context": "5.9\"\n }, \n {\n \"id\": 5,\n \"first_name\": \"Jaquith\",\n \"last_name\": \"Tredgold\",\n \"email\": \"jtre", "end": 801, "score": 0.9997305274009705, "start": 794, "tag": "NAME", "value": "Jaquith" }, { "context": "5,\n \"first_name\": \"Jaquith\",\n \"last_name\": \"Tredgold\",\n \"email\": \"jtredgold4@wikispaces.com\",\n \"", "end": 830, "score": 0.999724805355072, "start": 822, "tag": "NAME", "value": "Tredgold" }, { "context": "uith\",\n \"last_name\": \"Tredgold\",\n \"email\": \"jtredgold4@wikispaces.com\",\n \"gender\": \"Female\",\n \"ip_address\": \"241.", "end": 872, "score": 0.9999313354492188, "start": 847, "tag": "EMAIL", "value": "jtredgold4@wikispaces.com" }, { "context": ".com\",\n \"gender\": \"Female\",\n \"ip_address\": \"241.61.120.220\"\n }, \n {\n \"id\": 6,\n \"first_name\": \"Ort", "end": 932, "score": 0.9997391104698181, "start": 918, "tag": "IP_ADDRESS", "value": "241.61.120.220" }, { "context": "220\"\n }, \n {\n \"id\": 6,\n \"first_name\": \"Ortensia\",\n \"last_name\": \"Asquith\",\n \"email\": \"oasqu", "end": 987, "score": 0.9997513294219971, "start": 979, "tag": "NAME", "value": "Ortensia" }, { "context": ",\n \"first_name\": \"Ortensia\",\n \"last_name\": \"Asquith\",\n \"email\": \"oasquith5@google.cn\",\n \"gender", "end": 1015, "score": 0.9995064735412598, "start": 1008, "tag": "NAME", "value": "Asquith" }, { "context": "ensia\",\n \"last_name\": \"Asquith\",\n \"email\": \"oasquith5@google.cn\",\n \"gender\": \"Female\",\n \"ip_address\": \"52.1", "end": 1051, "score": 0.9999303817749023, "start": 1032, "tag": "EMAIL", "value": "oasquith5@google.cn" }, { "context": "e.cn\",\n \"gender\": \"Female\",\n \"ip_address\": \"52.17.48.13\"\n }, \n {\n \"id\": 7,\n \"first_name\": \"Rhe", "end": 1108, "score": 0.9996961951255798, "start": 1097, "tag": "IP_ADDRESS", "value": "52.17.48.13" }, { "context": ".13\"\n }, \n {\n \"id\": 7,\n \"first_name\": \"Rhea\",\n \"last_name\": \"Cashmore\",\n \"email\": \"rcas", "end": 1159, "score": 0.9997186064720154, "start": 1155, "tag": "NAME", "value": "Rhea" }, { "context": "\": 7,\n \"first_name\": \"Rhea\",\n \"last_name\": \"Cashmore\",\n \"email\": \"rcashmore6@a8.net\",\n \"gender\":", "end": 1188, "score": 0.9993327856063843, "start": 1180, "tag": "NAME", "value": "Cashmore" }, { "context": "Rhea\",\n \"last_name\": \"Cashmore\",\n \"email\": \"rcashmore6@a8.net\",\n \"gender\": \"Female\",\n \"ip_address\": \"247.", "end": 1222, "score": 0.9999226331710815, "start": 1205, "tag": "EMAIL", "value": "rcashmore6@a8.net" }, { "context": ".net\",\n \"gender\": \"Female\",\n \"ip_address\": \"247.172.162.162\"\n }, \n {\n \"id\": 8,\n \"first_name\": \"Tin", "end": 1283, "score": 0.9997411370277405, "start": 1268, "tag": "IP_ADDRESS", "value": "247.172.162.162" }, { "context": "162\"\n }, \n {\n \"id\": 8,\n \"first_name\": \"Tine\",\n \"last_name\": \"Sargison\",\n \"email\": \"tsar", "end": 1334, "score": 0.999651312828064, "start": 1330, "tag": "NAME", "value": "Tine" }, { "context": "\": 8,\n \"first_name\": \"Tine\",\n \"last_name\": \"Sargison\",\n \"email\": \"tsargison7@netlog.com\",\n \"gend", "end": 1363, "score": 0.9996340274810791, "start": 1355, "tag": "NAME", "value": "Sargison" }, { "context": "Tine\",\n \"last_name\": \"Sargison\",\n \"email\": \"tsargison7@netlog.com\",\n \"gender\": \"Female\",\n \"ip_address\": \"77.2", "end": 1401, "score": 0.9999275207519531, "start": 1380, "tag": "EMAIL", "value": "tsargison7@netlog.com" }, { "context": ".com\",\n \"gender\": \"Female\",\n \"ip_address\": \"77.228.51.227\"\n }, \n {\n \"id\": 9,\n \"first_name\": \"Bid", "end": 1460, "score": 0.9997378587722778, "start": 1447, "tag": "IP_ADDRESS", "value": "77.228.51.227" }, { "context": "227\"\n }, \n {\n \"id\": 9,\n \"first_name\": \"Bidget\",\n \"last_name\": \"Lasselle\",\n \"email\": \"blas", "end": 1513, "score": 0.9997049570083618, "start": 1507, "tag": "NAME", "value": "Bidget" }, { "context": " 9,\n \"first_name\": \"Bidget\",\n \"last_name\": \"Lasselle\",\n \"email\": \"blasselle8@surveymonkey.com\",\n ", "end": 1542, "score": 0.999609649181366, "start": 1534, "tag": "NAME", "value": "Lasselle" }, { "context": "dget\",\n \"last_name\": \"Lasselle\",\n \"email\": \"blasselle8@surveymonkey.com\",\n \"gender\": \"Female\",\n \"ip_address\": \"20.1", "end": 1586, "score": 0.9999300837516785, "start": 1559, "tag": "EMAIL", "value": "blasselle8@surveymonkey.com" }, { "context": ".com\",\n \"gender\": \"Female\",\n \"ip_address\": \"20.142.142.237\"\n }, \n {\n \"id\": 10,\n \"first_name\": \"Va", "end": 1646, "score": 0.9997394680976868, "start": 1632, "tag": "IP_ADDRESS", "value": "20.142.142.237" }, { "context": "37\"\n }, \n {\n \"id\": 10,\n \"first_name\": \"Valentia\",\n \"last_name\": \"Agney\",\n \"email\": \"vagney9", "end": 1702, "score": 0.9996819496154785, "start": 1694, "tag": "NAME", "value": "Valentia" }, { "context": ",\n \"first_name\": \"Valentia\",\n \"last_name\": \"Agney\",\n \"email\": \"vagney9@walmart.com\",\n \"gender", "end": 1728, "score": 0.9995174407958984, "start": 1723, "tag": "NAME", "value": "Agney" }, { "context": "alentia\",\n \"last_name\": \"Agney\",\n \"email\": \"vagney9@walmart.com\",\n \"gender\": \"Female\",\n \"ip_address\": \"182.", "end": 1764, "score": 0.9999256134033203, "start": 1745, "tag": "EMAIL", "value": "vagney9@walmart.com" }, { "context": ".com\",\n \"gender\": \"Female\",\n \"ip_address\": \"182.230.203.170\"\n }\n })\n", "end": 1825, "score": 0.9997497200965881, "start": 1810, "tag": "IP_ADDRESS", "value": "182.230.203.170" } ]
collections/mock_data.clj
travism26/random_clojure_stuff
0
(ns collections.mock-data) (def data-stuff { { "id": 1, "first_name": "Verne", "last_name": "Oganesian", "email": "voganesian0@newyorker.com", "gender": "Male", "ip_address": "206.44.174.25" }, { "id": 2, "first_name": "Hildagard", "last_name": "Dunnion", "email": "hdunnion1@slideshare.net", "gender": "Female", "ip_address": "79.89.58.25" }, { "id": 3, "first_name": "Bald", "last_name": "Knoton", "email": "bknoton2@geocities.jp", "gender": "Male", "ip_address": "41.119.138.48" }, { "id": 4, "first_name": "Artur", "last_name": "Winsom", "email": "awinsom3@nbcnews.com", "gender": "Male", "ip_address": "54.215.145.9" }, { "id": 5, "first_name": "Jaquith", "last_name": "Tredgold", "email": "jtredgold4@wikispaces.com", "gender": "Female", "ip_address": "241.61.120.220" }, { "id": 6, "first_name": "Ortensia", "last_name": "Asquith", "email": "oasquith5@google.cn", "gender": "Female", "ip_address": "52.17.48.13" }, { "id": 7, "first_name": "Rhea", "last_name": "Cashmore", "email": "rcashmore6@a8.net", "gender": "Female", "ip_address": "247.172.162.162" }, { "id": 8, "first_name": "Tine", "last_name": "Sargison", "email": "tsargison7@netlog.com", "gender": "Female", "ip_address": "77.228.51.227" }, { "id": 9, "first_name": "Bidget", "last_name": "Lasselle", "email": "blasselle8@surveymonkey.com", "gender": "Female", "ip_address": "20.142.142.237" }, { "id": 10, "first_name": "Valentia", "last_name": "Agney", "email": "vagney9@walmart.com", "gender": "Female", "ip_address": "182.230.203.170" } })
104630
(ns collections.mock-data) (def data-stuff { { "id": 1, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Male", "ip_address": "172.16.58.3" }, { "id": 2, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "172.16.31.10" }, { "id": 3, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Male", "ip_address": "172.16.17.32" }, { "id": 4, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Male", "ip_address": "192.168.127.12" }, { "id": 5, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "241.61.120.220" }, { "id": 6, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "172.16.58.3" }, { "id": 7, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "247.172.162.162" }, { "id": 8, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "172.16.17.32" }, { "id": 9, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "172.16.58.3" }, { "id": 10, "first_name": "<NAME>", "last_name": "<NAME>", "email": "<EMAIL>", "gender": "Female", "ip_address": "192.168.127.12" } })
true
(ns collections.mock-data) (def data-stuff { { "id": 1, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Male", "ip_address": "PI:IP_ADDRESS:172.16.58.3END_PI" }, { "id": 2, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "PI:IP_ADDRESS:172.16.31.10END_PI" }, { "id": 3, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Male", "ip_address": "PI:IP_ADDRESS:172.16.17.32END_PI" }, { "id": 4, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Male", "ip_address": "PI:IP_ADDRESS:192.168.127.12END_PI" }, { "id": 5, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "241.61.120.220" }, { "id": 6, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "PI:IP_ADDRESS:172.16.58.3END_PI" }, { "id": 7, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "247.172.162.162" }, { "id": 8, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "PI:IP_ADDRESS:172.16.17.32END_PI" }, { "id": 9, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "PI:IP_ADDRESS:172.16.58.3END_PI" }, { "id": 10, "first_name": "PI:NAME:<NAME>END_PI", "last_name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "gender": "Female", "ip_address": "PI:IP_ADDRESS:192.168.127.12END_PI" } })
[ { "context": "resql\"\n :username \"inflacao\"\n :password \"infla", "end": 789, "score": 0.996599018573761, "start": 781, "tag": "USERNAME", "value": "inflacao" }, { "context": "lacao\"\n :password \"inflacaopwd\"\n :database-name \"infla", "end": 845, "score": 0.9991437196731567, "start": 834, "tag": "PASSWORD", "value": "inflacaopwd" } ]
inflacao-pedestal-service/src/inflacao_pedestal_service/database.clj
giovanialtelino/InflacaoReagentClojure
0
(ns inflacao-pedestal-service.database (:require [hikari-cp.core :as hikari] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [java-time :as jt] [inflacao-pedestal-service.utils :as utils] [clojure.string :as str])) (def datasource-opts {:auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "inflacao" :adapter "postgresql" :username "inflacao" :password "inflacaopwd" :database-name "inflacao" :server-name "localhost" :port-number 5432 :register-mbeans false}) (defonce datasource (hikari/make-datasource datasource-opts)) (defn ds-get [ds] {:datasource ds}) (defn- pool-query ([conn query] (jdbc/with-db-connection [pool-conn (ds-get conn)] (let [result (jdbc/query pool-conn query)] result))) ([conn query args] (jdbc/with-db-connection [pool-conn (ds-get conn)] (let [result (jdbc/query pool-conn [query args])] result)))) (defn get-index [datasource name] (:index_id (first (pool-query datasource "SELECT index_id FROM indexes WHERE index_name = ?" (str/lower-case name))))) (defn check-if-exists [date table-name] (let [exist (count (pool-query datasource ["SELECT inflacao.valvalor AS valor FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE inflacao.valdata::date = ? AND indexes.index_name = ?" date table-name]))] (if (> exist 0) true false))) (defn check-if-date-key-already-exists [table date] (let [format-date (utils/format-date-to-javatime date) inpc12 "precos12_inpc12" ipc12 "igp12_ipc12" igpdi12 "igp12_igpdi12" igpm12 "igp12_igpm12" ipca12 "precos12_ipca12"] (cond (= table inpc12) (check-if-exists format-date inpc12) (= table ipc12) (check-if-exists format-date ipc12) (= table igpdi12) (check-if-exists format-date igpdi12) (= table igpm12) (check-if-exists format-date igpm12) (= table ipca12) (check-if-exists format-date ipca12) :else "error"))) (defn need-to-update? [key] (let [low-string-key (str/lower-case (name key)) last-update (pool-query datasource ["SELECT MAX(valdata) FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE indexes.index_name = ?" low-string-key]) date (:max (first last-update))] (if (nil? date) true (if (and (utils/same-month date) (utils/same-year date)) false true )))) (defn insert-data-inflacao [data] (let [{:keys [SERCODIGO VALDATA VALVALOR NIVNOME TERCODIGO]} data already-added? (check-if-date-key-already-exists (string/lower-case SERCODIGO) VALDATA)] (if (= false already-added?) (jdbc/insert! (ds-get datasource) :inflacao {:valdata (utils/format-date-to-javatime VALDATA) :valvalor VALVALOR :nivnome NIVNOME :tercodigo TERCODIGO :addedat (jt/sql-date (jt/local-date)) :indexname (get-index datasource SERCODIGO) })))) (defn- get-value-date-table [index-name date] (let [query (str "SELECT valvalor FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE indexes.index_name = ? AND inflacao.valdata = ?") result (pool-query datasource [query index-name date])] (if (< 0 (count result)) (:valvalor (first result)) 0 ))) (defn get-value-date-all-table [date] (let [formated-date (utils/format-date-to-javatime date) all-values {:precos12_inpc12 (get-value-date-table "precos12_inpc12" formated-date) :igp12_ipc12 (get-value-date-table "igp12_ipc12" formated-date) :igp12_igpdi12 (get-value-date-table "igp12_igpdi12" formated-date) :igp12_igpm12 (get-value-date-table "igp12_igpm12" formated-date) :precos12_ipca12 (get-value-date-table "precos12_ipca12" formated-date)}] all-values)) (defn- get-value-all-data [table] (let [query (str "SELECT TO_CHAR(inflacao.valvalor::FLOAT, 'FM999999990.00000000') AS Valor, TO_CHAR(inflacao.valdata, 'dd/mm/yyyy') AS Data, TO_CHAR(inflacao.addedat, 'dd/mm/yyyy') AS AddedAt " "FROM inflacao " "LEFT JOIN indexes " "ON inflacao.indexname = indexes.index_id " "WHERE indexes.index_name = ? " "ORDER BY inflacao.valdata DESC") result (pool-query datasource [query table])] result)) (defn get-all-data [] "Return all the data which is in the database" (let [all-values {:precos12_inpc12 (get-value-all-data "precos12_inpc12") :igp12_ipc12 (get-value-all-data "igp12_ipc12") :igp12_igpdi12 (get-value-all-data "igp12_igpdi12") :igp12_igpm12 (get-value-all-data "igp12_igpm12") :precos12_ipca12 (get-value-all-data "precos12_ipca12")}] all-values))
116426
(ns inflacao-pedestal-service.database (:require [hikari-cp.core :as hikari] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [java-time :as jt] [inflacao-pedestal-service.utils :as utils] [clojure.string :as str])) (def datasource-opts {:auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "inflacao" :adapter "postgresql" :username "inflacao" :password "<PASSWORD>" :database-name "inflacao" :server-name "localhost" :port-number 5432 :register-mbeans false}) (defonce datasource (hikari/make-datasource datasource-opts)) (defn ds-get [ds] {:datasource ds}) (defn- pool-query ([conn query] (jdbc/with-db-connection [pool-conn (ds-get conn)] (let [result (jdbc/query pool-conn query)] result))) ([conn query args] (jdbc/with-db-connection [pool-conn (ds-get conn)] (let [result (jdbc/query pool-conn [query args])] result)))) (defn get-index [datasource name] (:index_id (first (pool-query datasource "SELECT index_id FROM indexes WHERE index_name = ?" (str/lower-case name))))) (defn check-if-exists [date table-name] (let [exist (count (pool-query datasource ["SELECT inflacao.valvalor AS valor FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE inflacao.valdata::date = ? AND indexes.index_name = ?" date table-name]))] (if (> exist 0) true false))) (defn check-if-date-key-already-exists [table date] (let [format-date (utils/format-date-to-javatime date) inpc12 "precos12_inpc12" ipc12 "igp12_ipc12" igpdi12 "igp12_igpdi12" igpm12 "igp12_igpm12" ipca12 "precos12_ipca12"] (cond (= table inpc12) (check-if-exists format-date inpc12) (= table ipc12) (check-if-exists format-date ipc12) (= table igpdi12) (check-if-exists format-date igpdi12) (= table igpm12) (check-if-exists format-date igpm12) (= table ipca12) (check-if-exists format-date ipca12) :else "error"))) (defn need-to-update? [key] (let [low-string-key (str/lower-case (name key)) last-update (pool-query datasource ["SELECT MAX(valdata) FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE indexes.index_name = ?" low-string-key]) date (:max (first last-update))] (if (nil? date) true (if (and (utils/same-month date) (utils/same-year date)) false true )))) (defn insert-data-inflacao [data] (let [{:keys [SERCODIGO VALDATA VALVALOR NIVNOME TERCODIGO]} data already-added? (check-if-date-key-already-exists (string/lower-case SERCODIGO) VALDATA)] (if (= false already-added?) (jdbc/insert! (ds-get datasource) :inflacao {:valdata (utils/format-date-to-javatime VALDATA) :valvalor VALVALOR :nivnome NIVNOME :tercodigo TERCODIGO :addedat (jt/sql-date (jt/local-date)) :indexname (get-index datasource SERCODIGO) })))) (defn- get-value-date-table [index-name date] (let [query (str "SELECT valvalor FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE indexes.index_name = ? AND inflacao.valdata = ?") result (pool-query datasource [query index-name date])] (if (< 0 (count result)) (:valvalor (first result)) 0 ))) (defn get-value-date-all-table [date] (let [formated-date (utils/format-date-to-javatime date) all-values {:precos12_inpc12 (get-value-date-table "precos12_inpc12" formated-date) :igp12_ipc12 (get-value-date-table "igp12_ipc12" formated-date) :igp12_igpdi12 (get-value-date-table "igp12_igpdi12" formated-date) :igp12_igpm12 (get-value-date-table "igp12_igpm12" formated-date) :precos12_ipca12 (get-value-date-table "precos12_ipca12" formated-date)}] all-values)) (defn- get-value-all-data [table] (let [query (str "SELECT TO_CHAR(inflacao.valvalor::FLOAT, 'FM999999990.00000000') AS Valor, TO_CHAR(inflacao.valdata, 'dd/mm/yyyy') AS Data, TO_CHAR(inflacao.addedat, 'dd/mm/yyyy') AS AddedAt " "FROM inflacao " "LEFT JOIN indexes " "ON inflacao.indexname = indexes.index_id " "WHERE indexes.index_name = ? " "ORDER BY inflacao.valdata DESC") result (pool-query datasource [query table])] result)) (defn get-all-data [] "Return all the data which is in the database" (let [all-values {:precos12_inpc12 (get-value-all-data "precos12_inpc12") :igp12_ipc12 (get-value-all-data "igp12_ipc12") :igp12_igpdi12 (get-value-all-data "igp12_igpdi12") :igp12_igpm12 (get-value-all-data "igp12_igpm12") :precos12_ipca12 (get-value-all-data "precos12_ipca12")}] all-values))
true
(ns inflacao-pedestal-service.database (:require [hikari-cp.core :as hikari] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [java-time :as jt] [inflacao-pedestal-service.utils :as utils] [clojure.string :as str])) (def datasource-opts {:auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "inflacao" :adapter "postgresql" :username "inflacao" :password "PI:PASSWORD:<PASSWORD>END_PI" :database-name "inflacao" :server-name "localhost" :port-number 5432 :register-mbeans false}) (defonce datasource (hikari/make-datasource datasource-opts)) (defn ds-get [ds] {:datasource ds}) (defn- pool-query ([conn query] (jdbc/with-db-connection [pool-conn (ds-get conn)] (let [result (jdbc/query pool-conn query)] result))) ([conn query args] (jdbc/with-db-connection [pool-conn (ds-get conn)] (let [result (jdbc/query pool-conn [query args])] result)))) (defn get-index [datasource name] (:index_id (first (pool-query datasource "SELECT index_id FROM indexes WHERE index_name = ?" (str/lower-case name))))) (defn check-if-exists [date table-name] (let [exist (count (pool-query datasource ["SELECT inflacao.valvalor AS valor FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE inflacao.valdata::date = ? AND indexes.index_name = ?" date table-name]))] (if (> exist 0) true false))) (defn check-if-date-key-already-exists [table date] (let [format-date (utils/format-date-to-javatime date) inpc12 "precos12_inpc12" ipc12 "igp12_ipc12" igpdi12 "igp12_igpdi12" igpm12 "igp12_igpm12" ipca12 "precos12_ipca12"] (cond (= table inpc12) (check-if-exists format-date inpc12) (= table ipc12) (check-if-exists format-date ipc12) (= table igpdi12) (check-if-exists format-date igpdi12) (= table igpm12) (check-if-exists format-date igpm12) (= table ipca12) (check-if-exists format-date ipca12) :else "error"))) (defn need-to-update? [key] (let [low-string-key (str/lower-case (name key)) last-update (pool-query datasource ["SELECT MAX(valdata) FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE indexes.index_name = ?" low-string-key]) date (:max (first last-update))] (if (nil? date) true (if (and (utils/same-month date) (utils/same-year date)) false true )))) (defn insert-data-inflacao [data] (let [{:keys [SERCODIGO VALDATA VALVALOR NIVNOME TERCODIGO]} data already-added? (check-if-date-key-already-exists (string/lower-case SERCODIGO) VALDATA)] (if (= false already-added?) (jdbc/insert! (ds-get datasource) :inflacao {:valdata (utils/format-date-to-javatime VALDATA) :valvalor VALVALOR :nivnome NIVNOME :tercodigo TERCODIGO :addedat (jt/sql-date (jt/local-date)) :indexname (get-index datasource SERCODIGO) })))) (defn- get-value-date-table [index-name date] (let [query (str "SELECT valvalor FROM inflacao LEFT JOIN indexes ON inflacao.indexname = indexes.index_id WHERE indexes.index_name = ? AND inflacao.valdata = ?") result (pool-query datasource [query index-name date])] (if (< 0 (count result)) (:valvalor (first result)) 0 ))) (defn get-value-date-all-table [date] (let [formated-date (utils/format-date-to-javatime date) all-values {:precos12_inpc12 (get-value-date-table "precos12_inpc12" formated-date) :igp12_ipc12 (get-value-date-table "igp12_ipc12" formated-date) :igp12_igpdi12 (get-value-date-table "igp12_igpdi12" formated-date) :igp12_igpm12 (get-value-date-table "igp12_igpm12" formated-date) :precos12_ipca12 (get-value-date-table "precos12_ipca12" formated-date)}] all-values)) (defn- get-value-all-data [table] (let [query (str "SELECT TO_CHAR(inflacao.valvalor::FLOAT, 'FM999999990.00000000') AS Valor, TO_CHAR(inflacao.valdata, 'dd/mm/yyyy') AS Data, TO_CHAR(inflacao.addedat, 'dd/mm/yyyy') AS AddedAt " "FROM inflacao " "LEFT JOIN indexes " "ON inflacao.indexname = indexes.index_id " "WHERE indexes.index_name = ? " "ORDER BY inflacao.valdata DESC") result (pool-query datasource [query table])] result)) (defn get-all-data [] "Return all the data which is in the database" (let [all-values {:precos12_inpc12 (get-value-all-data "precos12_inpc12") :igp12_ipc12 (get-value-all-data "igp12_ipc12") :igp12_igpdi12 (get-value-all-data "igp12_igpdi12") :igp12_igpm12 (get-value-all-data "igp12_igpm12") :precos12_ipca12 (get-value-all-data "precos12_ipca12")}] all-values))
[ { "context": "process-fn (fn [res ctx]\n [{:name \"John\", :surname \"Doe\", :url \"/\", :processor :accounts}", "end": 5572, "score": 0.9997543692588806, "start": 5568, "tag": "NAME", "value": "John" }, { "context": "es ctx]\n [{:name \"John\", :surname \"Doe\", :url \"/\", :processor :accounts}])\n :skyscraper", "end": 5588, "score": 0.9985339641571045, "start": 5585, "tag": "NAME", "value": "Doe" }, { "context": " (sort-by :bank_account))\n [{:name \"John\", :surname \"Doe\", :bank_account \"0123-4567\"}\n ", "end": 6359, "score": 0.999738872051239, "start": 6355, "tag": "NAME", "value": "John" }, { "context": "nk_account))\n [{:name \"John\", :surname \"Doe\", :bank_account \"0123-4567\"}\n {:name \"", "end": 6375, "score": 0.9876245260238647, "start": 6372, "tag": "NAME", "value": "Doe" }, { "context": "\", :bank_account \"0123-4567\"}\n {:name \"John\", :surname \"Doe\", :bank_account \"8888-9999\"}]))\n ", "end": 6429, "score": 0.9997460842132568, "start": 6425, "tag": "NAME", "value": "John" }, { "context": "\"0123-4567\"}\n {:name \"John\", :surname \"Doe\", :bank_account \"8888-9999\"}]))\n (is (= (jdbc/", "end": 6445, "score": 0.9981581568717957, "start": 6442, "tag": "NAME", "value": "Doe" } ]
test/skyscraper/mock_test.clj
nathell/skyscraper
356
(ns skyscraper.mock-test (:require [clj-http.client :as http] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clojure.test :refer :all] [net.cgrand.enlive-html :refer [select text]] [skyscraper.cache :as cache] [skyscraper.core :refer :all] [skyscraper.enlive-helpers :refer [href]] [skyscraper.test-utils :refer [with-temporary-sqlite-db]] [taoensso.timbre :as timbre])) (defn dummy-site-content [i] (format "<html><h1>Number %s</h1>%s</html>" i (if (>= i 100) "" (apply str (for [n (range 10) :let [m (+ n (* 10 i))] :when (pos? m)] (format "<a href='/%s'>Page %s</a>" m m)))))) (defn url-number [url] (try (Integer/parseInt (last (string/split url #"/"))) (catch Exception _ 0))) (def hits (atom 0)) (defn mock-request [{:keys [url async?]} & [success-fn error-fn]] (swap! hits inc) (let [response {:headers {"content-type" "text/html; charset=utf-8"} :body (.getBytes (dummy-site-content (url-number url)))}] (if async? (success-fn response) response))) (defn process-root [res {:keys [i] :as ctx}] (let [numtext (text (first (select res [:h1]))) number (Long/parseLong (subs numtext 7)) subpages (select res [:a])] (if (seq subpages) (for [a subpages] (assoc {:processor :root, :url (href a), :i (inc i)} (keyword (str "level" i)) number)) {:number number}))) (defprocessor :root :cache-key-fn (fn [ctx] (str "numbers/" (url-number (:url ctx)))) :process-fn process-root) (defprocessor :root-uncached :process-fn process-root) (defn seed [& _] [{:url "http://localhost/0", :i 0, :processor :root}]) (defn seed-uncached [& _] [{:url "http://localhost/0", :i 0, :processor :root-uncached}]) (timbre/set-level! :warn) (deftest basic-scraping (is (= (count (scrape (seed) :html-cache nil :processed-cache nil :request-fn mock-request)) 900)) (is (= (count (scrape (seed) :html-cache nil :processed-cache nil :request-fn mock-request :download-mode :sync)) 900))) (deftest test-only (reset! hits 0) (is (= (->> (scrape (seed) :only {:level1 1} :html-cache nil :processed-cache nil :request-fn mock-request) (map :number) (sort)) (range 100 200)))) (deftest caches (reset! hits 0) (let [hcache (cache/memory) pcache (cache/memory)] (is (= (count (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) 900)) (let [hits-before @hits _ (dorun (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) hits-after @hits _ (dorun (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache :parallelism 1 :download-mode :sync)) hits-after-sync @hits] (is (= hits-before hits-after hits-after-sync))) (let [res1 (doall (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) res2 (doall (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache nil)) res3 (doall (scrape (seed) :request-fn mock-request :html-cache nil :processed-cache pcache)) res4 (doall (scrape (seed) :request-fn mock-request :html-cache nil :processed-cache nil)) res5 (doall (scrape (seed-uncached) :request-fn mock-request :html-cache nil :processed-cache nil))] (is (apply = (mapv #(sort-by :number %) [res1 res2 res3 res4 res5])))))) (deftest test-merge-urls (are [y z] (= (merge-urls "https://foo.pl/bar/baz" y) z) "http://bar.uk/baz/foo" "http://bar.uk/baz/foo" "//bar.uk/baz/foo" "https://bar.uk/baz/foo" "/baz/foo" "https://foo.pl/baz/foo" "foo" "https://foo.pl/bar/foo")) (deftest test-allows (is (allows? {:k1 1, :k2 2} {:k1 1, :k3 3})) (is (not (allows? {:k1 1, :k2 2} {:k1 1, :k2 3}))) (is (allows? {:k1 1} {:k1 1, :k2 2})) (is (allows? {} {:k1 1, :k2 2})) (is (allows? {:k1 1} {:k2 2}))) (defprocessor :nil-url-test-processor-root :cache-template "nil-url" :process-fn (fn [res ctx] (for [a (select res [:a])] {:title (text a), :url (href a), :processor :nil-url-test-processor-child}))) (defprocessor :nil-url-test-processor-child :cache-template "nil-url/:title" :process-fn (fn [res ctx] [{:info (text (first (select res [:h1])))}])) (deftest test-nil-url (let [html-main "<html><a href='/sub'>link</a><a name='anchor'>non-link</a></html>" html-child "<html><h1>Info</h1></html>" request (fn [{:keys [url]} success-fn error-fn] (success-fn {:headers {"content-type" "text/html; charset=utf-8"} :body (.getBytes (if (string/ends-with? url "/sub") html-child html-main))}))] (is (= (remove :processor (scrape [{:url "http://localhost/", :processor :nil-url-test-processor-root}] :html-cache nil :processed-cache nil :request-fn request)) [{:title "link", :info "Info"}])))) (defprocessor :users :process-fn (fn [res ctx] [{:name "John", :surname "Doe", :url "/", :processor :accounts}]) :skyscraper.db/columns [:name :surname] :skyscraper.db/key-columns [:name :surname]) (defprocessor :accounts :process-fn (fn [res ctx] [{:bank-account "0123-4567"} {:bank-account "8888-9999"}]) :skyscraper.db/columns [:bank-account] :skyscraper.db/key-columns [:bank-account]) (deftest test-sqlite (with-temporary-sqlite-db conn (dotimes [_ 2] (scrape! [{:url "http://example.com", :processor :users}] :request-fn mock-request :db (:connection-uri conn))) (is (= (->> (jdbc/query conn "SELECT name, surname, bank_account FROM accounts JOIN users ON accounts.parent = users.id") (sort-by :bank_account)) [{:name "John", :surname "Doe", :bank_account "0123-4567"} {:name "John", :surname "Doe", :bank_account "8888-9999"}])) (is (= (jdbc/query conn "SELECT count(*) cnt FROM accounts") [{:cnt 2}]))))
54678
(ns skyscraper.mock-test (:require [clj-http.client :as http] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clojure.test :refer :all] [net.cgrand.enlive-html :refer [select text]] [skyscraper.cache :as cache] [skyscraper.core :refer :all] [skyscraper.enlive-helpers :refer [href]] [skyscraper.test-utils :refer [with-temporary-sqlite-db]] [taoensso.timbre :as timbre])) (defn dummy-site-content [i] (format "<html><h1>Number %s</h1>%s</html>" i (if (>= i 100) "" (apply str (for [n (range 10) :let [m (+ n (* 10 i))] :when (pos? m)] (format "<a href='/%s'>Page %s</a>" m m)))))) (defn url-number [url] (try (Integer/parseInt (last (string/split url #"/"))) (catch Exception _ 0))) (def hits (atom 0)) (defn mock-request [{:keys [url async?]} & [success-fn error-fn]] (swap! hits inc) (let [response {:headers {"content-type" "text/html; charset=utf-8"} :body (.getBytes (dummy-site-content (url-number url)))}] (if async? (success-fn response) response))) (defn process-root [res {:keys [i] :as ctx}] (let [numtext (text (first (select res [:h1]))) number (Long/parseLong (subs numtext 7)) subpages (select res [:a])] (if (seq subpages) (for [a subpages] (assoc {:processor :root, :url (href a), :i (inc i)} (keyword (str "level" i)) number)) {:number number}))) (defprocessor :root :cache-key-fn (fn [ctx] (str "numbers/" (url-number (:url ctx)))) :process-fn process-root) (defprocessor :root-uncached :process-fn process-root) (defn seed [& _] [{:url "http://localhost/0", :i 0, :processor :root}]) (defn seed-uncached [& _] [{:url "http://localhost/0", :i 0, :processor :root-uncached}]) (timbre/set-level! :warn) (deftest basic-scraping (is (= (count (scrape (seed) :html-cache nil :processed-cache nil :request-fn mock-request)) 900)) (is (= (count (scrape (seed) :html-cache nil :processed-cache nil :request-fn mock-request :download-mode :sync)) 900))) (deftest test-only (reset! hits 0) (is (= (->> (scrape (seed) :only {:level1 1} :html-cache nil :processed-cache nil :request-fn mock-request) (map :number) (sort)) (range 100 200)))) (deftest caches (reset! hits 0) (let [hcache (cache/memory) pcache (cache/memory)] (is (= (count (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) 900)) (let [hits-before @hits _ (dorun (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) hits-after @hits _ (dorun (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache :parallelism 1 :download-mode :sync)) hits-after-sync @hits] (is (= hits-before hits-after hits-after-sync))) (let [res1 (doall (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) res2 (doall (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache nil)) res3 (doall (scrape (seed) :request-fn mock-request :html-cache nil :processed-cache pcache)) res4 (doall (scrape (seed) :request-fn mock-request :html-cache nil :processed-cache nil)) res5 (doall (scrape (seed-uncached) :request-fn mock-request :html-cache nil :processed-cache nil))] (is (apply = (mapv #(sort-by :number %) [res1 res2 res3 res4 res5])))))) (deftest test-merge-urls (are [y z] (= (merge-urls "https://foo.pl/bar/baz" y) z) "http://bar.uk/baz/foo" "http://bar.uk/baz/foo" "//bar.uk/baz/foo" "https://bar.uk/baz/foo" "/baz/foo" "https://foo.pl/baz/foo" "foo" "https://foo.pl/bar/foo")) (deftest test-allows (is (allows? {:k1 1, :k2 2} {:k1 1, :k3 3})) (is (not (allows? {:k1 1, :k2 2} {:k1 1, :k2 3}))) (is (allows? {:k1 1} {:k1 1, :k2 2})) (is (allows? {} {:k1 1, :k2 2})) (is (allows? {:k1 1} {:k2 2}))) (defprocessor :nil-url-test-processor-root :cache-template "nil-url" :process-fn (fn [res ctx] (for [a (select res [:a])] {:title (text a), :url (href a), :processor :nil-url-test-processor-child}))) (defprocessor :nil-url-test-processor-child :cache-template "nil-url/:title" :process-fn (fn [res ctx] [{:info (text (first (select res [:h1])))}])) (deftest test-nil-url (let [html-main "<html><a href='/sub'>link</a><a name='anchor'>non-link</a></html>" html-child "<html><h1>Info</h1></html>" request (fn [{:keys [url]} success-fn error-fn] (success-fn {:headers {"content-type" "text/html; charset=utf-8"} :body (.getBytes (if (string/ends-with? url "/sub") html-child html-main))}))] (is (= (remove :processor (scrape [{:url "http://localhost/", :processor :nil-url-test-processor-root}] :html-cache nil :processed-cache nil :request-fn request)) [{:title "link", :info "Info"}])))) (defprocessor :users :process-fn (fn [res ctx] [{:name "<NAME>", :surname "<NAME>", :url "/", :processor :accounts}]) :skyscraper.db/columns [:name :surname] :skyscraper.db/key-columns [:name :surname]) (defprocessor :accounts :process-fn (fn [res ctx] [{:bank-account "0123-4567"} {:bank-account "8888-9999"}]) :skyscraper.db/columns [:bank-account] :skyscraper.db/key-columns [:bank-account]) (deftest test-sqlite (with-temporary-sqlite-db conn (dotimes [_ 2] (scrape! [{:url "http://example.com", :processor :users}] :request-fn mock-request :db (:connection-uri conn))) (is (= (->> (jdbc/query conn "SELECT name, surname, bank_account FROM accounts JOIN users ON accounts.parent = users.id") (sort-by :bank_account)) [{:name "<NAME>", :surname "<NAME>", :bank_account "0123-4567"} {:name "<NAME>", :surname "<NAME>", :bank_account "8888-9999"}])) (is (= (jdbc/query conn "SELECT count(*) cnt FROM accounts") [{:cnt 2}]))))
true
(ns skyscraper.mock-test (:require [clj-http.client :as http] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clojure.test :refer :all] [net.cgrand.enlive-html :refer [select text]] [skyscraper.cache :as cache] [skyscraper.core :refer :all] [skyscraper.enlive-helpers :refer [href]] [skyscraper.test-utils :refer [with-temporary-sqlite-db]] [taoensso.timbre :as timbre])) (defn dummy-site-content [i] (format "<html><h1>Number %s</h1>%s</html>" i (if (>= i 100) "" (apply str (for [n (range 10) :let [m (+ n (* 10 i))] :when (pos? m)] (format "<a href='/%s'>Page %s</a>" m m)))))) (defn url-number [url] (try (Integer/parseInt (last (string/split url #"/"))) (catch Exception _ 0))) (def hits (atom 0)) (defn mock-request [{:keys [url async?]} & [success-fn error-fn]] (swap! hits inc) (let [response {:headers {"content-type" "text/html; charset=utf-8"} :body (.getBytes (dummy-site-content (url-number url)))}] (if async? (success-fn response) response))) (defn process-root [res {:keys [i] :as ctx}] (let [numtext (text (first (select res [:h1]))) number (Long/parseLong (subs numtext 7)) subpages (select res [:a])] (if (seq subpages) (for [a subpages] (assoc {:processor :root, :url (href a), :i (inc i)} (keyword (str "level" i)) number)) {:number number}))) (defprocessor :root :cache-key-fn (fn [ctx] (str "numbers/" (url-number (:url ctx)))) :process-fn process-root) (defprocessor :root-uncached :process-fn process-root) (defn seed [& _] [{:url "http://localhost/0", :i 0, :processor :root}]) (defn seed-uncached [& _] [{:url "http://localhost/0", :i 0, :processor :root-uncached}]) (timbre/set-level! :warn) (deftest basic-scraping (is (= (count (scrape (seed) :html-cache nil :processed-cache nil :request-fn mock-request)) 900)) (is (= (count (scrape (seed) :html-cache nil :processed-cache nil :request-fn mock-request :download-mode :sync)) 900))) (deftest test-only (reset! hits 0) (is (= (->> (scrape (seed) :only {:level1 1} :html-cache nil :processed-cache nil :request-fn mock-request) (map :number) (sort)) (range 100 200)))) (deftest caches (reset! hits 0) (let [hcache (cache/memory) pcache (cache/memory)] (is (= (count (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) 900)) (let [hits-before @hits _ (dorun (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) hits-after @hits _ (dorun (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache :parallelism 1 :download-mode :sync)) hits-after-sync @hits] (is (= hits-before hits-after hits-after-sync))) (let [res1 (doall (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache pcache)) res2 (doall (scrape (seed) :request-fn mock-request :html-cache hcache :processed-cache nil)) res3 (doall (scrape (seed) :request-fn mock-request :html-cache nil :processed-cache pcache)) res4 (doall (scrape (seed) :request-fn mock-request :html-cache nil :processed-cache nil)) res5 (doall (scrape (seed-uncached) :request-fn mock-request :html-cache nil :processed-cache nil))] (is (apply = (mapv #(sort-by :number %) [res1 res2 res3 res4 res5])))))) (deftest test-merge-urls (are [y z] (= (merge-urls "https://foo.pl/bar/baz" y) z) "http://bar.uk/baz/foo" "http://bar.uk/baz/foo" "//bar.uk/baz/foo" "https://bar.uk/baz/foo" "/baz/foo" "https://foo.pl/baz/foo" "foo" "https://foo.pl/bar/foo")) (deftest test-allows (is (allows? {:k1 1, :k2 2} {:k1 1, :k3 3})) (is (not (allows? {:k1 1, :k2 2} {:k1 1, :k2 3}))) (is (allows? {:k1 1} {:k1 1, :k2 2})) (is (allows? {} {:k1 1, :k2 2})) (is (allows? {:k1 1} {:k2 2}))) (defprocessor :nil-url-test-processor-root :cache-template "nil-url" :process-fn (fn [res ctx] (for [a (select res [:a])] {:title (text a), :url (href a), :processor :nil-url-test-processor-child}))) (defprocessor :nil-url-test-processor-child :cache-template "nil-url/:title" :process-fn (fn [res ctx] [{:info (text (first (select res [:h1])))}])) (deftest test-nil-url (let [html-main "<html><a href='/sub'>link</a><a name='anchor'>non-link</a></html>" html-child "<html><h1>Info</h1></html>" request (fn [{:keys [url]} success-fn error-fn] (success-fn {:headers {"content-type" "text/html; charset=utf-8"} :body (.getBytes (if (string/ends-with? url "/sub") html-child html-main))}))] (is (= (remove :processor (scrape [{:url "http://localhost/", :processor :nil-url-test-processor-root}] :html-cache nil :processed-cache nil :request-fn request)) [{:title "link", :info "Info"}])))) (defprocessor :users :process-fn (fn [res ctx] [{:name "PI:NAME:<NAME>END_PI", :surname "PI:NAME:<NAME>END_PI", :url "/", :processor :accounts}]) :skyscraper.db/columns [:name :surname] :skyscraper.db/key-columns [:name :surname]) (defprocessor :accounts :process-fn (fn [res ctx] [{:bank-account "0123-4567"} {:bank-account "8888-9999"}]) :skyscraper.db/columns [:bank-account] :skyscraper.db/key-columns [:bank-account]) (deftest test-sqlite (with-temporary-sqlite-db conn (dotimes [_ 2] (scrape! [{:url "http://example.com", :processor :users}] :request-fn mock-request :db (:connection-uri conn))) (is (= (->> (jdbc/query conn "SELECT name, surname, bank_account FROM accounts JOIN users ON accounts.parent = users.id") (sort-by :bank_account)) [{:name "PI:NAME:<NAME>END_PI", :surname "PI:NAME:<NAME>END_PI", :bank_account "0123-4567"} {:name "PI:NAME:<NAME>END_PI", :surname "PI:NAME:<NAME>END_PI", :bank_account "8888-9999"}])) (is (= (jdbc/query conn "SELECT count(*) cnt FROM accounts") [{:cnt 2}]))))
[ { "context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is", "end": 29, "score": 0.9998477101325989, "start": 13, "tag": "NAME", "value": "Fabian Schneider" }, { "context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is hereby granted, f", "end": 47, "score": 0.9998412728309631, "start": 34, "tag": "NAME", "value": "Gunnar Völkel" } ]
src/traqbio/actions/templates.clj
sysbio-bioinf/iBioTraq
2
;; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020 ;; ;; 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 traqbio.actions.templates (:require [clojure.data :as data] [clojure.string :as str] [traqbio.db.crud :as crud] [traqbio.actions.tools :as t] [traqbio.actions.diff :as diff])) (defn get-templates "Reads all templates and wrapps them in a response-map" [] {:body (crud/read-templates)}) (defn get-template "Reads a template with templatesteps by id and wrapps it in a response-map" [id] (if-let [template (crud/read-template id)] {:status 200, :body template} {:status 500})) (defn add-sequence-to-steps [template] (update template :templatesteps (fn [steps] (into [] (map-indexed #(assoc %2 :sequence (inc %1))) steps)))) (t/defaction create-template "Create a new template" {:description "Template \"{{parameters.template.name}}\" created", :error "Failed to create template \"{{parameters.template.name}}\"", :action-type :create} [template] (if (crud/create-template template (add-sequence-to-steps template)) {:status 200} {:status 500})) (comment (t/defaction update-template "Update the data and steps of a template." {:description "Template \"{{parameters.data.template.name}}\" updated", ;:capture (load-project (:id project)), ;:message project-diff, :error "Update of template \"{{parameters.data.template.name}}\" failed", :action-type :update} [{new-template :template, old-template :oldtemplate :as data}] (let [new-template (add-sequence-to-steps new-template) old-template (add-sequence-to-steps old-template) template-diff (-> (data/diff (dissoc new-template :templatesteps) (dissoc old-template :templatesteps)) ; extract modifications of the new template (newest wins with respect to modified properties) first ; add template id to diff (assoc :id (:id new-template))), step-changes (diff/step-modifications (:templatesteps new-template), (:templatesteps old-template)) ;:templatesteps and :textmodules are keys of templateData ;module-changes (diff/module-modifications (:textmodules new-template), (:textmodules old-template)) ;TODO: instead of module-changes, write new functions for writing to textmodule db once updateTemplate button is clicked ] ;end of let ;(crud/update-template template-diff, step-changes) ;crud function has already been modified accordingly (crud/update-template template-diff, step-changes);, module-changes) {:status 200, :body {}})) );end comment ;NOTE: This version of the function writes to textmodule table, including all additions, modifications and deletions (t/defaction update-template "Update the data and steps of a template." {:description "Template \"{{parameters.data.template.name}}\" updated", ;:capture (load-project (:id project)), ;:message project-diff, :error "Update of template \"{{parameters.data.template.name}}\" failed", :action-type :update} [{new-template :template, old-template :oldtemplate :as data}] (let [new-template (add-sequence-to-steps new-template) old-template (add-sequence-to-steps old-template) template-diff (-> (data/diff (dissoc new-template :templatesteps) (dissoc old-template :templatesteps)) ; extract modifications of the new template (newest wins with respect to modified properties) first ; add template id to diff (assoc :id (:id new-template))), step-changes (diff/step-modifications (:templatesteps new-template), (:templatesteps old-template)) ;:templatesteps and :textmodules are keys of templateData textmodules (dissoc new-template) ;Passes entire state of templateData at point where button is clicked with vector of maps stored in :textmodules ] ;end of let (crud/update-template template-diff, step-changes, textmodules);This crud function has been modified (passed textmodules arg from js here) to rewrite db table! {:status 200, :body {}})) (t/defaction delete-template "Delete the given template" {:description "Template \"{{captured.name}}\" deleted", :capture (crud/read-template template-id), :error "Failed to delete template with id \"{{parameters.templated-id}}\"", :action-type :delete} [template-id] (if (crud/delete-template template-id) {:status 200, :body {}} {:status 500}))
32588
;; Copyright <NAME> and <NAME> © 2014-2020 ;; ;; 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 traqbio.actions.templates (:require [clojure.data :as data] [clojure.string :as str] [traqbio.db.crud :as crud] [traqbio.actions.tools :as t] [traqbio.actions.diff :as diff])) (defn get-templates "Reads all templates and wrapps them in a response-map" [] {:body (crud/read-templates)}) (defn get-template "Reads a template with templatesteps by id and wrapps it in a response-map" [id] (if-let [template (crud/read-template id)] {:status 200, :body template} {:status 500})) (defn add-sequence-to-steps [template] (update template :templatesteps (fn [steps] (into [] (map-indexed #(assoc %2 :sequence (inc %1))) steps)))) (t/defaction create-template "Create a new template" {:description "Template \"{{parameters.template.name}}\" created", :error "Failed to create template \"{{parameters.template.name}}\"", :action-type :create} [template] (if (crud/create-template template (add-sequence-to-steps template)) {:status 200} {:status 500})) (comment (t/defaction update-template "Update the data and steps of a template." {:description "Template \"{{parameters.data.template.name}}\" updated", ;:capture (load-project (:id project)), ;:message project-diff, :error "Update of template \"{{parameters.data.template.name}}\" failed", :action-type :update} [{new-template :template, old-template :oldtemplate :as data}] (let [new-template (add-sequence-to-steps new-template) old-template (add-sequence-to-steps old-template) template-diff (-> (data/diff (dissoc new-template :templatesteps) (dissoc old-template :templatesteps)) ; extract modifications of the new template (newest wins with respect to modified properties) first ; add template id to diff (assoc :id (:id new-template))), step-changes (diff/step-modifications (:templatesteps new-template), (:templatesteps old-template)) ;:templatesteps and :textmodules are keys of templateData ;module-changes (diff/module-modifications (:textmodules new-template), (:textmodules old-template)) ;TODO: instead of module-changes, write new functions for writing to textmodule db once updateTemplate button is clicked ] ;end of let ;(crud/update-template template-diff, step-changes) ;crud function has already been modified accordingly (crud/update-template template-diff, step-changes);, module-changes) {:status 200, :body {}})) );end comment ;NOTE: This version of the function writes to textmodule table, including all additions, modifications and deletions (t/defaction update-template "Update the data and steps of a template." {:description "Template \"{{parameters.data.template.name}}\" updated", ;:capture (load-project (:id project)), ;:message project-diff, :error "Update of template \"{{parameters.data.template.name}}\" failed", :action-type :update} [{new-template :template, old-template :oldtemplate :as data}] (let [new-template (add-sequence-to-steps new-template) old-template (add-sequence-to-steps old-template) template-diff (-> (data/diff (dissoc new-template :templatesteps) (dissoc old-template :templatesteps)) ; extract modifications of the new template (newest wins with respect to modified properties) first ; add template id to diff (assoc :id (:id new-template))), step-changes (diff/step-modifications (:templatesteps new-template), (:templatesteps old-template)) ;:templatesteps and :textmodules are keys of templateData textmodules (dissoc new-template) ;Passes entire state of templateData at point where button is clicked with vector of maps stored in :textmodules ] ;end of let (crud/update-template template-diff, step-changes, textmodules);This crud function has been modified (passed textmodules arg from js here) to rewrite db table! {:status 200, :body {}})) (t/defaction delete-template "Delete the given template" {:description "Template \"{{captured.name}}\" deleted", :capture (crud/read-template template-id), :error "Failed to delete template with id \"{{parameters.templated-id}}\"", :action-type :delete} [template-id] (if (crud/delete-template template-id) {:status 200, :body {}} {:status 500}))
true
;; Copyright PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI © 2014-2020 ;; ;; 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 traqbio.actions.templates (:require [clojure.data :as data] [clojure.string :as str] [traqbio.db.crud :as crud] [traqbio.actions.tools :as t] [traqbio.actions.diff :as diff])) (defn get-templates "Reads all templates and wrapps them in a response-map" [] {:body (crud/read-templates)}) (defn get-template "Reads a template with templatesteps by id and wrapps it in a response-map" [id] (if-let [template (crud/read-template id)] {:status 200, :body template} {:status 500})) (defn add-sequence-to-steps [template] (update template :templatesteps (fn [steps] (into [] (map-indexed #(assoc %2 :sequence (inc %1))) steps)))) (t/defaction create-template "Create a new template" {:description "Template \"{{parameters.template.name}}\" created", :error "Failed to create template \"{{parameters.template.name}}\"", :action-type :create} [template] (if (crud/create-template template (add-sequence-to-steps template)) {:status 200} {:status 500})) (comment (t/defaction update-template "Update the data and steps of a template." {:description "Template \"{{parameters.data.template.name}}\" updated", ;:capture (load-project (:id project)), ;:message project-diff, :error "Update of template \"{{parameters.data.template.name}}\" failed", :action-type :update} [{new-template :template, old-template :oldtemplate :as data}] (let [new-template (add-sequence-to-steps new-template) old-template (add-sequence-to-steps old-template) template-diff (-> (data/diff (dissoc new-template :templatesteps) (dissoc old-template :templatesteps)) ; extract modifications of the new template (newest wins with respect to modified properties) first ; add template id to diff (assoc :id (:id new-template))), step-changes (diff/step-modifications (:templatesteps new-template), (:templatesteps old-template)) ;:templatesteps and :textmodules are keys of templateData ;module-changes (diff/module-modifications (:textmodules new-template), (:textmodules old-template)) ;TODO: instead of module-changes, write new functions for writing to textmodule db once updateTemplate button is clicked ] ;end of let ;(crud/update-template template-diff, step-changes) ;crud function has already been modified accordingly (crud/update-template template-diff, step-changes);, module-changes) {:status 200, :body {}})) );end comment ;NOTE: This version of the function writes to textmodule table, including all additions, modifications and deletions (t/defaction update-template "Update the data and steps of a template." {:description "Template \"{{parameters.data.template.name}}\" updated", ;:capture (load-project (:id project)), ;:message project-diff, :error "Update of template \"{{parameters.data.template.name}}\" failed", :action-type :update} [{new-template :template, old-template :oldtemplate :as data}] (let [new-template (add-sequence-to-steps new-template) old-template (add-sequence-to-steps old-template) template-diff (-> (data/diff (dissoc new-template :templatesteps) (dissoc old-template :templatesteps)) ; extract modifications of the new template (newest wins with respect to modified properties) first ; add template id to diff (assoc :id (:id new-template))), step-changes (diff/step-modifications (:templatesteps new-template), (:templatesteps old-template)) ;:templatesteps and :textmodules are keys of templateData textmodules (dissoc new-template) ;Passes entire state of templateData at point where button is clicked with vector of maps stored in :textmodules ] ;end of let (crud/update-template template-diff, step-changes, textmodules);This crud function has been modified (passed textmodules arg from js here) to rewrite db table! {:status 200, :body {}})) (t/defaction delete-template "Delete the given template" {:description "Template \"{{captured.name}}\" deleted", :capture (crud/read-template template-id), :error "Failed to delete template with id \"{{parameters.templated-id}}\"", :action-type :delete} [template-id] (if (crud/delete-template template-id) {:status 200, :body {}} {:status 500}))
[ { "context": ";; Copyright 2014 Timothy Brooks\n;;\n;; Licensed under the Apache License, Version ", "end": 32, "score": 0.9998695254325867, "start": 18, "tag": "NAME", "value": "Timothy Brooks" } ]
src/beehive/utils.clj
tbrooks8/fault
2
;; Copyright 2014 Timothy Brooks ;; ;; 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 beehive.utils (:import (java.util.concurrent TimeUnit))) (def time-units {:milliseconds TimeUnit/MILLISECONDS :seconds TimeUnit/SECONDS :minutes TimeUnit/MINUTES :hours TimeUnit/HOURS :days TimeUnit/DAYS}) (defn ->time-unit [unit-in-keyword] (if (instance? TimeUnit unit-in-keyword) unit-in-keyword (case unit-in-keyword :milliseconds TimeUnit/MILLISECONDS :seconds TimeUnit/SECONDS :minutes TimeUnit/MINUTES :hours TimeUnit/HOURS :days TimeUnit/DAYS (throw (IllegalArgumentException. ^String (format "Invalid time unit argument: %s. Valid arguments are: %s." unit-in-keyword (vec (keys time-units))))))))
91724
;; Copyright 2014 <NAME> ;; ;; 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 beehive.utils (:import (java.util.concurrent TimeUnit))) (def time-units {:milliseconds TimeUnit/MILLISECONDS :seconds TimeUnit/SECONDS :minutes TimeUnit/MINUTES :hours TimeUnit/HOURS :days TimeUnit/DAYS}) (defn ->time-unit [unit-in-keyword] (if (instance? TimeUnit unit-in-keyword) unit-in-keyword (case unit-in-keyword :milliseconds TimeUnit/MILLISECONDS :seconds TimeUnit/SECONDS :minutes TimeUnit/MINUTES :hours TimeUnit/HOURS :days TimeUnit/DAYS (throw (IllegalArgumentException. ^String (format "Invalid time unit argument: %s. Valid arguments are: %s." unit-in-keyword (vec (keys time-units))))))))
true
;; Copyright 2014 PI:NAME:<NAME>END_PI ;; ;; 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 beehive.utils (:import (java.util.concurrent TimeUnit))) (def time-units {:milliseconds TimeUnit/MILLISECONDS :seconds TimeUnit/SECONDS :minutes TimeUnit/MINUTES :hours TimeUnit/HOURS :days TimeUnit/DAYS}) (defn ->time-unit [unit-in-keyword] (if (instance? TimeUnit unit-in-keyword) unit-in-keyword (case unit-in-keyword :milliseconds TimeUnit/MILLISECONDS :seconds TimeUnit/SECONDS :minutes TimeUnit/MINUTES :hours TimeUnit/HOURS :days TimeUnit/DAYS (throw (IllegalArgumentException. ^String (format "Invalid time unit argument: %s. Valid arguments are: %s." unit-in-keyword (vec (keys time-units))))))))
[ { "context": "url\n callback :fake-callback\n username :fake-username\n logged-in-username \"johndoe\"\n password", "end": 365, "score": 0.9929711818695068, "start": 352, "tag": "USERNAME", "value": "fake-username" }, { "context": "username :fake-username\n logged-in-username \"johndoe\"\n password :fake-password\n data {:url \"", "end": 399, "score": 0.9993988871574402, "start": 392, "tag": "USERNAME", "value": "johndoe" }, { "context": " logged-in-username \"johndoe\"\n password :fake-password\n data {:url \"a/b/c/id\"}\n data-with-owne", "end": 430, "score": 0.9989321827888489, "start": 417, "tag": "PASSWORD", "value": "fake-password" }, { "context": "le :fake-role\n data {:username username :role role}\n data-remove (mer", "end": 3869, "score": 0.9928076267242432, "start": 3861, "tag": "USERNAME", "value": "username" } ]
test/clj/milia/api/project_test.clj
onaio/milia
9
(ns milia.api.project-test (:refer-clojure :exclude [update]) (:require [midje.sweet :refer :all] [milia.api.project :refer :all] [milia.api.http :refer [parse-http]] [milia.utils.remote :refer [make-url]] [milia.utils.file :as f])) (let [url :fake-url callback :fake-callback username :fake-username logged-in-username "johndoe" password :fake-password data {:url "a/b/c/id"} data-with-owner (merge data {:owner url}) parsed-data (merge data {:id "id"})] (facts "about projects all" (fact "Should get correct url" (all) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params nil} :no-cache? nil) => :response)) (fact "Should pass owner as a query parameter" (all username) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params {:owner username}} :no-cache? nil) => :response)) (fact "Should pass logged-in-user as a query parameter" (all username :logged-in-username logged-in-username) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params {:owner username :u logged-in-username}} :no-cache? nil) => :response))) (facts "about project-create" (fact "Should associate data" (create data username) => parsed-data (provided (make-url "users" ":fake-username.json") => url (make-url "projects.json") => url (parse-http :post url :http-options {:form-params data-with-owner :content-type :json}) => data)) (fact "Should throw an exception if special __all__ error key returned" (let [error :error] (create data username) => (throws clojure.lang.ExceptionInfo) (provided (make-url "users" ":fake-username.json") => url (make-url "projects.json") => url (parse-http :post url :http-options {:form-params data-with-owner :content-type :json}) => {:__all__ error})))) (facts "about get-project" (fact "Should find project for id" (get-project :id) => parsed-data (provided (make-url "projects" ":id.json") => url (parse-http :get url :no-cache? nil) => data)) (fact "Should handle when parse-http returns a string" (get-project :id) => nil (provided (make-url "projects" ":id.json") => url (parse-http :get url :no-cache? nil) => "a string"))) (facts "about get-forms" (fact "Should find forms for id" (get-forms :id) => data (provided (make-url "projects" :id "forms.json") => url (parse-http :get url) => data))) (facts "about share for project" (fact "Should return result of parse-http" (let [role :fake-role data {:username username :role role} data-remove (merge data {:remove "True"})] (share :id username role) => :204 (provided (make-url "projects" :id "share.json") => url (parse-http :put url :http-options {:form-params data}) => :204) (share :id username role true) => :204 (provided (make-url "projects" :id "share.json") => url (parse-http :put url :http-options {:form-params data-remove}) => :204)))) (facts "about update for project" (fact "Should return result of parse-http" (let [owner :fake-owner name :fake-project-name metadata :fake-metadata data {:owner owner :name name :metadata metadata}] (update :id data) => :updated-project (provided (make-url "projects" ":id.json") => url (parse-http :patch url :http-options {:form-params data :content-type :json}) => :updated-project)))) (facts "about add-tags" (fact "Should call parse-http with tags" (add-tags :id [:tag1 :tag2]) => :response (provided (make-url "projects" :id "labels.json") => url (parse-http :post url :http-options {:form-params {:tags ":tag1,:tag2"} :content-type :json}) => :response))) (facts "about starring" (fact "add-star should post star" (add-star :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :post url :callback nil) => :response)) (fact "add-star with callback should also post star" (add-star :id :callback callback) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :post url :callback callback) => :response)) (fact "remove-star should delete to star" (remove-star :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :delete url :callback nil) => :response)) (fact "remove-star with callback should also delete star" (remove-star :id :callback callback) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :delete url :callback callback) => :response)) (fact "get-starred should get to star no id" (get-starred username) => :response (provided (make-url "user" username "starred.json") => url (parse-http :get url) => :response)) (fact "starred-by should get to star with id" (starred-by :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :get url) => :response))) (facts "about delete" (fact "should call parse-http with delete" (delete :id) => :response (provided (make-url "projects" ":id.json") => url (parse-http :delete url) => :response))) (facts "about project owner transfer" (fact "should call parse-http with patch" (transfer-owner :id :new_owner) => :response (provided (make-url "projects" ":id.json") => url (make-url "users" ":new_owner.json") => :user-url (parse-http :patch url :http-options {:form-params {:owner :user-url} :content-type :json}) => :response))) (fact "about upload project files" (upload-file :project-id {:filename "image.png"}) => :response (provided (f/uploaded->file {:filename "image.png"}) => :file (make-url "metadata.json") => url (parse-http :post url :http-options {:multipart [{:name "data_value" :content "image.png"} {:name "data_type" :content "supporting_doc"} {:name "project" :content :project-id} {:name "data_file" :content :file}]} :suppress-4xx-exceptions? true) => :response)))
32848
(ns milia.api.project-test (:refer-clojure :exclude [update]) (:require [midje.sweet :refer :all] [milia.api.project :refer :all] [milia.api.http :refer [parse-http]] [milia.utils.remote :refer [make-url]] [milia.utils.file :as f])) (let [url :fake-url callback :fake-callback username :fake-username logged-in-username "johndoe" password :<PASSWORD> data {:url "a/b/c/id"} data-with-owner (merge data {:owner url}) parsed-data (merge data {:id "id"})] (facts "about projects all" (fact "Should get correct url" (all) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params nil} :no-cache? nil) => :response)) (fact "Should pass owner as a query parameter" (all username) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params {:owner username}} :no-cache? nil) => :response)) (fact "Should pass logged-in-user as a query parameter" (all username :logged-in-username logged-in-username) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params {:owner username :u logged-in-username}} :no-cache? nil) => :response))) (facts "about project-create" (fact "Should associate data" (create data username) => parsed-data (provided (make-url "users" ":fake-username.json") => url (make-url "projects.json") => url (parse-http :post url :http-options {:form-params data-with-owner :content-type :json}) => data)) (fact "Should throw an exception if special __all__ error key returned" (let [error :error] (create data username) => (throws clojure.lang.ExceptionInfo) (provided (make-url "users" ":fake-username.json") => url (make-url "projects.json") => url (parse-http :post url :http-options {:form-params data-with-owner :content-type :json}) => {:__all__ error})))) (facts "about get-project" (fact "Should find project for id" (get-project :id) => parsed-data (provided (make-url "projects" ":id.json") => url (parse-http :get url :no-cache? nil) => data)) (fact "Should handle when parse-http returns a string" (get-project :id) => nil (provided (make-url "projects" ":id.json") => url (parse-http :get url :no-cache? nil) => "a string"))) (facts "about get-forms" (fact "Should find forms for id" (get-forms :id) => data (provided (make-url "projects" :id "forms.json") => url (parse-http :get url) => data))) (facts "about share for project" (fact "Should return result of parse-http" (let [role :fake-role data {:username username :role role} data-remove (merge data {:remove "True"})] (share :id username role) => :204 (provided (make-url "projects" :id "share.json") => url (parse-http :put url :http-options {:form-params data}) => :204) (share :id username role true) => :204 (provided (make-url "projects" :id "share.json") => url (parse-http :put url :http-options {:form-params data-remove}) => :204)))) (facts "about update for project" (fact "Should return result of parse-http" (let [owner :fake-owner name :fake-project-name metadata :fake-metadata data {:owner owner :name name :metadata metadata}] (update :id data) => :updated-project (provided (make-url "projects" ":id.json") => url (parse-http :patch url :http-options {:form-params data :content-type :json}) => :updated-project)))) (facts "about add-tags" (fact "Should call parse-http with tags" (add-tags :id [:tag1 :tag2]) => :response (provided (make-url "projects" :id "labels.json") => url (parse-http :post url :http-options {:form-params {:tags ":tag1,:tag2"} :content-type :json}) => :response))) (facts "about starring" (fact "add-star should post star" (add-star :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :post url :callback nil) => :response)) (fact "add-star with callback should also post star" (add-star :id :callback callback) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :post url :callback callback) => :response)) (fact "remove-star should delete to star" (remove-star :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :delete url :callback nil) => :response)) (fact "remove-star with callback should also delete star" (remove-star :id :callback callback) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :delete url :callback callback) => :response)) (fact "get-starred should get to star no id" (get-starred username) => :response (provided (make-url "user" username "starred.json") => url (parse-http :get url) => :response)) (fact "starred-by should get to star with id" (starred-by :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :get url) => :response))) (facts "about delete" (fact "should call parse-http with delete" (delete :id) => :response (provided (make-url "projects" ":id.json") => url (parse-http :delete url) => :response))) (facts "about project owner transfer" (fact "should call parse-http with patch" (transfer-owner :id :new_owner) => :response (provided (make-url "projects" ":id.json") => url (make-url "users" ":new_owner.json") => :user-url (parse-http :patch url :http-options {:form-params {:owner :user-url} :content-type :json}) => :response))) (fact "about upload project files" (upload-file :project-id {:filename "image.png"}) => :response (provided (f/uploaded->file {:filename "image.png"}) => :file (make-url "metadata.json") => url (parse-http :post url :http-options {:multipart [{:name "data_value" :content "image.png"} {:name "data_type" :content "supporting_doc"} {:name "project" :content :project-id} {:name "data_file" :content :file}]} :suppress-4xx-exceptions? true) => :response)))
true
(ns milia.api.project-test (:refer-clojure :exclude [update]) (:require [midje.sweet :refer :all] [milia.api.project :refer :all] [milia.api.http :refer [parse-http]] [milia.utils.remote :refer [make-url]] [milia.utils.file :as f])) (let [url :fake-url callback :fake-callback username :fake-username logged-in-username "johndoe" password :PI:PASSWORD:<PASSWORD>END_PI data {:url "a/b/c/id"} data-with-owner (merge data {:owner url}) parsed-data (merge data {:id "id"})] (facts "about projects all" (fact "Should get correct url" (all) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params nil} :no-cache? nil) => :response)) (fact "Should pass owner as a query parameter" (all username) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params {:owner username}} :no-cache? nil) => :response)) (fact "Should pass logged-in-user as a query parameter" (all username :logged-in-username logged-in-username) => :response (provided (make-url "projects.json") => url (parse-http :get url :http-options {:query-params {:owner username :u logged-in-username}} :no-cache? nil) => :response))) (facts "about project-create" (fact "Should associate data" (create data username) => parsed-data (provided (make-url "users" ":fake-username.json") => url (make-url "projects.json") => url (parse-http :post url :http-options {:form-params data-with-owner :content-type :json}) => data)) (fact "Should throw an exception if special __all__ error key returned" (let [error :error] (create data username) => (throws clojure.lang.ExceptionInfo) (provided (make-url "users" ":fake-username.json") => url (make-url "projects.json") => url (parse-http :post url :http-options {:form-params data-with-owner :content-type :json}) => {:__all__ error})))) (facts "about get-project" (fact "Should find project for id" (get-project :id) => parsed-data (provided (make-url "projects" ":id.json") => url (parse-http :get url :no-cache? nil) => data)) (fact "Should handle when parse-http returns a string" (get-project :id) => nil (provided (make-url "projects" ":id.json") => url (parse-http :get url :no-cache? nil) => "a string"))) (facts "about get-forms" (fact "Should find forms for id" (get-forms :id) => data (provided (make-url "projects" :id "forms.json") => url (parse-http :get url) => data))) (facts "about share for project" (fact "Should return result of parse-http" (let [role :fake-role data {:username username :role role} data-remove (merge data {:remove "True"})] (share :id username role) => :204 (provided (make-url "projects" :id "share.json") => url (parse-http :put url :http-options {:form-params data}) => :204) (share :id username role true) => :204 (provided (make-url "projects" :id "share.json") => url (parse-http :put url :http-options {:form-params data-remove}) => :204)))) (facts "about update for project" (fact "Should return result of parse-http" (let [owner :fake-owner name :fake-project-name metadata :fake-metadata data {:owner owner :name name :metadata metadata}] (update :id data) => :updated-project (provided (make-url "projects" ":id.json") => url (parse-http :patch url :http-options {:form-params data :content-type :json}) => :updated-project)))) (facts "about add-tags" (fact "Should call parse-http with tags" (add-tags :id [:tag1 :tag2]) => :response (provided (make-url "projects" :id "labels.json") => url (parse-http :post url :http-options {:form-params {:tags ":tag1,:tag2"} :content-type :json}) => :response))) (facts "about starring" (fact "add-star should post star" (add-star :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :post url :callback nil) => :response)) (fact "add-star with callback should also post star" (add-star :id :callback callback) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :post url :callback callback) => :response)) (fact "remove-star should delete to star" (remove-star :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :delete url :callback nil) => :response)) (fact "remove-star with callback should also delete star" (remove-star :id :callback callback) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :delete url :callback callback) => :response)) (fact "get-starred should get to star no id" (get-starred username) => :response (provided (make-url "user" username "starred.json") => url (parse-http :get url) => :response)) (fact "starred-by should get to star with id" (starred-by :id) => :response (provided (make-url "projects" :id "star.json") => url (parse-http :get url) => :response))) (facts "about delete" (fact "should call parse-http with delete" (delete :id) => :response (provided (make-url "projects" ":id.json") => url (parse-http :delete url) => :response))) (facts "about project owner transfer" (fact "should call parse-http with patch" (transfer-owner :id :new_owner) => :response (provided (make-url "projects" ":id.json") => url (make-url "users" ":new_owner.json") => :user-url (parse-http :patch url :http-options {:form-params {:owner :user-url} :content-type :json}) => :response))) (fact "about upload project files" (upload-file :project-id {:filename "image.png"}) => :response (provided (f/uploaded->file {:filename "image.png"}) => :file (make-url "metadata.json") => url (parse-http :post url :http-options {:multipart [{:name "data_value" :content "image.png"} {:name "data_type" :content "supporting_doc"} {:name "project" :content :project-id} {:name "data_file" :content :file}]} :suppress-4xx-exceptions? true) => :response)))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998166561126709, "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.9998226165771484, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/internal/transaction.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.transaction "Internal functions that implement the transactional behavior." (:require [clojure.set :as set] [clojure.string :as str] [internal.util :as util] [internal.graph :as ig] [internal.graph.types :as gt] [internal.node :as in] [internal.system :as is] [schema.core :as s])) (set! *warn-on-reflection* true) ;; --------------------------------------------------------------------------- ;; Configuration parameters ;; --------------------------------------------------------------------------- (def maximum-retrigger-count 100) (def maximum-graph-coloring-recursion 1000) ;; --------------------------------------------------------------------------- ;; Internal state ;; --------------------------------------------------------------------------- (def ^:dynamic *tx-debug* nil) (def ^:private ^java.util.concurrent.atomic.AtomicInteger next-txid (java.util.concurrent.atomic.AtomicInteger. 1)) (defn- new-txid [] (.getAndIncrement next-txid)) (defmacro txerrstr [ctx & rest] `(str (:txid ~ctx) ": " ~@(interpose " " rest))) ;; --------------------------------------------------------------------------- ;; Building transactions ;; --------------------------------------------------------------------------- (defn new-node "*transaction step* - add a node to a graph" [node] [{:type :create-node :node node}]) (defn delete-node [node-id] [{:type :delete-node :node-id node-id}]) (defn- new-override [override-id root-id traverse-fn] [{:type :new-override :override-id override-id :root-id root-id :traverse-fn traverse-fn}]) (defn- override-node [original-node-id override-node-id] [{:type :override-node :original-node-id original-node-id :override-node-id override-node-id}]) (defn override [root-id traverse-fn init-fn properties-by-node-id] [{:type :override :root-id root-id :traverse-fn traverse-fn :init-fn init-fn :properties-by-node-id properties-by-node-id}]) (defn transfer-overrides [from-id->to-id] [{:type :transfer-overrides :from-id->to-id from-id->to-id}]) (defn update-property "*transaction step* - Expects a node, a property label, and a function f (with optional args) to be performed on the current value of the property." [node-id pr f args] [{:type :update-property :node-id node-id :property pr :fn f :args args}]) (defn clear-property [node-id pr] [{:type :clear-property :node-id node-id :property pr}]) (defn update-graph-value [graph-id f args] [{:type :update-graph-value :graph-id graph-id :fn f :args args}]) (defn callback [f args] [{:type :callback :fn f :args args}]) (defn connect "*transaction step* - Creates a transaction step connecting a source node and label and a target node and label. It returns a value suitable for consumption by [[perform]]." [source-id source-label target-id target-label] [{:type :connect :source-id source-id :source-label source-label :target-id target-id :target-label target-label}]) (defn disconnect "*transaction step* - The reverse of [[connect]]. Creates a transaction step disconnecting a source node and label from a target node and label. It returns a value suitable for consumption by [[perform]]." [source-id source-label target-id target-label] [{:type :disconnect :source-id source-id :source-label source-label :target-id target-id :target-label target-label}]) (defn disconnect-sources [basis target-id target-label] (for [[source-id source-label] (gt/sources basis target-id target-label)] (disconnect source-id source-label target-id target-label))) (defn label [label] [{:type :label :label label}]) (defn sequence-label [seq-label] [{:type :sequence-label :label seq-label}]) (defn invalidate [node-id] [{:type :invalidate :node-id node-id}]) ;; --------------------------------------------------------------------------- ;; Executing transactions ;; --------------------------------------------------------------------------- (defn- mark-input-activated [ctx node-id input-label] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (let [basis (:basis ctx) dirty-deps (-> (gt/node-by-id-at basis node-id) (gt/node-type basis) in/input-dependencies (get input-label))] (update ctx :nodes-affected assoc node-id (reduce conj nodes-affected dirty-deps))) ctx)) (defn- mark-output-activated [ctx node-id output-label] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (update ctx :nodes-affected assoc node-id (conj nodes-affected output-label)) ctx)) (defn- mark-outputs-activated [ctx node-id output-labels] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (update ctx :nodes-affected assoc node-id (reduce conj nodes-affected output-labels)) ctx)) (defn- mark-all-outputs-activated [ctx node-id] (let [basis (:basis ctx) all-labels (-> (gt/node-by-id-at basis node-id) (gt/node-type basis) in/output-labels)] (update ctx :nodes-affected assoc node-id (set all-labels)))) (defn- next-node-id [ctx graph-id] (is/next-node-id* (:node-id-generators ctx) graph-id)) (defn- next-override-id [ctx graph-id] (is/next-override-id* (:override-id-generator ctx) graph-id)) (defmulti perform "A multimethod used for defining methods that perform the individual actions within a transaction. This is for internal use, not intended to be extended by applications. Perform takes a transaction context (ctx) and a map (m) containing a value for keyword `:type`, and other keys and values appropriate to the transformation it represents. Callers should regard the map and context as opaque. Calls to perform are only executed by [[transact]]. The data required for `perform` calls are constructed in action functions, such as [[connect]] and [[update-property]]." (fn [ctx m] (:type m))) (def ^:private ctx-disconnect) (defn- ctx-disconnect-arc [ctx arc] (let [[source-id source-label] (gt/source arc) [target-id target-label] (gt/target arc)] (ctx-disconnect ctx source-id source-label target-id target-label))) (defn- disconnect-inputs [ctx target-id target-label] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-target (:basis ctx) target-id target-label))) (defn- disconnect-all-inputs [ctx target-id] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-target (:basis ctx) target-id))) (defn- disconnect-outputs [ctx source-id source-label] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-source (:basis ctx) source-id source-label))) (defn- disconnect-stale [ctx node-id old-node new-node labels-fn disconnect-fn] (let [basis (:basis ctx) stale-labels (set/difference (-> old-node (gt/node-type basis) labels-fn) (-> new-node (gt/node-type basis) labels-fn))] (loop [ctx ctx labels stale-labels] (if-let [label (first labels)] (recur (disconnect-fn ctx node-id label) (rest labels)) ctx)))) (defn- disconnect-stale-inputs [ctx node-id old-node new-node] (disconnect-stale ctx node-id old-node new-node in/input-labels disconnect-inputs)) (defn- disconnect-stale-outputs [ctx node-id old-node new-node] (disconnect-stale ctx node-id old-node new-node in/output-labels disconnect-outputs)) (def ^:private replace-node (comp first gt/replace-node)) (defn- delete-single [ctx node-id] (let [basis (:basis ctx)] (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [targets (ig/explicit-targets basis node-id)] (-> (reduce (fn [ctx [node-id input]] (mark-input-activated ctx node-id input)) ctx targets) (disconnect-all-inputs node-id) (mark-all-outputs-activated node-id) (update :basis gt/delete-node node-id) (assoc-in [:nodes-deleted node-id] node) (update :nodes-added (partial filterv #(not= node-id %))))) ctx))) (defn- ctx-delete-node [ctx node-id] (when *tx-debug* (println (txerrstr ctx "deleting " node-id))) (let [to-delete (ig/pre-traverse (:basis ctx) [node-id] ig/cascade-delete-sources)] (when (and *tx-debug* (not (empty? to-delete))) (println (txerrstr ctx "cascading delete of " (pr-str to-delete)))) (reduce delete-single ctx to-delete))) (defmethod perform :delete-node [ctx {:keys [node-id]}] (ctx-delete-node ctx node-id)) (defmethod perform :new-override [ctx {:keys [override-id root-id traverse-fn]}] (-> ctx (update :basis gt/add-override override-id (ig/make-override root-id traverse-fn)))) (defn- flag-all-successors-changed [ctx node-ids] (let [successors (get ctx :successors-changed)] (assoc ctx :successors-changed (reduce (fn [successors node-id] (assoc successors node-id nil)) successors node-ids)))) (defn- flag-successors-changed [ctx changes] (let [successors (get ctx :successors-changed)] (assoc ctx :successors-changed (reduce (fn [successors [node-id label]] (if-let [node-succ (get successors node-id #{})] (assoc successors node-id (conj node-succ label)) successors)) successors changes)))) (defn- ctx-override-node [ctx original-node-id override-node-id] (assert (= (gt/node-id->graph-id original-node-id) (gt/node-id->graph-id override-node-id)) "Override nodes must belong to the same graph as the original") (let [basis (:basis ctx) original (gt/node-by-id-at basis original-node-id) all-originals (ig/override-originals basis original-node-id)] (-> ctx (update :basis gt/override-node original-node-id override-node-id) (flag-all-successors-changed all-originals) (flag-successors-changed (mapcat #(gt/sources basis %) all-originals))))) (defmethod perform :override-node [ctx {:keys [original-node-id override-node-id]}] (ctx-override-node ctx original-node-id override-node-id)) (declare apply-tx) (defmethod perform :override [ctx {:keys [root-id traverse-fn init-fn properties-by-node-id]}] (let [basis (:basis ctx) graph-id (gt/node-id->graph-id root-id) node-ids (ig/pre-traverse basis [root-id] traverse-fn) override-id (next-override-id ctx graph-id) override-nodes (mapv #(in/make-override-node override-id (next-node-id ctx graph-id) % (properties-by-node-id %)) node-ids) override-node-ids (map gt/node-id override-nodes) original-node-id->override-node-id (zipmap node-ids override-node-ids) new-override-nodes-tx-data (map new-node override-nodes) new-override-tx-data (concat (new-override override-id root-id traverse-fn) (map (fn [node-id override-node-id] (override-node node-id override-node-id)) node-ids override-node-ids))] (as-> ctx ctx' (apply-tx ctx' (concat new-override-nodes-tx-data new-override-tx-data)) (apply-tx ctx' (init-fn (in/custom-evaluation-context {:basis (:basis ctx')}) original-node-id->override-node-id))))) (defn- node-id->override-id [basis node-id] (->> node-id (gt/node-by-id-at basis) gt/override-id)) (declare ctx-add-node) (defn- ctx-make-override-nodes [ctx override-id node-ids] (reduce (fn [ctx node-id] (let [basis (:basis ctx)] (if (some #(= override-id (node-id->override-id basis %)) (ig/get-overrides basis node-id)) ctx (let [graph-id (gt/node-id->graph-id node-id) new-override-node-id (next-node-id ctx graph-id) new-override-node (in/make-override-node override-id new-override-node-id node-id {})] (-> ctx (ctx-add-node new-override-node) (ctx-override-node node-id new-override-node-id)))))) ctx node-ids)) (defn- populate-overrides [ctx node-id] (let [basis (:basis ctx) override-nodes (ig/get-overrides basis node-id)] (reduce (fn [ctx override-node-id] (let [override-id (node-id->override-id basis override-node-id) override (ig/override-by-id basis override-id) traverse-fn (:traverse-fn override) node-ids (subvec (ig/pre-traverse basis [node-id] traverse-fn) 1)] (reduce populate-overrides (ctx-make-override-nodes ctx override-id node-ids) override-nodes))) ctx override-nodes))) (defmethod perform :transfer-overrides [ctx {:keys [from-id->to-id]}] (let [basis (:basis ctx) from-id->override-node-ids (into {} (map (juxt identity (partial ig/get-overrides basis))) (keys from-id->to-id)) ; "first level" override nodes override-node-ids (into #{} cat (vals from-id->override-node-ids)) retained override-node-ids override-node-id->override-id (into {} (map (fn [override-node-id] [override-node-id (gt/override-id (gt/node-by-id-at basis override-node-id))])) override-node-ids) override-id->override (into {} (map (fn [[_ override-id]] [override-id (ig/override-by-id basis override-id)])) override-node-id->override-id) override-node-id->override (comp override-id->override override-node-id->override-id) overrides-to-fix (into '() (filter (fn [[_ override]] (contains? from-id->to-id (:root-id override)))) override-id->override) nodes-to-delete (into '() (comp (mapcat (fn [override-node-id] (let [override (override-node-id->override override-node-id) traverse-fn (:traverse-fn override) node-ids-from-override (ig/pre-traverse basis [override-node-id] traverse-fn)] node-ids-from-override))) (remove retained)) override-node-ids)] (-> ctx (update :basis (fn [basis] (reduce (fn [basis from-node-id] (gt/override-node-clear basis from-node-id)) basis (keys from-id->to-id)))) ; from nodes no longer have any override nodes (update :basis (fn [basis] (reduce (fn [basis [override-id override]] (gt/replace-override basis override-id (update override :root-id from-id->to-id))) basis overrides-to-fix))) ; re-root overrides that used to have a from node id as root ((partial reduce ctx-delete-node) nodes-to-delete) ;; * repoint the first level override nodes to use to-node as original ;; * add as override nodes of to-node ((partial reduce (fn [ctx override-node-id] (let [basis (:basis ctx) override-node (gt/node-by-id-at basis override-node-id) old-original (gt/original override-node) new-original (from-id->to-id old-original) [new-basis new-node] (gt/replace-node basis override-node-id (gt/set-original override-node new-original))] (-> ctx (assoc :basis new-basis) (mark-all-outputs-activated override-node-id) (ctx-override-node new-original override-node-id))))) override-node-ids) ((partial reduce populate-overrides) (vals from-id->to-id))))) (defn- property-default-setter [basis node-id node property _ new-value] (first (gt/replace-node basis node-id (gt/set-property node basis property new-value)))) (defn- call-setter-fn [ctx property setter-fn basis node-id old-value new-value] (try (let [tx-data-context (:tx-data-context ctx) setter-actions (setter-fn (in/custom-evaluation-context {:basis basis :tx-data-context tx-data-context}) node-id old-value new-value)] (when *tx-debug* (println (txerrstr ctx "setter actions" (seq setter-actions)))) setter-actions) (catch clojure.lang.ArityException ae (when *tx-debug* (println "ArityException while inside " setter-fn " on node " node-id " with " old-value new-value (:node-type (gt/node-by-id-at basis node-id)))) (throw ae)) (catch Exception e (let [node-type (:name @(:node-type (gt/node-by-id-at basis node-id)))] (throw (Exception. (format "Setter of node %s (%s) %s could not be called" node-id node-type property) e)))))) (defn- invoke-setter [ctx node-id node property old-value new-value override-node? dynamic?] (let [basis (:basis ctx) node-type (gt/node-type node basis) value-type (some-> (in/property-type node-type property) deref in/schema s/maybe)] (if-let [validation-error (and in/*check-schemas* value-type (s/check value-type new-value))] (do (in/warn-output-schema node-id node-type property new-value value-type validation-error) (throw (ex-info "SCHEMA-VALIDATION" {:node-id node-id :type node-type :property property :expected value-type :actual new-value :validation-error validation-error}))) (let [setter-fn (in/property-setter node-type property)] (-> ctx (update :basis property-default-setter node-id node property old-value new-value) (cond-> (not= old-value new-value) (cond-> (not override-node?) (mark-output-activated node-id property) override-node? (mark-outputs-activated node-id (cond-> (if dynamic? [property :_properties] [property]) (not (gt/property-overridden? node property)) (conj :_overridden-properties))) (not (nil? setter-fn)) ((fn [ctx] (apply-tx ctx (call-setter-fn ctx property setter-fn (:basis ctx) node-id old-value new-value))))))))))) (defn- apply-defaults [ctx node] (let [node-id (gt/node-id node) override-node? (some? (gt/original node))] (loop [ctx ctx props (seq (in/declared-property-labels (gt/node-type node (:basis ctx))))] (if-let [prop (first props)] (let [ctx (if-let [v (get node prop)] (invoke-setter ctx node-id node prop nil v override-node? false) ctx)] (recur ctx (rest props))) ctx)))) (defn- ctx-add-node [ctx node] (let [[basis-after full-node] (gt/add-node (:basis ctx) node) node-id (gt/node-id full-node)] (-> ctx (assoc :basis basis-after) (apply-defaults node) (update :nodes-added conj node-id) (assoc-in [:successors-changed node-id] nil) (mark-all-outputs-activated node-id)))) (defmethod perform :create-node [ctx {:keys [node]}] (when (and *tx-debug* (nil? (gt/node-id node))) (println "NIL NODE ID: " node)) (ctx-add-node ctx node)) (defmethod perform :update-property [ctx {:keys [node-id property fn args] :as tx-step}] (let [basis (:basis ctx)] (when (and *tx-debug* (nil? node-id)) (println "NIL NODE ID: update-property " tx-step)) (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [;; Fetch the node value by either evaluating (value ...) for the property or looking in the node map ;; The context is intentionally bare, i.e. only :basis, for this reason old-value (in/node-property-value* node property (in/custom-evaluation-context {:basis basis})) new-value (apply fn old-value args) override-node? (some? (gt/original node)) dynamic? (not (contains? (some-> (gt/node-type node basis) in/all-properties) property))] (invoke-setter ctx node-id node property old-value new-value override-node? dynamic?)) ctx))) (defn- ctx-set-property-to-nil [ctx node-id node property] (let [basis (:basis ctx) old-value (gt/get-property node basis property) node-type (gt/node-type node basis)] (if-let [setter-fn (in/property-setter node-type property)] (apply-tx ctx (call-setter-fn ctx property setter-fn basis node-id old-value nil)) ctx))) (defmethod perform :clear-property [ctx {:keys [node-id property]}] (let [basis (:basis ctx)] (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [dynamic? (not (contains? (some-> (gt/node-type node basis) in/all-properties) property))] (-> ctx (mark-outputs-activated node-id (cond-> (if dynamic? [property :_properties] [property]) (and (gt/original node) (gt/property-overridden? node property)) (conj :_overridden-properties))) (update :basis replace-node node-id (gt/clear-property node basis property)) (ctx-set-property-to-nil node-id node property))) ctx))) (defmethod perform :callback [ctx {:keys [fn args]}] (apply fn args) ctx) (defn- ctx-disconnect-single [ctx target target-id target-label] (if (= :one (in/input-cardinality (gt/node-type target (:basis ctx)) target-label)) (disconnect-inputs ctx target-id target-label) ctx)) (defn- ctx-add-overrides [ctx source-id source source-label target target-label] (let [basis (:basis ctx) target-id (gt/node-id target)] (if ((in/cascade-deletes (gt/node-type target basis)) target-label) (populate-overrides ctx target-id) ctx))) (defn- assert-type-compatible [basis source-id source-node source-label target-id target-node target-label] (let [output-nodetype (gt/node-type source-node basis) output-valtype (in/output-type output-nodetype source-label) input-nodetype (gt/node-type target-node basis) input-valtype (in/input-type input-nodetype target-label)] (assert output-valtype (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s does not have an output or property named %s" source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (in/type-name output-nodetype) source-label)) (assert input-valtype (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s does not have an input named %s" source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (in/type-name input-nodetype) target-label)) (assert (in/type-compatible? output-valtype input-valtype) (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s and %s are not have compatible types." source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (:k output-valtype) (:k input-valtype))))) (defn- ctx-connect [ctx source-id source-label target-id target-label] (if-let [source (gt/node-by-id-at (:basis ctx) source-id)] ; nil if source node was deleted in this transaction (if-let [target (gt/node-by-id-at (:basis ctx) target-id)] ; nil if target node was deleted in this transaction (do (assert-type-compatible (:basis ctx) source-id source source-label target-id target target-label) (-> ctx ; If the input has :one cardinality, disconnect existing connections first (ctx-disconnect-single target target-id target-label) (mark-input-activated target-id target-label) (update :basis gt/connect source-id source-label target-id target-label) (flag-successors-changed [[source-id source-label]]) (ctx-add-overrides source-id source source-label target target-label))) ctx) ctx)) (defmethod perform :connect [ctx {:keys [source-id source-label target-id target-label] :as tx-data}] (ctx-connect ctx source-id source-label target-id target-label)) (defn- ctx-remove-overrides [ctx source-id source-label target-id target-label] (let [basis (:basis ctx) target (gt/node-by-id-at basis target-id)] (if (contains? (in/cascade-deletes (gt/node-type target basis)) target-label) (let [source-override-nodes (map (partial gt/node-by-id-at basis) (ig/get-overrides basis source-id))] (loop [target-override-node-ids (ig/get-overrides basis target-id) ctx ctx] (if-let [target-override-id (first target-override-node-ids)] (let [basis (:basis ctx) target-override-node (gt/node-by-id-at basis target-override-id) target-override-id (gt/override-id target-override-node) source-override-nodes-in-target-override (filter #(= target-override-id (gt/override-id %)) source-override-nodes) traverse-fn (ig/override-traverse-fn basis target-override-id) to-delete (ig/pre-traverse basis (mapv gt/node-id source-override-nodes-in-target-override) traverse-fn)] (recur (rest target-override-node-ids) (reduce ctx-delete-node ctx to-delete))) ctx))) ctx))) (defn- ctx-disconnect [ctx source-id source-label target-id target-label] (-> ctx (mark-input-activated target-id target-label) (update :basis gt/disconnect source-id source-label target-id target-label) (flag-successors-changed [[source-id source-label]]) (ctx-remove-overrides source-id source-label target-id target-label))) (defmethod perform :disconnect [ctx {:keys [source-id source-label target-id target-label]}] (ctx-disconnect ctx source-id source-label target-id target-label)) (defmethod perform :update-graph-value [ctx {:keys [graph-id fn args]}] (-> ctx (update-in [:basis :graphs graph-id :graph-values] #(apply fn % args)) (update :graphs-modified conj graph-id))) (defmethod perform :label [ctx {:keys [label]}] (assoc ctx :label label)) (defmethod perform :sequence-label [ctx {:keys [label]}] (assoc ctx :sequence-label label)) (defmethod perform :invalidate [ctx {:keys [node-id] :as tx-data}] (if (gt/node-by-id-at (:basis ctx) node-id) (mark-all-outputs-activated ctx node-id) ctx)) (defn- apply-tx [ctx actions] (loop [ctx ctx actions actions] (if (seq actions) (if-let [action (first actions)] (if (sequential? action) (recur (apply-tx ctx action) (next actions)) (recur (update (try (perform ctx action) (catch Exception e (when *tx-debug* (println (txerrstr ctx "Transaction failed on " action))) (throw e))) :completed conj action) (next actions))) (recur ctx (next actions))) ctx))) (defn- mark-nodes-modified [{:keys [nodes-affected] :as ctx}] (assoc ctx :nodes-modified (set (keys nodes-affected)))) (defn- map-vals-bargs [m f] (util/map-vals f m)) (defn- apply-tx-label [{:keys [basis label sequence-label] :as ctx}] (cond-> (update-in ctx [:basis :graphs] map-vals-bargs #(assoc % :tx-sequence-label sequence-label)) label (update-in [:basis :graphs] map-vals-bargs #(assoc % :tx-label label)))) (def tx-report-keys [:basis :graphs-modified :nodes-added :nodes-modified :nodes-deleted :outputs-modified :label :sequence-label]) (defn- finalize-update "Makes the transacted graph the new value of the world-state graph." [{:keys [nodes-modified graphs-modified] :as ctx}] (-> (select-keys ctx tx-report-keys) (assoc :status (if (empty? (:completed ctx)) :empty :ok) :graphs-modified (into graphs-modified (map gt/node-id->graph-id nodes-modified))))) (defn new-transaction-context [basis node-id-generators override-id-generator] {:basis basis :nodes-affected {} :nodes-added [] :nodes-modified #{} :nodes-deleted {} :outputs-modified #{} :graphs-modified #{} :successors-changed {} :node-id-generators node-id-generators :override-id-generator override-id-generator :completed [] :txid (new-txid) :tx-data-context (atom {}) :deferred-setters []}) (defn- update-successors [{:keys [successors-changed] :as ctx}] (update ctx :basis ig/update-successors successors-changed)) (defn- trace-dependencies [ctx] ;; at this point, :outputs-modified contains [node-id output] pairs. ;; afterwards, it will have the transitive closure of all [node-id output] pairs ;; reachable from the original collection. (let [outputs-modified (->> (:nodes-affected ctx) (gt/dependencies (:basis ctx)) (into [] (mapcat (fn [[nid ls]] (mapv #(vector nid %) ls)))))] (assoc ctx :outputs-modified outputs-modified))) (defn transact* [ctx actions] (when *tx-debug* (println (txerrstr ctx "actions" (seq actions)))) (-> ctx (apply-tx actions) mark-nodes-modified update-successors trace-dependencies apply-tx-label finalize-update))
35255
;; 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.transaction "Internal functions that implement the transactional behavior." (:require [clojure.set :as set] [clojure.string :as str] [internal.util :as util] [internal.graph :as ig] [internal.graph.types :as gt] [internal.node :as in] [internal.system :as is] [schema.core :as s])) (set! *warn-on-reflection* true) ;; --------------------------------------------------------------------------- ;; Configuration parameters ;; --------------------------------------------------------------------------- (def maximum-retrigger-count 100) (def maximum-graph-coloring-recursion 1000) ;; --------------------------------------------------------------------------- ;; Internal state ;; --------------------------------------------------------------------------- (def ^:dynamic *tx-debug* nil) (def ^:private ^java.util.concurrent.atomic.AtomicInteger next-txid (java.util.concurrent.atomic.AtomicInteger. 1)) (defn- new-txid [] (.getAndIncrement next-txid)) (defmacro txerrstr [ctx & rest] `(str (:txid ~ctx) ": " ~@(interpose " " rest))) ;; --------------------------------------------------------------------------- ;; Building transactions ;; --------------------------------------------------------------------------- (defn new-node "*transaction step* - add a node to a graph" [node] [{:type :create-node :node node}]) (defn delete-node [node-id] [{:type :delete-node :node-id node-id}]) (defn- new-override [override-id root-id traverse-fn] [{:type :new-override :override-id override-id :root-id root-id :traverse-fn traverse-fn}]) (defn- override-node [original-node-id override-node-id] [{:type :override-node :original-node-id original-node-id :override-node-id override-node-id}]) (defn override [root-id traverse-fn init-fn properties-by-node-id] [{:type :override :root-id root-id :traverse-fn traverse-fn :init-fn init-fn :properties-by-node-id properties-by-node-id}]) (defn transfer-overrides [from-id->to-id] [{:type :transfer-overrides :from-id->to-id from-id->to-id}]) (defn update-property "*transaction step* - Expects a node, a property label, and a function f (with optional args) to be performed on the current value of the property." [node-id pr f args] [{:type :update-property :node-id node-id :property pr :fn f :args args}]) (defn clear-property [node-id pr] [{:type :clear-property :node-id node-id :property pr}]) (defn update-graph-value [graph-id f args] [{:type :update-graph-value :graph-id graph-id :fn f :args args}]) (defn callback [f args] [{:type :callback :fn f :args args}]) (defn connect "*transaction step* - Creates a transaction step connecting a source node and label and a target node and label. It returns a value suitable for consumption by [[perform]]." [source-id source-label target-id target-label] [{:type :connect :source-id source-id :source-label source-label :target-id target-id :target-label target-label}]) (defn disconnect "*transaction step* - The reverse of [[connect]]. Creates a transaction step disconnecting a source node and label from a target node and label. It returns a value suitable for consumption by [[perform]]." [source-id source-label target-id target-label] [{:type :disconnect :source-id source-id :source-label source-label :target-id target-id :target-label target-label}]) (defn disconnect-sources [basis target-id target-label] (for [[source-id source-label] (gt/sources basis target-id target-label)] (disconnect source-id source-label target-id target-label))) (defn label [label] [{:type :label :label label}]) (defn sequence-label [seq-label] [{:type :sequence-label :label seq-label}]) (defn invalidate [node-id] [{:type :invalidate :node-id node-id}]) ;; --------------------------------------------------------------------------- ;; Executing transactions ;; --------------------------------------------------------------------------- (defn- mark-input-activated [ctx node-id input-label] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (let [basis (:basis ctx) dirty-deps (-> (gt/node-by-id-at basis node-id) (gt/node-type basis) in/input-dependencies (get input-label))] (update ctx :nodes-affected assoc node-id (reduce conj nodes-affected dirty-deps))) ctx)) (defn- mark-output-activated [ctx node-id output-label] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (update ctx :nodes-affected assoc node-id (conj nodes-affected output-label)) ctx)) (defn- mark-outputs-activated [ctx node-id output-labels] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (update ctx :nodes-affected assoc node-id (reduce conj nodes-affected output-labels)) ctx)) (defn- mark-all-outputs-activated [ctx node-id] (let [basis (:basis ctx) all-labels (-> (gt/node-by-id-at basis node-id) (gt/node-type basis) in/output-labels)] (update ctx :nodes-affected assoc node-id (set all-labels)))) (defn- next-node-id [ctx graph-id] (is/next-node-id* (:node-id-generators ctx) graph-id)) (defn- next-override-id [ctx graph-id] (is/next-override-id* (:override-id-generator ctx) graph-id)) (defmulti perform "A multimethod used for defining methods that perform the individual actions within a transaction. This is for internal use, not intended to be extended by applications. Perform takes a transaction context (ctx) and a map (m) containing a value for keyword `:type`, and other keys and values appropriate to the transformation it represents. Callers should regard the map and context as opaque. Calls to perform are only executed by [[transact]]. The data required for `perform` calls are constructed in action functions, such as [[connect]] and [[update-property]]." (fn [ctx m] (:type m))) (def ^:private ctx-disconnect) (defn- ctx-disconnect-arc [ctx arc] (let [[source-id source-label] (gt/source arc) [target-id target-label] (gt/target arc)] (ctx-disconnect ctx source-id source-label target-id target-label))) (defn- disconnect-inputs [ctx target-id target-label] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-target (:basis ctx) target-id target-label))) (defn- disconnect-all-inputs [ctx target-id] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-target (:basis ctx) target-id))) (defn- disconnect-outputs [ctx source-id source-label] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-source (:basis ctx) source-id source-label))) (defn- disconnect-stale [ctx node-id old-node new-node labels-fn disconnect-fn] (let [basis (:basis ctx) stale-labels (set/difference (-> old-node (gt/node-type basis) labels-fn) (-> new-node (gt/node-type basis) labels-fn))] (loop [ctx ctx labels stale-labels] (if-let [label (first labels)] (recur (disconnect-fn ctx node-id label) (rest labels)) ctx)))) (defn- disconnect-stale-inputs [ctx node-id old-node new-node] (disconnect-stale ctx node-id old-node new-node in/input-labels disconnect-inputs)) (defn- disconnect-stale-outputs [ctx node-id old-node new-node] (disconnect-stale ctx node-id old-node new-node in/output-labels disconnect-outputs)) (def ^:private replace-node (comp first gt/replace-node)) (defn- delete-single [ctx node-id] (let [basis (:basis ctx)] (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [targets (ig/explicit-targets basis node-id)] (-> (reduce (fn [ctx [node-id input]] (mark-input-activated ctx node-id input)) ctx targets) (disconnect-all-inputs node-id) (mark-all-outputs-activated node-id) (update :basis gt/delete-node node-id) (assoc-in [:nodes-deleted node-id] node) (update :nodes-added (partial filterv #(not= node-id %))))) ctx))) (defn- ctx-delete-node [ctx node-id] (when *tx-debug* (println (txerrstr ctx "deleting " node-id))) (let [to-delete (ig/pre-traverse (:basis ctx) [node-id] ig/cascade-delete-sources)] (when (and *tx-debug* (not (empty? to-delete))) (println (txerrstr ctx "cascading delete of " (pr-str to-delete)))) (reduce delete-single ctx to-delete))) (defmethod perform :delete-node [ctx {:keys [node-id]}] (ctx-delete-node ctx node-id)) (defmethod perform :new-override [ctx {:keys [override-id root-id traverse-fn]}] (-> ctx (update :basis gt/add-override override-id (ig/make-override root-id traverse-fn)))) (defn- flag-all-successors-changed [ctx node-ids] (let [successors (get ctx :successors-changed)] (assoc ctx :successors-changed (reduce (fn [successors node-id] (assoc successors node-id nil)) successors node-ids)))) (defn- flag-successors-changed [ctx changes] (let [successors (get ctx :successors-changed)] (assoc ctx :successors-changed (reduce (fn [successors [node-id label]] (if-let [node-succ (get successors node-id #{})] (assoc successors node-id (conj node-succ label)) successors)) successors changes)))) (defn- ctx-override-node [ctx original-node-id override-node-id] (assert (= (gt/node-id->graph-id original-node-id) (gt/node-id->graph-id override-node-id)) "Override nodes must belong to the same graph as the original") (let [basis (:basis ctx) original (gt/node-by-id-at basis original-node-id) all-originals (ig/override-originals basis original-node-id)] (-> ctx (update :basis gt/override-node original-node-id override-node-id) (flag-all-successors-changed all-originals) (flag-successors-changed (mapcat #(gt/sources basis %) all-originals))))) (defmethod perform :override-node [ctx {:keys [original-node-id override-node-id]}] (ctx-override-node ctx original-node-id override-node-id)) (declare apply-tx) (defmethod perform :override [ctx {:keys [root-id traverse-fn init-fn properties-by-node-id]}] (let [basis (:basis ctx) graph-id (gt/node-id->graph-id root-id) node-ids (ig/pre-traverse basis [root-id] traverse-fn) override-id (next-override-id ctx graph-id) override-nodes (mapv #(in/make-override-node override-id (next-node-id ctx graph-id) % (properties-by-node-id %)) node-ids) override-node-ids (map gt/node-id override-nodes) original-node-id->override-node-id (zipmap node-ids override-node-ids) new-override-nodes-tx-data (map new-node override-nodes) new-override-tx-data (concat (new-override override-id root-id traverse-fn) (map (fn [node-id override-node-id] (override-node node-id override-node-id)) node-ids override-node-ids))] (as-> ctx ctx' (apply-tx ctx' (concat new-override-nodes-tx-data new-override-tx-data)) (apply-tx ctx' (init-fn (in/custom-evaluation-context {:basis (:basis ctx')}) original-node-id->override-node-id))))) (defn- node-id->override-id [basis node-id] (->> node-id (gt/node-by-id-at basis) gt/override-id)) (declare ctx-add-node) (defn- ctx-make-override-nodes [ctx override-id node-ids] (reduce (fn [ctx node-id] (let [basis (:basis ctx)] (if (some #(= override-id (node-id->override-id basis %)) (ig/get-overrides basis node-id)) ctx (let [graph-id (gt/node-id->graph-id node-id) new-override-node-id (next-node-id ctx graph-id) new-override-node (in/make-override-node override-id new-override-node-id node-id {})] (-> ctx (ctx-add-node new-override-node) (ctx-override-node node-id new-override-node-id)))))) ctx node-ids)) (defn- populate-overrides [ctx node-id] (let [basis (:basis ctx) override-nodes (ig/get-overrides basis node-id)] (reduce (fn [ctx override-node-id] (let [override-id (node-id->override-id basis override-node-id) override (ig/override-by-id basis override-id) traverse-fn (:traverse-fn override) node-ids (subvec (ig/pre-traverse basis [node-id] traverse-fn) 1)] (reduce populate-overrides (ctx-make-override-nodes ctx override-id node-ids) override-nodes))) ctx override-nodes))) (defmethod perform :transfer-overrides [ctx {:keys [from-id->to-id]}] (let [basis (:basis ctx) from-id->override-node-ids (into {} (map (juxt identity (partial ig/get-overrides basis))) (keys from-id->to-id)) ; "first level" override nodes override-node-ids (into #{} cat (vals from-id->override-node-ids)) retained override-node-ids override-node-id->override-id (into {} (map (fn [override-node-id] [override-node-id (gt/override-id (gt/node-by-id-at basis override-node-id))])) override-node-ids) override-id->override (into {} (map (fn [[_ override-id]] [override-id (ig/override-by-id basis override-id)])) override-node-id->override-id) override-node-id->override (comp override-id->override override-node-id->override-id) overrides-to-fix (into '() (filter (fn [[_ override]] (contains? from-id->to-id (:root-id override)))) override-id->override) nodes-to-delete (into '() (comp (mapcat (fn [override-node-id] (let [override (override-node-id->override override-node-id) traverse-fn (:traverse-fn override) node-ids-from-override (ig/pre-traverse basis [override-node-id] traverse-fn)] node-ids-from-override))) (remove retained)) override-node-ids)] (-> ctx (update :basis (fn [basis] (reduce (fn [basis from-node-id] (gt/override-node-clear basis from-node-id)) basis (keys from-id->to-id)))) ; from nodes no longer have any override nodes (update :basis (fn [basis] (reduce (fn [basis [override-id override]] (gt/replace-override basis override-id (update override :root-id from-id->to-id))) basis overrides-to-fix))) ; re-root overrides that used to have a from node id as root ((partial reduce ctx-delete-node) nodes-to-delete) ;; * repoint the first level override nodes to use to-node as original ;; * add as override nodes of to-node ((partial reduce (fn [ctx override-node-id] (let [basis (:basis ctx) override-node (gt/node-by-id-at basis override-node-id) old-original (gt/original override-node) new-original (from-id->to-id old-original) [new-basis new-node] (gt/replace-node basis override-node-id (gt/set-original override-node new-original))] (-> ctx (assoc :basis new-basis) (mark-all-outputs-activated override-node-id) (ctx-override-node new-original override-node-id))))) override-node-ids) ((partial reduce populate-overrides) (vals from-id->to-id))))) (defn- property-default-setter [basis node-id node property _ new-value] (first (gt/replace-node basis node-id (gt/set-property node basis property new-value)))) (defn- call-setter-fn [ctx property setter-fn basis node-id old-value new-value] (try (let [tx-data-context (:tx-data-context ctx) setter-actions (setter-fn (in/custom-evaluation-context {:basis basis :tx-data-context tx-data-context}) node-id old-value new-value)] (when *tx-debug* (println (txerrstr ctx "setter actions" (seq setter-actions)))) setter-actions) (catch clojure.lang.ArityException ae (when *tx-debug* (println "ArityException while inside " setter-fn " on node " node-id " with " old-value new-value (:node-type (gt/node-by-id-at basis node-id)))) (throw ae)) (catch Exception e (let [node-type (:name @(:node-type (gt/node-by-id-at basis node-id)))] (throw (Exception. (format "Setter of node %s (%s) %s could not be called" node-id node-type property) e)))))) (defn- invoke-setter [ctx node-id node property old-value new-value override-node? dynamic?] (let [basis (:basis ctx) node-type (gt/node-type node basis) value-type (some-> (in/property-type node-type property) deref in/schema s/maybe)] (if-let [validation-error (and in/*check-schemas* value-type (s/check value-type new-value))] (do (in/warn-output-schema node-id node-type property new-value value-type validation-error) (throw (ex-info "SCHEMA-VALIDATION" {:node-id node-id :type node-type :property property :expected value-type :actual new-value :validation-error validation-error}))) (let [setter-fn (in/property-setter node-type property)] (-> ctx (update :basis property-default-setter node-id node property old-value new-value) (cond-> (not= old-value new-value) (cond-> (not override-node?) (mark-output-activated node-id property) override-node? (mark-outputs-activated node-id (cond-> (if dynamic? [property :_properties] [property]) (not (gt/property-overridden? node property)) (conj :_overridden-properties))) (not (nil? setter-fn)) ((fn [ctx] (apply-tx ctx (call-setter-fn ctx property setter-fn (:basis ctx) node-id old-value new-value))))))))))) (defn- apply-defaults [ctx node] (let [node-id (gt/node-id node) override-node? (some? (gt/original node))] (loop [ctx ctx props (seq (in/declared-property-labels (gt/node-type node (:basis ctx))))] (if-let [prop (first props)] (let [ctx (if-let [v (get node prop)] (invoke-setter ctx node-id node prop nil v override-node? false) ctx)] (recur ctx (rest props))) ctx)))) (defn- ctx-add-node [ctx node] (let [[basis-after full-node] (gt/add-node (:basis ctx) node) node-id (gt/node-id full-node)] (-> ctx (assoc :basis basis-after) (apply-defaults node) (update :nodes-added conj node-id) (assoc-in [:successors-changed node-id] nil) (mark-all-outputs-activated node-id)))) (defmethod perform :create-node [ctx {:keys [node]}] (when (and *tx-debug* (nil? (gt/node-id node))) (println "NIL NODE ID: " node)) (ctx-add-node ctx node)) (defmethod perform :update-property [ctx {:keys [node-id property fn args] :as tx-step}] (let [basis (:basis ctx)] (when (and *tx-debug* (nil? node-id)) (println "NIL NODE ID: update-property " tx-step)) (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [;; Fetch the node value by either evaluating (value ...) for the property or looking in the node map ;; The context is intentionally bare, i.e. only :basis, for this reason old-value (in/node-property-value* node property (in/custom-evaluation-context {:basis basis})) new-value (apply fn old-value args) override-node? (some? (gt/original node)) dynamic? (not (contains? (some-> (gt/node-type node basis) in/all-properties) property))] (invoke-setter ctx node-id node property old-value new-value override-node? dynamic?)) ctx))) (defn- ctx-set-property-to-nil [ctx node-id node property] (let [basis (:basis ctx) old-value (gt/get-property node basis property) node-type (gt/node-type node basis)] (if-let [setter-fn (in/property-setter node-type property)] (apply-tx ctx (call-setter-fn ctx property setter-fn basis node-id old-value nil)) ctx))) (defmethod perform :clear-property [ctx {:keys [node-id property]}] (let [basis (:basis ctx)] (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [dynamic? (not (contains? (some-> (gt/node-type node basis) in/all-properties) property))] (-> ctx (mark-outputs-activated node-id (cond-> (if dynamic? [property :_properties] [property]) (and (gt/original node) (gt/property-overridden? node property)) (conj :_overridden-properties))) (update :basis replace-node node-id (gt/clear-property node basis property)) (ctx-set-property-to-nil node-id node property))) ctx))) (defmethod perform :callback [ctx {:keys [fn args]}] (apply fn args) ctx) (defn- ctx-disconnect-single [ctx target target-id target-label] (if (= :one (in/input-cardinality (gt/node-type target (:basis ctx)) target-label)) (disconnect-inputs ctx target-id target-label) ctx)) (defn- ctx-add-overrides [ctx source-id source source-label target target-label] (let [basis (:basis ctx) target-id (gt/node-id target)] (if ((in/cascade-deletes (gt/node-type target basis)) target-label) (populate-overrides ctx target-id) ctx))) (defn- assert-type-compatible [basis source-id source-node source-label target-id target-node target-label] (let [output-nodetype (gt/node-type source-node basis) output-valtype (in/output-type output-nodetype source-label) input-nodetype (gt/node-type target-node basis) input-valtype (in/input-type input-nodetype target-label)] (assert output-valtype (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s does not have an output or property named %s" source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (in/type-name output-nodetype) source-label)) (assert input-valtype (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s does not have an input named %s" source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (in/type-name input-nodetype) target-label)) (assert (in/type-compatible? output-valtype input-valtype) (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s and %s are not have compatible types." source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (:k output-valtype) (:k input-valtype))))) (defn- ctx-connect [ctx source-id source-label target-id target-label] (if-let [source (gt/node-by-id-at (:basis ctx) source-id)] ; nil if source node was deleted in this transaction (if-let [target (gt/node-by-id-at (:basis ctx) target-id)] ; nil if target node was deleted in this transaction (do (assert-type-compatible (:basis ctx) source-id source source-label target-id target target-label) (-> ctx ; If the input has :one cardinality, disconnect existing connections first (ctx-disconnect-single target target-id target-label) (mark-input-activated target-id target-label) (update :basis gt/connect source-id source-label target-id target-label) (flag-successors-changed [[source-id source-label]]) (ctx-add-overrides source-id source source-label target target-label))) ctx) ctx)) (defmethod perform :connect [ctx {:keys [source-id source-label target-id target-label] :as tx-data}] (ctx-connect ctx source-id source-label target-id target-label)) (defn- ctx-remove-overrides [ctx source-id source-label target-id target-label] (let [basis (:basis ctx) target (gt/node-by-id-at basis target-id)] (if (contains? (in/cascade-deletes (gt/node-type target basis)) target-label) (let [source-override-nodes (map (partial gt/node-by-id-at basis) (ig/get-overrides basis source-id))] (loop [target-override-node-ids (ig/get-overrides basis target-id) ctx ctx] (if-let [target-override-id (first target-override-node-ids)] (let [basis (:basis ctx) target-override-node (gt/node-by-id-at basis target-override-id) target-override-id (gt/override-id target-override-node) source-override-nodes-in-target-override (filter #(= target-override-id (gt/override-id %)) source-override-nodes) traverse-fn (ig/override-traverse-fn basis target-override-id) to-delete (ig/pre-traverse basis (mapv gt/node-id source-override-nodes-in-target-override) traverse-fn)] (recur (rest target-override-node-ids) (reduce ctx-delete-node ctx to-delete))) ctx))) ctx))) (defn- ctx-disconnect [ctx source-id source-label target-id target-label] (-> ctx (mark-input-activated target-id target-label) (update :basis gt/disconnect source-id source-label target-id target-label) (flag-successors-changed [[source-id source-label]]) (ctx-remove-overrides source-id source-label target-id target-label))) (defmethod perform :disconnect [ctx {:keys [source-id source-label target-id target-label]}] (ctx-disconnect ctx source-id source-label target-id target-label)) (defmethod perform :update-graph-value [ctx {:keys [graph-id fn args]}] (-> ctx (update-in [:basis :graphs graph-id :graph-values] #(apply fn % args)) (update :graphs-modified conj graph-id))) (defmethod perform :label [ctx {:keys [label]}] (assoc ctx :label label)) (defmethod perform :sequence-label [ctx {:keys [label]}] (assoc ctx :sequence-label label)) (defmethod perform :invalidate [ctx {:keys [node-id] :as tx-data}] (if (gt/node-by-id-at (:basis ctx) node-id) (mark-all-outputs-activated ctx node-id) ctx)) (defn- apply-tx [ctx actions] (loop [ctx ctx actions actions] (if (seq actions) (if-let [action (first actions)] (if (sequential? action) (recur (apply-tx ctx action) (next actions)) (recur (update (try (perform ctx action) (catch Exception e (when *tx-debug* (println (txerrstr ctx "Transaction failed on " action))) (throw e))) :completed conj action) (next actions))) (recur ctx (next actions))) ctx))) (defn- mark-nodes-modified [{:keys [nodes-affected] :as ctx}] (assoc ctx :nodes-modified (set (keys nodes-affected)))) (defn- map-vals-bargs [m f] (util/map-vals f m)) (defn- apply-tx-label [{:keys [basis label sequence-label] :as ctx}] (cond-> (update-in ctx [:basis :graphs] map-vals-bargs #(assoc % :tx-sequence-label sequence-label)) label (update-in [:basis :graphs] map-vals-bargs #(assoc % :tx-label label)))) (def tx-report-keys [:basis :graphs-modified :nodes-added :nodes-modified :nodes-deleted :outputs-modified :label :sequence-label]) (defn- finalize-update "Makes the transacted graph the new value of the world-state graph." [{:keys [nodes-modified graphs-modified] :as ctx}] (-> (select-keys ctx tx-report-keys) (assoc :status (if (empty? (:completed ctx)) :empty :ok) :graphs-modified (into graphs-modified (map gt/node-id->graph-id nodes-modified))))) (defn new-transaction-context [basis node-id-generators override-id-generator] {:basis basis :nodes-affected {} :nodes-added [] :nodes-modified #{} :nodes-deleted {} :outputs-modified #{} :graphs-modified #{} :successors-changed {} :node-id-generators node-id-generators :override-id-generator override-id-generator :completed [] :txid (new-txid) :tx-data-context (atom {}) :deferred-setters []}) (defn- update-successors [{:keys [successors-changed] :as ctx}] (update ctx :basis ig/update-successors successors-changed)) (defn- trace-dependencies [ctx] ;; at this point, :outputs-modified contains [node-id output] pairs. ;; afterwards, it will have the transitive closure of all [node-id output] pairs ;; reachable from the original collection. (let [outputs-modified (->> (:nodes-affected ctx) (gt/dependencies (:basis ctx)) (into [] (mapcat (fn [[nid ls]] (mapv #(vector nid %) ls)))))] (assoc ctx :outputs-modified outputs-modified))) (defn transact* [ctx actions] (when *tx-debug* (println (txerrstr ctx "actions" (seq actions)))) (-> ctx (apply-tx actions) mark-nodes-modified update-successors trace-dependencies apply-tx-label finalize-update))
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.transaction "Internal functions that implement the transactional behavior." (:require [clojure.set :as set] [clojure.string :as str] [internal.util :as util] [internal.graph :as ig] [internal.graph.types :as gt] [internal.node :as in] [internal.system :as is] [schema.core :as s])) (set! *warn-on-reflection* true) ;; --------------------------------------------------------------------------- ;; Configuration parameters ;; --------------------------------------------------------------------------- (def maximum-retrigger-count 100) (def maximum-graph-coloring-recursion 1000) ;; --------------------------------------------------------------------------- ;; Internal state ;; --------------------------------------------------------------------------- (def ^:dynamic *tx-debug* nil) (def ^:private ^java.util.concurrent.atomic.AtomicInteger next-txid (java.util.concurrent.atomic.AtomicInteger. 1)) (defn- new-txid [] (.getAndIncrement next-txid)) (defmacro txerrstr [ctx & rest] `(str (:txid ~ctx) ": " ~@(interpose " " rest))) ;; --------------------------------------------------------------------------- ;; Building transactions ;; --------------------------------------------------------------------------- (defn new-node "*transaction step* - add a node to a graph" [node] [{:type :create-node :node node}]) (defn delete-node [node-id] [{:type :delete-node :node-id node-id}]) (defn- new-override [override-id root-id traverse-fn] [{:type :new-override :override-id override-id :root-id root-id :traverse-fn traverse-fn}]) (defn- override-node [original-node-id override-node-id] [{:type :override-node :original-node-id original-node-id :override-node-id override-node-id}]) (defn override [root-id traverse-fn init-fn properties-by-node-id] [{:type :override :root-id root-id :traverse-fn traverse-fn :init-fn init-fn :properties-by-node-id properties-by-node-id}]) (defn transfer-overrides [from-id->to-id] [{:type :transfer-overrides :from-id->to-id from-id->to-id}]) (defn update-property "*transaction step* - Expects a node, a property label, and a function f (with optional args) to be performed on the current value of the property." [node-id pr f args] [{:type :update-property :node-id node-id :property pr :fn f :args args}]) (defn clear-property [node-id pr] [{:type :clear-property :node-id node-id :property pr}]) (defn update-graph-value [graph-id f args] [{:type :update-graph-value :graph-id graph-id :fn f :args args}]) (defn callback [f args] [{:type :callback :fn f :args args}]) (defn connect "*transaction step* - Creates a transaction step connecting a source node and label and a target node and label. It returns a value suitable for consumption by [[perform]]." [source-id source-label target-id target-label] [{:type :connect :source-id source-id :source-label source-label :target-id target-id :target-label target-label}]) (defn disconnect "*transaction step* - The reverse of [[connect]]. Creates a transaction step disconnecting a source node and label from a target node and label. It returns a value suitable for consumption by [[perform]]." [source-id source-label target-id target-label] [{:type :disconnect :source-id source-id :source-label source-label :target-id target-id :target-label target-label}]) (defn disconnect-sources [basis target-id target-label] (for [[source-id source-label] (gt/sources basis target-id target-label)] (disconnect source-id source-label target-id target-label))) (defn label [label] [{:type :label :label label}]) (defn sequence-label [seq-label] [{:type :sequence-label :label seq-label}]) (defn invalidate [node-id] [{:type :invalidate :node-id node-id}]) ;; --------------------------------------------------------------------------- ;; Executing transactions ;; --------------------------------------------------------------------------- (defn- mark-input-activated [ctx node-id input-label] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (let [basis (:basis ctx) dirty-deps (-> (gt/node-by-id-at basis node-id) (gt/node-type basis) in/input-dependencies (get input-label))] (update ctx :nodes-affected assoc node-id (reduce conj nodes-affected dirty-deps))) ctx)) (defn- mark-output-activated [ctx node-id output-label] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (update ctx :nodes-affected assoc node-id (conj nodes-affected output-label)) ctx)) (defn- mark-outputs-activated [ctx node-id output-labels] (if-let [nodes-affected (get-in ctx [:nodes-affected node-id] #{})] (update ctx :nodes-affected assoc node-id (reduce conj nodes-affected output-labels)) ctx)) (defn- mark-all-outputs-activated [ctx node-id] (let [basis (:basis ctx) all-labels (-> (gt/node-by-id-at basis node-id) (gt/node-type basis) in/output-labels)] (update ctx :nodes-affected assoc node-id (set all-labels)))) (defn- next-node-id [ctx graph-id] (is/next-node-id* (:node-id-generators ctx) graph-id)) (defn- next-override-id [ctx graph-id] (is/next-override-id* (:override-id-generator ctx) graph-id)) (defmulti perform "A multimethod used for defining methods that perform the individual actions within a transaction. This is for internal use, not intended to be extended by applications. Perform takes a transaction context (ctx) and a map (m) containing a value for keyword `:type`, and other keys and values appropriate to the transformation it represents. Callers should regard the map and context as opaque. Calls to perform are only executed by [[transact]]. The data required for `perform` calls are constructed in action functions, such as [[connect]] and [[update-property]]." (fn [ctx m] (:type m))) (def ^:private ctx-disconnect) (defn- ctx-disconnect-arc [ctx arc] (let [[source-id source-label] (gt/source arc) [target-id target-label] (gt/target arc)] (ctx-disconnect ctx source-id source-label target-id target-label))) (defn- disconnect-inputs [ctx target-id target-label] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-target (:basis ctx) target-id target-label))) (defn- disconnect-all-inputs [ctx target-id] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-target (:basis ctx) target-id))) (defn- disconnect-outputs [ctx source-id source-label] (reduce ctx-disconnect-arc ctx (ig/explicit-arcs-by-source (:basis ctx) source-id source-label))) (defn- disconnect-stale [ctx node-id old-node new-node labels-fn disconnect-fn] (let [basis (:basis ctx) stale-labels (set/difference (-> old-node (gt/node-type basis) labels-fn) (-> new-node (gt/node-type basis) labels-fn))] (loop [ctx ctx labels stale-labels] (if-let [label (first labels)] (recur (disconnect-fn ctx node-id label) (rest labels)) ctx)))) (defn- disconnect-stale-inputs [ctx node-id old-node new-node] (disconnect-stale ctx node-id old-node new-node in/input-labels disconnect-inputs)) (defn- disconnect-stale-outputs [ctx node-id old-node new-node] (disconnect-stale ctx node-id old-node new-node in/output-labels disconnect-outputs)) (def ^:private replace-node (comp first gt/replace-node)) (defn- delete-single [ctx node-id] (let [basis (:basis ctx)] (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [targets (ig/explicit-targets basis node-id)] (-> (reduce (fn [ctx [node-id input]] (mark-input-activated ctx node-id input)) ctx targets) (disconnect-all-inputs node-id) (mark-all-outputs-activated node-id) (update :basis gt/delete-node node-id) (assoc-in [:nodes-deleted node-id] node) (update :nodes-added (partial filterv #(not= node-id %))))) ctx))) (defn- ctx-delete-node [ctx node-id] (when *tx-debug* (println (txerrstr ctx "deleting " node-id))) (let [to-delete (ig/pre-traverse (:basis ctx) [node-id] ig/cascade-delete-sources)] (when (and *tx-debug* (not (empty? to-delete))) (println (txerrstr ctx "cascading delete of " (pr-str to-delete)))) (reduce delete-single ctx to-delete))) (defmethod perform :delete-node [ctx {:keys [node-id]}] (ctx-delete-node ctx node-id)) (defmethod perform :new-override [ctx {:keys [override-id root-id traverse-fn]}] (-> ctx (update :basis gt/add-override override-id (ig/make-override root-id traverse-fn)))) (defn- flag-all-successors-changed [ctx node-ids] (let [successors (get ctx :successors-changed)] (assoc ctx :successors-changed (reduce (fn [successors node-id] (assoc successors node-id nil)) successors node-ids)))) (defn- flag-successors-changed [ctx changes] (let [successors (get ctx :successors-changed)] (assoc ctx :successors-changed (reduce (fn [successors [node-id label]] (if-let [node-succ (get successors node-id #{})] (assoc successors node-id (conj node-succ label)) successors)) successors changes)))) (defn- ctx-override-node [ctx original-node-id override-node-id] (assert (= (gt/node-id->graph-id original-node-id) (gt/node-id->graph-id override-node-id)) "Override nodes must belong to the same graph as the original") (let [basis (:basis ctx) original (gt/node-by-id-at basis original-node-id) all-originals (ig/override-originals basis original-node-id)] (-> ctx (update :basis gt/override-node original-node-id override-node-id) (flag-all-successors-changed all-originals) (flag-successors-changed (mapcat #(gt/sources basis %) all-originals))))) (defmethod perform :override-node [ctx {:keys [original-node-id override-node-id]}] (ctx-override-node ctx original-node-id override-node-id)) (declare apply-tx) (defmethod perform :override [ctx {:keys [root-id traverse-fn init-fn properties-by-node-id]}] (let [basis (:basis ctx) graph-id (gt/node-id->graph-id root-id) node-ids (ig/pre-traverse basis [root-id] traverse-fn) override-id (next-override-id ctx graph-id) override-nodes (mapv #(in/make-override-node override-id (next-node-id ctx graph-id) % (properties-by-node-id %)) node-ids) override-node-ids (map gt/node-id override-nodes) original-node-id->override-node-id (zipmap node-ids override-node-ids) new-override-nodes-tx-data (map new-node override-nodes) new-override-tx-data (concat (new-override override-id root-id traverse-fn) (map (fn [node-id override-node-id] (override-node node-id override-node-id)) node-ids override-node-ids))] (as-> ctx ctx' (apply-tx ctx' (concat new-override-nodes-tx-data new-override-tx-data)) (apply-tx ctx' (init-fn (in/custom-evaluation-context {:basis (:basis ctx')}) original-node-id->override-node-id))))) (defn- node-id->override-id [basis node-id] (->> node-id (gt/node-by-id-at basis) gt/override-id)) (declare ctx-add-node) (defn- ctx-make-override-nodes [ctx override-id node-ids] (reduce (fn [ctx node-id] (let [basis (:basis ctx)] (if (some #(= override-id (node-id->override-id basis %)) (ig/get-overrides basis node-id)) ctx (let [graph-id (gt/node-id->graph-id node-id) new-override-node-id (next-node-id ctx graph-id) new-override-node (in/make-override-node override-id new-override-node-id node-id {})] (-> ctx (ctx-add-node new-override-node) (ctx-override-node node-id new-override-node-id)))))) ctx node-ids)) (defn- populate-overrides [ctx node-id] (let [basis (:basis ctx) override-nodes (ig/get-overrides basis node-id)] (reduce (fn [ctx override-node-id] (let [override-id (node-id->override-id basis override-node-id) override (ig/override-by-id basis override-id) traverse-fn (:traverse-fn override) node-ids (subvec (ig/pre-traverse basis [node-id] traverse-fn) 1)] (reduce populate-overrides (ctx-make-override-nodes ctx override-id node-ids) override-nodes))) ctx override-nodes))) (defmethod perform :transfer-overrides [ctx {:keys [from-id->to-id]}] (let [basis (:basis ctx) from-id->override-node-ids (into {} (map (juxt identity (partial ig/get-overrides basis))) (keys from-id->to-id)) ; "first level" override nodes override-node-ids (into #{} cat (vals from-id->override-node-ids)) retained override-node-ids override-node-id->override-id (into {} (map (fn [override-node-id] [override-node-id (gt/override-id (gt/node-by-id-at basis override-node-id))])) override-node-ids) override-id->override (into {} (map (fn [[_ override-id]] [override-id (ig/override-by-id basis override-id)])) override-node-id->override-id) override-node-id->override (comp override-id->override override-node-id->override-id) overrides-to-fix (into '() (filter (fn [[_ override]] (contains? from-id->to-id (:root-id override)))) override-id->override) nodes-to-delete (into '() (comp (mapcat (fn [override-node-id] (let [override (override-node-id->override override-node-id) traverse-fn (:traverse-fn override) node-ids-from-override (ig/pre-traverse basis [override-node-id] traverse-fn)] node-ids-from-override))) (remove retained)) override-node-ids)] (-> ctx (update :basis (fn [basis] (reduce (fn [basis from-node-id] (gt/override-node-clear basis from-node-id)) basis (keys from-id->to-id)))) ; from nodes no longer have any override nodes (update :basis (fn [basis] (reduce (fn [basis [override-id override]] (gt/replace-override basis override-id (update override :root-id from-id->to-id))) basis overrides-to-fix))) ; re-root overrides that used to have a from node id as root ((partial reduce ctx-delete-node) nodes-to-delete) ;; * repoint the first level override nodes to use to-node as original ;; * add as override nodes of to-node ((partial reduce (fn [ctx override-node-id] (let [basis (:basis ctx) override-node (gt/node-by-id-at basis override-node-id) old-original (gt/original override-node) new-original (from-id->to-id old-original) [new-basis new-node] (gt/replace-node basis override-node-id (gt/set-original override-node new-original))] (-> ctx (assoc :basis new-basis) (mark-all-outputs-activated override-node-id) (ctx-override-node new-original override-node-id))))) override-node-ids) ((partial reduce populate-overrides) (vals from-id->to-id))))) (defn- property-default-setter [basis node-id node property _ new-value] (first (gt/replace-node basis node-id (gt/set-property node basis property new-value)))) (defn- call-setter-fn [ctx property setter-fn basis node-id old-value new-value] (try (let [tx-data-context (:tx-data-context ctx) setter-actions (setter-fn (in/custom-evaluation-context {:basis basis :tx-data-context tx-data-context}) node-id old-value new-value)] (when *tx-debug* (println (txerrstr ctx "setter actions" (seq setter-actions)))) setter-actions) (catch clojure.lang.ArityException ae (when *tx-debug* (println "ArityException while inside " setter-fn " on node " node-id " with " old-value new-value (:node-type (gt/node-by-id-at basis node-id)))) (throw ae)) (catch Exception e (let [node-type (:name @(:node-type (gt/node-by-id-at basis node-id)))] (throw (Exception. (format "Setter of node %s (%s) %s could not be called" node-id node-type property) e)))))) (defn- invoke-setter [ctx node-id node property old-value new-value override-node? dynamic?] (let [basis (:basis ctx) node-type (gt/node-type node basis) value-type (some-> (in/property-type node-type property) deref in/schema s/maybe)] (if-let [validation-error (and in/*check-schemas* value-type (s/check value-type new-value))] (do (in/warn-output-schema node-id node-type property new-value value-type validation-error) (throw (ex-info "SCHEMA-VALIDATION" {:node-id node-id :type node-type :property property :expected value-type :actual new-value :validation-error validation-error}))) (let [setter-fn (in/property-setter node-type property)] (-> ctx (update :basis property-default-setter node-id node property old-value new-value) (cond-> (not= old-value new-value) (cond-> (not override-node?) (mark-output-activated node-id property) override-node? (mark-outputs-activated node-id (cond-> (if dynamic? [property :_properties] [property]) (not (gt/property-overridden? node property)) (conj :_overridden-properties))) (not (nil? setter-fn)) ((fn [ctx] (apply-tx ctx (call-setter-fn ctx property setter-fn (:basis ctx) node-id old-value new-value))))))))))) (defn- apply-defaults [ctx node] (let [node-id (gt/node-id node) override-node? (some? (gt/original node))] (loop [ctx ctx props (seq (in/declared-property-labels (gt/node-type node (:basis ctx))))] (if-let [prop (first props)] (let [ctx (if-let [v (get node prop)] (invoke-setter ctx node-id node prop nil v override-node? false) ctx)] (recur ctx (rest props))) ctx)))) (defn- ctx-add-node [ctx node] (let [[basis-after full-node] (gt/add-node (:basis ctx) node) node-id (gt/node-id full-node)] (-> ctx (assoc :basis basis-after) (apply-defaults node) (update :nodes-added conj node-id) (assoc-in [:successors-changed node-id] nil) (mark-all-outputs-activated node-id)))) (defmethod perform :create-node [ctx {:keys [node]}] (when (and *tx-debug* (nil? (gt/node-id node))) (println "NIL NODE ID: " node)) (ctx-add-node ctx node)) (defmethod perform :update-property [ctx {:keys [node-id property fn args] :as tx-step}] (let [basis (:basis ctx)] (when (and *tx-debug* (nil? node-id)) (println "NIL NODE ID: update-property " tx-step)) (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [;; Fetch the node value by either evaluating (value ...) for the property or looking in the node map ;; The context is intentionally bare, i.e. only :basis, for this reason old-value (in/node-property-value* node property (in/custom-evaluation-context {:basis basis})) new-value (apply fn old-value args) override-node? (some? (gt/original node)) dynamic? (not (contains? (some-> (gt/node-type node basis) in/all-properties) property))] (invoke-setter ctx node-id node property old-value new-value override-node? dynamic?)) ctx))) (defn- ctx-set-property-to-nil [ctx node-id node property] (let [basis (:basis ctx) old-value (gt/get-property node basis property) node-type (gt/node-type node basis)] (if-let [setter-fn (in/property-setter node-type property)] (apply-tx ctx (call-setter-fn ctx property setter-fn basis node-id old-value nil)) ctx))) (defmethod perform :clear-property [ctx {:keys [node-id property]}] (let [basis (:basis ctx)] (if-let [node (gt/node-by-id-at basis node-id)] ; nil if node was deleted in this transaction (let [dynamic? (not (contains? (some-> (gt/node-type node basis) in/all-properties) property))] (-> ctx (mark-outputs-activated node-id (cond-> (if dynamic? [property :_properties] [property]) (and (gt/original node) (gt/property-overridden? node property)) (conj :_overridden-properties))) (update :basis replace-node node-id (gt/clear-property node basis property)) (ctx-set-property-to-nil node-id node property))) ctx))) (defmethod perform :callback [ctx {:keys [fn args]}] (apply fn args) ctx) (defn- ctx-disconnect-single [ctx target target-id target-label] (if (= :one (in/input-cardinality (gt/node-type target (:basis ctx)) target-label)) (disconnect-inputs ctx target-id target-label) ctx)) (defn- ctx-add-overrides [ctx source-id source source-label target target-label] (let [basis (:basis ctx) target-id (gt/node-id target)] (if ((in/cascade-deletes (gt/node-type target basis)) target-label) (populate-overrides ctx target-id) ctx))) (defn- assert-type-compatible [basis source-id source-node source-label target-id target-node target-label] (let [output-nodetype (gt/node-type source-node basis) output-valtype (in/output-type output-nodetype source-label) input-nodetype (gt/node-type target-node basis) input-valtype (in/input-type input-nodetype target-label)] (assert output-valtype (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s does not have an output or property named %s" source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (in/type-name output-nodetype) source-label)) (assert input-valtype (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s does not have an input named %s" source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (in/type-name input-nodetype) target-label)) (assert (in/type-compatible? output-valtype input-valtype) (format "Attempting to connect %s (a %s) %s to %s (a %s) %s, but %s and %s are not have compatible types." source-id (in/type-name output-nodetype) source-label target-id (in/type-name input-nodetype) target-label (:k output-valtype) (:k input-valtype))))) (defn- ctx-connect [ctx source-id source-label target-id target-label] (if-let [source (gt/node-by-id-at (:basis ctx) source-id)] ; nil if source node was deleted in this transaction (if-let [target (gt/node-by-id-at (:basis ctx) target-id)] ; nil if target node was deleted in this transaction (do (assert-type-compatible (:basis ctx) source-id source source-label target-id target target-label) (-> ctx ; If the input has :one cardinality, disconnect existing connections first (ctx-disconnect-single target target-id target-label) (mark-input-activated target-id target-label) (update :basis gt/connect source-id source-label target-id target-label) (flag-successors-changed [[source-id source-label]]) (ctx-add-overrides source-id source source-label target target-label))) ctx) ctx)) (defmethod perform :connect [ctx {:keys [source-id source-label target-id target-label] :as tx-data}] (ctx-connect ctx source-id source-label target-id target-label)) (defn- ctx-remove-overrides [ctx source-id source-label target-id target-label] (let [basis (:basis ctx) target (gt/node-by-id-at basis target-id)] (if (contains? (in/cascade-deletes (gt/node-type target basis)) target-label) (let [source-override-nodes (map (partial gt/node-by-id-at basis) (ig/get-overrides basis source-id))] (loop [target-override-node-ids (ig/get-overrides basis target-id) ctx ctx] (if-let [target-override-id (first target-override-node-ids)] (let [basis (:basis ctx) target-override-node (gt/node-by-id-at basis target-override-id) target-override-id (gt/override-id target-override-node) source-override-nodes-in-target-override (filter #(= target-override-id (gt/override-id %)) source-override-nodes) traverse-fn (ig/override-traverse-fn basis target-override-id) to-delete (ig/pre-traverse basis (mapv gt/node-id source-override-nodes-in-target-override) traverse-fn)] (recur (rest target-override-node-ids) (reduce ctx-delete-node ctx to-delete))) ctx))) ctx))) (defn- ctx-disconnect [ctx source-id source-label target-id target-label] (-> ctx (mark-input-activated target-id target-label) (update :basis gt/disconnect source-id source-label target-id target-label) (flag-successors-changed [[source-id source-label]]) (ctx-remove-overrides source-id source-label target-id target-label))) (defmethod perform :disconnect [ctx {:keys [source-id source-label target-id target-label]}] (ctx-disconnect ctx source-id source-label target-id target-label)) (defmethod perform :update-graph-value [ctx {:keys [graph-id fn args]}] (-> ctx (update-in [:basis :graphs graph-id :graph-values] #(apply fn % args)) (update :graphs-modified conj graph-id))) (defmethod perform :label [ctx {:keys [label]}] (assoc ctx :label label)) (defmethod perform :sequence-label [ctx {:keys [label]}] (assoc ctx :sequence-label label)) (defmethod perform :invalidate [ctx {:keys [node-id] :as tx-data}] (if (gt/node-by-id-at (:basis ctx) node-id) (mark-all-outputs-activated ctx node-id) ctx)) (defn- apply-tx [ctx actions] (loop [ctx ctx actions actions] (if (seq actions) (if-let [action (first actions)] (if (sequential? action) (recur (apply-tx ctx action) (next actions)) (recur (update (try (perform ctx action) (catch Exception e (when *tx-debug* (println (txerrstr ctx "Transaction failed on " action))) (throw e))) :completed conj action) (next actions))) (recur ctx (next actions))) ctx))) (defn- mark-nodes-modified [{:keys [nodes-affected] :as ctx}] (assoc ctx :nodes-modified (set (keys nodes-affected)))) (defn- map-vals-bargs [m f] (util/map-vals f m)) (defn- apply-tx-label [{:keys [basis label sequence-label] :as ctx}] (cond-> (update-in ctx [:basis :graphs] map-vals-bargs #(assoc % :tx-sequence-label sequence-label)) label (update-in [:basis :graphs] map-vals-bargs #(assoc % :tx-label label)))) (def tx-report-keys [:basis :graphs-modified :nodes-added :nodes-modified :nodes-deleted :outputs-modified :label :sequence-label]) (defn- finalize-update "Makes the transacted graph the new value of the world-state graph." [{:keys [nodes-modified graphs-modified] :as ctx}] (-> (select-keys ctx tx-report-keys) (assoc :status (if (empty? (:completed ctx)) :empty :ok) :graphs-modified (into graphs-modified (map gt/node-id->graph-id nodes-modified))))) (defn new-transaction-context [basis node-id-generators override-id-generator] {:basis basis :nodes-affected {} :nodes-added [] :nodes-modified #{} :nodes-deleted {} :outputs-modified #{} :graphs-modified #{} :successors-changed {} :node-id-generators node-id-generators :override-id-generator override-id-generator :completed [] :txid (new-txid) :tx-data-context (atom {}) :deferred-setters []}) (defn- update-successors [{:keys [successors-changed] :as ctx}] (update ctx :basis ig/update-successors successors-changed)) (defn- trace-dependencies [ctx] ;; at this point, :outputs-modified contains [node-id output] pairs. ;; afterwards, it will have the transitive closure of all [node-id output] pairs ;; reachable from the original collection. (let [outputs-modified (->> (:nodes-affected ctx) (gt/dependencies (:basis ctx)) (into [] (mapcat (fn [[nid ls]] (mapv #(vector nid %) ls)))))] (assoc ctx :outputs-modified outputs-modified))) (defn transact* [ctx actions] (when *tx-debug* (println (txerrstr ctx "actions" (seq actions)))) (-> ctx (apply-tx actions) mark-nodes-modified update-successors trace-dependencies apply-tx-label finalize-update))
[ { "context": "bj [o]\n (assoc o :age 28))\n\n(def person { :name \"travis\" })\n\n(println person)\n\n(change-obj person)\n\n;immu", "end": 71, "score": 0.9949097037315369, "start": 65, "tag": "NAME", "value": "travis" } ]
basic_clojure_stuff/data_stuff.clj
travism26/random_clojure_stuff
0
(defn change-obj [o] (assoc o :age 28)) (def person { :name "travis" }) (println person) (change-obj person) ;immutable stuff cannot be mod can be overwritten though (println person) ;overwrite the data with a return value from the function. (def person (change-obj person)) (println person)
91243
(defn change-obj [o] (assoc o :age 28)) (def person { :name "<NAME>" }) (println person) (change-obj person) ;immutable stuff cannot be mod can be overwritten though (println person) ;overwrite the data with a return value from the function. (def person (change-obj person)) (println person)
true
(defn change-obj [o] (assoc o :age 28)) (def person { :name "PI:NAME:<NAME>END_PI" }) (println person) (change-obj person) ;immutable stuff cannot be mod can be overwritten though (println person) ;overwrite the data with a return value from the function. (def person (change-obj person)) (println person)
[ { "context": "al :start\n :context {:name \"Peter\"}\n :states {:start {:entry", "end": 3817, "score": 0.9995360374450684, "start": 3812, "tag": "NAME", "value": "Peter" }, { "context": " [:on-entry-start]\n :context {:name \"Peter\"}\n }\n (start-machine mac", "end": 4038, "score": 0.9995248317718506, "start": 4033, "tag": "NAME", "value": "Peter" }, { "context": "est-machine-1\n :initial :a\n :context {:name \"Peter\"\n :years 47}\n :states {:a {:exit ", "end": 4897, "score": 0.9995554685592651, "start": 4892, "tag": "NAME", "value": "Peter" } ]
test/glasgolia/glas_state/stateless_test.cljc
glasgolia/glas-state
5
(ns glasgolia.glas-state.stateless-test (:require [clojure.test :refer :all] [glasgolia.glas-state.stateless :refer :all])) (defmacro validate [{exp-value :value exp-actions :actions exp-context :context} state] `(do (is (= ~exp-value (:value ~state)) "Values are not equal") (is (= (into #{} ~exp-actions) (into #{} (:actions ~state))) "Actions are not equal") (is (= ~exp-context (:context ~state)) "Context are not equal") nil)) (deftest event-type-tests (testing "event-type handling" (is (= :kw/test (event-type :kw/test))) (is (= :blabla (event-type [:blabla :extra]))) (is (= :the-type (event-type {:type :the-type :a :b}))) (is (= "Peter" (event-type "Peter"))) (is (= 1234 (event-type 1234))) (is (= "true" (event-type true))) )) (deftest create-initial-transition-state-tests (testing "Initial for leaf state" (let [state-def {:entry :lets-enter :on [:on-first :on-second]}] (is (= {:actions [:lets-enter]} (create-initial-transition-state "" state-def))))) (testing "Initial for branch state" (let [state-def {:initial :state-2 :states {:state-1 {} :state-2 {:entry [:a :b [:c]] :on [:on-state2]}}}] (is (= {:value :state-2 :actions [:a :b :c] :on-done-events []} (create-initial-transition-state "" state-def))))) (testing "Initial for hierarchy state" (let [state-def {:initial :state-2 :states {:state-1 {} :state-2 {:initial :state-2-2 :entry :entry-state-2 :on [:a :b] :states {:state-2-1 {} :state-2-2 {:entry :entry-state-2-2} }}}}] (is (= {:value {:state-2 :state-2-2} :actions [:entry-state-2 :entry-state-2-2] :on-done-events []} (create-initial-transition-state "" state-def))))) (testing "Initial for Parallel state" (let [state-def {:type :parallel :states {:bold {:initial :off :states {:on {:entry [:entry-bold-on]} :off {}}} :underline {:initial :on :states {:on {:entry :entry-underline-on } :off {:entry :entry-underline-off}}}}}] (is (= {:value {:bold :off :underline :on} :actions [:entry-underline-on] :on-done-events [] } (create-initial-transition-state "" state-def)))))) (deftest create-machine-test (testing "Create Machine" (let [ m-def {:initial :a :context {:init-context "test"} :states {:a {} :b {}}} options {:guards {:g-a :guard-a-value}} expected {:initial :a :context {:init-context "test"} :states {:a {} :b {}} :guards (:guards options) :actions nil :activity-functions nil :services nil}] (is (= expected (machine-options m-def options)))))) (deftest start-machine-test (testing "minimal machine" (let [machine-def {:initial :start :context {:name "Peter"} :states {:start {:entry :on-entry-start} :stop {}}}] (is (= {:value :start :actions [:on-entry-start] :context {:name "Peter"} } (start-machine machine-def)))))) (deftest find-valid-handler-test (testing "event handlers handling" (let [] (is (= {:target :new-target} (find-valid-handler :new-target {} {} :event))) (is (nil? (find-valid-handler nil {} {} :event))) (is (= {:target :new-target} (find-valid-handler [:new-target] {} {} :event))) (is (= {:target :second :cond :check-second} (find-valid-handler [{:target :first :cond :check-first} {:target :second :cond :check-second}] {:check-first (fn [context event] (= {} context)) :check-second (fn [context event] (:take-this context))} {:take-this true} :the-event)))))) (def test-machine-1 {:id :test-machine-1 :initial :a :context {:name "Peter" :years 47} :states {:a {:exit :exit-a :entry :enter-a :on {:switch :b :to-d :d}} :b {:entry :enter-b :exit :exit-b :on {:switch :c}} :c {:entry :enter-c :exit :exit-c :on {:switch :a} :initial :c-1 :states {:c-1 {:entry :entry-c1 :exit :exit-c1 :on {:switch :c-2}} :c-2 {:entry :entry-c2 :exit :exit-c2 }}} :d {:entry :entry-d :exit :exit-d :type :parallel :on {:to-c :c} :states {:p1 {:initial :on :entry :entry-p1 :exit :exit-p1 :states {:on {:on {:switch :off}} :off {:on {:switch :on}}}} :p2 {:initial :off :entry :entry-p2 :exit :exit-p2 :states {:on {:entry :p2-on-entry :exit :p2-on-exit :on {:switch :off}} :off {:entry :p2-off-entry :exit :p2-off-exit :on {:switch :on}}}}}}}}) (deftest transition-machine-test (testing "Transition tests" (let [state (start-machine test-machine-1) state (transition-machine test-machine-1 state :switch) _ (validate {:value :b :actions [:exit-a :enter-b]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:c :c-1} :actions [:exit-b :enter-c :entry-c1]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:c :c-2} :actions [:exit-c1 :entry-c2]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value :a :actions [:exit-c2 :exit-c :enter-a]} state) state (transition-machine test-machine-1 state :to-d) _ (validate {:value {:d {:p1 :on :p2 :off}} :actions [:exit-a :entry-d :entry-p1 :entry-p2 :p2-off-entry]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:d {:p1 :off :p2 :on}} :actions [:p2-off-exit :p2-on-entry]} state) state (transition-machine test-machine-1 state :to-c) _ (validate {:value {:c :c-1} :actions [:p2-on-exit :exit-p1 :exit-p2 :exit-d :enter-c :entry-c1]} state) state (transition-machine test-machine-1 state :non-existing-event) _ (validate {:value {:c :c-1} :actions []} state) ]))) ;(defn on-off-switch [initial switch-event] ; {:initial initial ; {:states {:off {:on {switch-event :on}} ; :on {:on {switch-event :off}}}}}) ;(defn bold-on-off-switch (on-off-switch :off :bold-switch)) ;(defn underline-on-off-switch (on-off-switch :off :underline-switch)) ;(def color-def {:initial :color-black ; {:states {:color-black {:on {:color-switch :color-red}} ; :color-red {:on {:color-switch :color-green}} ; :color-green {:on {:color-switch :color-black}}}}}) ; (deftest ^:test-refresh/focus_not on-done-init-test (testing "Testing on-done initial states" (let [state (start-machine {:initial :a :states {:a {:initial :a1 :states {:a1 {:initial :a12 :states {:a11 {} :a12 {:type :final}}} :a2 {}}} :b {} }})] (is (= {:value {:a {:a1 :a12}} :actions [{:type :glas-state/send :event :done/.a.a1}] :context nil} state))) (let [state (start-machine {:initial :a :states {:a {:type :final} :b {} }})] (is (= {:value :a :actions [{:type :glas-state/send :event :done/.}] :context nil} state))) (let [state (start-machine {:initial :a :states {:a {:initial :p :states {:p {:type :parallel :states {:p1 {} :p2 {:type :final} }}}}}})] (is (= {:value {:a {:p {:p1 nil :p2 nil}}} :actions [] :context nil} state)) ) (let [state (start-machine {:initial :a :states {:a {:initial :p :states {:p {:type :parallel :states {:p1 {:type :final} :p2 {:type :final} }}}}}})] (is (= {:value {:a {:p {:p1 nil :p2 nil}}} :actions [(done-event ".a.p")] :context nil} state)) ) ) ) (deftest ^:test-refresh/focus-not relative-target-test (let [machine {:initial :c :on {:go-to-b {:target :.b :actions [:test]}} :states {:a {} :b {} :c {:initial :c1 :entry :entry-c :exit :exit-c :on {:c2 {:target :.c2 :actions :goto-c2-action} :c1 :.c1} :states {:c1 {:entry :entry-c1 :exit :exit-c1} :c2 {}}} } } state (start-machine machine) _ (validate {:value {:c :c1} :actions [:entry-c1 :entry-c]} state) state (transition-machine machine state :c2) _ (validate {:value {:c :c2} :actions [:exit-c1 :goto-c2-action]} state) state (transition-machine machine state :go-to-b) _ (validate {:value :b :actions [:exit-c :test]} state) ])) ;(def example-cmp-machine ; {:id :examples-component ; :initial :please-select-example ; :states ; {:please-select-example {:on ; {:select-example ; {:target :show-example ; :actions (assign (fn [c e m] ; (println "......." e) ; (assoc c :selected (:example-id e))))}}} ; :show-example {}} ; :context {:list [] ; :selected nil}}) ; ;(deftest ^:test-refresh/focus on-with-actions-test ; (let[state (start-machine example-cmp-machine) ; _ (validate {:value :please-select-example :context {:list[] :selected nil}} state) ; state (transition-machine example-cmp-machine state {:type :select-example :example-id :the-selected-id}) ; _ (validate {:value :show-example :context {:list[] :selected :the-selected-id}} state) ; ; ])) (deftest ^:test-refresh/focus_not invoke-test) (deftest ^:test-refresh/focus_not on-done-transition-test (let [the-machine {:initial :a :states {:a {:on {:switch :b}} :b {:type :final}}} state (start-machine the-machine) _ (validate {:value :a :actions [] :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value :b :actions [(done-event "")]} state) ] ) (let [the-machine {:initial :a :states {:a {:initial :a1 :states {:a1 {:on {:switch :a2}} :a2 {:type :final}} :b {:type :final}}} } state (start-machine the-machine) _ (validate {:value {:a :a1} :actions [] :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value {:a :a2} :actions [(done-event ".a")]} state) ] ) (let [the-machine {:initial :a :states {:a {:initial :p :states {:p { :type :parallel :states {:bold {:initial :off :states {:on {:on {:switch-bold :off :bold-finish :bold-done}} :off {:on {:switch-bold :on :bold-finish :bold-done}} :bold-done {:type :final} }} :color {:initial :black :states {:black {:on {:switch-color :red :color-finish :color-done}} :red {:on {:switch-color :black :color-finish :color-done}} :color-done {:type :final}}}}}}}} } state (start-machine the-machine) _ (validate {:value {:a {:p {:bold :off :color :black}}} :actions [] :context nil} state) state (transition-machine the-machine state :bold-finish) _ (validate {:value {:a {:p {:bold :bold-done :color :black}}} :actions []} state) state (transition-machine the-machine state :color-finish) _ (validate {:value {:a {:p {:bold :bold-done :color :color-done}}} :actions [(done-event ".a.p")]} state) ] ) ) #_(deftest ^:test-refresh/focus-not invoke-test2 (let [the-machine {:initial :a :states {:a {:invoke {:id :invoke-in-a} :on {:next :b}} :b {:initial :b1 :on {:next :c} :invoke {:id :invoke-in-b} :states {:b1 {:invoke {:id :invoke-in-b1} }}} :c {:type :parallel :states {:c1 {:invoke {:id :invoke-in-c1}} :c2 {:invoke {:id :invoke-in-c2}}}} :done {:type :final}}} state (start-machine the-machine) _ (validate {:value :a :actions [{:type :glas-state/invoke :config {:id :invoke-in-a}}] :context nil} state) state (transition-machine the-machine state :next) _ (validate {:value {:b :b1} :actions [{:type :glas-state/invoke-cleanup :id :invoke-in-a} {:type :glas-state/invoke :config {:id :invoke-in-b1}} {:type :glas-state/invoke :config {:id :invoke-in-b}}] :context nil} state) state (transition-machine the-machine state :next) _ (validate {:value {:c {:c1 nil :c2 nil}} :actions [{:type :glas-state/invoke-cleanup :id :invoke-in-b1} {:type :glas-state/invoke-cleanup :id :invoke-in-b} {:type :glas-state/invoke :config {:id :invoke-in-c1}} {:type :glas-state/invoke :config {:id :invoke-in-c2}}] :context nil} state) ] ) ) (deftest ^:test-refresh/focus-not done-events-tests (let [the-machine {:initial :a :id :test :states {:a {:type :parallel :states {:par1 {:initial :par11 :states {:par11 {:on {:switch :par12}} :par12 {:type :final}}} :par2 {:type :final}}}}} state (start-machine the-machine) _ (validate {:value {:a {:par1 :par11 :par2 nil}} :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value {:a {:par1 :par12 :par2 nil}} :actions [(done-event ".a")] :context nil} state) the-machine {:id :shopping :type :parallel :states {:user {:initial :pending :states {:pending {:on {:resolve-user :success :reject-user :failure}} :success {:type :final} :failure {} }} :items {:initial :pending :states {:pending {:on {:resolve-items :success :reject-items :failure}} :success {:type :final} :failure {}}}} :on-done {:actions (assign (fn [c e] assoc c :done true)) }} state (start-machine the-machine) _ (validate {:value {:user :pending :items :pending} :context nil} state) state (transition-machine the-machine state :resolve-user) _ (validate {:value {:user :success :items :pending} :context nil} state) state (transition-machine the-machine state :resolve-items) _ (validate {:value {:user :success :items :success} :actions [(done-event "")] :context nil} state) the-machine {:id :test :initial :state-a :on-done {:actions :root-done} :states { :state-a {:initial :state-aa :on {:go-b :state-b} :on-done {:actions :a-done} :states {:state-aa {:initial :state-aaa :on {:go-bb :state-bb} :on-done {:actions :aa-done} :states {:state-aaa {:on {:go-bbb :state-bbb}} :state-bbb {:type :final}}} :state-bb {:type :final}}} :state-b {:type :final} } } state (start-machine the-machine) _ (validate {:value {:state-a {:state-aa :state-aaa}}} state) state (transition-machine the-machine state :go-bbb) _ (validate {:value {:state-a {:state-aa :state-bbb}} :actions [(done-event ".state-a.state-aa")]} state) state (transition-machine the-machine state :done/.state-a.state-aa) _ (validate {:value {:state-a {:state-aa :state-bbb}} :actions [:aa-done]} state) ])) (deftest ^:test-refresh/focus-not activitie-test (let[ the-machine {:id :activity-test :initial :start :states {:start {:activities [:act-1] :initial :sub1 :on {:done :done} :states {:sub1 {:on {:next :sub2}} :sub2 {:on {:next :sub1} :activities [:act-1 :act-2]}}} :done {:type :final}}} state (start-machine the-machine) _ (validate {:value {:start :sub1} :actions [(create-activities-event [:act-1])]} state) state (transition-machine the-machine state :next) _ (validate {:value {:start :sub2} :actions [(create-activities-event [:act-1 :act-2])]} state) state (transition-machine the-machine state :next) _ (validate {:value {:start :sub1} :actions [(create-activities-cleanup-event[:act-1 :act-2])]} state) state (transition-machine the-machine state :done) _ (validate {:value :done :actions [(create-activities-cleanup-event[:act-1])(done-event ".")]} state) ]))
108887
(ns glasgolia.glas-state.stateless-test (:require [clojure.test :refer :all] [glasgolia.glas-state.stateless :refer :all])) (defmacro validate [{exp-value :value exp-actions :actions exp-context :context} state] `(do (is (= ~exp-value (:value ~state)) "Values are not equal") (is (= (into #{} ~exp-actions) (into #{} (:actions ~state))) "Actions are not equal") (is (= ~exp-context (:context ~state)) "Context are not equal") nil)) (deftest event-type-tests (testing "event-type handling" (is (= :kw/test (event-type :kw/test))) (is (= :blabla (event-type [:blabla :extra]))) (is (= :the-type (event-type {:type :the-type :a :b}))) (is (= "Peter" (event-type "Peter"))) (is (= 1234 (event-type 1234))) (is (= "true" (event-type true))) )) (deftest create-initial-transition-state-tests (testing "Initial for leaf state" (let [state-def {:entry :lets-enter :on [:on-first :on-second]}] (is (= {:actions [:lets-enter]} (create-initial-transition-state "" state-def))))) (testing "Initial for branch state" (let [state-def {:initial :state-2 :states {:state-1 {} :state-2 {:entry [:a :b [:c]] :on [:on-state2]}}}] (is (= {:value :state-2 :actions [:a :b :c] :on-done-events []} (create-initial-transition-state "" state-def))))) (testing "Initial for hierarchy state" (let [state-def {:initial :state-2 :states {:state-1 {} :state-2 {:initial :state-2-2 :entry :entry-state-2 :on [:a :b] :states {:state-2-1 {} :state-2-2 {:entry :entry-state-2-2} }}}}] (is (= {:value {:state-2 :state-2-2} :actions [:entry-state-2 :entry-state-2-2] :on-done-events []} (create-initial-transition-state "" state-def))))) (testing "Initial for Parallel state" (let [state-def {:type :parallel :states {:bold {:initial :off :states {:on {:entry [:entry-bold-on]} :off {}}} :underline {:initial :on :states {:on {:entry :entry-underline-on } :off {:entry :entry-underline-off}}}}}] (is (= {:value {:bold :off :underline :on} :actions [:entry-underline-on] :on-done-events [] } (create-initial-transition-state "" state-def)))))) (deftest create-machine-test (testing "Create Machine" (let [ m-def {:initial :a :context {:init-context "test"} :states {:a {} :b {}}} options {:guards {:g-a :guard-a-value}} expected {:initial :a :context {:init-context "test"} :states {:a {} :b {}} :guards (:guards options) :actions nil :activity-functions nil :services nil}] (is (= expected (machine-options m-def options)))))) (deftest start-machine-test (testing "minimal machine" (let [machine-def {:initial :start :context {:name "<NAME>"} :states {:start {:entry :on-entry-start} :stop {}}}] (is (= {:value :start :actions [:on-entry-start] :context {:name "<NAME>"} } (start-machine machine-def)))))) (deftest find-valid-handler-test (testing "event handlers handling" (let [] (is (= {:target :new-target} (find-valid-handler :new-target {} {} :event))) (is (nil? (find-valid-handler nil {} {} :event))) (is (= {:target :new-target} (find-valid-handler [:new-target] {} {} :event))) (is (= {:target :second :cond :check-second} (find-valid-handler [{:target :first :cond :check-first} {:target :second :cond :check-second}] {:check-first (fn [context event] (= {} context)) :check-second (fn [context event] (:take-this context))} {:take-this true} :the-event)))))) (def test-machine-1 {:id :test-machine-1 :initial :a :context {:name "<NAME>" :years 47} :states {:a {:exit :exit-a :entry :enter-a :on {:switch :b :to-d :d}} :b {:entry :enter-b :exit :exit-b :on {:switch :c}} :c {:entry :enter-c :exit :exit-c :on {:switch :a} :initial :c-1 :states {:c-1 {:entry :entry-c1 :exit :exit-c1 :on {:switch :c-2}} :c-2 {:entry :entry-c2 :exit :exit-c2 }}} :d {:entry :entry-d :exit :exit-d :type :parallel :on {:to-c :c} :states {:p1 {:initial :on :entry :entry-p1 :exit :exit-p1 :states {:on {:on {:switch :off}} :off {:on {:switch :on}}}} :p2 {:initial :off :entry :entry-p2 :exit :exit-p2 :states {:on {:entry :p2-on-entry :exit :p2-on-exit :on {:switch :off}} :off {:entry :p2-off-entry :exit :p2-off-exit :on {:switch :on}}}}}}}}) (deftest transition-machine-test (testing "Transition tests" (let [state (start-machine test-machine-1) state (transition-machine test-machine-1 state :switch) _ (validate {:value :b :actions [:exit-a :enter-b]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:c :c-1} :actions [:exit-b :enter-c :entry-c1]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:c :c-2} :actions [:exit-c1 :entry-c2]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value :a :actions [:exit-c2 :exit-c :enter-a]} state) state (transition-machine test-machine-1 state :to-d) _ (validate {:value {:d {:p1 :on :p2 :off}} :actions [:exit-a :entry-d :entry-p1 :entry-p2 :p2-off-entry]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:d {:p1 :off :p2 :on}} :actions [:p2-off-exit :p2-on-entry]} state) state (transition-machine test-machine-1 state :to-c) _ (validate {:value {:c :c-1} :actions [:p2-on-exit :exit-p1 :exit-p2 :exit-d :enter-c :entry-c1]} state) state (transition-machine test-machine-1 state :non-existing-event) _ (validate {:value {:c :c-1} :actions []} state) ]))) ;(defn on-off-switch [initial switch-event] ; {:initial initial ; {:states {:off {:on {switch-event :on}} ; :on {:on {switch-event :off}}}}}) ;(defn bold-on-off-switch (on-off-switch :off :bold-switch)) ;(defn underline-on-off-switch (on-off-switch :off :underline-switch)) ;(def color-def {:initial :color-black ; {:states {:color-black {:on {:color-switch :color-red}} ; :color-red {:on {:color-switch :color-green}} ; :color-green {:on {:color-switch :color-black}}}}}) ; (deftest ^:test-refresh/focus_not on-done-init-test (testing "Testing on-done initial states" (let [state (start-machine {:initial :a :states {:a {:initial :a1 :states {:a1 {:initial :a12 :states {:a11 {} :a12 {:type :final}}} :a2 {}}} :b {} }})] (is (= {:value {:a {:a1 :a12}} :actions [{:type :glas-state/send :event :done/.a.a1}] :context nil} state))) (let [state (start-machine {:initial :a :states {:a {:type :final} :b {} }})] (is (= {:value :a :actions [{:type :glas-state/send :event :done/.}] :context nil} state))) (let [state (start-machine {:initial :a :states {:a {:initial :p :states {:p {:type :parallel :states {:p1 {} :p2 {:type :final} }}}}}})] (is (= {:value {:a {:p {:p1 nil :p2 nil}}} :actions [] :context nil} state)) ) (let [state (start-machine {:initial :a :states {:a {:initial :p :states {:p {:type :parallel :states {:p1 {:type :final} :p2 {:type :final} }}}}}})] (is (= {:value {:a {:p {:p1 nil :p2 nil}}} :actions [(done-event ".a.p")] :context nil} state)) ) ) ) (deftest ^:test-refresh/focus-not relative-target-test (let [machine {:initial :c :on {:go-to-b {:target :.b :actions [:test]}} :states {:a {} :b {} :c {:initial :c1 :entry :entry-c :exit :exit-c :on {:c2 {:target :.c2 :actions :goto-c2-action} :c1 :.c1} :states {:c1 {:entry :entry-c1 :exit :exit-c1} :c2 {}}} } } state (start-machine machine) _ (validate {:value {:c :c1} :actions [:entry-c1 :entry-c]} state) state (transition-machine machine state :c2) _ (validate {:value {:c :c2} :actions [:exit-c1 :goto-c2-action]} state) state (transition-machine machine state :go-to-b) _ (validate {:value :b :actions [:exit-c :test]} state) ])) ;(def example-cmp-machine ; {:id :examples-component ; :initial :please-select-example ; :states ; {:please-select-example {:on ; {:select-example ; {:target :show-example ; :actions (assign (fn [c e m] ; (println "......." e) ; (assoc c :selected (:example-id e))))}}} ; :show-example {}} ; :context {:list [] ; :selected nil}}) ; ;(deftest ^:test-refresh/focus on-with-actions-test ; (let[state (start-machine example-cmp-machine) ; _ (validate {:value :please-select-example :context {:list[] :selected nil}} state) ; state (transition-machine example-cmp-machine state {:type :select-example :example-id :the-selected-id}) ; _ (validate {:value :show-example :context {:list[] :selected :the-selected-id}} state) ; ; ])) (deftest ^:test-refresh/focus_not invoke-test) (deftest ^:test-refresh/focus_not on-done-transition-test (let [the-machine {:initial :a :states {:a {:on {:switch :b}} :b {:type :final}}} state (start-machine the-machine) _ (validate {:value :a :actions [] :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value :b :actions [(done-event "")]} state) ] ) (let [the-machine {:initial :a :states {:a {:initial :a1 :states {:a1 {:on {:switch :a2}} :a2 {:type :final}} :b {:type :final}}} } state (start-machine the-machine) _ (validate {:value {:a :a1} :actions [] :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value {:a :a2} :actions [(done-event ".a")]} state) ] ) (let [the-machine {:initial :a :states {:a {:initial :p :states {:p { :type :parallel :states {:bold {:initial :off :states {:on {:on {:switch-bold :off :bold-finish :bold-done}} :off {:on {:switch-bold :on :bold-finish :bold-done}} :bold-done {:type :final} }} :color {:initial :black :states {:black {:on {:switch-color :red :color-finish :color-done}} :red {:on {:switch-color :black :color-finish :color-done}} :color-done {:type :final}}}}}}}} } state (start-machine the-machine) _ (validate {:value {:a {:p {:bold :off :color :black}}} :actions [] :context nil} state) state (transition-machine the-machine state :bold-finish) _ (validate {:value {:a {:p {:bold :bold-done :color :black}}} :actions []} state) state (transition-machine the-machine state :color-finish) _ (validate {:value {:a {:p {:bold :bold-done :color :color-done}}} :actions [(done-event ".a.p")]} state) ] ) ) #_(deftest ^:test-refresh/focus-not invoke-test2 (let [the-machine {:initial :a :states {:a {:invoke {:id :invoke-in-a} :on {:next :b}} :b {:initial :b1 :on {:next :c} :invoke {:id :invoke-in-b} :states {:b1 {:invoke {:id :invoke-in-b1} }}} :c {:type :parallel :states {:c1 {:invoke {:id :invoke-in-c1}} :c2 {:invoke {:id :invoke-in-c2}}}} :done {:type :final}}} state (start-machine the-machine) _ (validate {:value :a :actions [{:type :glas-state/invoke :config {:id :invoke-in-a}}] :context nil} state) state (transition-machine the-machine state :next) _ (validate {:value {:b :b1} :actions [{:type :glas-state/invoke-cleanup :id :invoke-in-a} {:type :glas-state/invoke :config {:id :invoke-in-b1}} {:type :glas-state/invoke :config {:id :invoke-in-b}}] :context nil} state) state (transition-machine the-machine state :next) _ (validate {:value {:c {:c1 nil :c2 nil}} :actions [{:type :glas-state/invoke-cleanup :id :invoke-in-b1} {:type :glas-state/invoke-cleanup :id :invoke-in-b} {:type :glas-state/invoke :config {:id :invoke-in-c1}} {:type :glas-state/invoke :config {:id :invoke-in-c2}}] :context nil} state) ] ) ) (deftest ^:test-refresh/focus-not done-events-tests (let [the-machine {:initial :a :id :test :states {:a {:type :parallel :states {:par1 {:initial :par11 :states {:par11 {:on {:switch :par12}} :par12 {:type :final}}} :par2 {:type :final}}}}} state (start-machine the-machine) _ (validate {:value {:a {:par1 :par11 :par2 nil}} :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value {:a {:par1 :par12 :par2 nil}} :actions [(done-event ".a")] :context nil} state) the-machine {:id :shopping :type :parallel :states {:user {:initial :pending :states {:pending {:on {:resolve-user :success :reject-user :failure}} :success {:type :final} :failure {} }} :items {:initial :pending :states {:pending {:on {:resolve-items :success :reject-items :failure}} :success {:type :final} :failure {}}}} :on-done {:actions (assign (fn [c e] assoc c :done true)) }} state (start-machine the-machine) _ (validate {:value {:user :pending :items :pending} :context nil} state) state (transition-machine the-machine state :resolve-user) _ (validate {:value {:user :success :items :pending} :context nil} state) state (transition-machine the-machine state :resolve-items) _ (validate {:value {:user :success :items :success} :actions [(done-event "")] :context nil} state) the-machine {:id :test :initial :state-a :on-done {:actions :root-done} :states { :state-a {:initial :state-aa :on {:go-b :state-b} :on-done {:actions :a-done} :states {:state-aa {:initial :state-aaa :on {:go-bb :state-bb} :on-done {:actions :aa-done} :states {:state-aaa {:on {:go-bbb :state-bbb}} :state-bbb {:type :final}}} :state-bb {:type :final}}} :state-b {:type :final} } } state (start-machine the-machine) _ (validate {:value {:state-a {:state-aa :state-aaa}}} state) state (transition-machine the-machine state :go-bbb) _ (validate {:value {:state-a {:state-aa :state-bbb}} :actions [(done-event ".state-a.state-aa")]} state) state (transition-machine the-machine state :done/.state-a.state-aa) _ (validate {:value {:state-a {:state-aa :state-bbb}} :actions [:aa-done]} state) ])) (deftest ^:test-refresh/focus-not activitie-test (let[ the-machine {:id :activity-test :initial :start :states {:start {:activities [:act-1] :initial :sub1 :on {:done :done} :states {:sub1 {:on {:next :sub2}} :sub2 {:on {:next :sub1} :activities [:act-1 :act-2]}}} :done {:type :final}}} state (start-machine the-machine) _ (validate {:value {:start :sub1} :actions [(create-activities-event [:act-1])]} state) state (transition-machine the-machine state :next) _ (validate {:value {:start :sub2} :actions [(create-activities-event [:act-1 :act-2])]} state) state (transition-machine the-machine state :next) _ (validate {:value {:start :sub1} :actions [(create-activities-cleanup-event[:act-1 :act-2])]} state) state (transition-machine the-machine state :done) _ (validate {:value :done :actions [(create-activities-cleanup-event[:act-1])(done-event ".")]} state) ]))
true
(ns glasgolia.glas-state.stateless-test (:require [clojure.test :refer :all] [glasgolia.glas-state.stateless :refer :all])) (defmacro validate [{exp-value :value exp-actions :actions exp-context :context} state] `(do (is (= ~exp-value (:value ~state)) "Values are not equal") (is (= (into #{} ~exp-actions) (into #{} (:actions ~state))) "Actions are not equal") (is (= ~exp-context (:context ~state)) "Context are not equal") nil)) (deftest event-type-tests (testing "event-type handling" (is (= :kw/test (event-type :kw/test))) (is (= :blabla (event-type [:blabla :extra]))) (is (= :the-type (event-type {:type :the-type :a :b}))) (is (= "Peter" (event-type "Peter"))) (is (= 1234 (event-type 1234))) (is (= "true" (event-type true))) )) (deftest create-initial-transition-state-tests (testing "Initial for leaf state" (let [state-def {:entry :lets-enter :on [:on-first :on-second]}] (is (= {:actions [:lets-enter]} (create-initial-transition-state "" state-def))))) (testing "Initial for branch state" (let [state-def {:initial :state-2 :states {:state-1 {} :state-2 {:entry [:a :b [:c]] :on [:on-state2]}}}] (is (= {:value :state-2 :actions [:a :b :c] :on-done-events []} (create-initial-transition-state "" state-def))))) (testing "Initial for hierarchy state" (let [state-def {:initial :state-2 :states {:state-1 {} :state-2 {:initial :state-2-2 :entry :entry-state-2 :on [:a :b] :states {:state-2-1 {} :state-2-2 {:entry :entry-state-2-2} }}}}] (is (= {:value {:state-2 :state-2-2} :actions [:entry-state-2 :entry-state-2-2] :on-done-events []} (create-initial-transition-state "" state-def))))) (testing "Initial for Parallel state" (let [state-def {:type :parallel :states {:bold {:initial :off :states {:on {:entry [:entry-bold-on]} :off {}}} :underline {:initial :on :states {:on {:entry :entry-underline-on } :off {:entry :entry-underline-off}}}}}] (is (= {:value {:bold :off :underline :on} :actions [:entry-underline-on] :on-done-events [] } (create-initial-transition-state "" state-def)))))) (deftest create-machine-test (testing "Create Machine" (let [ m-def {:initial :a :context {:init-context "test"} :states {:a {} :b {}}} options {:guards {:g-a :guard-a-value}} expected {:initial :a :context {:init-context "test"} :states {:a {} :b {}} :guards (:guards options) :actions nil :activity-functions nil :services nil}] (is (= expected (machine-options m-def options)))))) (deftest start-machine-test (testing "minimal machine" (let [machine-def {:initial :start :context {:name "PI:NAME:<NAME>END_PI"} :states {:start {:entry :on-entry-start} :stop {}}}] (is (= {:value :start :actions [:on-entry-start] :context {:name "PI:NAME:<NAME>END_PI"} } (start-machine machine-def)))))) (deftest find-valid-handler-test (testing "event handlers handling" (let [] (is (= {:target :new-target} (find-valid-handler :new-target {} {} :event))) (is (nil? (find-valid-handler nil {} {} :event))) (is (= {:target :new-target} (find-valid-handler [:new-target] {} {} :event))) (is (= {:target :second :cond :check-second} (find-valid-handler [{:target :first :cond :check-first} {:target :second :cond :check-second}] {:check-first (fn [context event] (= {} context)) :check-second (fn [context event] (:take-this context))} {:take-this true} :the-event)))))) (def test-machine-1 {:id :test-machine-1 :initial :a :context {:name "PI:NAME:<NAME>END_PI" :years 47} :states {:a {:exit :exit-a :entry :enter-a :on {:switch :b :to-d :d}} :b {:entry :enter-b :exit :exit-b :on {:switch :c}} :c {:entry :enter-c :exit :exit-c :on {:switch :a} :initial :c-1 :states {:c-1 {:entry :entry-c1 :exit :exit-c1 :on {:switch :c-2}} :c-2 {:entry :entry-c2 :exit :exit-c2 }}} :d {:entry :entry-d :exit :exit-d :type :parallel :on {:to-c :c} :states {:p1 {:initial :on :entry :entry-p1 :exit :exit-p1 :states {:on {:on {:switch :off}} :off {:on {:switch :on}}}} :p2 {:initial :off :entry :entry-p2 :exit :exit-p2 :states {:on {:entry :p2-on-entry :exit :p2-on-exit :on {:switch :off}} :off {:entry :p2-off-entry :exit :p2-off-exit :on {:switch :on}}}}}}}}) (deftest transition-machine-test (testing "Transition tests" (let [state (start-machine test-machine-1) state (transition-machine test-machine-1 state :switch) _ (validate {:value :b :actions [:exit-a :enter-b]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:c :c-1} :actions [:exit-b :enter-c :entry-c1]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:c :c-2} :actions [:exit-c1 :entry-c2]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value :a :actions [:exit-c2 :exit-c :enter-a]} state) state (transition-machine test-machine-1 state :to-d) _ (validate {:value {:d {:p1 :on :p2 :off}} :actions [:exit-a :entry-d :entry-p1 :entry-p2 :p2-off-entry]} state) state (transition-machine test-machine-1 state :switch) _ (validate {:value {:d {:p1 :off :p2 :on}} :actions [:p2-off-exit :p2-on-entry]} state) state (transition-machine test-machine-1 state :to-c) _ (validate {:value {:c :c-1} :actions [:p2-on-exit :exit-p1 :exit-p2 :exit-d :enter-c :entry-c1]} state) state (transition-machine test-machine-1 state :non-existing-event) _ (validate {:value {:c :c-1} :actions []} state) ]))) ;(defn on-off-switch [initial switch-event] ; {:initial initial ; {:states {:off {:on {switch-event :on}} ; :on {:on {switch-event :off}}}}}) ;(defn bold-on-off-switch (on-off-switch :off :bold-switch)) ;(defn underline-on-off-switch (on-off-switch :off :underline-switch)) ;(def color-def {:initial :color-black ; {:states {:color-black {:on {:color-switch :color-red}} ; :color-red {:on {:color-switch :color-green}} ; :color-green {:on {:color-switch :color-black}}}}}) ; (deftest ^:test-refresh/focus_not on-done-init-test (testing "Testing on-done initial states" (let [state (start-machine {:initial :a :states {:a {:initial :a1 :states {:a1 {:initial :a12 :states {:a11 {} :a12 {:type :final}}} :a2 {}}} :b {} }})] (is (= {:value {:a {:a1 :a12}} :actions [{:type :glas-state/send :event :done/.a.a1}] :context nil} state))) (let [state (start-machine {:initial :a :states {:a {:type :final} :b {} }})] (is (= {:value :a :actions [{:type :glas-state/send :event :done/.}] :context nil} state))) (let [state (start-machine {:initial :a :states {:a {:initial :p :states {:p {:type :parallel :states {:p1 {} :p2 {:type :final} }}}}}})] (is (= {:value {:a {:p {:p1 nil :p2 nil}}} :actions [] :context nil} state)) ) (let [state (start-machine {:initial :a :states {:a {:initial :p :states {:p {:type :parallel :states {:p1 {:type :final} :p2 {:type :final} }}}}}})] (is (= {:value {:a {:p {:p1 nil :p2 nil}}} :actions [(done-event ".a.p")] :context nil} state)) ) ) ) (deftest ^:test-refresh/focus-not relative-target-test (let [machine {:initial :c :on {:go-to-b {:target :.b :actions [:test]}} :states {:a {} :b {} :c {:initial :c1 :entry :entry-c :exit :exit-c :on {:c2 {:target :.c2 :actions :goto-c2-action} :c1 :.c1} :states {:c1 {:entry :entry-c1 :exit :exit-c1} :c2 {}}} } } state (start-machine machine) _ (validate {:value {:c :c1} :actions [:entry-c1 :entry-c]} state) state (transition-machine machine state :c2) _ (validate {:value {:c :c2} :actions [:exit-c1 :goto-c2-action]} state) state (transition-machine machine state :go-to-b) _ (validate {:value :b :actions [:exit-c :test]} state) ])) ;(def example-cmp-machine ; {:id :examples-component ; :initial :please-select-example ; :states ; {:please-select-example {:on ; {:select-example ; {:target :show-example ; :actions (assign (fn [c e m] ; (println "......." e) ; (assoc c :selected (:example-id e))))}}} ; :show-example {}} ; :context {:list [] ; :selected nil}}) ; ;(deftest ^:test-refresh/focus on-with-actions-test ; (let[state (start-machine example-cmp-machine) ; _ (validate {:value :please-select-example :context {:list[] :selected nil}} state) ; state (transition-machine example-cmp-machine state {:type :select-example :example-id :the-selected-id}) ; _ (validate {:value :show-example :context {:list[] :selected :the-selected-id}} state) ; ; ])) (deftest ^:test-refresh/focus_not invoke-test) (deftest ^:test-refresh/focus_not on-done-transition-test (let [the-machine {:initial :a :states {:a {:on {:switch :b}} :b {:type :final}}} state (start-machine the-machine) _ (validate {:value :a :actions [] :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value :b :actions [(done-event "")]} state) ] ) (let [the-machine {:initial :a :states {:a {:initial :a1 :states {:a1 {:on {:switch :a2}} :a2 {:type :final}} :b {:type :final}}} } state (start-machine the-machine) _ (validate {:value {:a :a1} :actions [] :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value {:a :a2} :actions [(done-event ".a")]} state) ] ) (let [the-machine {:initial :a :states {:a {:initial :p :states {:p { :type :parallel :states {:bold {:initial :off :states {:on {:on {:switch-bold :off :bold-finish :bold-done}} :off {:on {:switch-bold :on :bold-finish :bold-done}} :bold-done {:type :final} }} :color {:initial :black :states {:black {:on {:switch-color :red :color-finish :color-done}} :red {:on {:switch-color :black :color-finish :color-done}} :color-done {:type :final}}}}}}}} } state (start-machine the-machine) _ (validate {:value {:a {:p {:bold :off :color :black}}} :actions [] :context nil} state) state (transition-machine the-machine state :bold-finish) _ (validate {:value {:a {:p {:bold :bold-done :color :black}}} :actions []} state) state (transition-machine the-machine state :color-finish) _ (validate {:value {:a {:p {:bold :bold-done :color :color-done}}} :actions [(done-event ".a.p")]} state) ] ) ) #_(deftest ^:test-refresh/focus-not invoke-test2 (let [the-machine {:initial :a :states {:a {:invoke {:id :invoke-in-a} :on {:next :b}} :b {:initial :b1 :on {:next :c} :invoke {:id :invoke-in-b} :states {:b1 {:invoke {:id :invoke-in-b1} }}} :c {:type :parallel :states {:c1 {:invoke {:id :invoke-in-c1}} :c2 {:invoke {:id :invoke-in-c2}}}} :done {:type :final}}} state (start-machine the-machine) _ (validate {:value :a :actions [{:type :glas-state/invoke :config {:id :invoke-in-a}}] :context nil} state) state (transition-machine the-machine state :next) _ (validate {:value {:b :b1} :actions [{:type :glas-state/invoke-cleanup :id :invoke-in-a} {:type :glas-state/invoke :config {:id :invoke-in-b1}} {:type :glas-state/invoke :config {:id :invoke-in-b}}] :context nil} state) state (transition-machine the-machine state :next) _ (validate {:value {:c {:c1 nil :c2 nil}} :actions [{:type :glas-state/invoke-cleanup :id :invoke-in-b1} {:type :glas-state/invoke-cleanup :id :invoke-in-b} {:type :glas-state/invoke :config {:id :invoke-in-c1}} {:type :glas-state/invoke :config {:id :invoke-in-c2}}] :context nil} state) ] ) ) (deftest ^:test-refresh/focus-not done-events-tests (let [the-machine {:initial :a :id :test :states {:a {:type :parallel :states {:par1 {:initial :par11 :states {:par11 {:on {:switch :par12}} :par12 {:type :final}}} :par2 {:type :final}}}}} state (start-machine the-machine) _ (validate {:value {:a {:par1 :par11 :par2 nil}} :context nil} state) state (transition-machine the-machine state :switch) _ (validate {:value {:a {:par1 :par12 :par2 nil}} :actions [(done-event ".a")] :context nil} state) the-machine {:id :shopping :type :parallel :states {:user {:initial :pending :states {:pending {:on {:resolve-user :success :reject-user :failure}} :success {:type :final} :failure {} }} :items {:initial :pending :states {:pending {:on {:resolve-items :success :reject-items :failure}} :success {:type :final} :failure {}}}} :on-done {:actions (assign (fn [c e] assoc c :done true)) }} state (start-machine the-machine) _ (validate {:value {:user :pending :items :pending} :context nil} state) state (transition-machine the-machine state :resolve-user) _ (validate {:value {:user :success :items :pending} :context nil} state) state (transition-machine the-machine state :resolve-items) _ (validate {:value {:user :success :items :success} :actions [(done-event "")] :context nil} state) the-machine {:id :test :initial :state-a :on-done {:actions :root-done} :states { :state-a {:initial :state-aa :on {:go-b :state-b} :on-done {:actions :a-done} :states {:state-aa {:initial :state-aaa :on {:go-bb :state-bb} :on-done {:actions :aa-done} :states {:state-aaa {:on {:go-bbb :state-bbb}} :state-bbb {:type :final}}} :state-bb {:type :final}}} :state-b {:type :final} } } state (start-machine the-machine) _ (validate {:value {:state-a {:state-aa :state-aaa}}} state) state (transition-machine the-machine state :go-bbb) _ (validate {:value {:state-a {:state-aa :state-bbb}} :actions [(done-event ".state-a.state-aa")]} state) state (transition-machine the-machine state :done/.state-a.state-aa) _ (validate {:value {:state-a {:state-aa :state-bbb}} :actions [:aa-done]} state) ])) (deftest ^:test-refresh/focus-not activitie-test (let[ the-machine {:id :activity-test :initial :start :states {:start {:activities [:act-1] :initial :sub1 :on {:done :done} :states {:sub1 {:on {:next :sub2}} :sub2 {:on {:next :sub1} :activities [:act-1 :act-2]}}} :done {:type :final}}} state (start-machine the-machine) _ (validate {:value {:start :sub1} :actions [(create-activities-event [:act-1])]} state) state (transition-machine the-machine state :next) _ (validate {:value {:start :sub2} :actions [(create-activities-event [:act-1 :act-2])]} state) state (transition-machine the-machine state :next) _ (validate {:value {:start :sub1} :actions [(create-activities-cleanup-event[:act-1 :act-2])]} state) state (transition-machine the-machine state :done) _ (validate {:value :done :actions [(create-activities-cleanup-event[:act-1])(done-event ".")]} state) ]))
[ { "context": ".list-group-item.d-flex.list-group-flush\n [:h4 \"Ranger Bob\"]])\n\n(defmethod dndv/drag-handle\n :redbox\n [{:k", "end": 1461, "score": 0.9987130165100098, "start": 1451, "tag": "NAME", "value": "Ranger Bob" }, { "context": " [{:type :character\n ;; :name \"Ranger Bob\"\n ;; :id \"ranger.bob\"}\n ", "end": 2383, "score": 0.9997686743736267, "start": 2373, "tag": "NAME", "value": "Ranger Bob" }, { "context": " :name \"Ranger Bob\"\n ;; :id \"ranger.bob\"}\n ;; {:type :character\n ", "end": 2423, "score": 0.9792003035545349, "start": 2413, "tag": "USERNAME", "value": "ranger.bob" }, { "context": " {:type :character\n ;; :name \"Larissa\"\n ;; :id (keyword (cuerdas/keb", "end": 2503, "score": 0.9997519850730896, "start": 2496, "tag": "NAME", "value": "Larissa" }, { "context": " ;; :id (keyword (cuerdas/kebab \"Larissa\"))}]\n ])\n (fn []\n [:div.", "end": 2564, "score": 0.9985678195953369, "start": 2557, "tag": "NAME", "value": "Larissa" } ]
src/app/renderer/settings.cljs
allison-casey/combat-tracker
0
(ns app.renderer.settings (:require [re-frame.core :as rf] [reagent.core :as r] [re-com.core :refer [button input-text label]] [re-dnd.events :as dnd] [re-dnd.views :as dndv] [cuerdas.core :as cuerdas] [app.renderer.subs :as subs])) (def electron (js/window.require "electron")) (def ipc (.-ipcRenderer electron)) ;; ** Drag and Drop Test (def last-id (r/atom 0)) (rf/reg-event-fx :my-drop-dispatch (fn [{db :db} [_ [source-drop-zone-id source-element-id] [drop-zone-id dropped-element-id dropped-position]]] (swap! last-id inc) {:db db :dispatch (if (= source-drop-zone-id drop-zone-id) [:dnd/move-drop-zone-element drop-zone-id source-element-id dropped-position] [:dnd/add-drop-zone-element drop-zone-id {:id (keyword (str (name source-element-id) "-dropped-" @last-id)) :type (if (odd? @last-id ) :bluebox :redbox)} dropped-position])})) (defmethod dndv/dropped-widget :my-drop-marker [{:keys [type id]}] [:div.drop-marker]) (defmethod dndv/dropped-widget :bluebox [{:keys [type id]}] [:div.box.blue-box (str type ", " id)]) (defmethod dndv/drag-handle :bluebox [{:keys [type id]}] [:div "bluedraghandle"]) (defmethod dndv/dropped-widget :redbox [{:keys [type id]}] [:div.list-group-item.d-flex.list-group-flush [:h4 "Ranger Bob"]]) (defmethod dndv/drag-handle :redbox [{:keys [type id]}] [:div "handle"]) (defmethod dndv/drag-handle "character" [_] [:div [:i.fa.fa-fw.fa-bars]]) (defmethod dndv/dropped-widget "character" [{:keys [name]}] [:div.list-group-item {:style {:padding-left "2.5em"}} [:span name]]) (defn dnd-example "test drag and drop component" [] (let [drag-box-state (rf/subscribe [:dnd/drag-box]) last-id (r/atom 1) characters @(rf/subscribe [::subs/characters])] (rf/dispatch [:dnd/initialize-drop-zone :initiative-tracker {:drop-dispatch [:my-drop-dispatch] :drop-marker :my-drop-marker} (->> characters (sort-by (comp :initiative :tracker/internal)) (map #(update % :id keyword))) ;; [{:type :character ;; :name "Ranger Bob" ;; :id "ranger.bob"} ;; {:type :character ;; :name "Larissa" ;; :id (keyword (cuerdas/kebab "Larissa"))}] ]) (fn [] [:div.container (when @drag-box-state [dndv/drag-box]) [dndv/drop-zone :initiative-tracker]]))) ;; ** Render (defn render [] [:div.column [:div.row [label :label "Template Directory"]] [:div.row [input-text :model (rf/subscribe [::subs/template-dir]) :on-change (constantly nil) :style {:cursor "pointer"} :attr {:on-click #(.send ipc "set-template-directory") :readOnly true}]] [dnd-example]])
13094
(ns app.renderer.settings (:require [re-frame.core :as rf] [reagent.core :as r] [re-com.core :refer [button input-text label]] [re-dnd.events :as dnd] [re-dnd.views :as dndv] [cuerdas.core :as cuerdas] [app.renderer.subs :as subs])) (def electron (js/window.require "electron")) (def ipc (.-ipcRenderer electron)) ;; ** Drag and Drop Test (def last-id (r/atom 0)) (rf/reg-event-fx :my-drop-dispatch (fn [{db :db} [_ [source-drop-zone-id source-element-id] [drop-zone-id dropped-element-id dropped-position]]] (swap! last-id inc) {:db db :dispatch (if (= source-drop-zone-id drop-zone-id) [:dnd/move-drop-zone-element drop-zone-id source-element-id dropped-position] [:dnd/add-drop-zone-element drop-zone-id {:id (keyword (str (name source-element-id) "-dropped-" @last-id)) :type (if (odd? @last-id ) :bluebox :redbox)} dropped-position])})) (defmethod dndv/dropped-widget :my-drop-marker [{:keys [type id]}] [:div.drop-marker]) (defmethod dndv/dropped-widget :bluebox [{:keys [type id]}] [:div.box.blue-box (str type ", " id)]) (defmethod dndv/drag-handle :bluebox [{:keys [type id]}] [:div "bluedraghandle"]) (defmethod dndv/dropped-widget :redbox [{:keys [type id]}] [:div.list-group-item.d-flex.list-group-flush [:h4 "<NAME>"]]) (defmethod dndv/drag-handle :redbox [{:keys [type id]}] [:div "handle"]) (defmethod dndv/drag-handle "character" [_] [:div [:i.fa.fa-fw.fa-bars]]) (defmethod dndv/dropped-widget "character" [{:keys [name]}] [:div.list-group-item {:style {:padding-left "2.5em"}} [:span name]]) (defn dnd-example "test drag and drop component" [] (let [drag-box-state (rf/subscribe [:dnd/drag-box]) last-id (r/atom 1) characters @(rf/subscribe [::subs/characters])] (rf/dispatch [:dnd/initialize-drop-zone :initiative-tracker {:drop-dispatch [:my-drop-dispatch] :drop-marker :my-drop-marker} (->> characters (sort-by (comp :initiative :tracker/internal)) (map #(update % :id keyword))) ;; [{:type :character ;; :name "<NAME>" ;; :id "ranger.bob"} ;; {:type :character ;; :name "<NAME>" ;; :id (keyword (cuerdas/kebab "<NAME>"))}] ]) (fn [] [:div.container (when @drag-box-state [dndv/drag-box]) [dndv/drop-zone :initiative-tracker]]))) ;; ** Render (defn render [] [:div.column [:div.row [label :label "Template Directory"]] [:div.row [input-text :model (rf/subscribe [::subs/template-dir]) :on-change (constantly nil) :style {:cursor "pointer"} :attr {:on-click #(.send ipc "set-template-directory") :readOnly true}]] [dnd-example]])
true
(ns app.renderer.settings (:require [re-frame.core :as rf] [reagent.core :as r] [re-com.core :refer [button input-text label]] [re-dnd.events :as dnd] [re-dnd.views :as dndv] [cuerdas.core :as cuerdas] [app.renderer.subs :as subs])) (def electron (js/window.require "electron")) (def ipc (.-ipcRenderer electron)) ;; ** Drag and Drop Test (def last-id (r/atom 0)) (rf/reg-event-fx :my-drop-dispatch (fn [{db :db} [_ [source-drop-zone-id source-element-id] [drop-zone-id dropped-element-id dropped-position]]] (swap! last-id inc) {:db db :dispatch (if (= source-drop-zone-id drop-zone-id) [:dnd/move-drop-zone-element drop-zone-id source-element-id dropped-position] [:dnd/add-drop-zone-element drop-zone-id {:id (keyword (str (name source-element-id) "-dropped-" @last-id)) :type (if (odd? @last-id ) :bluebox :redbox)} dropped-position])})) (defmethod dndv/dropped-widget :my-drop-marker [{:keys [type id]}] [:div.drop-marker]) (defmethod dndv/dropped-widget :bluebox [{:keys [type id]}] [:div.box.blue-box (str type ", " id)]) (defmethod dndv/drag-handle :bluebox [{:keys [type id]}] [:div "bluedraghandle"]) (defmethod dndv/dropped-widget :redbox [{:keys [type id]}] [:div.list-group-item.d-flex.list-group-flush [:h4 "PI:NAME:<NAME>END_PI"]]) (defmethod dndv/drag-handle :redbox [{:keys [type id]}] [:div "handle"]) (defmethod dndv/drag-handle "character" [_] [:div [:i.fa.fa-fw.fa-bars]]) (defmethod dndv/dropped-widget "character" [{:keys [name]}] [:div.list-group-item {:style {:padding-left "2.5em"}} [:span name]]) (defn dnd-example "test drag and drop component" [] (let [drag-box-state (rf/subscribe [:dnd/drag-box]) last-id (r/atom 1) characters @(rf/subscribe [::subs/characters])] (rf/dispatch [:dnd/initialize-drop-zone :initiative-tracker {:drop-dispatch [:my-drop-dispatch] :drop-marker :my-drop-marker} (->> characters (sort-by (comp :initiative :tracker/internal)) (map #(update % :id keyword))) ;; [{:type :character ;; :name "PI:NAME:<NAME>END_PI" ;; :id "ranger.bob"} ;; {:type :character ;; :name "PI:NAME:<NAME>END_PI" ;; :id (keyword (cuerdas/kebab "PI:NAME:<NAME>END_PI"))}] ]) (fn [] [:div.container (when @drag-box-state [dndv/drag-box]) [dndv/drop-zone :initiative-tracker]]))) ;; ** Render (defn render [] [:div.column [:div.row [label :label "Template Directory"]] [:div.row [input-text :model (rf/subscribe [::subs/template-dir]) :on-change (constantly nil) :style {:cursor "pointer"} :attr {:on-click #(.send ipc "set-template-directory") :readOnly true}]] [dnd-example]])
[ { "context": " fake-client-id \"o8-id\")\n(def fake-client-secret \"shh\")\n(def fake-request {:facebook-config {:client-id", "end": 339, "score": 0.8110867738723755, "start": 336, "tag": "KEY", "value": "shh" }, { "context": "\n(def login-code \"fb-code\")\n\n(def access-token \"fb-token\")\n(def access-token-response {:body (json/ge", "end": 532, "score": 0.4350813031196594, "start": 532, "tag": "PASSWORD", "value": "" }, { "context": " fb-user-id \"facebook-1234567\")\n(def valid-email \"facebook@example.com\")\n(def invalid-email \"floogle wizard\")\n(defn toke", "end": 860, "score": 0.999904453754425, "start": 840, "tag": "EMAIL", "value": "facebook@example.com" }, { "context": "facebook@example.com\")\n(def invalid-email \"floogle wizard\")\n(defn token-info-response [& {:keys [user-id ap", "end": 897, "score": 0.5408995747566223, "start": 891, "tag": "USERNAME", "value": "wizard" } ]
test/objective8/unit/workflows/facebook_test.clj
d-cent/objective8
23
(ns objective8.unit.workflows.facebook-test (:require [midje.sweet :refer :all] [objective8.front-end.workflows.facebook :refer :all] [cheshire.core :as json] [objective8.front-end.api.http :as http] [objective8.utils :as utils])) (def fake-client-id "o8-id") (def fake-client-secret "shh") (def fake-request {:facebook-config {:client-id fake-client-id :client-secret fake-client-secret}}) (def login-code "fb-code") (def access-token "fb-token") (def access-token-response {:body (json/generate-string {:access_token access-token})}) (def graph-api-error {:body (json/generate-string {:error {:code 190 :type "OAuthException"}})}) (def fb-user-id "facebook-1234567") (def valid-email "facebook@example.com") (def invalid-email "floogle wizard") (defn token-info-response [& {:keys [user-id app-id expires_at] :or {user-id 1234567 app-id fake-client-id expires_at 9876543210}}] {:body (json/generate-string {:data {:user_id user-id :app_id app-id :expires_at expires_at}})}) (defn user-info-response [email] {:body (json/generate-string {:id fb-user-id :email email})}) (defn with-code [request] (assoc-in request [:params :code] login-code)) (defn with-error [request] (assoc-in request [:params :error] "access_denied")) (fact "step 1: redirect to facebook auth page" (let [response (facebook-sign-in fake-request)] response => (contains {:status 302 :headers {"Location" (str "https://www.facebook.com/dialog/oauth?client_id=" fake-client-id "&redirect_uri=" redirect-uri "&scope=public_profile,email")}}))) ;; (fact "step 2: login and permissions acceptance handled by facebook") (facts "step 3: authenticating user" (fact "stores the facebook user id and email in the session and redirects to sign-up" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id fb-user-id :auth-provider-user-email valid-email}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response) (http/get-request "https://graph.facebook.com/v2.5/1234567/?fields=email") => (user-info-response valid-email))) (tabular (fact "stores the flash message in the request if email is invalid and redirects to sign-up" (facebook-callback (-> fake-request with-code)) => (contains (into {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id fb-user-id}} {:flash {:validation :auth-email}})) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response) (http/get-request "https://graph.facebook.com/v2.5/1234567/?fields=email") => (user-info-response ?fb-user-email))) ?fb-user-email invalid-email " " nil) (fact "redirects to homepage when user doesn't authorise application or error in fb" (facebook-callback (-> fake-request with-error)) => (contains {:status 302 :headers {"Location" utils/host-url}})) (fact "redirects to homepage when access token returns an error" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => graph-api-error)) (fact "redirects to homepage when debug token returns an error" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => graph-api-error)) (fact "redirects to homepage when app id in token info doesn't match client id" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response :app-id "error"))) (fact "redirects to homepage when expiry time in token info is before now" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response :expires_at 111))))
82851
(ns objective8.unit.workflows.facebook-test (:require [midje.sweet :refer :all] [objective8.front-end.workflows.facebook :refer :all] [cheshire.core :as json] [objective8.front-end.api.http :as http] [objective8.utils :as utils])) (def fake-client-id "o8-id") (def fake-client-secret "<KEY>") (def fake-request {:facebook-config {:client-id fake-client-id :client-secret fake-client-secret}}) (def login-code "fb-code") (def access-token "fb<PASSWORD>-token") (def access-token-response {:body (json/generate-string {:access_token access-token})}) (def graph-api-error {:body (json/generate-string {:error {:code 190 :type "OAuthException"}})}) (def fb-user-id "facebook-1234567") (def valid-email "<EMAIL>") (def invalid-email "floogle wizard") (defn token-info-response [& {:keys [user-id app-id expires_at] :or {user-id 1234567 app-id fake-client-id expires_at 9876543210}}] {:body (json/generate-string {:data {:user_id user-id :app_id app-id :expires_at expires_at}})}) (defn user-info-response [email] {:body (json/generate-string {:id fb-user-id :email email})}) (defn with-code [request] (assoc-in request [:params :code] login-code)) (defn with-error [request] (assoc-in request [:params :error] "access_denied")) (fact "step 1: redirect to facebook auth page" (let [response (facebook-sign-in fake-request)] response => (contains {:status 302 :headers {"Location" (str "https://www.facebook.com/dialog/oauth?client_id=" fake-client-id "&redirect_uri=" redirect-uri "&scope=public_profile,email")}}))) ;; (fact "step 2: login and permissions acceptance handled by facebook") (facts "step 3: authenticating user" (fact "stores the facebook user id and email in the session and redirects to sign-up" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id fb-user-id :auth-provider-user-email valid-email}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response) (http/get-request "https://graph.facebook.com/v2.5/1234567/?fields=email") => (user-info-response valid-email))) (tabular (fact "stores the flash message in the request if email is invalid and redirects to sign-up" (facebook-callback (-> fake-request with-code)) => (contains (into {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id fb-user-id}} {:flash {:validation :auth-email}})) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response) (http/get-request "https://graph.facebook.com/v2.5/1234567/?fields=email") => (user-info-response ?fb-user-email))) ?fb-user-email invalid-email " " nil) (fact "redirects to homepage when user doesn't authorise application or error in fb" (facebook-callback (-> fake-request with-error)) => (contains {:status 302 :headers {"Location" utils/host-url}})) (fact "redirects to homepage when access token returns an error" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => graph-api-error)) (fact "redirects to homepage when debug token returns an error" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => graph-api-error)) (fact "redirects to homepage when app id in token info doesn't match client id" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response :app-id "error"))) (fact "redirects to homepage when expiry time in token info is before now" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response :expires_at 111))))
true
(ns objective8.unit.workflows.facebook-test (:require [midje.sweet :refer :all] [objective8.front-end.workflows.facebook :refer :all] [cheshire.core :as json] [objective8.front-end.api.http :as http] [objective8.utils :as utils])) (def fake-client-id "o8-id") (def fake-client-secret "PI:KEY:<KEY>END_PI") (def fake-request {:facebook-config {:client-id fake-client-id :client-secret fake-client-secret}}) (def login-code "fb-code") (def access-token "fbPI:PASSWORD:<PASSWORD>END_PI-token") (def access-token-response {:body (json/generate-string {:access_token access-token})}) (def graph-api-error {:body (json/generate-string {:error {:code 190 :type "OAuthException"}})}) (def fb-user-id "facebook-1234567") (def valid-email "PI:EMAIL:<EMAIL>END_PI") (def invalid-email "floogle wizard") (defn token-info-response [& {:keys [user-id app-id expires_at] :or {user-id 1234567 app-id fake-client-id expires_at 9876543210}}] {:body (json/generate-string {:data {:user_id user-id :app_id app-id :expires_at expires_at}})}) (defn user-info-response [email] {:body (json/generate-string {:id fb-user-id :email email})}) (defn with-code [request] (assoc-in request [:params :code] login-code)) (defn with-error [request] (assoc-in request [:params :error] "access_denied")) (fact "step 1: redirect to facebook auth page" (let [response (facebook-sign-in fake-request)] response => (contains {:status 302 :headers {"Location" (str "https://www.facebook.com/dialog/oauth?client_id=" fake-client-id "&redirect_uri=" redirect-uri "&scope=public_profile,email")}}))) ;; (fact "step 2: login and permissions acceptance handled by facebook") (facts "step 3: authenticating user" (fact "stores the facebook user id and email in the session and redirects to sign-up" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id fb-user-id :auth-provider-user-email valid-email}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response) (http/get-request "https://graph.facebook.com/v2.5/1234567/?fields=email") => (user-info-response valid-email))) (tabular (fact "stores the flash message in the request if email is invalid and redirects to sign-up" (facebook-callback (-> fake-request with-code)) => (contains (into {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id fb-user-id}} {:flash {:validation :auth-email}})) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response) (http/get-request "https://graph.facebook.com/v2.5/1234567/?fields=email") => (user-info-response ?fb-user-email))) ?fb-user-email invalid-email " " nil) (fact "redirects to homepage when user doesn't authorise application or error in fb" (facebook-callback (-> fake-request with-error)) => (contains {:status 302 :headers {"Location" utils/host-url}})) (fact "redirects to homepage when access token returns an error" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => graph-api-error)) (fact "redirects to homepage when debug token returns an error" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => graph-api-error)) (fact "redirects to homepage when app id in token info doesn't match client id" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response :app-id "error"))) (fact "redirects to homepage when expiry time in token info is before now" (facebook-callback (-> fake-request with-code)) => (contains {:status 302 :headers {"Location" (str utils/host-url "/error/log-in")}}) (provided (http/get-request "https://graph.facebook.com/v2.3/oauth/access_token" {:query-params {:client_id fake-client-id :redirect_uri redirect-uri :client_secret fake-client-secret :code login-code}}) => access-token-response (http/get-request "https://graph.facebook.com/debug_token" {:query-params {:input_token access-token :access_token (str fake-client-id "|" fake-client-secret)}}) => (token-info-response :expires_at 111))))
[ { "context": "ion, check for unify in prop\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 104, "score": 0.9998648166656494, "start": 90, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/lwb/nd/swap/prop.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Natural deduction, check for unify in prop ; Copyright (c) 2016 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.nd.swap.prop (:require [lwb.prop :as prop] [lwb.nd.error :refer :all])) ;; # Checking constraints of propositional logic ;; ## Checking the constraints for prop in swap (defn check-swap "Check whether `old` and `new` can be swapped in `proof`. Throws exception if not. In the case of propositional logic we just assure that `new` is well-formed." [_ _ new] (if-not (prop/wff? new) (throw (ex-error (format "'%s' must be a well-formed formula of propositional logic." new)))))
96105
; lwb Logic WorkBench -- Natural deduction, check for unify in prop ; Copyright (c) 2016 <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.nd.swap.prop (:require [lwb.prop :as prop] [lwb.nd.error :refer :all])) ;; # Checking constraints of propositional logic ;; ## Checking the constraints for prop in swap (defn check-swap "Check whether `old` and `new` can be swapped in `proof`. Throws exception if not. In the case of propositional logic we just assure that `new` is well-formed." [_ _ new] (if-not (prop/wff? new) (throw (ex-error (format "'%s' must be a well-formed formula of propositional logic." new)))))
true
; lwb Logic WorkBench -- Natural deduction, check for unify in prop ; Copyright (c) 2016 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.nd.swap.prop (:require [lwb.prop :as prop] [lwb.nd.error :refer :all])) ;; # Checking constraints of propositional logic ;; ## Checking the constraints for prop in swap (defn check-swap "Check whether `old` and `new` can be swapped in `proof`. Throws exception if not. In the case of propositional logic we just assure that `new` is well-formed." [_ _ new] (if-not (prop/wff? new) (throw (ex-error (format "'%s' must be a well-formed formula of propositional logic." new)))))
[ { "context": "he whole material is from http://www.blogjava.net/killme2008/archive/2012/02/16/370144.html by 庄周蝶梦\n(ns langua", "end": 62, "score": 0.9936584830284119, "start": 52, "tag": "USERNAME", "value": "killme2008" }, { "context": ".net/killme2008/archive/2012/02/16/370144.html by 庄周蝶梦\n(ns language.io\n (:require [clojure.java.io :as ", "end": 101, "score": 0.9992464780807495, "start": 97, "tag": "NAME", "value": "庄周蝶梦" } ]
data/train/clojure/3fd8522375a5aa89d43572cc4d31dd04ce746912io.clj
harshp8l/deep-learning-lang-detection
84
;the whole material is from http://www.blogjava.net/killme2008/archive/2012/02/16/370144.html by 庄周蝶梦 (ns language.io (:require [clojure.java.io :as io])) ;obtain a java.io.File object (def f (io/file "D:/data/big.txt")) ;copy file (io/copy f (io/file "D:/data/b.txt")) ;copy is a tolerant function, ;it accepts InputStream Reader File byte[] or String as input ;it accepts OutputStream Writer File as io/output ;this is realized by clojure's protocol and defmulti ;但是,copy并不帮你处理文件的关闭问题, ;假设你传入的input是一个File,output也是一个File,copy会自动帮你打开InputStream和OutputStream并建立缓冲区做拷贝, ;但是它不会帮你关闭这两个流,因此你要小心,如果你经常使用copy,这可能是个内存泄漏的隐患。 ;delete-file calls File.delete (io/delete-file (io/file "D:/data/b.txt")) ;if file does not exist, this will throw an exception, to make it quiet, add this: (io/delete-file (io/file "D:/data/afasfjalf.txt") true) ;more commonly used reader and writer (def rdr (io/reader "D:/data/big.txt" :encoding "utf-8")) (def wtr (io/writer "D:/data/b.txt" :append true)) ;copy accepts many types of parameters (io/copy rdr wtr :buffer-size 4096) ;close files (.close wtr) (.close rdr) ;judge if file exists (.exists (io/file "D:/data/big.txt")) (.exists (io/file "D:/data/hehhehehe.txt")) ;更常用的,我们一般都是用reader和writer函数来打开一个BufferedReader和BufferedWriter做读写, ;同样reader和writer也可以接受多种多样的参数类型,甚至包括Socket也可以。 ;因为writer打开的通常是一个BufferedWriter,所以你如果用它写文件,有时候发现write之后文件还是没有内容, ;这是因为数据暂时写到了缓冲区里,没有刷入到磁盘,可以明确地调用(.flush wtr)来强制写入;或者在wtr关闭后系统帮你写入。 ;reader和writer还可以传入一些配置项,如:encoding指定读写的字符串编码,writer可以指定是否为append模式等。 ;Clojure并没有提供关闭文件的函数或者宏,你简单地调用close方法即可。 ;clojure.java.io的设计很有原则,它不准备将java.io都封装一遍,而是提供一些最常用方法的简便wrapper供你使用。 ;although copy will not close the document flow for you, we can utilize with-open to manage the flow (with-open [rdr (io/reader "D:/data/big.txt") wtr (io/writer "D:/data/b.txt")] (io/copy rdr wtr)) ;with-open宏会自动帮你关闭在binding vector里打开的流, ;你不再需要自己调用close,也不用担心不小心造成内存泄漏。 ;因此我会推荐你尽量用reader和writer结合with-open来做文件操作,而不要使用file函数。 ;file函数应该用在一些判断是否存在,判断文件是否为目录等操作上。 ;slurp & spit ;在clojure.core里,还有两个最常用的函数slurp和spit, ;一个吃,一个吐,也就是slurp读文件,而spit写文件, ;他们类似Ruby的File里的read和write,用来完整地读或者写文件 ;slurp 接受 :encoding 指定字符串编码 ;spit 接受 :append 和 :encoding,将content转化为字符串写入文件 (spit "D:/data/c.txt" "hello world!") ;;;;;;;;;;;;;;;;十颗星重要!读取文件序列!!!!!!!!!!!!! ;返回深度优先顺序遍历的目录列表,且是一个LazySeq (file-seq (java.io.File. ".")) (with-open [rdr (io/reader "D:/data/big.txt")] (doall (line-seq rdr))) (line-seq (io/reader "D:/data/big.txt")) (with-open [rdr (clojure.java.io/reader "D:/data/")] (count (line-seq rdr))) ;I don't know if the following is correct. (defn safe-line-seq "Similar to line-seq, add a .close at the end." [file] (let [in-file (io/reader file) lazy (fn lazy [wrapped] (lazy-seq (if-let [line (.readLine wrapped)] (cons line (lazy-seq (lazy wrapped))) (.close in-file))))] (lazy in-file))) (safe-line-seq "D:/data/big.txt") (line-seq (io/reader "D:/data/big.txt"))
5127
;the whole material is from http://www.blogjava.net/killme2008/archive/2012/02/16/370144.html by <NAME> (ns language.io (:require [clojure.java.io :as io])) ;obtain a java.io.File object (def f (io/file "D:/data/big.txt")) ;copy file (io/copy f (io/file "D:/data/b.txt")) ;copy is a tolerant function, ;it accepts InputStream Reader File byte[] or String as input ;it accepts OutputStream Writer File as io/output ;this is realized by clojure's protocol and defmulti ;但是,copy并不帮你处理文件的关闭问题, ;假设你传入的input是一个File,output也是一个File,copy会自动帮你打开InputStream和OutputStream并建立缓冲区做拷贝, ;但是它不会帮你关闭这两个流,因此你要小心,如果你经常使用copy,这可能是个内存泄漏的隐患。 ;delete-file calls File.delete (io/delete-file (io/file "D:/data/b.txt")) ;if file does not exist, this will throw an exception, to make it quiet, add this: (io/delete-file (io/file "D:/data/afasfjalf.txt") true) ;more commonly used reader and writer (def rdr (io/reader "D:/data/big.txt" :encoding "utf-8")) (def wtr (io/writer "D:/data/b.txt" :append true)) ;copy accepts many types of parameters (io/copy rdr wtr :buffer-size 4096) ;close files (.close wtr) (.close rdr) ;judge if file exists (.exists (io/file "D:/data/big.txt")) (.exists (io/file "D:/data/hehhehehe.txt")) ;更常用的,我们一般都是用reader和writer函数来打开一个BufferedReader和BufferedWriter做读写, ;同样reader和writer也可以接受多种多样的参数类型,甚至包括Socket也可以。 ;因为writer打开的通常是一个BufferedWriter,所以你如果用它写文件,有时候发现write之后文件还是没有内容, ;这是因为数据暂时写到了缓冲区里,没有刷入到磁盘,可以明确地调用(.flush wtr)来强制写入;或者在wtr关闭后系统帮你写入。 ;reader和writer还可以传入一些配置项,如:encoding指定读写的字符串编码,writer可以指定是否为append模式等。 ;Clojure并没有提供关闭文件的函数或者宏,你简单地调用close方法即可。 ;clojure.java.io的设计很有原则,它不准备将java.io都封装一遍,而是提供一些最常用方法的简便wrapper供你使用。 ;although copy will not close the document flow for you, we can utilize with-open to manage the flow (with-open [rdr (io/reader "D:/data/big.txt") wtr (io/writer "D:/data/b.txt")] (io/copy rdr wtr)) ;with-open宏会自动帮你关闭在binding vector里打开的流, ;你不再需要自己调用close,也不用担心不小心造成内存泄漏。 ;因此我会推荐你尽量用reader和writer结合with-open来做文件操作,而不要使用file函数。 ;file函数应该用在一些判断是否存在,判断文件是否为目录等操作上。 ;slurp & spit ;在clojure.core里,还有两个最常用的函数slurp和spit, ;一个吃,一个吐,也就是slurp读文件,而spit写文件, ;他们类似Ruby的File里的read和write,用来完整地读或者写文件 ;slurp 接受 :encoding 指定字符串编码 ;spit 接受 :append 和 :encoding,将content转化为字符串写入文件 (spit "D:/data/c.txt" "hello world!") ;;;;;;;;;;;;;;;;十颗星重要!读取文件序列!!!!!!!!!!!!! ;返回深度优先顺序遍历的目录列表,且是一个LazySeq (file-seq (java.io.File. ".")) (with-open [rdr (io/reader "D:/data/big.txt")] (doall (line-seq rdr))) (line-seq (io/reader "D:/data/big.txt")) (with-open [rdr (clojure.java.io/reader "D:/data/")] (count (line-seq rdr))) ;I don't know if the following is correct. (defn safe-line-seq "Similar to line-seq, add a .close at the end." [file] (let [in-file (io/reader file) lazy (fn lazy [wrapped] (lazy-seq (if-let [line (.readLine wrapped)] (cons line (lazy-seq (lazy wrapped))) (.close in-file))))] (lazy in-file))) (safe-line-seq "D:/data/big.txt") (line-seq (io/reader "D:/data/big.txt"))
true
;the whole material is from http://www.blogjava.net/killme2008/archive/2012/02/16/370144.html by PI:NAME:<NAME>END_PI (ns language.io (:require [clojure.java.io :as io])) ;obtain a java.io.File object (def f (io/file "D:/data/big.txt")) ;copy file (io/copy f (io/file "D:/data/b.txt")) ;copy is a tolerant function, ;it accepts InputStream Reader File byte[] or String as input ;it accepts OutputStream Writer File as io/output ;this is realized by clojure's protocol and defmulti ;但是,copy并不帮你处理文件的关闭问题, ;假设你传入的input是一个File,output也是一个File,copy会自动帮你打开InputStream和OutputStream并建立缓冲区做拷贝, ;但是它不会帮你关闭这两个流,因此你要小心,如果你经常使用copy,这可能是个内存泄漏的隐患。 ;delete-file calls File.delete (io/delete-file (io/file "D:/data/b.txt")) ;if file does not exist, this will throw an exception, to make it quiet, add this: (io/delete-file (io/file "D:/data/afasfjalf.txt") true) ;more commonly used reader and writer (def rdr (io/reader "D:/data/big.txt" :encoding "utf-8")) (def wtr (io/writer "D:/data/b.txt" :append true)) ;copy accepts many types of parameters (io/copy rdr wtr :buffer-size 4096) ;close files (.close wtr) (.close rdr) ;judge if file exists (.exists (io/file "D:/data/big.txt")) (.exists (io/file "D:/data/hehhehehe.txt")) ;更常用的,我们一般都是用reader和writer函数来打开一个BufferedReader和BufferedWriter做读写, ;同样reader和writer也可以接受多种多样的参数类型,甚至包括Socket也可以。 ;因为writer打开的通常是一个BufferedWriter,所以你如果用它写文件,有时候发现write之后文件还是没有内容, ;这是因为数据暂时写到了缓冲区里,没有刷入到磁盘,可以明确地调用(.flush wtr)来强制写入;或者在wtr关闭后系统帮你写入。 ;reader和writer还可以传入一些配置项,如:encoding指定读写的字符串编码,writer可以指定是否为append模式等。 ;Clojure并没有提供关闭文件的函数或者宏,你简单地调用close方法即可。 ;clojure.java.io的设计很有原则,它不准备将java.io都封装一遍,而是提供一些最常用方法的简便wrapper供你使用。 ;although copy will not close the document flow for you, we can utilize with-open to manage the flow (with-open [rdr (io/reader "D:/data/big.txt") wtr (io/writer "D:/data/b.txt")] (io/copy rdr wtr)) ;with-open宏会自动帮你关闭在binding vector里打开的流, ;你不再需要自己调用close,也不用担心不小心造成内存泄漏。 ;因此我会推荐你尽量用reader和writer结合with-open来做文件操作,而不要使用file函数。 ;file函数应该用在一些判断是否存在,判断文件是否为目录等操作上。 ;slurp & spit ;在clojure.core里,还有两个最常用的函数slurp和spit, ;一个吃,一个吐,也就是slurp读文件,而spit写文件, ;他们类似Ruby的File里的read和write,用来完整地读或者写文件 ;slurp 接受 :encoding 指定字符串编码 ;spit 接受 :append 和 :encoding,将content转化为字符串写入文件 (spit "D:/data/c.txt" "hello world!") ;;;;;;;;;;;;;;;;十颗星重要!读取文件序列!!!!!!!!!!!!! ;返回深度优先顺序遍历的目录列表,且是一个LazySeq (file-seq (java.io.File. ".")) (with-open [rdr (io/reader "D:/data/big.txt")] (doall (line-seq rdr))) (line-seq (io/reader "D:/data/big.txt")) (with-open [rdr (clojure.java.io/reader "D:/data/")] (count (line-seq rdr))) ;I don't know if the following is correct. (defn safe-line-seq "Similar to line-seq, add a .close at the end." [file] (let [in-file (io/reader file) lazy (fn lazy [wrapped] (lazy-seq (if-let [line (.readLine wrapped)] (cons line (lazy-seq (lazy wrapped))) (.close in-file))))] (lazy in-file))) (safe-line-seq "D:/data/big.txt") (line-seq (io/reader "D:/data/big.txt"))
[ { "context": ":visible @modal-visible\n :title \"CIKISS YAPIYORSUNNN\"\n :on-ok #(reset! modal-visible ", "end": 3481, "score": 0.761833906173706, "start": 3462, "tag": "NAME", "value": "CIKISS YAPIYORSUNNN" } ]
src/crud_app/profile.cljs
alicancelik/CRUD-App
3
(ns crud-app.profile (:require [reagent.core :as r] [antizer.reagent :as ant] [clojure.string :as s] [crud-app.db :refer [app-state]] [crud-app.home :refer [submit]] [crud-app.actions :refer [get-data]] )) (def change-button-clicked (r/atom false)) (def source-avatar (r/atom "")) (def source-giphy (r/atom "")) (def modal-visible (r/atom false)) (defn render-avatar [] (fn [] (r/as-element [ant/avatar { :style {:background-color (:avatar-color (:current-employee @app-state))} :class "va-middle" :src @source-avatar :shape "square" :size 128 } (subs (clojure.string/upper-case (:name (:current-employee @app-state))) 0 1)]))) (defn change-condition [] (get-data) (println @change-button-clicked) (if @change-button-clicked (reset! change-button-clicked false) (reset! change-button-clicked true))) (defn render-info-button [] (fn [] (r/as-element [ant/button { :on-click change-condition :type "ghost" :style {:margin-top 10} } "Change Info"]))) (defn input [value k margin-left] (fn [] [:input {:value (-> @app-state :current-employee k) :style {:width "200px" :height "30px" :border-radius 5 :margin-right 50 :margin-top 20 :margin-left margin-left} :on-change #(swap! app-state assoc-in [:current-employee k] (-> % .-target .-value))}])) (defn handle-change-name [] (fn [] [:div [:p "Name: " [input (:name {:current-employee @app-state}) :name 20]]])) (defn handle-change-surname [] (fn [] [:div [:p "Surname: " [input (:surname {:current-employee @app-state}) :surname 0]]])) (defn render-inputs [] [:<> [handle-change-name] [handle-change-surname] ]) (defn change-avatar [title] (fn [] (case title "The Matrix" ((reset! source-giphy "https://media.giphy.com/media/zhJR6HbK4fthC/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/thumb/c/c6/NeoTheMatrix.jpg/220px-NeoTheMatrix.jpg")) "Inception" ((reset! source-giphy "https://media.giphy.com/media/z1meXneq0oUh2/giphy.gif") (reset! source-avatar "https://vignette.wikia.nocookie.net/inception/images/2/2b/Dom_cobb.jpg/revision/latest?cb=20150125061140")) "Back to the Future" ((reset! source-giphy "https://media.giphy.com/media/zZeCRfPyXi9UI/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/thumb/d/db/Back_to_the_Future_%28time_travel_test%29_with_Michael_J._Fox_as_Marty_McFly.jpg/250px-Back_to_the_Future_%28time_travel_test%29_with_Michael_J._Fox_as_Marty_McFly.jpg")) "Star Wars" ((reset! source-giphy "https://media.giphy.com/media/l0K4k1O7RJSghST3a/giphy.gif") (reset! source-avatar "https://localtvkdvr.files.wordpress.com/2012/10/darth.jpg?quality=85&strip=all&w=400")) "Interstellar" ((reset! source-giphy "https://media1.giphy.com/media/z01pLEplVpc5O/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/b/bc/Interstellar_film_poster.jpg")) ))) (defn render-modal-fn [] (fn [] [ant/modal { :visible @modal-visible :title "CIKISS YAPIYORSUNNN" :on-ok #(reset! modal-visible false) :on-cancel #(reset! modal-visible false) } [:img { :style {:width "100%" :height "100%"} :src "http://c12.incisozluk.com.tr/res/incisozluk//11508/4/3194194_o013c.jpg\n" }] ] ) ) (defn favorite-movies [] (fn [] [:<> [:p [:h2 "Click to Choose Your Side"]] [:ul (doall (for [movie (:movies @app-state)] [:li {:key (:title movie)} [ant/button {:on-click (change-avatar (:title movie)) :style {:border "none" :text-decoration "none" :box-shadow "none" :background-color "transparent"} } (str (:title movie))]]) )]])) (defn cikis-yap-fn [] [ant/button { :type "primary" :on-click #(reset! modal-visible true)} "CIKIS YAP"]) (defn update-employee [] (fn [] (r/as-element [ant/button { :on-click #(submit true) :href "#/" :type "primary" :style {:margin-top 20 :margin-bottom 20} } "Update"]))) (defn profile [] (get-data) (fn [] [:<> [:div {:style {:background-color (:avatar-color (:current-employee @app-state)) :display "flex" :justify-content "center" :vertical-align "center"}} [:p [:h1 {:style {:margin-top 20 :color "white"}} "Profile"]] ] [:div {:style { :display "flex" :justify-content "center" }} [:div {:style {:display "flex" :justify-content "center" :flex-direction "column" :vertical-align "center" :align-items "center" :margin-top 20 }} [render-avatar] [:div [:h2 (:name (:current-employee @app-state))]] [render-info-button] [:div (when @change-button-clicked [render-inputs])] [update-employee] [favorite-movies] [cikis-yap-fn] [render-modal-fn] ] [:div {:style {:height "100%" :margin-left 20}} [:img {:style {:float "right" :position "absolute" :margin-top 20} :src @source-giphy}] ] ] ]))
109750
(ns crud-app.profile (:require [reagent.core :as r] [antizer.reagent :as ant] [clojure.string :as s] [crud-app.db :refer [app-state]] [crud-app.home :refer [submit]] [crud-app.actions :refer [get-data]] )) (def change-button-clicked (r/atom false)) (def source-avatar (r/atom "")) (def source-giphy (r/atom "")) (def modal-visible (r/atom false)) (defn render-avatar [] (fn [] (r/as-element [ant/avatar { :style {:background-color (:avatar-color (:current-employee @app-state))} :class "va-middle" :src @source-avatar :shape "square" :size 128 } (subs (clojure.string/upper-case (:name (:current-employee @app-state))) 0 1)]))) (defn change-condition [] (get-data) (println @change-button-clicked) (if @change-button-clicked (reset! change-button-clicked false) (reset! change-button-clicked true))) (defn render-info-button [] (fn [] (r/as-element [ant/button { :on-click change-condition :type "ghost" :style {:margin-top 10} } "Change Info"]))) (defn input [value k margin-left] (fn [] [:input {:value (-> @app-state :current-employee k) :style {:width "200px" :height "30px" :border-radius 5 :margin-right 50 :margin-top 20 :margin-left margin-left} :on-change #(swap! app-state assoc-in [:current-employee k] (-> % .-target .-value))}])) (defn handle-change-name [] (fn [] [:div [:p "Name: " [input (:name {:current-employee @app-state}) :name 20]]])) (defn handle-change-surname [] (fn [] [:div [:p "Surname: " [input (:surname {:current-employee @app-state}) :surname 0]]])) (defn render-inputs [] [:<> [handle-change-name] [handle-change-surname] ]) (defn change-avatar [title] (fn [] (case title "The Matrix" ((reset! source-giphy "https://media.giphy.com/media/zhJR6HbK4fthC/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/thumb/c/c6/NeoTheMatrix.jpg/220px-NeoTheMatrix.jpg")) "Inception" ((reset! source-giphy "https://media.giphy.com/media/z1meXneq0oUh2/giphy.gif") (reset! source-avatar "https://vignette.wikia.nocookie.net/inception/images/2/2b/Dom_cobb.jpg/revision/latest?cb=20150125061140")) "Back to the Future" ((reset! source-giphy "https://media.giphy.com/media/zZeCRfPyXi9UI/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/thumb/d/db/Back_to_the_Future_%28time_travel_test%29_with_Michael_J._Fox_as_Marty_McFly.jpg/250px-Back_to_the_Future_%28time_travel_test%29_with_Michael_J._Fox_as_Marty_McFly.jpg")) "Star Wars" ((reset! source-giphy "https://media.giphy.com/media/l0K4k1O7RJSghST3a/giphy.gif") (reset! source-avatar "https://localtvkdvr.files.wordpress.com/2012/10/darth.jpg?quality=85&strip=all&w=400")) "Interstellar" ((reset! source-giphy "https://media1.giphy.com/media/z01pLEplVpc5O/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/b/bc/Interstellar_film_poster.jpg")) ))) (defn render-modal-fn [] (fn [] [ant/modal { :visible @modal-visible :title "<NAME>" :on-ok #(reset! modal-visible false) :on-cancel #(reset! modal-visible false) } [:img { :style {:width "100%" :height "100%"} :src "http://c12.incisozluk.com.tr/res/incisozluk//11508/4/3194194_o013c.jpg\n" }] ] ) ) (defn favorite-movies [] (fn [] [:<> [:p [:h2 "Click to Choose Your Side"]] [:ul (doall (for [movie (:movies @app-state)] [:li {:key (:title movie)} [ant/button {:on-click (change-avatar (:title movie)) :style {:border "none" :text-decoration "none" :box-shadow "none" :background-color "transparent"} } (str (:title movie))]]) )]])) (defn cikis-yap-fn [] [ant/button { :type "primary" :on-click #(reset! modal-visible true)} "CIKIS YAP"]) (defn update-employee [] (fn [] (r/as-element [ant/button { :on-click #(submit true) :href "#/" :type "primary" :style {:margin-top 20 :margin-bottom 20} } "Update"]))) (defn profile [] (get-data) (fn [] [:<> [:div {:style {:background-color (:avatar-color (:current-employee @app-state)) :display "flex" :justify-content "center" :vertical-align "center"}} [:p [:h1 {:style {:margin-top 20 :color "white"}} "Profile"]] ] [:div {:style { :display "flex" :justify-content "center" }} [:div {:style {:display "flex" :justify-content "center" :flex-direction "column" :vertical-align "center" :align-items "center" :margin-top 20 }} [render-avatar] [:div [:h2 (:name (:current-employee @app-state))]] [render-info-button] [:div (when @change-button-clicked [render-inputs])] [update-employee] [favorite-movies] [cikis-yap-fn] [render-modal-fn] ] [:div {:style {:height "100%" :margin-left 20}} [:img {:style {:float "right" :position "absolute" :margin-top 20} :src @source-giphy}] ] ] ]))
true
(ns crud-app.profile (:require [reagent.core :as r] [antizer.reagent :as ant] [clojure.string :as s] [crud-app.db :refer [app-state]] [crud-app.home :refer [submit]] [crud-app.actions :refer [get-data]] )) (def change-button-clicked (r/atom false)) (def source-avatar (r/atom "")) (def source-giphy (r/atom "")) (def modal-visible (r/atom false)) (defn render-avatar [] (fn [] (r/as-element [ant/avatar { :style {:background-color (:avatar-color (:current-employee @app-state))} :class "va-middle" :src @source-avatar :shape "square" :size 128 } (subs (clojure.string/upper-case (:name (:current-employee @app-state))) 0 1)]))) (defn change-condition [] (get-data) (println @change-button-clicked) (if @change-button-clicked (reset! change-button-clicked false) (reset! change-button-clicked true))) (defn render-info-button [] (fn [] (r/as-element [ant/button { :on-click change-condition :type "ghost" :style {:margin-top 10} } "Change Info"]))) (defn input [value k margin-left] (fn [] [:input {:value (-> @app-state :current-employee k) :style {:width "200px" :height "30px" :border-radius 5 :margin-right 50 :margin-top 20 :margin-left margin-left} :on-change #(swap! app-state assoc-in [:current-employee k] (-> % .-target .-value))}])) (defn handle-change-name [] (fn [] [:div [:p "Name: " [input (:name {:current-employee @app-state}) :name 20]]])) (defn handle-change-surname [] (fn [] [:div [:p "Surname: " [input (:surname {:current-employee @app-state}) :surname 0]]])) (defn render-inputs [] [:<> [handle-change-name] [handle-change-surname] ]) (defn change-avatar [title] (fn [] (case title "The Matrix" ((reset! source-giphy "https://media.giphy.com/media/zhJR6HbK4fthC/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/thumb/c/c6/NeoTheMatrix.jpg/220px-NeoTheMatrix.jpg")) "Inception" ((reset! source-giphy "https://media.giphy.com/media/z1meXneq0oUh2/giphy.gif") (reset! source-avatar "https://vignette.wikia.nocookie.net/inception/images/2/2b/Dom_cobb.jpg/revision/latest?cb=20150125061140")) "Back to the Future" ((reset! source-giphy "https://media.giphy.com/media/zZeCRfPyXi9UI/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/thumb/d/db/Back_to_the_Future_%28time_travel_test%29_with_Michael_J._Fox_as_Marty_McFly.jpg/250px-Back_to_the_Future_%28time_travel_test%29_with_Michael_J._Fox_as_Marty_McFly.jpg")) "Star Wars" ((reset! source-giphy "https://media.giphy.com/media/l0K4k1O7RJSghST3a/giphy.gif") (reset! source-avatar "https://localtvkdvr.files.wordpress.com/2012/10/darth.jpg?quality=85&strip=all&w=400")) "Interstellar" ((reset! source-giphy "https://media1.giphy.com/media/z01pLEplVpc5O/giphy.gif") (reset! source-avatar "https://upload.wikimedia.org/wikipedia/en/b/bc/Interstellar_film_poster.jpg")) ))) (defn render-modal-fn [] (fn [] [ant/modal { :visible @modal-visible :title "PI:NAME:<NAME>END_PI" :on-ok #(reset! modal-visible false) :on-cancel #(reset! modal-visible false) } [:img { :style {:width "100%" :height "100%"} :src "http://c12.incisozluk.com.tr/res/incisozluk//11508/4/3194194_o013c.jpg\n" }] ] ) ) (defn favorite-movies [] (fn [] [:<> [:p [:h2 "Click to Choose Your Side"]] [:ul (doall (for [movie (:movies @app-state)] [:li {:key (:title movie)} [ant/button {:on-click (change-avatar (:title movie)) :style {:border "none" :text-decoration "none" :box-shadow "none" :background-color "transparent"} } (str (:title movie))]]) )]])) (defn cikis-yap-fn [] [ant/button { :type "primary" :on-click #(reset! modal-visible true)} "CIKIS YAP"]) (defn update-employee [] (fn [] (r/as-element [ant/button { :on-click #(submit true) :href "#/" :type "primary" :style {:margin-top 20 :margin-bottom 20} } "Update"]))) (defn profile [] (get-data) (fn [] [:<> [:div {:style {:background-color (:avatar-color (:current-employee @app-state)) :display "flex" :justify-content "center" :vertical-align "center"}} [:p [:h1 {:style {:margin-top 20 :color "white"}} "Profile"]] ] [:div {:style { :display "flex" :justify-content "center" }} [:div {:style {:display "flex" :justify-content "center" :flex-direction "column" :vertical-align "center" :align-items "center" :margin-top 20 }} [render-avatar] [:div [:h2 (:name (:current-employee @app-state))]] [render-info-button] [:div (when @change-button-clicked [render-inputs])] [update-employee] [favorite-movies] [cikis-yap-fn] [render-modal-fn] ] [:div {:style {:height "100%" :margin-left 20}} [:img {:style {:float "right" :position "absolute" :margin-top 20} :src @source-giphy}] ] ] ]))
[ { "context": "1 2 3)\n\n(seq #{1 2 3})\n; => (1 2 3)\n\n(seq {:name \"Bill Compton\" :occupation \"Dead mopey guy\"})\n; => ([:name \"Bil", "end": 634, "score": 0.999812662601471, "start": 622, "tag": "NAME", "value": "Bill Compton" }, { "context": "ton\" :occupation \"Dead mopey guy\"})\n; => ([:name \"Bill Compton\"] [:occupation \"Dead mopey guy\"])\n\n(into {} (seq ", "end": 693, "score": 0.9996566772460938, "start": 681, "tag": "NAME", "value": "Bill Compton" }, { "context": "\n; => (144 5 144/5)\n\n\n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :re", "end": 1506, "score": 0.9993512630462646, "start": 1500, "tag": "NAME", "value": "Batman" }, { "context": "4/5)\n\n\n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n ", "end": 1526, "score": 0.9995622634887695, "start": 1515, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"", "end": 1551, "score": 0.9856380820274353, "start": 1541, "tag": "NAME", "value": "Spider-Man" }, { "context": "eal \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias", "end": 1572, "score": 0.9994993805885315, "start": 1560, "tag": "NAME", "value": "Peter Parker" }, { "context": "as \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :rea", "end": 1592, "score": 0.9971122741699219, "start": 1587, "tag": "NAME", "value": "Santa" }, { "context": "\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :real \"Your dad\"}])\n\n(map :real identities)\n; =>", "end": 1636, "score": 0.9962368607521057, "start": 1624, "tag": "NAME", "value": "Easter Bunny" }, { "context": "real \"Your dad\"}])\n\n(map :real identities)\n; => (\"Bruce Wayne\" \"Peter Parker\" \"Your mom\" \"Your dad\")\n\n(reduce (", "end": 1700, "score": 0.9996269941329956, "start": 1689, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "\"}])\n\n(map :real identities)\n; => (\"Bruce Wayne\" \"Peter Parker\" \"Your mom\" \"Your dad\")\n\n(reduce (fn [new-map [ke", "end": 1715, "score": 0.999596357345581, "start": 1703, "tag": "NAME", "value": "Peter Parker" }, { "context": "makes-blood-puns? false, :has-pulse? true :name \"McFishwich\"}\n 1 {:makes-blood-puns? false, :has-pu", "end": 4174, "score": 0.9811869859695435, "start": 4172, "tag": "NAME", "value": "Mc" }, { "context": "kes-blood-puns? false, :has-pulse? true :name \"McFishwich\"}\n 1 {:makes-blood-puns? false, :has-pulse?", "end": 4178, "score": 0.5096263885498047, "start": 4174, "tag": "USERNAME", "value": "Fish" }, { "context": "blood-puns? false, :has-pulse? true :name \"McFishwich\"}\n 1 {:makes-blood-puns? false, :has-pulse? tru", "end": 4182, "score": 0.9181634187698364, "start": 4178, "tag": "NAME", "value": "wich" }, { "context": "makes-blood-puns? false, :has-pulse? true :name \"McMackson\"}\n 2 {:makes-blood-puns? true, :has-pulse? fal", "end": 4251, "score": 0.9687768816947937, "start": 4242, "tag": "NAME", "value": "McMackson" }, { "context": "makes-blood-puns? true, :has-pulse? false :name \"Damon Salvatore\"}\n 3 {:makes-blood-puns? true, :has-pulse? tru", "end": 4326, "score": 0.9998099207878113, "start": 4311, "tag": "NAME", "value": "Damon Salvatore" }, { "context": "makes-blood-puns? true, :has-pulse? true :name \"Mickey Mouse\"}})\n\n(defn vampire-related-details\n [social-secu", "end": 4398, "score": 0.9988975524902344, "start": 4386, "tag": "NAME", "value": "Mickey Mouse" }, { "context": "\n; => \"Elapsed time: 1001.042 msecs\"\n; => {:name \"McFishwich\", :makes-blood-puns? false, :has-pulse? true}\n\n(t", "end": 4892, "score": 0.8933453559875488, "start": 4882, "tag": "USERNAME", "value": "McFishwich" }, { "context": "; => \"Elapsed time: 32030.767 msecs\"\n; => {:name \"McFishwich\", :makes-blood-puns? false, :has-pulse? t", "end": 5159, "score": 0.4989221692085266, "start": 5157, "tag": "NAME", "value": "Mc" }, { "context": "=> \"Elapsed time: 32030.767 msecs\"\n; => {:name \"McFishwich\", :makes-blood-puns? false, :has-pulse? true}\n\n(t", "end": 5167, "score": 0.9584161639213562, "start": 5159, "tag": "USERNAME", "value": "Fishwich" }, { "context": "s))\n; => \"Elapsed time: 0.022 msecs\"\n; => {:name \"McFishwich\", :makes-blood-puns? false, :has-pulse? true}\n\n(t", "end": 5301, "score": 0.9048097729682922, "start": 5291, "tag": "USERNAME", "value": "McFishwich" }, { "context": "0)))\n\"Elapsed time: 32019.912 msecs\"\n; => {:name \"Damon Salvatore\", :makes-blood-puns? true, :has-pulse? false}\n\n(c", "end": 5453, "score": 0.9998178482055664, "start": 5438, "tag": "NAME", "value": "Damon Salvatore" }, { "context": "s-pulse? false}\n\n(concat (take 8 (repeat \"na\")) [\"Batman!\"])\n; => (\"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\"", "end": 5540, "score": 0.8669093251228333, "start": 5534, "tag": "NAME", "value": "Batman" }, { "context": "])\n; => (\"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"Batman!\")\n\n(take 3 (repeatedly (fn [] (rand-int 10))))\n;", "end": 5598, "score": 0.9456841349601746, "start": 5592, "tag": "NAME", "value": "Batman" }, { "context": "e\n\n\n;; Examples from FWPD\n\n(slurp filename)\n; => \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\n", "end": 8644, "score": 0.9998453855514526, "start": 8631, "tag": "NAME", "value": "Edward Cullen" }, { "context": "rom FWPD\n\n(slurp filename)\n; => \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen", "end": 8659, "score": 0.9864775538444519, "start": 8648, "tag": "NAME", "value": "nBella Swan" }, { "context": "p filename)\n; => \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\"\n\n(parse (slu", "end": 8675, "score": 0.9997791051864624, "start": 8663, "tag": "NAME", "value": "Charlie Swan" }, { "context": " \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\"\n\n(parse (slurp filename))\n;", "end": 8690, "score": 0.9998371005058289, "start": 8679, "tag": "NAME", "value": "Jacob Black" }, { "context": ",10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\"\n\n(parse (slurp filename))\n; => ([\"Edward Culle", "end": 8709, "score": 0.9998634457588196, "start": 8694, "tag": "NAME", "value": "Carlisle Cullen" }, { "context": "lisle Cullen,6\"\n\n(parse (slurp filename))\n; => ([\"Edward Cullen\" \"10\"] [\"Bella Swan\" \"0\"] [\"Charlie Swan\" \"0\"]\n; ", "end": 8760, "score": 0.9998583793640137, "start": 8747, "tag": "NAME", "value": "Edward Cullen" }, { "context": " (slurp filename))\n; => ([\"Edward Cullen\" \"10\"] [\"Bella Swan\" \"0\"] [\"Charlie Swan\" \"0\"]\n; => [\"Jacob Black\" \"", "end": 8780, "score": 0.9997836351394653, "start": 8770, "tag": "NAME", "value": "Bella Swan" }, { "context": "; => ([\"Edward Cullen\" \"10\"] [\"Bella Swan\" \"0\"] [\"Charlie Swan\" \"0\"]\n; => [\"Jacob Black\" \"3\"] [\"Carlisle Cullen", "end": 8801, "score": 0.9998226165771484, "start": 8789, "tag": "NAME", "value": "Charlie Swan" }, { "context": "] [\"Bella Swan\" \"0\"] [\"Charlie Swan\" \"0\"]\n; => [\"Jacob Black\" \"3\"] [\"Carlisle Cullen\" \"6\"])\n\n\n(first (mapify (", "end": 8827, "score": 0.9998431205749512, "start": 8816, "tag": "NAME", "value": "Jacob Black" }, { "context": " [\"Charlie Swan\" \"0\"]\n; => [\"Jacob Black\" \"3\"] [\"Carlisle Cullen\" \"6\"])\n\n\n(first (mapify (parse (slurp filename)))", "end": 8851, "score": 0.9998809695243835, "start": 8836, "tag": "NAME", "value": "Carlisle Cullen" }, { "context": "lurp filename))))\n; => {:glitter-index 10, :name \"Edward Cullen\"}\n\n(glitter-filter 3 (mapify (parse (slurp filena", "end": 8948, "score": 0.9998596906661987, "start": 8935, "tag": "NAME", "value": "Edward Cullen" }, { "context": "ter 3 (mapify (parse (slurp filename))))\n({:name \"Edward Cullen\", :glitter-index 10}\n {:name \"Jacob Black\", :glit", "end": 9027, "score": 0.9998636245727539, "start": 9014, "tag": "NAME", "value": "Edward Cullen" }, { "context": "name \"Edward Cullen\", :glitter-index 10}\n {:name \"Jacob Black\", :glitter-index 3}\n {:name \"Carlisle Cullen\", :g", "end": 9069, "score": 0.9998478889465332, "start": 9058, "tag": "NAME", "value": "Jacob Black" }, { "context": " {:name \"Jacob Black\", :glitter-index 3}\n {:name \"Carlisle Cullen\", :glitter-index 6})\n", "end": 9114, "score": 0.999885082244873, "start": 9099, "tag": "NAME", "value": "Carlisle Cullen" } ]
master/cftbat-code-master/cftbat-code-master/04/code.clj
AlexRogalskiy/DevArtifacts
4
(defn titleize [topic] (str topic " for the Brave and True")) (map titleize ["Hamsters" "Ragnarok"]) ; => ("Hamsters for the Brave and True" "Ragnarok for the Brave and True") (map titleize '("Empathy" "Decorating")) ; => ("Empathy for the Brave and True" "Decorating for the Brave and True") (map titleize #{"Elbows" "Soap Carving"}) ; => ("Elbows for the Brave and True" "Soap Carving for the Brave and True") (map #(titleize (second %)) {:uncomfortable-thing "Winking"}) ; => ("Winking for the Brave and True") (seq '(1 2 3)) ; => (1 2 3) (seq [1 2 3]) ; => (1 2 3) (seq #{1 2 3}) ; => (1 2 3) (seq {:name "Bill Compton" :occupation "Dead mopey guy"}) ; => ([:name "Bill Compton"] [:occupation "Dead mopey guy"]) (into {} (seq {:a 1 :b 2 :c 3})) ; => {:a 1, :c 3, :b 2} (map inc [1 2 3]) ; => (2 3 4) (map str ["a" "b" "c"] ["A" "B" "C"]) ; => ("aA" "bB" "cC") (list (str "a" "A") (str "b" "B") (str "c" "C")) (def human-consumption [8.1 7.3 6.6 5.0]) (def critter-consumption [0.0 0.2 0.3 1.1]) (defn unify-diet-data [human critter] {:human human :critter critter}) (map unify-diet-data human-consumption critter-consumption) ; => ({:human 8.1, :critter 0.0} {:human 7.3, :critter 0.2} {:human 6.6, :critter 0.3} {:human 5.0, :critter 1.8} (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [3 4 10]) ; => (17 3 17/3) (stats [80 1 44 13 6]) ; => (144 5 144/5) (def identities [{:alias "Batman" :real "Bruce Wayne"} {:alias "Spider-Man" :real "Peter Parker"} {:alias "Santa" :real "Your mom"} {:alias "Easter Bunny" :real "Your dad"}]) (map :real identities) ; => ("Bruce Wayne" "Peter Parker" "Your mom" "Your dad") (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:max 30 :min 10}) ; => {:max 31, :min 11} (assoc (assoc {} :max (inc 30)) :min (inc 10)) (reduce (fn [new-map [key val]] (if (> val 4) (assoc new-map key val) new-map)) {} {:human 4.1 :critter 3.9}) ; => {:human 4.1} (take 3 [1 2 3 4 5 6 7 8 9 10]) ; => (1 2 3) (drop 3 [1 2 3 4 5 6 7 8 9 10]) ; => (4 5 6 7 8 9 10) (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) ; => ({:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} (drop-while #(< (:month %) 3) food-journal) ; => ({:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6} (take-while #(< (:month %) 4) (drop-while #(< (:month %) 2) food-journal)) ; => ({:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} (filter #(< (:human %) 5) food-journal) ; => ({:month 2 :day 1 :human 4.9 :critter 2.1} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6} (filter #(< (:month %) 3) food-journal) ; => ({:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} (some #(> (:critter %) 5) food-journal) ; => nil (some #(> (:critter %) 3) food-journal) ; => true (some #(and (> (:critter %) 3) %) food-journal) ; => {:month 3 :day 1 :human 4.2 :critter 3.3} (sort [3 1 2]) ; => (1 2 3) (sort-by count ["aaa" "c" "bb"]) ; => ("c" "bb" "aaa") (concat [1 2] [3 4]) ; => (1 2 3 4) (def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "McFishwich"} 1 {:makes-blood-puns? false, :has-pulse? true :name "McMackson"} 2 {:makes-blood-puns? true, :has-pulse? false :name "Damon Salvatore"} 3 {:makes-blood-puns? true, :has-pulse? true :name "Mickey Mouse"}}) (defn vampire-related-details [social-security-number] (Thread/sleep 1000) (get vampire-database social-security-number)) (defn vampire? [record] (and (:makes-blood-puns? record) (not (:has-pulse? record)) record)) (defn identify-vampire [social-security-numbers] (first (filter vampire? (map vampire-related-details social-security-numbers)))) (time (vampire-related-details 0)) ; => "Elapsed time: 1001.042 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (def mapped-details (map vampire-related-details (range 0 1000000)))) ; => "Elapsed time: 0.049 msecs" ; => #'user/mapped-details (time (first mapped-details)) ; => "Elapsed time: 32030.767 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (first mapped-details)) ; => "Elapsed time: 0.022 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (identify-vampire (range 0 1000000))) "Elapsed time: 32019.912 msecs" ; => {:name "Damon Salvatore", :makes-blood-puns? true, :has-pulse? false} (concat (take 8 (repeat "na")) ["Batman!"]) ; => ("na" "na" "na" "na" "na" "na" "na" "na" "Batman!") (take 3 (repeatedly (fn [] (rand-int 10)))) ; => (1 4 0) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (take 10 (even-numbers)) ; => (0 2 4 6 8 10 12 14 16 18) (cons 0 '(2 4 6)) ; => (0 2 4 6) (empty? []) ; => true (empty? ["no!"]) ; => false (map identity {:sunlight-reaction "Glitter!"}) ; => ([:sunlight-reaction "Glitter!"]) (into {} (map identity {:sunlight-reaction "Glitter!"})) ; => {:sunlight-reaction "Glitter!"} (map identity [:garlic :sesame-oil :fried-eggs]) ; => (:garlic :sesame-oil :fried-eggs) (into [] (map identity [:garlic :sesame-oil :fried-eggs])) ; => [:garlic :sesame-oil :fried-eggs] (map identity [:garlic-clove :garlic-clove]) ; => (:garlic-clove :garlic-clove) (into #{} (map identity [:garlic-clove :garlic-clove])) ; => #{:garlic-clove} (into {:favorite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]]) ; => {:favorite-emotion "gloomy" :sunlight-reaction "Glitter!"} (into ["cherry"] '("pine" "spruce")) ; => ["cherry" "pine" "spruce"] (into {:favorite-animal "kitty"} {:least-favorite-smell "dog" :relationship-with-teenager "creepy"}) ; => {:favorite-animal "kitty" ; => :relationship-with-teenager "creepy" ; => :least-favorite-smell "dog"} (conj [0] [1]) ; => [0 [1]] (into [0] [1]) ; => [0 1] (conj [0] 1) ; => [0 1] (conj [0] 1 2 3 4) ; => [0 1 2 3 4] (conj {:time "midnight"} [:place "ye olde cemetarium"]) ; => {:place "ye olde cemetarium" :time "midnight"} (defn my-conj [target & additions] (into target additions)) (my-conj [0] 1 2 3) ; => [0 1 2 3] (max 0 1 2) ; => 2 (max [0 1 2]) ; => [0 1 2] (apply max [0 1 2]) ; => 2 (defn my-into [target additions] (apply conj target additions)) (my-into [0] [1 2 3]) ; => [0 1 2 3] (def add10 (partial + 10)) (add10 3) ; => 13 (add10 5) ; => 15 (def add-missing-elements (partial conj ["water" "earth" "air"])) (add-missing-elements "unobtainium" "adamantium") ; => ["water" "earth" "air" "unobtainium" "adamantium"] (defn my-partial [partialized-fn & args] (fn [& more-args] (apply partialized-fn (into args more-args)))) (def add20 (my-partial + 20)) (add20 3) ; => 23 (fn [& more-args] (apply + (into [20] more-args))) (defn lousy-logger [log-level message] (condp = log-level :warn (clojure.string/lower-case message) :emergency (clojure.string/upper-case message))) (def warn (partial lousy-logger :warn)) (warn "Red light ahead") ; => "red light ahead" (defn identify-humans [social-security-numbers] (filter #(not (vampire? %)) (map vampire-related-details social-security-numbers))) (def not-vampire? (complement vampire?)) (defn identify-humans [social-security-numbers] (filter not-vampire? (map vampire-related-details social-security-numbers))) (defn my-complement [fun] (fn [& args] (not (apply fun args)))) (def my-pos? (complement neg?)) (my-pos? 1) ; => true (my-pos? -1) ; => false ;; Examples from FWPD (slurp filename) ; => "Edward Cullen,10\nBella Swan,0\nCharlie Swan,0\nJacob Black,3\nCarlisle Cullen,6" (parse (slurp filename)) ; => (["Edward Cullen" "10"] ["Bella Swan" "0"] ["Charlie Swan" "0"] ; => ["Jacob Black" "3"] ["Carlisle Cullen" "6"]) (first (mapify (parse (slurp filename)))) ; => {:glitter-index 10, :name "Edward Cullen"} (glitter-filter 3 (mapify (parse (slurp filename)))) ({:name "Edward Cullen", :glitter-index 10} {:name "Jacob Black", :glitter-index 3} {:name "Carlisle Cullen", :glitter-index 6})
74343
(defn titleize [topic] (str topic " for the Brave and True")) (map titleize ["Hamsters" "Ragnarok"]) ; => ("Hamsters for the Brave and True" "Ragnarok for the Brave and True") (map titleize '("Empathy" "Decorating")) ; => ("Empathy for the Brave and True" "Decorating for the Brave and True") (map titleize #{"Elbows" "Soap Carving"}) ; => ("Elbows for the Brave and True" "Soap Carving for the Brave and True") (map #(titleize (second %)) {:uncomfortable-thing "Winking"}) ; => ("Winking for the Brave and True") (seq '(1 2 3)) ; => (1 2 3) (seq [1 2 3]) ; => (1 2 3) (seq #{1 2 3}) ; => (1 2 3) (seq {:name "<NAME>" :occupation "Dead mopey guy"}) ; => ([:name "<NAME>"] [:occupation "Dead mopey guy"]) (into {} (seq {:a 1 :b 2 :c 3})) ; => {:a 1, :c 3, :b 2} (map inc [1 2 3]) ; => (2 3 4) (map str ["a" "b" "c"] ["A" "B" "C"]) ; => ("aA" "bB" "cC") (list (str "a" "A") (str "b" "B") (str "c" "C")) (def human-consumption [8.1 7.3 6.6 5.0]) (def critter-consumption [0.0 0.2 0.3 1.1]) (defn unify-diet-data [human critter] {:human human :critter critter}) (map unify-diet-data human-consumption critter-consumption) ; => ({:human 8.1, :critter 0.0} {:human 7.3, :critter 0.2} {:human 6.6, :critter 0.3} {:human 5.0, :critter 1.8} (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [3 4 10]) ; => (17 3 17/3) (stats [80 1 44 13 6]) ; => (144 5 144/5) (def identities [{:alias "<NAME>" :real "<NAME>"} {:alias "<NAME>" :real "<NAME>"} {:alias "<NAME>" :real "Your mom"} {:alias "<NAME>" :real "Your dad"}]) (map :real identities) ; => ("<NAME>" "<NAME>" "Your mom" "Your dad") (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:max 30 :min 10}) ; => {:max 31, :min 11} (assoc (assoc {} :max (inc 30)) :min (inc 10)) (reduce (fn [new-map [key val]] (if (> val 4) (assoc new-map key val) new-map)) {} {:human 4.1 :critter 3.9}) ; => {:human 4.1} (take 3 [1 2 3 4 5 6 7 8 9 10]) ; => (1 2 3) (drop 3 [1 2 3 4 5 6 7 8 9 10]) ; => (4 5 6 7 8 9 10) (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) ; => ({:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} (drop-while #(< (:month %) 3) food-journal) ; => ({:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6} (take-while #(< (:month %) 4) (drop-while #(< (:month %) 2) food-journal)) ; => ({:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} (filter #(< (:human %) 5) food-journal) ; => ({:month 2 :day 1 :human 4.9 :critter 2.1} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6} (filter #(< (:month %) 3) food-journal) ; => ({:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} (some #(> (:critter %) 5) food-journal) ; => nil (some #(> (:critter %) 3) food-journal) ; => true (some #(and (> (:critter %) 3) %) food-journal) ; => {:month 3 :day 1 :human 4.2 :critter 3.3} (sort [3 1 2]) ; => (1 2 3) (sort-by count ["aaa" "c" "bb"]) ; => ("c" "bb" "aaa") (concat [1 2] [3 4]) ; => (1 2 3 4) (def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "<NAME>Fish<NAME>"} 1 {:makes-blood-puns? false, :has-pulse? true :name "<NAME>"} 2 {:makes-blood-puns? true, :has-pulse? false :name "<NAME>"} 3 {:makes-blood-puns? true, :has-pulse? true :name "<NAME>"}}) (defn vampire-related-details [social-security-number] (Thread/sleep 1000) (get vampire-database social-security-number)) (defn vampire? [record] (and (:makes-blood-puns? record) (not (:has-pulse? record)) record)) (defn identify-vampire [social-security-numbers] (first (filter vampire? (map vampire-related-details social-security-numbers)))) (time (vampire-related-details 0)) ; => "Elapsed time: 1001.042 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (def mapped-details (map vampire-related-details (range 0 1000000)))) ; => "Elapsed time: 0.049 msecs" ; => #'user/mapped-details (time (first mapped-details)) ; => "Elapsed time: 32030.767 msecs" ; => {:name "<NAME>Fishwich", :makes-blood-puns? false, :has-pulse? true} (time (first mapped-details)) ; => "Elapsed time: 0.022 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (identify-vampire (range 0 1000000))) "Elapsed time: 32019.912 msecs" ; => {:name "<NAME>", :makes-blood-puns? true, :has-pulse? false} (concat (take 8 (repeat "na")) ["<NAME>!"]) ; => ("na" "na" "na" "na" "na" "na" "na" "na" "<NAME>!") (take 3 (repeatedly (fn [] (rand-int 10)))) ; => (1 4 0) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (take 10 (even-numbers)) ; => (0 2 4 6 8 10 12 14 16 18) (cons 0 '(2 4 6)) ; => (0 2 4 6) (empty? []) ; => true (empty? ["no!"]) ; => false (map identity {:sunlight-reaction "Glitter!"}) ; => ([:sunlight-reaction "Glitter!"]) (into {} (map identity {:sunlight-reaction "Glitter!"})) ; => {:sunlight-reaction "Glitter!"} (map identity [:garlic :sesame-oil :fried-eggs]) ; => (:garlic :sesame-oil :fried-eggs) (into [] (map identity [:garlic :sesame-oil :fried-eggs])) ; => [:garlic :sesame-oil :fried-eggs] (map identity [:garlic-clove :garlic-clove]) ; => (:garlic-clove :garlic-clove) (into #{} (map identity [:garlic-clove :garlic-clove])) ; => #{:garlic-clove} (into {:favorite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]]) ; => {:favorite-emotion "gloomy" :sunlight-reaction "Glitter!"} (into ["cherry"] '("pine" "spruce")) ; => ["cherry" "pine" "spruce"] (into {:favorite-animal "kitty"} {:least-favorite-smell "dog" :relationship-with-teenager "creepy"}) ; => {:favorite-animal "kitty" ; => :relationship-with-teenager "creepy" ; => :least-favorite-smell "dog"} (conj [0] [1]) ; => [0 [1]] (into [0] [1]) ; => [0 1] (conj [0] 1) ; => [0 1] (conj [0] 1 2 3 4) ; => [0 1 2 3 4] (conj {:time "midnight"} [:place "ye olde cemetarium"]) ; => {:place "ye olde cemetarium" :time "midnight"} (defn my-conj [target & additions] (into target additions)) (my-conj [0] 1 2 3) ; => [0 1 2 3] (max 0 1 2) ; => 2 (max [0 1 2]) ; => [0 1 2] (apply max [0 1 2]) ; => 2 (defn my-into [target additions] (apply conj target additions)) (my-into [0] [1 2 3]) ; => [0 1 2 3] (def add10 (partial + 10)) (add10 3) ; => 13 (add10 5) ; => 15 (def add-missing-elements (partial conj ["water" "earth" "air"])) (add-missing-elements "unobtainium" "adamantium") ; => ["water" "earth" "air" "unobtainium" "adamantium"] (defn my-partial [partialized-fn & args] (fn [& more-args] (apply partialized-fn (into args more-args)))) (def add20 (my-partial + 20)) (add20 3) ; => 23 (fn [& more-args] (apply + (into [20] more-args))) (defn lousy-logger [log-level message] (condp = log-level :warn (clojure.string/lower-case message) :emergency (clojure.string/upper-case message))) (def warn (partial lousy-logger :warn)) (warn "Red light ahead") ; => "red light ahead" (defn identify-humans [social-security-numbers] (filter #(not (vampire? %)) (map vampire-related-details social-security-numbers))) (def not-vampire? (complement vampire?)) (defn identify-humans [social-security-numbers] (filter not-vampire? (map vampire-related-details social-security-numbers))) (defn my-complement [fun] (fn [& args] (not (apply fun args)))) (def my-pos? (complement neg?)) (my-pos? 1) ; => true (my-pos? -1) ; => false ;; Examples from FWPD (slurp filename) ; => "<NAME>,10\<NAME>,0\n<NAME>,0\n<NAME>,3\n<NAME>,6" (parse (slurp filename)) ; => (["<NAME>" "10"] ["<NAME>" "0"] ["<NAME>" "0"] ; => ["<NAME>" "3"] ["<NAME>" "6"]) (first (mapify (parse (slurp filename)))) ; => {:glitter-index 10, :name "<NAME>"} (glitter-filter 3 (mapify (parse (slurp filename)))) ({:name "<NAME>", :glitter-index 10} {:name "<NAME>", :glitter-index 3} {:name "<NAME>", :glitter-index 6})
true
(defn titleize [topic] (str topic " for the Brave and True")) (map titleize ["Hamsters" "Ragnarok"]) ; => ("Hamsters for the Brave and True" "Ragnarok for the Brave and True") (map titleize '("Empathy" "Decorating")) ; => ("Empathy for the Brave and True" "Decorating for the Brave and True") (map titleize #{"Elbows" "Soap Carving"}) ; => ("Elbows for the Brave and True" "Soap Carving for the Brave and True") (map #(titleize (second %)) {:uncomfortable-thing "Winking"}) ; => ("Winking for the Brave and True") (seq '(1 2 3)) ; => (1 2 3) (seq [1 2 3]) ; => (1 2 3) (seq #{1 2 3}) ; => (1 2 3) (seq {:name "PI:NAME:<NAME>END_PI" :occupation "Dead mopey guy"}) ; => ([:name "PI:NAME:<NAME>END_PI"] [:occupation "Dead mopey guy"]) (into {} (seq {:a 1 :b 2 :c 3})) ; => {:a 1, :c 3, :b 2} (map inc [1 2 3]) ; => (2 3 4) (map str ["a" "b" "c"] ["A" "B" "C"]) ; => ("aA" "bB" "cC") (list (str "a" "A") (str "b" "B") (str "c" "C")) (def human-consumption [8.1 7.3 6.6 5.0]) (def critter-consumption [0.0 0.2 0.3 1.1]) (defn unify-diet-data [human critter] {:human human :critter critter}) (map unify-diet-data human-consumption critter-consumption) ; => ({:human 8.1, :critter 0.0} {:human 7.3, :critter 0.2} {:human 6.6, :critter 0.3} {:human 5.0, :critter 1.8} (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [3 4 10]) ; => (17 3 17/3) (stats [80 1 44 13 6]) ; => (144 5 144/5) (def identities [{:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"} {:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"} {:alias "PI:NAME:<NAME>END_PI" :real "Your mom"} {:alias "PI:NAME:<NAME>END_PI" :real "Your dad"}]) (map :real identities) ; => ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Your mom" "Your dad") (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:max 30 :min 10}) ; => {:max 31, :min 11} (assoc (assoc {} :max (inc 30)) :min (inc 10)) (reduce (fn [new-map [key val]] (if (> val 4) (assoc new-map key val) new-map)) {} {:human 4.1 :critter 3.9}) ; => {:human 4.1} (take 3 [1 2 3 4 5 6 7 8 9 10]) ; => (1 2 3) (drop 3 [1 2 3 4 5 6 7 8 9 10]) ; => (4 5 6 7 8 9 10) (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) ; => ({:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} (drop-while #(< (:month %) 3) food-journal) ; => ({:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6} (take-while #(< (:month %) 4) (drop-while #(< (:month %) 2) food-journal)) ; => ({:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} (filter #(< (:human %) 5) food-journal) ; => ({:month 2 :day 1 :human 4.9 :critter 2.1} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6} (filter #(< (:month %) 3) food-journal) ; => ({:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} (some #(> (:critter %) 5) food-journal) ; => nil (some #(> (:critter %) 3) food-journal) ; => true (some #(and (> (:critter %) 3) %) food-journal) ; => {:month 3 :day 1 :human 4.2 :critter 3.3} (sort [3 1 2]) ; => (1 2 3) (sort-by count ["aaa" "c" "bb"]) ; => ("c" "bb" "aaa") (concat [1 2] [3 4]) ; => (1 2 3 4) (def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "PI:NAME:<NAME>END_PIFishPI:NAME:<NAME>END_PI"} 1 {:makes-blood-puns? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"} 2 {:makes-blood-puns? true, :has-pulse? false :name "PI:NAME:<NAME>END_PI"} 3 {:makes-blood-puns? true, :has-pulse? true :name "PI:NAME:<NAME>END_PI"}}) (defn vampire-related-details [social-security-number] (Thread/sleep 1000) (get vampire-database social-security-number)) (defn vampire? [record] (and (:makes-blood-puns? record) (not (:has-pulse? record)) record)) (defn identify-vampire [social-security-numbers] (first (filter vampire? (map vampire-related-details social-security-numbers)))) (time (vampire-related-details 0)) ; => "Elapsed time: 1001.042 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (def mapped-details (map vampire-related-details (range 0 1000000)))) ; => "Elapsed time: 0.049 msecs" ; => #'user/mapped-details (time (first mapped-details)) ; => "Elapsed time: 32030.767 msecs" ; => {:name "PI:NAME:<NAME>END_PIFishwich", :makes-blood-puns? false, :has-pulse? true} (time (first mapped-details)) ; => "Elapsed time: 0.022 msecs" ; => {:name "McFishwich", :makes-blood-puns? false, :has-pulse? true} (time (identify-vampire (range 0 1000000))) "Elapsed time: 32019.912 msecs" ; => {:name "PI:NAME:<NAME>END_PI", :makes-blood-puns? true, :has-pulse? false} (concat (take 8 (repeat "na")) ["PI:NAME:<NAME>END_PI!"]) ; => ("na" "na" "na" "na" "na" "na" "na" "na" "PI:NAME:<NAME>END_PI!") (take 3 (repeatedly (fn [] (rand-int 10)))) ; => (1 4 0) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (take 10 (even-numbers)) ; => (0 2 4 6 8 10 12 14 16 18) (cons 0 '(2 4 6)) ; => (0 2 4 6) (empty? []) ; => true (empty? ["no!"]) ; => false (map identity {:sunlight-reaction "Glitter!"}) ; => ([:sunlight-reaction "Glitter!"]) (into {} (map identity {:sunlight-reaction "Glitter!"})) ; => {:sunlight-reaction "Glitter!"} (map identity [:garlic :sesame-oil :fried-eggs]) ; => (:garlic :sesame-oil :fried-eggs) (into [] (map identity [:garlic :sesame-oil :fried-eggs])) ; => [:garlic :sesame-oil :fried-eggs] (map identity [:garlic-clove :garlic-clove]) ; => (:garlic-clove :garlic-clove) (into #{} (map identity [:garlic-clove :garlic-clove])) ; => #{:garlic-clove} (into {:favorite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]]) ; => {:favorite-emotion "gloomy" :sunlight-reaction "Glitter!"} (into ["cherry"] '("pine" "spruce")) ; => ["cherry" "pine" "spruce"] (into {:favorite-animal "kitty"} {:least-favorite-smell "dog" :relationship-with-teenager "creepy"}) ; => {:favorite-animal "kitty" ; => :relationship-with-teenager "creepy" ; => :least-favorite-smell "dog"} (conj [0] [1]) ; => [0 [1]] (into [0] [1]) ; => [0 1] (conj [0] 1) ; => [0 1] (conj [0] 1 2 3 4) ; => [0 1 2 3 4] (conj {:time "midnight"} [:place "ye olde cemetarium"]) ; => {:place "ye olde cemetarium" :time "midnight"} (defn my-conj [target & additions] (into target additions)) (my-conj [0] 1 2 3) ; => [0 1 2 3] (max 0 1 2) ; => 2 (max [0 1 2]) ; => [0 1 2] (apply max [0 1 2]) ; => 2 (defn my-into [target additions] (apply conj target additions)) (my-into [0] [1 2 3]) ; => [0 1 2 3] (def add10 (partial + 10)) (add10 3) ; => 13 (add10 5) ; => 15 (def add-missing-elements (partial conj ["water" "earth" "air"])) (add-missing-elements "unobtainium" "adamantium") ; => ["water" "earth" "air" "unobtainium" "adamantium"] (defn my-partial [partialized-fn & args] (fn [& more-args] (apply partialized-fn (into args more-args)))) (def add20 (my-partial + 20)) (add20 3) ; => 23 (fn [& more-args] (apply + (into [20] more-args))) (defn lousy-logger [log-level message] (condp = log-level :warn (clojure.string/lower-case message) :emergency (clojure.string/upper-case message))) (def warn (partial lousy-logger :warn)) (warn "Red light ahead") ; => "red light ahead" (defn identify-humans [social-security-numbers] (filter #(not (vampire? %)) (map vampire-related-details social-security-numbers))) (def not-vampire? (complement vampire?)) (defn identify-humans [social-security-numbers] (filter not-vampire? (map vampire-related-details social-security-numbers))) (defn my-complement [fun] (fn [& args] (not (apply fun args)))) (def my-pos? (complement neg?)) (my-pos? 1) ; => true (my-pos? -1) ; => false ;; Examples from FWPD (slurp filename) ; => "PI:NAME:<NAME>END_PI,10\PI:NAME:<NAME>END_PI,0\nPI:NAME:<NAME>END_PI,0\nPI:NAME:<NAME>END_PI,3\nPI:NAME:<NAME>END_PI,6" (parse (slurp filename)) ; => (["PI:NAME:<NAME>END_PI" "10"] ["PI:NAME:<NAME>END_PI" "0"] ["PI:NAME:<NAME>END_PI" "0"] ; => ["PI:NAME:<NAME>END_PI" "3"] ["PI:NAME:<NAME>END_PI" "6"]) (first (mapify (parse (slurp filename)))) ; => {:glitter-index 10, :name "PI:NAME:<NAME>END_PI"} (glitter-filter 3 (mapify (parse (slurp filename)))) ({:name "PI:NAME:<NAME>END_PI", :glitter-index 10} {:name "PI:NAME:<NAME>END_PI", :glitter-index 3} {:name "PI:NAME:<NAME>END_PI", :glitter-index 6})
[ { "context": "\n\n(ns ^{ :doc \"alavita :: util\"\n :author \"Istvan Szukacs\" }\n alavita.util\n (:import\n [java.util ", "end": 131, "score": 0.9998818635940552, "start": 117, "tag": "NAME", "value": "Istvan Szukacs" } ]
src/alavita/util.clj
StreamBright/alavita
0
;; Copyright 2017 StreamBright LLC and contributors ;; See LICENSE (ns ^{ :doc "alavita :: util" :author "Istvan Szukacs" } alavita.util (:import [java.util UUID ] [java.text SimpleDateFormat ] [java.time Instant ] [java.util Date ] ) ) (defn get-utc-string-of-now "Return a string of UTC now" [] (.format (SimpleDateFormat. "yyyy_MM_dd_HH_mm") (Date/from (Instant/now)))) (defn uuid "Returns a new java.util.UUID as string" [] (str (UUID/randomUUID))) (defn exit [n] (System/exit n))
53051
;; Copyright 2017 StreamBright LLC and contributors ;; See LICENSE (ns ^{ :doc "alavita :: util" :author "<NAME>" } alavita.util (:import [java.util UUID ] [java.text SimpleDateFormat ] [java.time Instant ] [java.util Date ] ) ) (defn get-utc-string-of-now "Return a string of UTC now" [] (.format (SimpleDateFormat. "yyyy_MM_dd_HH_mm") (Date/from (Instant/now)))) (defn uuid "Returns a new java.util.UUID as string" [] (str (UUID/randomUUID))) (defn exit [n] (System/exit n))
true
;; Copyright 2017 StreamBright LLC and contributors ;; See LICENSE (ns ^{ :doc "alavita :: util" :author "PI:NAME:<NAME>END_PI" } alavita.util (:import [java.util UUID ] [java.text SimpleDateFormat ] [java.time Instant ] [java.util Date ] ) ) (defn get-utc-string-of-now "Return a string of UTC now" [] (.format (SimpleDateFormat. "yyyy_MM_dd_HH_mm") (Date/from (Instant/now)))) (defn uuid "Returns a new java.util.UUID as string" [] (str (UUID/randomUUID))) (defn exit [n] (System/exit n))
[ { "context": "(ns keyboard-warrior.figure)\n\n(def alice \"Alice was beginning to get very tired of sitting by her", "end": 47, "score": 0.9984225034713745, "start": 42, "tag": "NAME", "value": "Alice" }, { "context": "ns in it, `and what is the use of a book,' thought Alice `without pictures or conversation?'\")\n", "end": 307, "score": 0.9113971590995789, "start": 302, "tag": "NAME", "value": "Alice" } ]
src/cljs/keyboard_warrior/figure.cljs
agarick/keyboard-warrior
1
(ns keyboard-warrior.figure) (def alice "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought Alice `without pictures or conversation?'")
95852
(ns keyboard-warrior.figure) (def alice "<NAME> was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought <NAME> `without pictures or conversation?'")
true
(ns keyboard-warrior.figure) (def alice "PI:NAME:<NAME>END_PI was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought PI:NAME:<NAME>END_PI `without pictures or conversation?'")
[ { "context": "Proxy API\"\n :apiVersion \"0.0.0\"\n :contact \"festapp@futurice.com\")\n (swaggered \"festapp\"\n :description \"Provide", "end": 1027, "score": 0.9999286532402039, "start": 1007, "tag": "EMAIL", "value": "festapp@futurice.com" } ]
src/festapp/web.clj
futurice/festapp-proxy
1
(ns festapp.web (:require [ring.util.http-response :refer :all] [compojure.route :as route] [compojure.api.sweet :refer :all] [schema.core :as s] [festapp.db :refer :all]) (:import [org.joda.time DateTime])) ;;; Models (def Festival {:stages [String] :days [String]}) (def Artist {:id String :image-url String :name String :info String (s/optional-key :wikipedia) String}) (def Gig {:id String :artist Artist :name String :stage String :day String :start-time DateTime :end-time DateTime}) (def NewsItem {:title String :published DateTime :content String}) (def InfoItem {:title String :content String}) ;;; Routes (defapi app (route/resources "/") (swagger-ui "/") (swagger-docs "/api/api-docs" :title "Festapp Proxy API" :apiVersion "0.0.0" :contact "festapp@futurice.com") (swaggered "festapp" :description "Provide data of your festival" (context "/api" [] (GET* "/artists" [] :return [Artist] :summary "List of all artists" (ok artists)) (GET* "/gigs" [] :return [Gig] :summary "List of all gigs" (ok gigs)) (GET* "/news" [] :return [NewsItem] :summary "List of all news" (ok news)) (GET* "/info" [] :return [InfoItem] :summary "List of all info items" (ok info)) (GET* "/festival" [] :return Festival :summary "Festival general configuration" (ok festival)))))
10389
(ns festapp.web (:require [ring.util.http-response :refer :all] [compojure.route :as route] [compojure.api.sweet :refer :all] [schema.core :as s] [festapp.db :refer :all]) (:import [org.joda.time DateTime])) ;;; Models (def Festival {:stages [String] :days [String]}) (def Artist {:id String :image-url String :name String :info String (s/optional-key :wikipedia) String}) (def Gig {:id String :artist Artist :name String :stage String :day String :start-time DateTime :end-time DateTime}) (def NewsItem {:title String :published DateTime :content String}) (def InfoItem {:title String :content String}) ;;; Routes (defapi app (route/resources "/") (swagger-ui "/") (swagger-docs "/api/api-docs" :title "Festapp Proxy API" :apiVersion "0.0.0" :contact "<EMAIL>") (swaggered "festapp" :description "Provide data of your festival" (context "/api" [] (GET* "/artists" [] :return [Artist] :summary "List of all artists" (ok artists)) (GET* "/gigs" [] :return [Gig] :summary "List of all gigs" (ok gigs)) (GET* "/news" [] :return [NewsItem] :summary "List of all news" (ok news)) (GET* "/info" [] :return [InfoItem] :summary "List of all info items" (ok info)) (GET* "/festival" [] :return Festival :summary "Festival general configuration" (ok festival)))))
true
(ns festapp.web (:require [ring.util.http-response :refer :all] [compojure.route :as route] [compojure.api.sweet :refer :all] [schema.core :as s] [festapp.db :refer :all]) (:import [org.joda.time DateTime])) ;;; Models (def Festival {:stages [String] :days [String]}) (def Artist {:id String :image-url String :name String :info String (s/optional-key :wikipedia) String}) (def Gig {:id String :artist Artist :name String :stage String :day String :start-time DateTime :end-time DateTime}) (def NewsItem {:title String :published DateTime :content String}) (def InfoItem {:title String :content String}) ;;; Routes (defapi app (route/resources "/") (swagger-ui "/") (swagger-docs "/api/api-docs" :title "Festapp Proxy API" :apiVersion "0.0.0" :contact "PI:EMAIL:<EMAIL>END_PI") (swaggered "festapp" :description "Provide data of your festival" (context "/api" [] (GET* "/artists" [] :return [Artist] :summary "List of all artists" (ok artists)) (GET* "/gigs" [] :return [Gig] :summary "List of all gigs" (ok gigs)) (GET* "/news" [] :return [NewsItem] :summary "List of all news" (ok news)) (GET* "/info" [] :return [InfoItem] :summary "List of all info items" (ok info)) (GET* "/festival" [] :return Festival :summary "Festival general configuration" (ok festival)))))
[ { "context": " rabbitmq)\n :password (:password rabbitmq)\n :port (Integ", "end": 1142, "score": 0.9885941743850708, "start": 1134, "tag": "PASSWORD", "value": "password" }, { "context": "q)\n :password (:password rabbitmq)\n :port (Integer/parseI", "end": 1151, "score": 0.9952174425125122, "start": 1143, "tag": "PASSWORD", "value": "rabbitmq" } ]
src/amqp/message_handler.clj
WeavingTheWeb/daily-press-review-clojure
1
(ns amqp.message-handler (:require [clojure.data.json :as json] [clojure.edn :as edn] [clojure.spec.alpha :as s] [environ.core :refer [env]] [langohr.channel :as lch] [langohr.basic :as lb] [langohr.core :as rmq] [clojure.tools.logging :as log] [php_clj.core :refer [php->clj clj->php]]) (:use [twitter.favorited-status] [repository.entity-manager] [twitter.status] [twitter.member] [amqp.handling-errors] [amqp.favorite-status-handler] [amqp.list-handler] [amqp.network-handler] [twitter.api-client])) (defn disconnect-from-amqp-server "Close connection and channel" [ch conn] (println "[main] Disconnecting...") (rmq/close ch) (rmq/close conn)) (defn connect-to-amqp-server [environment-configuration] (let [rabbitmq (edn/read-string (:rabbitmq environment-configuration)) conn (rmq/connect {:host (:host rabbitmq) :username (:user rabbitmq) :password (:password rabbitmq) :port (Integer/parseInt (:port rabbitmq)) :vhost (:vhost rabbitmq)}) ch (lch/open conn)] (println (format "[main] Connected. Channel id: %d" (.getChannelNumber ch))) {:channel ch :connection conn})) (defn pull-messages-from-network-queue "Pull messages from a queue dedicated to network discovery" [options] (let [{auto-ack :auto-ack channel :channel queue :queue entity-manager :entity-manager} options [{:keys [delivery-tag]} payload] (lb/get channel queue auto-ack)] (when (not (nil? payload)) (process-network payload entity-manager)) (when (not (nil? delivery-tag)) (lb/ack channel delivery-tag)) (when (and (nil? delivery-tag) (nil? payload)) (throw (Exception. (str error-invalid-amqp-message-payload)))))) (defn pull-messages-from-likes-queue "Pull messages from a queue dedicated to likes collection" [options] (let [{auto-ack :auto-ack channel :channel queue :queue entity-manager :entity-manager} options [{:keys [delivery-tag]} payload] (lb/get channel queue auto-ack) payload-body (json/read-str (php->clj (String. payload "UTF-8"))) screen-name (get payload-body "screen_name") aggregate-id (get payload-body "aggregate_id")] (when payload (try (do (process-likes screen-name aggregate-id entity-manager error-unavailable-aggregate) (lb/ack channel delivery-tag)) (catch Exception e (cond (= (.getMessage e) error-mismatching-favorites-cols-length) (log/error "Likes of \"" screen-name "\" related to aggregate #" aggregate-id " could not be processed") (= (.getMessage e) error-unavailable-aggregate) (do (log/error "Likes of \"" screen-name "\" related to aggregate #" aggregate-id " could not be bound to an actual aggregate") (lb/ack channel delivery-tag)) :else (log/error (str "An error occurred with message " (.getMessage e))))))))) (defn consume-message [entity-manager rabbitmq channel queue & [message-index]] (cond (= queue :likes) (pull-messages-from-likes-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-likes rabbitmq) :channel channel}) (= queue :lists) (pull-messages-from-lists-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-lists rabbitmq) :channel channel}) (= queue :network) (pull-messages-from-network-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-network rabbitmq) :channel channel}) :else (println (str "Unknown queue name, please select one of the following: lists, likes or network"))) (when message-index (log/info (str "Consumed message #" message-index)))) (s/def ::total-messages #(pos-int? %)) (defn consume-messages [queue total-messages parallel-consumers] {:pre [(s/valid? ::total-messages total-messages)]} (let [entity-manager (get-entity-manager (:database env)) rabbitmq (edn/read-string (:rabbitmq env)) {connection :connection channel :channel} (connect-to-amqp-server env) single-message-consumption (= 1 parallel-consumers) next-total (if single-message-consumption #(dec %) #(max 0 (- % parallel-consumers)))] (log/info (str "About to consume " total-messages " messages.")) (if total-messages (loop [messages-to-consume (if total-messages total-messages 0)] (when (> messages-to-consume 0) (if single-message-consumption (consume-message entity-manager rabbitmq channel queue)) (doall (pmap #(consume-message entity-manager rabbitmq channel queue %) (take total-messages (iterate inc 1)))) (recur (next-total messages-to-consume))))) (Thread/sleep 1000) (disconnect-from-amqp-server channel connection)))
63109
(ns amqp.message-handler (:require [clojure.data.json :as json] [clojure.edn :as edn] [clojure.spec.alpha :as s] [environ.core :refer [env]] [langohr.channel :as lch] [langohr.basic :as lb] [langohr.core :as rmq] [clojure.tools.logging :as log] [php_clj.core :refer [php->clj clj->php]]) (:use [twitter.favorited-status] [repository.entity-manager] [twitter.status] [twitter.member] [amqp.handling-errors] [amqp.favorite-status-handler] [amqp.list-handler] [amqp.network-handler] [twitter.api-client])) (defn disconnect-from-amqp-server "Close connection and channel" [ch conn] (println "[main] Disconnecting...") (rmq/close ch) (rmq/close conn)) (defn connect-to-amqp-server [environment-configuration] (let [rabbitmq (edn/read-string (:rabbitmq environment-configuration)) conn (rmq/connect {:host (:host rabbitmq) :username (:user rabbitmq) :password (:<PASSWORD> <PASSWORD>) :port (Integer/parseInt (:port rabbitmq)) :vhost (:vhost rabbitmq)}) ch (lch/open conn)] (println (format "[main] Connected. Channel id: %d" (.getChannelNumber ch))) {:channel ch :connection conn})) (defn pull-messages-from-network-queue "Pull messages from a queue dedicated to network discovery" [options] (let [{auto-ack :auto-ack channel :channel queue :queue entity-manager :entity-manager} options [{:keys [delivery-tag]} payload] (lb/get channel queue auto-ack)] (when (not (nil? payload)) (process-network payload entity-manager)) (when (not (nil? delivery-tag)) (lb/ack channel delivery-tag)) (when (and (nil? delivery-tag) (nil? payload)) (throw (Exception. (str error-invalid-amqp-message-payload)))))) (defn pull-messages-from-likes-queue "Pull messages from a queue dedicated to likes collection" [options] (let [{auto-ack :auto-ack channel :channel queue :queue entity-manager :entity-manager} options [{:keys [delivery-tag]} payload] (lb/get channel queue auto-ack) payload-body (json/read-str (php->clj (String. payload "UTF-8"))) screen-name (get payload-body "screen_name") aggregate-id (get payload-body "aggregate_id")] (when payload (try (do (process-likes screen-name aggregate-id entity-manager error-unavailable-aggregate) (lb/ack channel delivery-tag)) (catch Exception e (cond (= (.getMessage e) error-mismatching-favorites-cols-length) (log/error "Likes of \"" screen-name "\" related to aggregate #" aggregate-id " could not be processed") (= (.getMessage e) error-unavailable-aggregate) (do (log/error "Likes of \"" screen-name "\" related to aggregate #" aggregate-id " could not be bound to an actual aggregate") (lb/ack channel delivery-tag)) :else (log/error (str "An error occurred with message " (.getMessage e))))))))) (defn consume-message [entity-manager rabbitmq channel queue & [message-index]] (cond (= queue :likes) (pull-messages-from-likes-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-likes rabbitmq) :channel channel}) (= queue :lists) (pull-messages-from-lists-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-lists rabbitmq) :channel channel}) (= queue :network) (pull-messages-from-network-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-network rabbitmq) :channel channel}) :else (println (str "Unknown queue name, please select one of the following: lists, likes or network"))) (when message-index (log/info (str "Consumed message #" message-index)))) (s/def ::total-messages #(pos-int? %)) (defn consume-messages [queue total-messages parallel-consumers] {:pre [(s/valid? ::total-messages total-messages)]} (let [entity-manager (get-entity-manager (:database env)) rabbitmq (edn/read-string (:rabbitmq env)) {connection :connection channel :channel} (connect-to-amqp-server env) single-message-consumption (= 1 parallel-consumers) next-total (if single-message-consumption #(dec %) #(max 0 (- % parallel-consumers)))] (log/info (str "About to consume " total-messages " messages.")) (if total-messages (loop [messages-to-consume (if total-messages total-messages 0)] (when (> messages-to-consume 0) (if single-message-consumption (consume-message entity-manager rabbitmq channel queue)) (doall (pmap #(consume-message entity-manager rabbitmq channel queue %) (take total-messages (iterate inc 1)))) (recur (next-total messages-to-consume))))) (Thread/sleep 1000) (disconnect-from-amqp-server channel connection)))
true
(ns amqp.message-handler (:require [clojure.data.json :as json] [clojure.edn :as edn] [clojure.spec.alpha :as s] [environ.core :refer [env]] [langohr.channel :as lch] [langohr.basic :as lb] [langohr.core :as rmq] [clojure.tools.logging :as log] [php_clj.core :refer [php->clj clj->php]]) (:use [twitter.favorited-status] [repository.entity-manager] [twitter.status] [twitter.member] [amqp.handling-errors] [amqp.favorite-status-handler] [amqp.list-handler] [amqp.network-handler] [twitter.api-client])) (defn disconnect-from-amqp-server "Close connection and channel" [ch conn] (println "[main] Disconnecting...") (rmq/close ch) (rmq/close conn)) (defn connect-to-amqp-server [environment-configuration] (let [rabbitmq (edn/read-string (:rabbitmq environment-configuration)) conn (rmq/connect {:host (:host rabbitmq) :username (:user rabbitmq) :password (:PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI) :port (Integer/parseInt (:port rabbitmq)) :vhost (:vhost rabbitmq)}) ch (lch/open conn)] (println (format "[main] Connected. Channel id: %d" (.getChannelNumber ch))) {:channel ch :connection conn})) (defn pull-messages-from-network-queue "Pull messages from a queue dedicated to network discovery" [options] (let [{auto-ack :auto-ack channel :channel queue :queue entity-manager :entity-manager} options [{:keys [delivery-tag]} payload] (lb/get channel queue auto-ack)] (when (not (nil? payload)) (process-network payload entity-manager)) (when (not (nil? delivery-tag)) (lb/ack channel delivery-tag)) (when (and (nil? delivery-tag) (nil? payload)) (throw (Exception. (str error-invalid-amqp-message-payload)))))) (defn pull-messages-from-likes-queue "Pull messages from a queue dedicated to likes collection" [options] (let [{auto-ack :auto-ack channel :channel queue :queue entity-manager :entity-manager} options [{:keys [delivery-tag]} payload] (lb/get channel queue auto-ack) payload-body (json/read-str (php->clj (String. payload "UTF-8"))) screen-name (get payload-body "screen_name") aggregate-id (get payload-body "aggregate_id")] (when payload (try (do (process-likes screen-name aggregate-id entity-manager error-unavailable-aggregate) (lb/ack channel delivery-tag)) (catch Exception e (cond (= (.getMessage e) error-mismatching-favorites-cols-length) (log/error "Likes of \"" screen-name "\" related to aggregate #" aggregate-id " could not be processed") (= (.getMessage e) error-unavailable-aggregate) (do (log/error "Likes of \"" screen-name "\" related to aggregate #" aggregate-id " could not be bound to an actual aggregate") (lb/ack channel delivery-tag)) :else (log/error (str "An error occurred with message " (.getMessage e))))))))) (defn consume-message [entity-manager rabbitmq channel queue & [message-index]] (cond (= queue :likes) (pull-messages-from-likes-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-likes rabbitmq) :channel channel}) (= queue :lists) (pull-messages-from-lists-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-lists rabbitmq) :channel channel}) (= queue :network) (pull-messages-from-network-queue {:auto-ack false :entity-manager entity-manager :queue (:queue-network rabbitmq) :channel channel}) :else (println (str "Unknown queue name, please select one of the following: lists, likes or network"))) (when message-index (log/info (str "Consumed message #" message-index)))) (s/def ::total-messages #(pos-int? %)) (defn consume-messages [queue total-messages parallel-consumers] {:pre [(s/valid? ::total-messages total-messages)]} (let [entity-manager (get-entity-manager (:database env)) rabbitmq (edn/read-string (:rabbitmq env)) {connection :connection channel :channel} (connect-to-amqp-server env) single-message-consumption (= 1 parallel-consumers) next-total (if single-message-consumption #(dec %) #(max 0 (- % parallel-consumers)))] (log/info (str "About to consume " total-messages " messages.")) (if total-messages (loop [messages-to-consume (if total-messages total-messages 0)] (when (> messages-to-consume 0) (if single-message-consumption (consume-message entity-manager rabbitmq channel queue)) (doall (pmap #(consume-message entity-manager rabbitmq channel queue %) (take total-messages (iterate inc 1)))) (recur (next-total messages-to-consume))))) (Thread/sleep 1000) (disconnect-from-amqp-server channel connection)))
[ { "context": "s]\n (println \"Door 1 password: \" (find-password \"wtnhxymk\"))\n (println \"Door 2 password: \" (find-second-pa", "end": 2229, "score": 0.999286949634552, "start": 2221, "tag": "PASSWORD", "value": "wtnhxymk" }, { "context": "rintln \"Door 2 password: \" (find-second-password \"wtnhxymk\"))\n (shutdown-agents))\n", "end": 2295, "score": 0.999179482460022, "start": 2287, "tag": "PASSWORD", "value": "wtnhxymk" } ]
day_05/src/day_05/core.clj
lux01/advent-of-code-2016
0
(ns day-05.core (:require [digest] [clojure.string :as string]) (:gen-class)) (defn password-digit? "Checks if the integer x " [door-id x] (string/starts-with? (digest/md5 (str door-id x)) "00000")) (def integers (iterate inc 1)) (defn find-password [door-id] (->> (pmap #(digest/md5 (str door-id %)) integers) (filter #(string/starts-with? % "00000")) (take 8) (map #(nth % 5)) (apply str))) (defn hash->digit [hash] (list (Integer/parseUnsignedInt (str (nth hash 5)) 16) (nth hash 6))) (defn find-second-password ([door-id passwd hashes] (let [h (first hashes) hs (rest hashes) pwd-chars (hash->digit h)] (cond (= 8 (count passwd)) (->> passwd (vec) (sort-by first) (map second) (apply str)) (not (contains? passwd (first pwd-chars))) (recur door-id (assoc passwd (first pwd-chars) (second pwd-chars)) hs) :else (recur door-id passwd hs)))) ([door-id] (find-second-password door-id (hash-map) (filter #(and (string/starts-with? % "00000") (< (Integer/parseInt (str (nth % 5)) 16) 8)) (pmap #(digest/md5 (str door-id %)) integers))))) (defn find-more-interesting-password [door-id] (->> (pmap #(digest/md5 (str door-id %)) integers) (filter #(and (string/starts-with? % "00000") (< (Integer/parseUnsignedInt (str (nth % 5)) 16) 8))) (take 8) (reduce #(assoc %1 (Integer/parseUnsignedInt (str (nth %2 5)) 16) (nth %2 6)) (vec "________")) (apply str))) (defn -main "I don't do a whole lot ... yet." [& args] (println "Door 1 password: " (find-password "wtnhxymk")) (println "Door 2 password: " (find-second-password "wtnhxymk")) (shutdown-agents))
98848
(ns day-05.core (:require [digest] [clojure.string :as string]) (:gen-class)) (defn password-digit? "Checks if the integer x " [door-id x] (string/starts-with? (digest/md5 (str door-id x)) "00000")) (def integers (iterate inc 1)) (defn find-password [door-id] (->> (pmap #(digest/md5 (str door-id %)) integers) (filter #(string/starts-with? % "00000")) (take 8) (map #(nth % 5)) (apply str))) (defn hash->digit [hash] (list (Integer/parseUnsignedInt (str (nth hash 5)) 16) (nth hash 6))) (defn find-second-password ([door-id passwd hashes] (let [h (first hashes) hs (rest hashes) pwd-chars (hash->digit h)] (cond (= 8 (count passwd)) (->> passwd (vec) (sort-by first) (map second) (apply str)) (not (contains? passwd (first pwd-chars))) (recur door-id (assoc passwd (first pwd-chars) (second pwd-chars)) hs) :else (recur door-id passwd hs)))) ([door-id] (find-second-password door-id (hash-map) (filter #(and (string/starts-with? % "00000") (< (Integer/parseInt (str (nth % 5)) 16) 8)) (pmap #(digest/md5 (str door-id %)) integers))))) (defn find-more-interesting-password [door-id] (->> (pmap #(digest/md5 (str door-id %)) integers) (filter #(and (string/starts-with? % "00000") (< (Integer/parseUnsignedInt (str (nth % 5)) 16) 8))) (take 8) (reduce #(assoc %1 (Integer/parseUnsignedInt (str (nth %2 5)) 16) (nth %2 6)) (vec "________")) (apply str))) (defn -main "I don't do a whole lot ... yet." [& args] (println "Door 1 password: " (find-password "<PASSWORD>")) (println "Door 2 password: " (find-second-password "<PASSWORD>")) (shutdown-agents))
true
(ns day-05.core (:require [digest] [clojure.string :as string]) (:gen-class)) (defn password-digit? "Checks if the integer x " [door-id x] (string/starts-with? (digest/md5 (str door-id x)) "00000")) (def integers (iterate inc 1)) (defn find-password [door-id] (->> (pmap #(digest/md5 (str door-id %)) integers) (filter #(string/starts-with? % "00000")) (take 8) (map #(nth % 5)) (apply str))) (defn hash->digit [hash] (list (Integer/parseUnsignedInt (str (nth hash 5)) 16) (nth hash 6))) (defn find-second-password ([door-id passwd hashes] (let [h (first hashes) hs (rest hashes) pwd-chars (hash->digit h)] (cond (= 8 (count passwd)) (->> passwd (vec) (sort-by first) (map second) (apply str)) (not (contains? passwd (first pwd-chars))) (recur door-id (assoc passwd (first pwd-chars) (second pwd-chars)) hs) :else (recur door-id passwd hs)))) ([door-id] (find-second-password door-id (hash-map) (filter #(and (string/starts-with? % "00000") (< (Integer/parseInt (str (nth % 5)) 16) 8)) (pmap #(digest/md5 (str door-id %)) integers))))) (defn find-more-interesting-password [door-id] (->> (pmap #(digest/md5 (str door-id %)) integers) (filter #(and (string/starts-with? % "00000") (< (Integer/parseUnsignedInt (str (nth % 5)) 16) 8))) (take 8) (reduce #(assoc %1 (Integer/parseUnsignedInt (str (nth %2 5)) 16) (nth %2 6)) (vec "________")) (apply str))) (defn -main "I don't do a whole lot ... yet." [& args] (println "Door 1 password: " (find-password "PI:PASSWORD:<PASSWORD>END_PI")) (println "Door 2 password: " (find-second-password "PI:PASSWORD:<PASSWORD>END_PI")) (shutdown-agents))
[ { "context": "rd\"\n \"Password\"\n \"password\"\n password-atom\n ", "end": 2230, "score": 0.7576348185539246, "start": 2222, "tag": "PASSWORD", "value": "password" } ]
src/cljs/notes_app_frontend/components.cljs
Eskotus/notes-app-frontend
0
(ns notes-app-frontend.components (:require [notes-app-frontend.aws-lib2 :as aws] [reagent.core :as r] [reagent.session :as session] [clojure.string :as s] [wilson.react-bootstrap :refer [navbar navbar-header navbar-brand navbar-toggle navbar-collapse nav nav-item]])) (defn- handle-input-change "Resets atom associated with input based on input type" [event value type] (if (= type "file") (reset! value (get (-> event .target .files) 0)) (reset! value (-> event .-target .-value)))) (defn route-nav-item [props & content] (fn [] (let [new-props (if (s/ends-with? js/window.location.href (get props :href)) (conj props {:class "active"}) props) view (session/get :current-page)] [nav-item new-props content]))) (defn navigation [] [navbar {:fluid true :collapseOnSelect true} [navbar-header [navbar-brand [:a {:href "/"} "Scratch"]] [navbar-toggle]] [navbar-collapse (if (session/get :authenticated?) [nav {:pullRight true} [nav-item {:on-click #(aws/logout)} "Logout"]] [nav {:pullRight true} [route-nav-item {:href "#/signup"} "Signup"] [route-nav-item {:href "#/login"} "Login"]])]]) (defn input-element "An input element which updates its value and on focus parameters on change, blur, and focus" ([id name type value] (input-element id name type value false)) ([id name type value auto-focus] [:div {:class "form-group form-group-lg"} [:label {:for id :class "control-label"} name] [:input {:id id :class "form-control" :auto-focus auto-focus :type type :value @value :on-change #(handle-input-change % value type)}]])) (defn email-form [email-address-atom] (input-element "email" "Email" "email" email-address-atom true)) (defn password-form [password-atom] (input-element "password" "Password" "password" password-atom false)) (defn confirm-password-form [confirm-password-atom] (input-element "confirmPassword" "Confirm password" "password" confirm-password-atom false)) (defn confirmation-form [confirmation-atom] (input-element "confirmationCode" "Confirmation code" "tel" confirmation-atom true)) (defn loader-button "Button with loader animation" [] (let [this (r/current-component) props (r/props this) {:keys [loading? text loading-text disabled]} props updated-props (assoc-in props [:disabled] (or loading? disabled)) new-props (dissoc updated-props :loading? :text :loading-text)] [:button.LoaderButton new-props (if loading? [:span.glyphicon.glyphicon-refresh.spinning]) (if loading? loading-text text)]))
69151
(ns notes-app-frontend.components (:require [notes-app-frontend.aws-lib2 :as aws] [reagent.core :as r] [reagent.session :as session] [clojure.string :as s] [wilson.react-bootstrap :refer [navbar navbar-header navbar-brand navbar-toggle navbar-collapse nav nav-item]])) (defn- handle-input-change "Resets atom associated with input based on input type" [event value type] (if (= type "file") (reset! value (get (-> event .target .files) 0)) (reset! value (-> event .-target .-value)))) (defn route-nav-item [props & content] (fn [] (let [new-props (if (s/ends-with? js/window.location.href (get props :href)) (conj props {:class "active"}) props) view (session/get :current-page)] [nav-item new-props content]))) (defn navigation [] [navbar {:fluid true :collapseOnSelect true} [navbar-header [navbar-brand [:a {:href "/"} "Scratch"]] [navbar-toggle]] [navbar-collapse (if (session/get :authenticated?) [nav {:pullRight true} [nav-item {:on-click #(aws/logout)} "Logout"]] [nav {:pullRight true} [route-nav-item {:href "#/signup"} "Signup"] [route-nav-item {:href "#/login"} "Login"]])]]) (defn input-element "An input element which updates its value and on focus parameters on change, blur, and focus" ([id name type value] (input-element id name type value false)) ([id name type value auto-focus] [:div {:class "form-group form-group-lg"} [:label {:for id :class "control-label"} name] [:input {:id id :class "form-control" :auto-focus auto-focus :type type :value @value :on-change #(handle-input-change % value type)}]])) (defn email-form [email-address-atom] (input-element "email" "Email" "email" email-address-atom true)) (defn password-form [password-atom] (input-element "password" "Password" "<PASSWORD>" password-atom false)) (defn confirm-password-form [confirm-password-atom] (input-element "confirmPassword" "Confirm password" "password" confirm-password-atom false)) (defn confirmation-form [confirmation-atom] (input-element "confirmationCode" "Confirmation code" "tel" confirmation-atom true)) (defn loader-button "Button with loader animation" [] (let [this (r/current-component) props (r/props this) {:keys [loading? text loading-text disabled]} props updated-props (assoc-in props [:disabled] (or loading? disabled)) new-props (dissoc updated-props :loading? :text :loading-text)] [:button.LoaderButton new-props (if loading? [:span.glyphicon.glyphicon-refresh.spinning]) (if loading? loading-text text)]))
true
(ns notes-app-frontend.components (:require [notes-app-frontend.aws-lib2 :as aws] [reagent.core :as r] [reagent.session :as session] [clojure.string :as s] [wilson.react-bootstrap :refer [navbar navbar-header navbar-brand navbar-toggle navbar-collapse nav nav-item]])) (defn- handle-input-change "Resets atom associated with input based on input type" [event value type] (if (= type "file") (reset! value (get (-> event .target .files) 0)) (reset! value (-> event .-target .-value)))) (defn route-nav-item [props & content] (fn [] (let [new-props (if (s/ends-with? js/window.location.href (get props :href)) (conj props {:class "active"}) props) view (session/get :current-page)] [nav-item new-props content]))) (defn navigation [] [navbar {:fluid true :collapseOnSelect true} [navbar-header [navbar-brand [:a {:href "/"} "Scratch"]] [navbar-toggle]] [navbar-collapse (if (session/get :authenticated?) [nav {:pullRight true} [nav-item {:on-click #(aws/logout)} "Logout"]] [nav {:pullRight true} [route-nav-item {:href "#/signup"} "Signup"] [route-nav-item {:href "#/login"} "Login"]])]]) (defn input-element "An input element which updates its value and on focus parameters on change, blur, and focus" ([id name type value] (input-element id name type value false)) ([id name type value auto-focus] [:div {:class "form-group form-group-lg"} [:label {:for id :class "control-label"} name] [:input {:id id :class "form-control" :auto-focus auto-focus :type type :value @value :on-change #(handle-input-change % value type)}]])) (defn email-form [email-address-atom] (input-element "email" "Email" "email" email-address-atom true)) (defn password-form [password-atom] (input-element "password" "Password" "PI:PASSWORD:<PASSWORD>END_PI" password-atom false)) (defn confirm-password-form [confirm-password-atom] (input-element "confirmPassword" "Confirm password" "password" confirm-password-atom false)) (defn confirmation-form [confirmation-atom] (input-element "confirmationCode" "Confirmation code" "tel" confirmation-atom true)) (defn loader-button "Button with loader animation" [] (let [this (r/current-component) props (r/props this) {:keys [loading? text loading-text disabled]} props updated-props (assoc-in props [:disabled] (or loading? disabled)) new-props (dissoc updated-props :loading? :text :loading-text)] [:button.LoaderButton new-props (if loading? [:span.glyphicon.glyphicon-refresh.spinning]) (if loading? loading-text text)]))
[ { "context": "defn mapify\n \"Return a seq of maps like {:name \\\"Edward Cullen\\\" :glitter-index 10}\"\n [rows]\n (map (fn [unmapp", "end": 505, "score": 0.9998412132263184, "start": 492, "tag": "NAME", "value": "Edward Cullen" } ]
src/clj_brave_and_true/chapter04.clj
artemy/clj-brave-and-true-exercises
0
(ns clj-brave-and-true.chapter04 (:require [clojure.string])) (def filename "suspects.csv") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse "Convert a CSV into rows of columns" [string] (map #(clojure.string/split % #",") (clojure.string/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def suspects (mapify (parse (slurp filename)))) ;; Exercise 1: Turn the result of your glitter filter into a list of names. (defn glitter-filter-names [minimum-glitter records] (map :name (glitter-filter minimum-glitter records))) ;; Exercise 2: Write a function, append, which will append a new suspect to your list of suspects. (defn append [map new-suspect] (conj map new-suspect)) ;; Exercise 3: Write a function, validate, which will check that ;; :name and :glitter-index are present when you append. ;; The validate function should accept two arguments: ;; a map of keywords to validating functions, similar to conversions, and the record to be validated. (defn validate [entry] (and (contains? entry :name) (contains? entry :glitter-index))) (defn append-with-validate [map new-suspect] (if (validate new-suspect) (conj map new-suspect) map)) ;; Exercise 4: Write a function that will take your list of maps ;; and convert it back to a CSV string. You’ll need to use the clojure.string/join function. (defn suspects->csv [suspects] (reduce (fn [input-str values] (str input-str (clojure.string/join "," values) "\n")) "" (map #(vals %) suspects)))
13104
(ns clj-brave-and-true.chapter04 (:require [clojure.string])) (def filename "suspects.csv") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse "Convert a CSV into rows of columns" [string] (map #(clojure.string/split % #",") (clojure.string/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"<NAME>\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def suspects (mapify (parse (slurp filename)))) ;; Exercise 1: Turn the result of your glitter filter into a list of names. (defn glitter-filter-names [minimum-glitter records] (map :name (glitter-filter minimum-glitter records))) ;; Exercise 2: Write a function, append, which will append a new suspect to your list of suspects. (defn append [map new-suspect] (conj map new-suspect)) ;; Exercise 3: Write a function, validate, which will check that ;; :name and :glitter-index are present when you append. ;; The validate function should accept two arguments: ;; a map of keywords to validating functions, similar to conversions, and the record to be validated. (defn validate [entry] (and (contains? entry :name) (contains? entry :glitter-index))) (defn append-with-validate [map new-suspect] (if (validate new-suspect) (conj map new-suspect) map)) ;; Exercise 4: Write a function that will take your list of maps ;; and convert it back to a CSV string. You’ll need to use the clojure.string/join function. (defn suspects->csv [suspects] (reduce (fn [input-str values] (str input-str (clojure.string/join "," values) "\n")) "" (map #(vals %) suspects)))
true
(ns clj-brave-and-true.chapter04 (:require [clojure.string])) (def filename "suspects.csv") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse "Convert a CSV into rows of columns" [string] (map #(clojure.string/split % #",") (clojure.string/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"PI:NAME:<NAME>END_PI\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def suspects (mapify (parse (slurp filename)))) ;; Exercise 1: Turn the result of your glitter filter into a list of names. (defn glitter-filter-names [minimum-glitter records] (map :name (glitter-filter minimum-glitter records))) ;; Exercise 2: Write a function, append, which will append a new suspect to your list of suspects. (defn append [map new-suspect] (conj map new-suspect)) ;; Exercise 3: Write a function, validate, which will check that ;; :name and :glitter-index are present when you append. ;; The validate function should accept two arguments: ;; a map of keywords to validating functions, similar to conversions, and the record to be validated. (defn validate [entry] (and (contains? entry :name) (contains? entry :glitter-index))) (defn append-with-validate [map new-suspect] (if (validate new-suspect) (conj map new-suspect) map)) ;; Exercise 4: Write a function that will take your list of maps ;; and convert it back to a CSV string. You’ll need to use the clojure.string/join function. (defn suspects->csv [suspects] (reduce (fn [input-str values] (str input-str (clojure.string/join "," values) "\n")) "" (map #(vals %) suspects)))
[ { "context": "; Copyright 2018-2021 Rahul De\n;\n; Use of this source code is governed by an MIT", "end": 30, "score": 0.9998641610145569, "start": 22, "tag": "NAME", "value": "Rahul De" } ]
entities/src/entities/resource_provider.clj
bob-cd/bob
88
; Copyright 2018-2021 Rahul De ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns entities.resource-provider (:require [failjure.core :as f] [taoensso.timbre :as log] [xtdb.api :as xt] [common.errors :as err])) (defn register-resource-provider "Registers a rersource provider with an unique name and an url supplied in a map." [db-client queue-chan data] (let [result (f/try* (xt/submit-tx db-client [[::xt/put {:xt/id (keyword (str "bob.resource-provider/" (:name data))) :type :resource-provider :name (:name data) :url (:url data)}]]))] (if (f/failed? result) (err/publish-error queue-chan (format "Could not register resource provider: %s" (f/message result))) (do (log/infof "Registered resource provider at: %s" data) "Ok")))) (defn un-register-resource-provider "Unregisters an resource provider by its name supplied in a map." [db-client _queue-chan data] (f/try* (xt/submit-tx db-client [[::xt/delete (keyword (str "bob.resource-provider/" (:name data)))]])) (log/infof "Un-registered resource provider %s" (:name data)) "Ok")
122719
; Copyright 2018-2021 <NAME> ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns entities.resource-provider (:require [failjure.core :as f] [taoensso.timbre :as log] [xtdb.api :as xt] [common.errors :as err])) (defn register-resource-provider "Registers a rersource provider with an unique name and an url supplied in a map." [db-client queue-chan data] (let [result (f/try* (xt/submit-tx db-client [[::xt/put {:xt/id (keyword (str "bob.resource-provider/" (:name data))) :type :resource-provider :name (:name data) :url (:url data)}]]))] (if (f/failed? result) (err/publish-error queue-chan (format "Could not register resource provider: %s" (f/message result))) (do (log/infof "Registered resource provider at: %s" data) "Ok")))) (defn un-register-resource-provider "Unregisters an resource provider by its name supplied in a map." [db-client _queue-chan data] (f/try* (xt/submit-tx db-client [[::xt/delete (keyword (str "bob.resource-provider/" (:name data)))]])) (log/infof "Un-registered resource provider %s" (:name data)) "Ok")
true
; Copyright 2018-2021 PI:NAME:<NAME>END_PI ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns entities.resource-provider (:require [failjure.core :as f] [taoensso.timbre :as log] [xtdb.api :as xt] [common.errors :as err])) (defn register-resource-provider "Registers a rersource provider with an unique name and an url supplied in a map." [db-client queue-chan data] (let [result (f/try* (xt/submit-tx db-client [[::xt/put {:xt/id (keyword (str "bob.resource-provider/" (:name data))) :type :resource-provider :name (:name data) :url (:url data)}]]))] (if (f/failed? result) (err/publish-error queue-chan (format "Could not register resource provider: %s" (f/message result))) (do (log/infof "Registered resource provider at: %s" data) "Ok")))) (defn un-register-resource-provider "Unregisters an resource provider by its name supplied in a map." [db-client _queue-chan data] (f/try* (xt/submit-tx db-client [[::xt/delete (keyword (str "bob.resource-provider/" (:name data)))]])) (log/infof "Un-registered resource provider %s" (:name data)) "Ok")
[ { "context": "ormally be made available at run-time via env\"\n \"24rakMBbFOhlpLYV\")\n\n(def api-secret\n \"API Secret. S", "end": 142, "score": 0.7778438329696655, "start": 140, "tag": "KEY", "value": "24" }, { "context": "ormally be made available at run-time via env\"\n \"ejobaTely5Jud4j64cnXp4se2ZP457on\")\n\n(def encoded-api-key\n \"Construct Basic auth c", "end": 281, "score": 0.998894453048706, "start": 249, "tag": "KEY", "value": "ejobaTely5Jud4j64cnXp4se2ZP457on" } ]
src/fullstack/ui/api.cljs
alexdao3/audio-transcription-client
0
(ns fullstack.ui.api (:require [ajax.core :as ajax])) (def api-key "API Key. Should normally be made available at run-time via env" "24rakMBbFOhlpLYV") (def api-secret "API Secret. Should normally be made available at run-time via env" "ejobaTely5Jud4j64cnXp4se2ZP457on") (def encoded-api-key "Construct Basic auth credentials via b64 encoding" (str "Basic " (js/btoa (str api-key ":" api-secret)))) (def deepbrain-url "Where the magic happens" "https://brain.deepgram.com/v2/listen") (defn request "Sets defaults for constructing API requests" [{need-auth? :need-auth? :as params}] (cond-> (merge {:format (ajax/json-request-format) :response-format (ajax/json-response-format (select-keys params [:keywords?]))} params) need-auth? (assoc-in [:headers :authorization] encoded-api-key)))
84461
(ns fullstack.ui.api (:require [ajax.core :as ajax])) (def api-key "API Key. Should normally be made available at run-time via env" "<KEY>rakMBbFOhlpLYV") (def api-secret "API Secret. Should normally be made available at run-time via env" "<KEY>") (def encoded-api-key "Construct Basic auth credentials via b64 encoding" (str "Basic " (js/btoa (str api-key ":" api-secret)))) (def deepbrain-url "Where the magic happens" "https://brain.deepgram.com/v2/listen") (defn request "Sets defaults for constructing API requests" [{need-auth? :need-auth? :as params}] (cond-> (merge {:format (ajax/json-request-format) :response-format (ajax/json-response-format (select-keys params [:keywords?]))} params) need-auth? (assoc-in [:headers :authorization] encoded-api-key)))
true
(ns fullstack.ui.api (:require [ajax.core :as ajax])) (def api-key "API Key. Should normally be made available at run-time via env" "PI:KEY:<KEY>END_PIrakMBbFOhlpLYV") (def api-secret "API Secret. Should normally be made available at run-time via env" "PI:KEY:<KEY>END_PI") (def encoded-api-key "Construct Basic auth credentials via b64 encoding" (str "Basic " (js/btoa (str api-key ":" api-secret)))) (def deepbrain-url "Where the magic happens" "https://brain.deepgram.com/v2/listen") (defn request "Sets defaults for constructing API requests" [{need-auth? :need-auth? :as params}] (cond-> (merge {:format (ajax/json-request-format) :response-format (ajax/json-response-format (select-keys params [:keywords?]))} params) need-auth? (assoc-in [:headers :authorization] encoded-api-key)))
[ { "context": "state\"\n :partition-key #{\"tx_id\"}\n :clustering-key #{}\n ", "end": 280, "score": 0.6038778424263, "start": 275, "tag": "KEY", "value": "tx_id" } ]
tools/scalar-schema/src/scalar_schema/common.clj
Torch3333/scalardb
0
(ns scalar-schema.common (:require [clojure.string :as str] [clojure.java.io :as io] [cheshire.core :as cheshire])) (def COORDINATOR_SCHEMA {:database "coordinator" :table "state" :partition-key #{"tx_id"} :clustering-key #{} :columns {"tx_id" "text" "tx_state" "int" "tx_created_at" "bigint"}}) (def TRANSACTION_METADATA_COLUMNS {"tx_committed_at" "bigint" "tx_id" "text" "tx_prepared_at" "bigint" "tx_state" "int" "tx_version" "int"}) (defn get-fullname [database table] (str database "." table)) (defn- format-schema [schema] (map (fn [[k v]] (let [[db tbl] (str/split (name k) #"\.") v' (merge v {:columns (reduce-kv (fn [m c t] (assoc m (name c) (.toLowerCase t))) {} (:columns v))})] (assoc v' :database db :table tbl))) schema)) (defn parse-schema [schema-file] (->> (cheshire/parse-stream (io/reader schema-file) true #(when (or (= % "partition-key") (= % "clustering-key")) #{})) format-schema)) (defn- add-transaction-columns [schema] (let [s (merge (:columns schema) TRANSACTION_METADATA_COLUMNS)] (->> (reduce (fn [m [name type]] (if (or (contains? (:partition-key schema) name) (contains? (:clustering-key schema) name)) m (assoc m (str "before_" name) type))) {} s) (merge s)))) (defn update-for-transaction [schema] (merge schema {:columns (add-transaction-columns schema)}))
40609
(ns scalar-schema.common (:require [clojure.string :as str] [clojure.java.io :as io] [cheshire.core :as cheshire])) (def COORDINATOR_SCHEMA {:database "coordinator" :table "state" :partition-key #{"<KEY>"} :clustering-key #{} :columns {"tx_id" "text" "tx_state" "int" "tx_created_at" "bigint"}}) (def TRANSACTION_METADATA_COLUMNS {"tx_committed_at" "bigint" "tx_id" "text" "tx_prepared_at" "bigint" "tx_state" "int" "tx_version" "int"}) (defn get-fullname [database table] (str database "." table)) (defn- format-schema [schema] (map (fn [[k v]] (let [[db tbl] (str/split (name k) #"\.") v' (merge v {:columns (reduce-kv (fn [m c t] (assoc m (name c) (.toLowerCase t))) {} (:columns v))})] (assoc v' :database db :table tbl))) schema)) (defn parse-schema [schema-file] (->> (cheshire/parse-stream (io/reader schema-file) true #(when (or (= % "partition-key") (= % "clustering-key")) #{})) format-schema)) (defn- add-transaction-columns [schema] (let [s (merge (:columns schema) TRANSACTION_METADATA_COLUMNS)] (->> (reduce (fn [m [name type]] (if (or (contains? (:partition-key schema) name) (contains? (:clustering-key schema) name)) m (assoc m (str "before_" name) type))) {} s) (merge s)))) (defn update-for-transaction [schema] (merge schema {:columns (add-transaction-columns schema)}))
true
(ns scalar-schema.common (:require [clojure.string :as str] [clojure.java.io :as io] [cheshire.core :as cheshire])) (def COORDINATOR_SCHEMA {:database "coordinator" :table "state" :partition-key #{"PI:KEY:<KEY>END_PI"} :clustering-key #{} :columns {"tx_id" "text" "tx_state" "int" "tx_created_at" "bigint"}}) (def TRANSACTION_METADATA_COLUMNS {"tx_committed_at" "bigint" "tx_id" "text" "tx_prepared_at" "bigint" "tx_state" "int" "tx_version" "int"}) (defn get-fullname [database table] (str database "." table)) (defn- format-schema [schema] (map (fn [[k v]] (let [[db tbl] (str/split (name k) #"\.") v' (merge v {:columns (reduce-kv (fn [m c t] (assoc m (name c) (.toLowerCase t))) {} (:columns v))})] (assoc v' :database db :table tbl))) schema)) (defn parse-schema [schema-file] (->> (cheshire/parse-stream (io/reader schema-file) true #(when (or (= % "partition-key") (= % "clustering-key")) #{})) format-schema)) (defn- add-transaction-columns [schema] (let [s (merge (:columns schema) TRANSACTION_METADATA_COLUMNS)] (->> (reduce (fn [m [name type]] (if (or (contains? (:partition-key schema) name) (contains? (:clustering-key schema) name)) m (assoc m (str "before_" name) type))) {} s) (merge s)))) (defn update-for-transaction [schema] (merge schema {:columns (add-transaction-columns schema)}))
[ { "context": "re\n [?e :decide.models.user/display-name \"Christian\"]] @conn) ; => 26, 27, 28\n\n (let [db (d/since @c", "end": 1150, "score": 0.9994931817054749, "start": 1141, "tag": "NAME", "value": "Christian" } ]
src/dev/analysis.clj
fivejjs/decide3
4
(ns analysis (:require [datahike.api :as d] [decide.server-components.database :refer [conn]])) (defn query-all-entities [] (let [db (d/db conn)] (->> db (d/q '[:find [?e ...] :where [?e]]) (d/pull-many db '[*]) (sort-by :db/id)))) (defn query-all-processes [] (let [db (d/db conn)] (->> db (d/q '[:find [(pull ?e [*]) ...] :where [?e :decide.models.process/slug]])))) (defn get-all-transactions-by [db user-eid] (->> (d/q '[:find [(pull ?e [*]) ...] :in $ ?user :where [?e :db/txInstant] [?e :tx/by ?user]] db user-eid) (sort-by :db/txInstant))) (defn get-transaction [db tx] (d/q '[:find [?e ?a ?v ?tx ?op] :in $ ?tx :where [?e ?a ?v ?tx ?op]] db tx)) (defn query-process [slug] (d/q '[:find [(pull ?e [*]) ...] :in $ ?slug :where [?e :decide.models.process/slug ?slug]] (d/db conn) slug)) (comment (get-transaction (d/history (d/since @conn #inst"2021-07-13")) 536871519) (d/q '[:find ?e :where [?e :decide.models.user/display-name "Christian"]] @conn) ; => 26, 27, 28 (let [db (d/since @conn #inst"2021-07-13")] (->> (get-all-transactions-by db 26) (map :db/id) (map #(get-transaction db %)))) (map #(get-transaction @conn %) (d/q '[:find [?tx ...] :where [?process :decide.models.process/slug "wie-richten-wir-die-kueche-ein"] [?process :process/features _ ?tx]] @conn)) (query-all-entities) (d/datoms @conn {:index :aevt :components [:decide.models.opinion/value]}) (d/pull @conn [:decide.models.opinion/value {:decide.models.proposal/_opinions [:decide.models.proposal/title]}] 523) (d/pull @conn ['*] 536871546) (d/pull @conn [{:decide.models.user/opinions [:db/id :decide.models.opinion/value]}] 26) (d/q '[:find (pull ?user [:db/id :decide.models.user/display-name]) (pull ?proposal [:db/id :decide.models.proposal/title]) (pull ?opinion [:db/id :decide.models.opinion/value]) :in $ ?user ?process :where [?process :decide.models.process/proposals ?proposal] [?proposal :decide.models.proposal/opinions ?opinion] [?user :decide.models.user/opinions ?opinion]] @conn 27 [:decide.models.process/slug "wie-richten-wir-die-kueche-ein"]) (get-transaction @conn 536871481) (def db @conn) (d/pull db [{:decide.models.process/proposals [:decide.models.proposal/title {:decide.models.proposal/original-author [:decide.models.user/display-name :decide.models.user/email]}]}] [:decide.models.process/slug "decide-experiment2"]) (group-by first (d/q '[:find (pull ?user [:decide.models.user/email :decide.models.user/display-name]) (pull ?proposal [:decide.models.proposal/title]) :in $ ?process :where [?proposal :decide.models.proposal/original-author ?user]] db [:decide.models.process/slug "decide-experiment2"])) (defn pprint-by [f coll] (doseq [[k vals] (group-by f coll)] (print k) (pprint/print-table vals) (println))) (pprint-by :who (sort-by :when (d/q '[:find ?nick ?when :keys who when :where [?e :tx/by ?who] [?e :db/txInstant ?when] [?who :decide.models.user/email ?nick]] (d/history db)))) (d/pull @conn [:decide.models.user/display-name] 26))
73525
(ns analysis (:require [datahike.api :as d] [decide.server-components.database :refer [conn]])) (defn query-all-entities [] (let [db (d/db conn)] (->> db (d/q '[:find [?e ...] :where [?e]]) (d/pull-many db '[*]) (sort-by :db/id)))) (defn query-all-processes [] (let [db (d/db conn)] (->> db (d/q '[:find [(pull ?e [*]) ...] :where [?e :decide.models.process/slug]])))) (defn get-all-transactions-by [db user-eid] (->> (d/q '[:find [(pull ?e [*]) ...] :in $ ?user :where [?e :db/txInstant] [?e :tx/by ?user]] db user-eid) (sort-by :db/txInstant))) (defn get-transaction [db tx] (d/q '[:find [?e ?a ?v ?tx ?op] :in $ ?tx :where [?e ?a ?v ?tx ?op]] db tx)) (defn query-process [slug] (d/q '[:find [(pull ?e [*]) ...] :in $ ?slug :where [?e :decide.models.process/slug ?slug]] (d/db conn) slug)) (comment (get-transaction (d/history (d/since @conn #inst"2021-07-13")) 536871519) (d/q '[:find ?e :where [?e :decide.models.user/display-name "<NAME>"]] @conn) ; => 26, 27, 28 (let [db (d/since @conn #inst"2021-07-13")] (->> (get-all-transactions-by db 26) (map :db/id) (map #(get-transaction db %)))) (map #(get-transaction @conn %) (d/q '[:find [?tx ...] :where [?process :decide.models.process/slug "wie-richten-wir-die-kueche-ein"] [?process :process/features _ ?tx]] @conn)) (query-all-entities) (d/datoms @conn {:index :aevt :components [:decide.models.opinion/value]}) (d/pull @conn [:decide.models.opinion/value {:decide.models.proposal/_opinions [:decide.models.proposal/title]}] 523) (d/pull @conn ['*] 536871546) (d/pull @conn [{:decide.models.user/opinions [:db/id :decide.models.opinion/value]}] 26) (d/q '[:find (pull ?user [:db/id :decide.models.user/display-name]) (pull ?proposal [:db/id :decide.models.proposal/title]) (pull ?opinion [:db/id :decide.models.opinion/value]) :in $ ?user ?process :where [?process :decide.models.process/proposals ?proposal] [?proposal :decide.models.proposal/opinions ?opinion] [?user :decide.models.user/opinions ?opinion]] @conn 27 [:decide.models.process/slug "wie-richten-wir-die-kueche-ein"]) (get-transaction @conn 536871481) (def db @conn) (d/pull db [{:decide.models.process/proposals [:decide.models.proposal/title {:decide.models.proposal/original-author [:decide.models.user/display-name :decide.models.user/email]}]}] [:decide.models.process/slug "decide-experiment2"]) (group-by first (d/q '[:find (pull ?user [:decide.models.user/email :decide.models.user/display-name]) (pull ?proposal [:decide.models.proposal/title]) :in $ ?process :where [?proposal :decide.models.proposal/original-author ?user]] db [:decide.models.process/slug "decide-experiment2"])) (defn pprint-by [f coll] (doseq [[k vals] (group-by f coll)] (print k) (pprint/print-table vals) (println))) (pprint-by :who (sort-by :when (d/q '[:find ?nick ?when :keys who when :where [?e :tx/by ?who] [?e :db/txInstant ?when] [?who :decide.models.user/email ?nick]] (d/history db)))) (d/pull @conn [:decide.models.user/display-name] 26))
true
(ns analysis (:require [datahike.api :as d] [decide.server-components.database :refer [conn]])) (defn query-all-entities [] (let [db (d/db conn)] (->> db (d/q '[:find [?e ...] :where [?e]]) (d/pull-many db '[*]) (sort-by :db/id)))) (defn query-all-processes [] (let [db (d/db conn)] (->> db (d/q '[:find [(pull ?e [*]) ...] :where [?e :decide.models.process/slug]])))) (defn get-all-transactions-by [db user-eid] (->> (d/q '[:find [(pull ?e [*]) ...] :in $ ?user :where [?e :db/txInstant] [?e :tx/by ?user]] db user-eid) (sort-by :db/txInstant))) (defn get-transaction [db tx] (d/q '[:find [?e ?a ?v ?tx ?op] :in $ ?tx :where [?e ?a ?v ?tx ?op]] db tx)) (defn query-process [slug] (d/q '[:find [(pull ?e [*]) ...] :in $ ?slug :where [?e :decide.models.process/slug ?slug]] (d/db conn) slug)) (comment (get-transaction (d/history (d/since @conn #inst"2021-07-13")) 536871519) (d/q '[:find ?e :where [?e :decide.models.user/display-name "PI:NAME:<NAME>END_PI"]] @conn) ; => 26, 27, 28 (let [db (d/since @conn #inst"2021-07-13")] (->> (get-all-transactions-by db 26) (map :db/id) (map #(get-transaction db %)))) (map #(get-transaction @conn %) (d/q '[:find [?tx ...] :where [?process :decide.models.process/slug "wie-richten-wir-die-kueche-ein"] [?process :process/features _ ?tx]] @conn)) (query-all-entities) (d/datoms @conn {:index :aevt :components [:decide.models.opinion/value]}) (d/pull @conn [:decide.models.opinion/value {:decide.models.proposal/_opinions [:decide.models.proposal/title]}] 523) (d/pull @conn ['*] 536871546) (d/pull @conn [{:decide.models.user/opinions [:db/id :decide.models.opinion/value]}] 26) (d/q '[:find (pull ?user [:db/id :decide.models.user/display-name]) (pull ?proposal [:db/id :decide.models.proposal/title]) (pull ?opinion [:db/id :decide.models.opinion/value]) :in $ ?user ?process :where [?process :decide.models.process/proposals ?proposal] [?proposal :decide.models.proposal/opinions ?opinion] [?user :decide.models.user/opinions ?opinion]] @conn 27 [:decide.models.process/slug "wie-richten-wir-die-kueche-ein"]) (get-transaction @conn 536871481) (def db @conn) (d/pull db [{:decide.models.process/proposals [:decide.models.proposal/title {:decide.models.proposal/original-author [:decide.models.user/display-name :decide.models.user/email]}]}] [:decide.models.process/slug "decide-experiment2"]) (group-by first (d/q '[:find (pull ?user [:decide.models.user/email :decide.models.user/display-name]) (pull ?proposal [:decide.models.proposal/title]) :in $ ?process :where [?proposal :decide.models.proposal/original-author ?user]] db [:decide.models.process/slug "decide-experiment2"])) (defn pprint-by [f coll] (doseq [[k vals] (group-by f coll)] (print k) (pprint/print-table vals) (println))) (pprint-by :who (sort-by :when (d/q '[:find ?nick ?when :keys who when :where [?e :tx/by ?who] [?e :db/txInstant ?when] [?who :decide.models.user/email ?nick]] (d/history db)))) (d/pull @conn [:decide.models.user/display-name] 26))
[ { "context": "ls-port tls-cert]} :web-server\n {key-password :password} :keystore\n {trust-password :password}", "end": 11885, "score": 0.9959446787834167, "start": 11877, "tag": "PASSWORD", "value": "password" }, { "context": ":password} :keystore\n {trust-password :password} :truststore}]\n (let [http? (boolean port)", "end": 11934, "score": 0.9979363679885864, "start": 11926, "tag": "PASSWORD", "value": "password" } ]
src/documint/web.clj
jonathanj/clj-documint
0
(ns documint.web "Documint web service. The API is REST-JSON with the following structure: POST /sessions Create a new session. Contains hrefs for: * Performing an action; * Creating new session content; * Referencing itself. POST /<session_uri>/perform Perform an action within a session. Action inputs and outputs are specific to each action being performed. Inputs and outputs are specified as URIs. {\"action\": \"some_action\", \"parameters\": { ... some parameters ... }} Contains hrefs for: * The contents of outputs (of which there may be more than one). POST /<session_uri>/contents/ Create new session content. Contains hrefs for: * Referencing itself. GET /<session_uri>/contents/<content_id> Fetch the content of an output. DELETE /<session_uri> Remove a session and all its contents. GET /metrics Retrieve Prometheus metrics. " (:require [clojure.data.json :as json] [clojure.tools.logging :as log] [com.stuartsierra.component :as component] [liberator.core :refer [defresource]] [liberator.dev :refer [wrap-trace]] [bidi.bidi :as bidi] [bidi.ring :refer [make-handler]] [ring.middleware.defaults :refer [wrap-defaults api-defaults]] [iapetos.collector.ring :as ring] [manifold.deferred :as d] [documint.content :as content] [documint.session :as session] [documint.actions :refer [perform-action]] [documint.util :refer [transform-map]] [documint.metrics :refer [registry]]) (:import [org.eclipse.jetty.server SslConnectionFactory])) (def routes "API routes definition." ["/sessions/" {"" ::session-index [::session-id] ::session-resource [::session-id "/perform"] ::session-perform [::session-id "/contents/"] ::content-index [::session-id "/contents/" ::content-id] ::content-resource}]) (defn session? "Look up the session in a request. If found, the session is associated with the `:documint.web/session` key." [session-factory] (fn [ctx] (let [id (get-in ctx [:request :params ::session-id]) session (session/get-session session-factory id)] (if-not (nil? session) [true {::session session}] [false {:representation {:media-type "application/json"} ::causes [[:unknown-session "Unknown session identifier" id]]}])))) (defn content? "Look up the content for a session in the request. If found, the content is associated with the `:documint.web/content` key." [ctx] (let [id (get-in ctx [:request :params ::content-id]) deferred-content (session/get-content (::session ctx) id) content (try (deref deferred-content 10000 ::no-response) (catch Exception e e))] (cond (= ::no-response content) [false {:representation {:media-type "application/json"} ::causes [[:content-timed-out id]]}] (nil? content) [false {:representation {:media-type "application/json"} ::causes [[:unknown-content "Unknown content identifier" id]]}] (instance? Exception content) [false {:representation {:media-type "application/json"} :exception content}] :else [true {:representation {:media-type (:content-type content)} ::content content}]))) (defn- cause "Construct a cause map from a cause vector." ([type reason] (cause type reason nil)) ([type reason description] {:type type :reason (if (instance? Exception reason) (.toString ^Exception reason) reason) :description description})) (defn- error-response "Convert a `:documint.web/causes` key into a map of causes and their reasons." [ctx] (log/error (:exception ctx) "Error handling a web request") (let [exc (:exception ctx) causes (or (if exc (get (ex-data exc) :causes) (get ctx ::causes)) [[:unhandled-exception exc]])] {:causes (map (partial apply cause) causes)})) (defn- uri-for "Construct a URI given a Ring request map and a URI path." [{req :request} path] (.toString (java.net.URI. (name (:scheme req)) nil (:server-name req) (:server-port req) path nil nil))) (defn- session-uri "Construct the URI for a session resource." ([ctx session] (uri-for ctx (bidi/path-for routes ::session-resource ::session-id (session/session-id session))))) (defn- session-perform-uri "Construct the URI for a session perform resource." ([ctx session] (uri-for ctx (bidi/path-for routes ::session-perform ::session-id (session/session-id session))))) (defn- content-index-uri "Construct the URI for a content index." ([ctx session] (uri-for ctx (bidi/path-for routes ::content-index ::session-id (session/session-id session))))) (defn- content-uri "Construct the URI for a content resource." ([ctx content] (uri-for ctx (bidi/path-for routes ::content-resource ::session-id (content/session-id content) ::content-id (content/content-id content))))) (defn parse-json "Parse a Liberator request's body as JSON." [key ctx] (try [false {key (-> ctx (get-in [:request :body]) clojure.java.io/reader (json/read :key-fn keyword))}] (catch Exception e [true {:representation {:media-type "application/json"} ::causes [[:invalid-json e]]}]))) (defn- normalize-decision-result "Convert a decision result to it's canonical form." [result] (cond (nil? result) [false {}] (false? result) [false result] (vector? result) result)) (defn- comp-decisions "Compose several Liberator decision functions together. Short-circuits upon the first failed decision. Note: This only works for decisions whose failure value is `false`. " [& fs] (fn [ctx] (reduce (fn [[success?' prev-result] f] (let [[success? result] (normalize-decision-result (f (merge ctx prev-result)))] (if success? [success? (merge prev-result result)] (reduced [success? result])))) [true ctx] (reverse fs)))) (defresource session-index [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :can-post-to-missing? false :post-redirect? true :post! (fn [ctx] {:location (session-uri ctx (session/new-session session-factory))})) (defresource session-resource [session-factory] :available-media-types ["application/json"] :allowed-methods [:get :delete] :handle-exception error-response :exists? (session? session-factory) :handle-not-found error-response :handle-ok (fn [{session ::session :as ctx}] {:links {:self (session-uri ctx session) :perform (session-perform-uri ctx session) :store-content (content-index-uri ctx session)}}) :delete! (fn [{session ::session}] (session/destroy session))) (defn- transform-response "Transform an action response map." [make-uri response] (transform-map (fn [v] (if (satisfies? content/IStorageEntry v) (make-uri v) v)) response)) (defresource session-perform [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :malformed? #(parse-json ::data %) :handle-malformed error-response :exists? (session? session-factory) :handle-not-found error-response :can-post-to-missing? false :post! (fn [{session ::session {:keys [action parameters]} ::data :as ctx}] (let [make-uri (partial content-uri ctx) outputs (perform-action action parameters session) d (d/chain outputs #(transform-response make-uri %) #(assoc {} ::response %)) ; We deref here because Liberator doesn't really do async. response (deref d 30000 ::no-response)] (if (= ::no-response response) (throw (ex-info "Performing an action timed out" {:causes [[:perform-timed-out action]]})) response))) :handle-created ::response) (defresource content-index [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :exists? (session? session-factory) :handle-not-found error-response :can-post-to-missing? false :post! (fn [{session ::session :as ctx}] (let [body (get-in ctx [:request :body]) content-type (get-in ctx [:request :headers "content-type"] "application/octet-stream") content (session/put-content session content-type body)] {::response {:links {:self (content-uri ctx content)}}})) :handle-created ::response) (defresource content-resource [session-factory] :available-media-types ["*"] :allowed-methods [:get] :handle-exception error-response :exists? (comp-decisions content? (session? session-factory)) :handle-not-found error-response :handle-ok #(get-in % [::content :stream])) (defn route-handlers "" [session-factory] {::session-index (session-index session-factory) ::session-resource (session-resource session-factory) ::session-perform (session-perform session-factory) ::content-index (content-index session-factory) ::content-resource (content-resource session-factory)}) (defn- path-fn "Describe a request path according to a route map" [routes] (fn [{uri :uri}] (pr-str (:handler (bidi/match-route routes uri))))) (defrecord App [handler session-factory] component/Lifecycle (start [this] (let [handlers (route-handlers session-factory)] (assoc this :handler (-> (make-handler routes handlers) #_(wrap-trace :header :ui) (wrap-defaults api-defaults) (ring/wrap-metrics registry {:path "/metrics" :path-fn (path-fn routes)}))))) (stop [this] this)) (defn new-app [] (map->App {})) (defn- configure-ssl-connector "Configure the SSL context factory. Primarily we want to set the certificate alias and remove any HTTP connectors." [cert-alias http? server] (doseq [connector (.getConnectors server)] (if-let [ssl-context-factory (some-> connector (.getConnectionFactory SslConnectionFactory) .getSslContextFactory)] (.setCertAlias ssl-context-factory cert-alias) ; We need this since the `http?` ring-jetty-adapter option is not in a ; release yet. (when-not http? (.removeConnector server connector))))) (defn jetty-options "ring-jetty-adapter options." [keystore truststore {{:keys [port tls-port tls-cert]} :web-server {key-password :password} :keystore {trust-password :password} :truststore}] (let [http? (boolean port) tls? (boolean tls-port)] (cond-> {:join? false :ssl? tls?} http? (conj {:port port}) tls? (conj {:configurator (partial configure-ssl-connector tls-cert http?) :ssl-port tls-port}) keystore (conj {:keystore keystore :key-password key-password}) truststore (conj {:client-auth :need :truststore truststore :trust-password trust-password}))))
106909
(ns documint.web "Documint web service. The API is REST-JSON with the following structure: POST /sessions Create a new session. Contains hrefs for: * Performing an action; * Creating new session content; * Referencing itself. POST /<session_uri>/perform Perform an action within a session. Action inputs and outputs are specific to each action being performed. Inputs and outputs are specified as URIs. {\"action\": \"some_action\", \"parameters\": { ... some parameters ... }} Contains hrefs for: * The contents of outputs (of which there may be more than one). POST /<session_uri>/contents/ Create new session content. Contains hrefs for: * Referencing itself. GET /<session_uri>/contents/<content_id> Fetch the content of an output. DELETE /<session_uri> Remove a session and all its contents. GET /metrics Retrieve Prometheus metrics. " (:require [clojure.data.json :as json] [clojure.tools.logging :as log] [com.stuartsierra.component :as component] [liberator.core :refer [defresource]] [liberator.dev :refer [wrap-trace]] [bidi.bidi :as bidi] [bidi.ring :refer [make-handler]] [ring.middleware.defaults :refer [wrap-defaults api-defaults]] [iapetos.collector.ring :as ring] [manifold.deferred :as d] [documint.content :as content] [documint.session :as session] [documint.actions :refer [perform-action]] [documint.util :refer [transform-map]] [documint.metrics :refer [registry]]) (:import [org.eclipse.jetty.server SslConnectionFactory])) (def routes "API routes definition." ["/sessions/" {"" ::session-index [::session-id] ::session-resource [::session-id "/perform"] ::session-perform [::session-id "/contents/"] ::content-index [::session-id "/contents/" ::content-id] ::content-resource}]) (defn session? "Look up the session in a request. If found, the session is associated with the `:documint.web/session` key." [session-factory] (fn [ctx] (let [id (get-in ctx [:request :params ::session-id]) session (session/get-session session-factory id)] (if-not (nil? session) [true {::session session}] [false {:representation {:media-type "application/json"} ::causes [[:unknown-session "Unknown session identifier" id]]}])))) (defn content? "Look up the content for a session in the request. If found, the content is associated with the `:documint.web/content` key." [ctx] (let [id (get-in ctx [:request :params ::content-id]) deferred-content (session/get-content (::session ctx) id) content (try (deref deferred-content 10000 ::no-response) (catch Exception e e))] (cond (= ::no-response content) [false {:representation {:media-type "application/json"} ::causes [[:content-timed-out id]]}] (nil? content) [false {:representation {:media-type "application/json"} ::causes [[:unknown-content "Unknown content identifier" id]]}] (instance? Exception content) [false {:representation {:media-type "application/json"} :exception content}] :else [true {:representation {:media-type (:content-type content)} ::content content}]))) (defn- cause "Construct a cause map from a cause vector." ([type reason] (cause type reason nil)) ([type reason description] {:type type :reason (if (instance? Exception reason) (.toString ^Exception reason) reason) :description description})) (defn- error-response "Convert a `:documint.web/causes` key into a map of causes and their reasons." [ctx] (log/error (:exception ctx) "Error handling a web request") (let [exc (:exception ctx) causes (or (if exc (get (ex-data exc) :causes) (get ctx ::causes)) [[:unhandled-exception exc]])] {:causes (map (partial apply cause) causes)})) (defn- uri-for "Construct a URI given a Ring request map and a URI path." [{req :request} path] (.toString (java.net.URI. (name (:scheme req)) nil (:server-name req) (:server-port req) path nil nil))) (defn- session-uri "Construct the URI for a session resource." ([ctx session] (uri-for ctx (bidi/path-for routes ::session-resource ::session-id (session/session-id session))))) (defn- session-perform-uri "Construct the URI for a session perform resource." ([ctx session] (uri-for ctx (bidi/path-for routes ::session-perform ::session-id (session/session-id session))))) (defn- content-index-uri "Construct the URI for a content index." ([ctx session] (uri-for ctx (bidi/path-for routes ::content-index ::session-id (session/session-id session))))) (defn- content-uri "Construct the URI for a content resource." ([ctx content] (uri-for ctx (bidi/path-for routes ::content-resource ::session-id (content/session-id content) ::content-id (content/content-id content))))) (defn parse-json "Parse a Liberator request's body as JSON." [key ctx] (try [false {key (-> ctx (get-in [:request :body]) clojure.java.io/reader (json/read :key-fn keyword))}] (catch Exception e [true {:representation {:media-type "application/json"} ::causes [[:invalid-json e]]}]))) (defn- normalize-decision-result "Convert a decision result to it's canonical form." [result] (cond (nil? result) [false {}] (false? result) [false result] (vector? result) result)) (defn- comp-decisions "Compose several Liberator decision functions together. Short-circuits upon the first failed decision. Note: This only works for decisions whose failure value is `false`. " [& fs] (fn [ctx] (reduce (fn [[success?' prev-result] f] (let [[success? result] (normalize-decision-result (f (merge ctx prev-result)))] (if success? [success? (merge prev-result result)] (reduced [success? result])))) [true ctx] (reverse fs)))) (defresource session-index [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :can-post-to-missing? false :post-redirect? true :post! (fn [ctx] {:location (session-uri ctx (session/new-session session-factory))})) (defresource session-resource [session-factory] :available-media-types ["application/json"] :allowed-methods [:get :delete] :handle-exception error-response :exists? (session? session-factory) :handle-not-found error-response :handle-ok (fn [{session ::session :as ctx}] {:links {:self (session-uri ctx session) :perform (session-perform-uri ctx session) :store-content (content-index-uri ctx session)}}) :delete! (fn [{session ::session}] (session/destroy session))) (defn- transform-response "Transform an action response map." [make-uri response] (transform-map (fn [v] (if (satisfies? content/IStorageEntry v) (make-uri v) v)) response)) (defresource session-perform [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :malformed? #(parse-json ::data %) :handle-malformed error-response :exists? (session? session-factory) :handle-not-found error-response :can-post-to-missing? false :post! (fn [{session ::session {:keys [action parameters]} ::data :as ctx}] (let [make-uri (partial content-uri ctx) outputs (perform-action action parameters session) d (d/chain outputs #(transform-response make-uri %) #(assoc {} ::response %)) ; We deref here because Liberator doesn't really do async. response (deref d 30000 ::no-response)] (if (= ::no-response response) (throw (ex-info "Performing an action timed out" {:causes [[:perform-timed-out action]]})) response))) :handle-created ::response) (defresource content-index [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :exists? (session? session-factory) :handle-not-found error-response :can-post-to-missing? false :post! (fn [{session ::session :as ctx}] (let [body (get-in ctx [:request :body]) content-type (get-in ctx [:request :headers "content-type"] "application/octet-stream") content (session/put-content session content-type body)] {::response {:links {:self (content-uri ctx content)}}})) :handle-created ::response) (defresource content-resource [session-factory] :available-media-types ["*"] :allowed-methods [:get] :handle-exception error-response :exists? (comp-decisions content? (session? session-factory)) :handle-not-found error-response :handle-ok #(get-in % [::content :stream])) (defn route-handlers "" [session-factory] {::session-index (session-index session-factory) ::session-resource (session-resource session-factory) ::session-perform (session-perform session-factory) ::content-index (content-index session-factory) ::content-resource (content-resource session-factory)}) (defn- path-fn "Describe a request path according to a route map" [routes] (fn [{uri :uri}] (pr-str (:handler (bidi/match-route routes uri))))) (defrecord App [handler session-factory] component/Lifecycle (start [this] (let [handlers (route-handlers session-factory)] (assoc this :handler (-> (make-handler routes handlers) #_(wrap-trace :header :ui) (wrap-defaults api-defaults) (ring/wrap-metrics registry {:path "/metrics" :path-fn (path-fn routes)}))))) (stop [this] this)) (defn new-app [] (map->App {})) (defn- configure-ssl-connector "Configure the SSL context factory. Primarily we want to set the certificate alias and remove any HTTP connectors." [cert-alias http? server] (doseq [connector (.getConnectors server)] (if-let [ssl-context-factory (some-> connector (.getConnectionFactory SslConnectionFactory) .getSslContextFactory)] (.setCertAlias ssl-context-factory cert-alias) ; We need this since the `http?` ring-jetty-adapter option is not in a ; release yet. (when-not http? (.removeConnector server connector))))) (defn jetty-options "ring-jetty-adapter options." [keystore truststore {{:keys [port tls-port tls-cert]} :web-server {key-password :<PASSWORD>} :keystore {trust-password :<PASSWORD>} :truststore}] (let [http? (boolean port) tls? (boolean tls-port)] (cond-> {:join? false :ssl? tls?} http? (conj {:port port}) tls? (conj {:configurator (partial configure-ssl-connector tls-cert http?) :ssl-port tls-port}) keystore (conj {:keystore keystore :key-password key-password}) truststore (conj {:client-auth :need :truststore truststore :trust-password trust-password}))))
true
(ns documint.web "Documint web service. The API is REST-JSON with the following structure: POST /sessions Create a new session. Contains hrefs for: * Performing an action; * Creating new session content; * Referencing itself. POST /<session_uri>/perform Perform an action within a session. Action inputs and outputs are specific to each action being performed. Inputs and outputs are specified as URIs. {\"action\": \"some_action\", \"parameters\": { ... some parameters ... }} Contains hrefs for: * The contents of outputs (of which there may be more than one). POST /<session_uri>/contents/ Create new session content. Contains hrefs for: * Referencing itself. GET /<session_uri>/contents/<content_id> Fetch the content of an output. DELETE /<session_uri> Remove a session and all its contents. GET /metrics Retrieve Prometheus metrics. " (:require [clojure.data.json :as json] [clojure.tools.logging :as log] [com.stuartsierra.component :as component] [liberator.core :refer [defresource]] [liberator.dev :refer [wrap-trace]] [bidi.bidi :as bidi] [bidi.ring :refer [make-handler]] [ring.middleware.defaults :refer [wrap-defaults api-defaults]] [iapetos.collector.ring :as ring] [manifold.deferred :as d] [documint.content :as content] [documint.session :as session] [documint.actions :refer [perform-action]] [documint.util :refer [transform-map]] [documint.metrics :refer [registry]]) (:import [org.eclipse.jetty.server SslConnectionFactory])) (def routes "API routes definition." ["/sessions/" {"" ::session-index [::session-id] ::session-resource [::session-id "/perform"] ::session-perform [::session-id "/contents/"] ::content-index [::session-id "/contents/" ::content-id] ::content-resource}]) (defn session? "Look up the session in a request. If found, the session is associated with the `:documint.web/session` key." [session-factory] (fn [ctx] (let [id (get-in ctx [:request :params ::session-id]) session (session/get-session session-factory id)] (if-not (nil? session) [true {::session session}] [false {:representation {:media-type "application/json"} ::causes [[:unknown-session "Unknown session identifier" id]]}])))) (defn content? "Look up the content for a session in the request. If found, the content is associated with the `:documint.web/content` key." [ctx] (let [id (get-in ctx [:request :params ::content-id]) deferred-content (session/get-content (::session ctx) id) content (try (deref deferred-content 10000 ::no-response) (catch Exception e e))] (cond (= ::no-response content) [false {:representation {:media-type "application/json"} ::causes [[:content-timed-out id]]}] (nil? content) [false {:representation {:media-type "application/json"} ::causes [[:unknown-content "Unknown content identifier" id]]}] (instance? Exception content) [false {:representation {:media-type "application/json"} :exception content}] :else [true {:representation {:media-type (:content-type content)} ::content content}]))) (defn- cause "Construct a cause map from a cause vector." ([type reason] (cause type reason nil)) ([type reason description] {:type type :reason (if (instance? Exception reason) (.toString ^Exception reason) reason) :description description})) (defn- error-response "Convert a `:documint.web/causes` key into a map of causes and their reasons." [ctx] (log/error (:exception ctx) "Error handling a web request") (let [exc (:exception ctx) causes (or (if exc (get (ex-data exc) :causes) (get ctx ::causes)) [[:unhandled-exception exc]])] {:causes (map (partial apply cause) causes)})) (defn- uri-for "Construct a URI given a Ring request map and a URI path." [{req :request} path] (.toString (java.net.URI. (name (:scheme req)) nil (:server-name req) (:server-port req) path nil nil))) (defn- session-uri "Construct the URI for a session resource." ([ctx session] (uri-for ctx (bidi/path-for routes ::session-resource ::session-id (session/session-id session))))) (defn- session-perform-uri "Construct the URI for a session perform resource." ([ctx session] (uri-for ctx (bidi/path-for routes ::session-perform ::session-id (session/session-id session))))) (defn- content-index-uri "Construct the URI for a content index." ([ctx session] (uri-for ctx (bidi/path-for routes ::content-index ::session-id (session/session-id session))))) (defn- content-uri "Construct the URI for a content resource." ([ctx content] (uri-for ctx (bidi/path-for routes ::content-resource ::session-id (content/session-id content) ::content-id (content/content-id content))))) (defn parse-json "Parse a Liberator request's body as JSON." [key ctx] (try [false {key (-> ctx (get-in [:request :body]) clojure.java.io/reader (json/read :key-fn keyword))}] (catch Exception e [true {:representation {:media-type "application/json"} ::causes [[:invalid-json e]]}]))) (defn- normalize-decision-result "Convert a decision result to it's canonical form." [result] (cond (nil? result) [false {}] (false? result) [false result] (vector? result) result)) (defn- comp-decisions "Compose several Liberator decision functions together. Short-circuits upon the first failed decision. Note: This only works for decisions whose failure value is `false`. " [& fs] (fn [ctx] (reduce (fn [[success?' prev-result] f] (let [[success? result] (normalize-decision-result (f (merge ctx prev-result)))] (if success? [success? (merge prev-result result)] (reduced [success? result])))) [true ctx] (reverse fs)))) (defresource session-index [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :can-post-to-missing? false :post-redirect? true :post! (fn [ctx] {:location (session-uri ctx (session/new-session session-factory))})) (defresource session-resource [session-factory] :available-media-types ["application/json"] :allowed-methods [:get :delete] :handle-exception error-response :exists? (session? session-factory) :handle-not-found error-response :handle-ok (fn [{session ::session :as ctx}] {:links {:self (session-uri ctx session) :perform (session-perform-uri ctx session) :store-content (content-index-uri ctx session)}}) :delete! (fn [{session ::session}] (session/destroy session))) (defn- transform-response "Transform an action response map." [make-uri response] (transform-map (fn [v] (if (satisfies? content/IStorageEntry v) (make-uri v) v)) response)) (defresource session-perform [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :malformed? #(parse-json ::data %) :handle-malformed error-response :exists? (session? session-factory) :handle-not-found error-response :can-post-to-missing? false :post! (fn [{session ::session {:keys [action parameters]} ::data :as ctx}] (let [make-uri (partial content-uri ctx) outputs (perform-action action parameters session) d (d/chain outputs #(transform-response make-uri %) #(assoc {} ::response %)) ; We deref here because Liberator doesn't really do async. response (deref d 30000 ::no-response)] (if (= ::no-response response) (throw (ex-info "Performing an action timed out" {:causes [[:perform-timed-out action]]})) response))) :handle-created ::response) (defresource content-index [session-factory] :available-media-types ["application/json"] :allowed-methods [:post] :handle-exception error-response :exists? (session? session-factory) :handle-not-found error-response :can-post-to-missing? false :post! (fn [{session ::session :as ctx}] (let [body (get-in ctx [:request :body]) content-type (get-in ctx [:request :headers "content-type"] "application/octet-stream") content (session/put-content session content-type body)] {::response {:links {:self (content-uri ctx content)}}})) :handle-created ::response) (defresource content-resource [session-factory] :available-media-types ["*"] :allowed-methods [:get] :handle-exception error-response :exists? (comp-decisions content? (session? session-factory)) :handle-not-found error-response :handle-ok #(get-in % [::content :stream])) (defn route-handlers "" [session-factory] {::session-index (session-index session-factory) ::session-resource (session-resource session-factory) ::session-perform (session-perform session-factory) ::content-index (content-index session-factory) ::content-resource (content-resource session-factory)}) (defn- path-fn "Describe a request path according to a route map" [routes] (fn [{uri :uri}] (pr-str (:handler (bidi/match-route routes uri))))) (defrecord App [handler session-factory] component/Lifecycle (start [this] (let [handlers (route-handlers session-factory)] (assoc this :handler (-> (make-handler routes handlers) #_(wrap-trace :header :ui) (wrap-defaults api-defaults) (ring/wrap-metrics registry {:path "/metrics" :path-fn (path-fn routes)}))))) (stop [this] this)) (defn new-app [] (map->App {})) (defn- configure-ssl-connector "Configure the SSL context factory. Primarily we want to set the certificate alias and remove any HTTP connectors." [cert-alias http? server] (doseq [connector (.getConnectors server)] (if-let [ssl-context-factory (some-> connector (.getConnectionFactory SslConnectionFactory) .getSslContextFactory)] (.setCertAlias ssl-context-factory cert-alias) ; We need this since the `http?` ring-jetty-adapter option is not in a ; release yet. (when-not http? (.removeConnector server connector))))) (defn jetty-options "ring-jetty-adapter options." [keystore truststore {{:keys [port tls-port tls-cert]} :web-server {key-password :PI:PASSWORD:<PASSWORD>END_PI} :keystore {trust-password :PI:PASSWORD:<PASSWORD>END_PI} :truststore}] (let [http? (boolean port) tls? (boolean tls-port)] (cond-> {:join? false :ssl? tls?} http? (conj {:port port}) tls? (conj {:configurator (partial configure-ssl-connector tls-cert http?) :ssl-port tls-port}) keystore (conj {:keystore keystore :key-password key-password}) truststore (conj {:client-auth :need :truststore truststore :trust-password trust-password}))))
[ { "context": "ormation from AWS ARNs\"\n :url \"http://github.com/skybet/aws-arn\"\n :license {:name \"MIT License\"\n ", "end": 164, "score": 0.9992812871932983, "start": 158, "tag": "USERNAME", "value": "skybet" }, { "context": "username\n :password :env/clojars_password\n :sign-releases fals", "end": 684, "score": 0.7311210036277771, "start": 664, "tag": "PASSWORD", "value": "env/clojars_password" }, { "context": " org.clojure/tools.cli]]\n [jonase/eastwood \"0.2.3\"]\n [lein-bikeshed \"0.3", "end": 963, "score": 0.937890887260437, "start": 957, "tag": "USERNAME", "value": "jonase" } ]
project.clj
skybet/aws-arn
4
(defproject aws-arn (or (System/getenv "PROJECT_VERSION") "0.0.0-SNAPSHOT") :description "Parse useful information from AWS ARNs" :url "http://github.com/skybet/aws-arn" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :year 2017 :key "mit"} :repositories [["snapshots" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password}] ["releases" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]] :plugins [[lein-license "0.1.6"] [lein-ancient "0.6.10"] [lein-kibit "0.1.2" :exclusions [org.clojure/clojure org.clojure/tools.cli]] [jonase/eastwood "0.2.3"] [lein-bikeshed "0.3.0"] [lein-cloverage "1.0.6"] [lein-codox "0.9.6"]] :target-path "target/%s" :aliases {"qa" ["do" ["clean"] ["check"] ["eastwood"] ["bikeshed" "-m" "120"] ["ancient"] ["cloverage"]]} :profiles {:dev {} :provided {:dependencies [[org.clojure/clojure "1.8.0"]]}})
103453
(defproject aws-arn (or (System/getenv "PROJECT_VERSION") "0.0.0-SNAPSHOT") :description "Parse useful information from AWS ARNs" :url "http://github.com/skybet/aws-arn" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :year 2017 :key "mit"} :repositories [["snapshots" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password}] ["releases" {:url "https://clojars.org/repo" :username :env/clojars_username :password :<PASSWORD> :sign-releases false}]] :plugins [[lein-license "0.1.6"] [lein-ancient "0.6.10"] [lein-kibit "0.1.2" :exclusions [org.clojure/clojure org.clojure/tools.cli]] [jonase/eastwood "0.2.3"] [lein-bikeshed "0.3.0"] [lein-cloverage "1.0.6"] [lein-codox "0.9.6"]] :target-path "target/%s" :aliases {"qa" ["do" ["clean"] ["check"] ["eastwood"] ["bikeshed" "-m" "120"] ["ancient"] ["cloverage"]]} :profiles {:dev {} :provided {:dependencies [[org.clojure/clojure "1.8.0"]]}})
true
(defproject aws-arn (or (System/getenv "PROJECT_VERSION") "0.0.0-SNAPSHOT") :description "Parse useful information from AWS ARNs" :url "http://github.com/skybet/aws-arn" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :year 2017 :key "mit"} :repositories [["snapshots" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password}] ["releases" {:url "https://clojars.org/repo" :username :env/clojars_username :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}]] :plugins [[lein-license "0.1.6"] [lein-ancient "0.6.10"] [lein-kibit "0.1.2" :exclusions [org.clojure/clojure org.clojure/tools.cli]] [jonase/eastwood "0.2.3"] [lein-bikeshed "0.3.0"] [lein-cloverage "1.0.6"] [lein-codox "0.9.6"]] :target-path "target/%s" :aliases {"qa" ["do" ["clean"] ["check"] ["eastwood"] ["bikeshed" "-m" "120"] ["ancient"] ["cloverage"]]} :profiles {:dev {} :provided {:dependencies [[org.clojure/clojure "1.8.0"]]}})
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998496174812317, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998365640640259, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/tools/analyzer/passes/jvm/box.clj
OctavioBR/healthcheck
0
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; 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 clojure.tools.analyzer.passes.jvm.box (:require [clojure.tools.analyzer.jvm.utils :as u] [clojure.tools.analyzer.utils :refer [protocol-node? arglist-for-arity]] [clojure.tools.analyzer.passes.jvm [validate :refer [validate]] [infer-tag :refer [infer-tag]]])) (defmulti box "Box the AST node tag where necessary" {:pass-info {:walk :pre :depends #{#'infer-tag} :after #{#'validate}}} :op) (defmacro if-let-box [class then else] `(let [c# ~class ~class (u/box c#)] (if (u/primitive? c#) ~then ~else))) (defn -box [ast] (let [tag (:tag ast)] (if (u/primitive? tag) (assoc ast :tag (u/box tag)) ast))) (defn boxed? [tag expr] (and (or (nil? tag) (not (u/primitive? tag))) (u/primitive? (:tag expr)))) (defmethod box :instance-call [{:keys [args class validated? tag] :as ast}] (let [ast (if-let-box class (assoc (update-in ast [:instance :tag] u/box) :class class) ast)] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object :tag (if (not (#{Void Void/TYPE} tag)) tag Object))))) (defmethod box :static-call [{:keys [args validated? tag] :as ast}] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object :tag (if (not (#{Void Void/TYPE} tag)) tag Object)))) (defmethod box :new [{:keys [args validated?] :as ast}] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object))) (defmethod box :instance-field [{:keys [class] :as ast}] (if-let-box class (assoc (update-in ast [:instance :tag] u/box) :class class) ast)) (defmethod box :def [{:keys [init] :as ast}] (if (and init (u/primitive? (:tag init))) (update-in ast [:init] -box) ast)) (defmethod box :vector [ast] (assoc ast :items (mapv -box (:items ast)))) (defmethod box :set [ast] (assoc ast :items (mapv -box (:items ast)))) (defmethod box :map [ast] (let [keys (mapv -box (:keys ast)) vals (mapv -box (:vals ast))] (assoc ast :keys keys :vals vals))) (defmethod box :do [ast] (if (boxed? (:tag ast) (:ret ast)) (-> ast (update-in [:ret] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :quote [ast] (if (boxed? (:tag ast) (:ret ast)) (-> ast (update-in [:expr] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :protocol-invoke [ast] (assoc ast :args (mapv -box (:args ast)))) (defmethod box :let [{:keys [tag body] :as ast}] (if (boxed? tag body) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :letfn [ast] (if (boxed? (:tag ast) (:body ast)) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :loop [ast] (if (boxed? (:tag ast) (:body ast)) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :fn-method [{:keys [params tag] :as ast}] (let [ast (if (u/primitive? tag) ast (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)))] (assoc ast :params (mapv (fn [{:keys [o-tag] :as p}] (assoc p :o-tag (u/prim-or-obj o-tag))) params) :tag (u/prim-or-obj tag) :o-tag (u/prim-or-obj tag)))) (defmethod box :if [{:keys [test then else tag o-tag] :as ast}] (let [test-tag (:tag test) test (if (and (u/primitive? test-tag) (not= Boolean/TYPE test-tag)) (assoc test :tag (u/box test-tag)) test) [then else o-tag] (if (or (boxed? tag then) (boxed? tag else) (not o-tag)) (conj (mapv -box [then else]) (u/box o-tag)) [then else o-tag])] (merge ast {:test test :o-tag o-tag :then then :else else}))) (defmethod box :case [{:keys [tag default tests thens test-type] :as ast}] (let [ast (if (and tag (u/primitive? tag)) ast (-> ast (assoc-in [:thens] (mapv (fn [t] (update-in t [:then] -box)) thens)) (update-in [:default] -box) (update-in [:o-tag] u/box)))] (if (= :hash-equiv test-type) (-> ast (update-in [:test] -box) (assoc-in [:tests] (mapv (fn [t] (update-in t [:test] -box)) tests))) ast))) (defmethod box :try [{:keys [tag] :as ast}] (let [ast (if (and tag (u/primitive? tag)) ast (-> ast (update-in [:catches] #(mapv -box %)) (update-in [:body] -box) (update-in [:o-tag] u/box)))] (-> ast (update-in [:finally] -box)))) (defmethod box :invoke [ast] (assoc ast :args (mapv -box (:args ast)) :o-tag Object)) (defmethod box :default [ast] ast)
32503
;; Copyright (c) <NAME>, <NAME> & contributors. ;; 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 clojure.tools.analyzer.passes.jvm.box (:require [clojure.tools.analyzer.jvm.utils :as u] [clojure.tools.analyzer.utils :refer [protocol-node? arglist-for-arity]] [clojure.tools.analyzer.passes.jvm [validate :refer [validate]] [infer-tag :refer [infer-tag]]])) (defmulti box "Box the AST node tag where necessary" {:pass-info {:walk :pre :depends #{#'infer-tag} :after #{#'validate}}} :op) (defmacro if-let-box [class then else] `(let [c# ~class ~class (u/box c#)] (if (u/primitive? c#) ~then ~else))) (defn -box [ast] (let [tag (:tag ast)] (if (u/primitive? tag) (assoc ast :tag (u/box tag)) ast))) (defn boxed? [tag expr] (and (or (nil? tag) (not (u/primitive? tag))) (u/primitive? (:tag expr)))) (defmethod box :instance-call [{:keys [args class validated? tag] :as ast}] (let [ast (if-let-box class (assoc (update-in ast [:instance :tag] u/box) :class class) ast)] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object :tag (if (not (#{Void Void/TYPE} tag)) tag Object))))) (defmethod box :static-call [{:keys [args validated? tag] :as ast}] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object :tag (if (not (#{Void Void/TYPE} tag)) tag Object)))) (defmethod box :new [{:keys [args validated?] :as ast}] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object))) (defmethod box :instance-field [{:keys [class] :as ast}] (if-let-box class (assoc (update-in ast [:instance :tag] u/box) :class class) ast)) (defmethod box :def [{:keys [init] :as ast}] (if (and init (u/primitive? (:tag init))) (update-in ast [:init] -box) ast)) (defmethod box :vector [ast] (assoc ast :items (mapv -box (:items ast)))) (defmethod box :set [ast] (assoc ast :items (mapv -box (:items ast)))) (defmethod box :map [ast] (let [keys (mapv -box (:keys ast)) vals (mapv -box (:vals ast))] (assoc ast :keys keys :vals vals))) (defmethod box :do [ast] (if (boxed? (:tag ast) (:ret ast)) (-> ast (update-in [:ret] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :quote [ast] (if (boxed? (:tag ast) (:ret ast)) (-> ast (update-in [:expr] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :protocol-invoke [ast] (assoc ast :args (mapv -box (:args ast)))) (defmethod box :let [{:keys [tag body] :as ast}] (if (boxed? tag body) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :letfn [ast] (if (boxed? (:tag ast) (:body ast)) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :loop [ast] (if (boxed? (:tag ast) (:body ast)) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :fn-method [{:keys [params tag] :as ast}] (let [ast (if (u/primitive? tag) ast (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)))] (assoc ast :params (mapv (fn [{:keys [o-tag] :as p}] (assoc p :o-tag (u/prim-or-obj o-tag))) params) :tag (u/prim-or-obj tag) :o-tag (u/prim-or-obj tag)))) (defmethod box :if [{:keys [test then else tag o-tag] :as ast}] (let [test-tag (:tag test) test (if (and (u/primitive? test-tag) (not= Boolean/TYPE test-tag)) (assoc test :tag (u/box test-tag)) test) [then else o-tag] (if (or (boxed? tag then) (boxed? tag else) (not o-tag)) (conj (mapv -box [then else]) (u/box o-tag)) [then else o-tag])] (merge ast {:test test :o-tag o-tag :then then :else else}))) (defmethod box :case [{:keys [tag default tests thens test-type] :as ast}] (let [ast (if (and tag (u/primitive? tag)) ast (-> ast (assoc-in [:thens] (mapv (fn [t] (update-in t [:then] -box)) thens)) (update-in [:default] -box) (update-in [:o-tag] u/box)))] (if (= :hash-equiv test-type) (-> ast (update-in [:test] -box) (assoc-in [:tests] (mapv (fn [t] (update-in t [:test] -box)) tests))) ast))) (defmethod box :try [{:keys [tag] :as ast}] (let [ast (if (and tag (u/primitive? tag)) ast (-> ast (update-in [:catches] #(mapv -box %)) (update-in [:body] -box) (update-in [:o-tag] u/box)))] (-> ast (update-in [:finally] -box)))) (defmethod box :invoke [ast] (assoc ast :args (mapv -box (:args ast)) :o-tag Object)) (defmethod box :default [ast] ast)
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; 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 clojure.tools.analyzer.passes.jvm.box (:require [clojure.tools.analyzer.jvm.utils :as u] [clojure.tools.analyzer.utils :refer [protocol-node? arglist-for-arity]] [clojure.tools.analyzer.passes.jvm [validate :refer [validate]] [infer-tag :refer [infer-tag]]])) (defmulti box "Box the AST node tag where necessary" {:pass-info {:walk :pre :depends #{#'infer-tag} :after #{#'validate}}} :op) (defmacro if-let-box [class then else] `(let [c# ~class ~class (u/box c#)] (if (u/primitive? c#) ~then ~else))) (defn -box [ast] (let [tag (:tag ast)] (if (u/primitive? tag) (assoc ast :tag (u/box tag)) ast))) (defn boxed? [tag expr] (and (or (nil? tag) (not (u/primitive? tag))) (u/primitive? (:tag expr)))) (defmethod box :instance-call [{:keys [args class validated? tag] :as ast}] (let [ast (if-let-box class (assoc (update-in ast [:instance :tag] u/box) :class class) ast)] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object :tag (if (not (#{Void Void/TYPE} tag)) tag Object))))) (defmethod box :static-call [{:keys [args validated? tag] :as ast}] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object :tag (if (not (#{Void Void/TYPE} tag)) tag Object)))) (defmethod box :new [{:keys [args validated?] :as ast}] (if validated? ast (assoc ast :args (mapv -box args) :o-tag Object))) (defmethod box :instance-field [{:keys [class] :as ast}] (if-let-box class (assoc (update-in ast [:instance :tag] u/box) :class class) ast)) (defmethod box :def [{:keys [init] :as ast}] (if (and init (u/primitive? (:tag init))) (update-in ast [:init] -box) ast)) (defmethod box :vector [ast] (assoc ast :items (mapv -box (:items ast)))) (defmethod box :set [ast] (assoc ast :items (mapv -box (:items ast)))) (defmethod box :map [ast] (let [keys (mapv -box (:keys ast)) vals (mapv -box (:vals ast))] (assoc ast :keys keys :vals vals))) (defmethod box :do [ast] (if (boxed? (:tag ast) (:ret ast)) (-> ast (update-in [:ret] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :quote [ast] (if (boxed? (:tag ast) (:ret ast)) (-> ast (update-in [:expr] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :protocol-invoke [ast] (assoc ast :args (mapv -box (:args ast)))) (defmethod box :let [{:keys [tag body] :as ast}] (if (boxed? tag body) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :letfn [ast] (if (boxed? (:tag ast) (:body ast)) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :loop [ast] (if (boxed? (:tag ast) (:body ast)) (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)) ast)) (defmethod box :fn-method [{:keys [params tag] :as ast}] (let [ast (if (u/primitive? tag) ast (-> ast (update-in [:body] -box) (update-in [:o-tag] u/box)))] (assoc ast :params (mapv (fn [{:keys [o-tag] :as p}] (assoc p :o-tag (u/prim-or-obj o-tag))) params) :tag (u/prim-or-obj tag) :o-tag (u/prim-or-obj tag)))) (defmethod box :if [{:keys [test then else tag o-tag] :as ast}] (let [test-tag (:tag test) test (if (and (u/primitive? test-tag) (not= Boolean/TYPE test-tag)) (assoc test :tag (u/box test-tag)) test) [then else o-tag] (if (or (boxed? tag then) (boxed? tag else) (not o-tag)) (conj (mapv -box [then else]) (u/box o-tag)) [then else o-tag])] (merge ast {:test test :o-tag o-tag :then then :else else}))) (defmethod box :case [{:keys [tag default tests thens test-type] :as ast}] (let [ast (if (and tag (u/primitive? tag)) ast (-> ast (assoc-in [:thens] (mapv (fn [t] (update-in t [:then] -box)) thens)) (update-in [:default] -box) (update-in [:o-tag] u/box)))] (if (= :hash-equiv test-type) (-> ast (update-in [:test] -box) (assoc-in [:tests] (mapv (fn [t] (update-in t [:test] -box)) tests))) ast))) (defmethod box :try [{:keys [tag] :as ast}] (let [ast (if (and tag (u/primitive? tag)) ast (-> ast (update-in [:catches] #(mapv -box %)) (update-in [:body] -box) (update-in [:o-tag] u/box)))] (-> ast (update-in [:finally] -box)))) (defmethod box :invoke [ast] (assoc ast :args (mapv -box (:args ast)) :o-tag Object)) (defmethod box :default [ast] ast)
[ { "context": " usuario es requerido\"\n [:pass] \"Password de 8+ caracteres es requerido\"\n [:pass-confirm] \"Los Passwords no coin", "end": 1046, "score": 0.9865361452102661, "start": 1008, "tag": "PASSWORD", "value": "Password de 8+ caracteres es requerido" }, { "context": "racteres es requerido\"\n [:pass-confirm] \"Los Passwords no coinciden\"\n [:is-admin] \"Debe especificar si e", "end": 1101, "score": 0.8955775499343872, "start": 1075, "tag": "PASSWORD", "value": "Los Passwords no coinciden" }, { "context": "o es un administrador\"\n [:pass-confirm] \"Los Passwords no coinciden\"\n [:active] \"Debe especificar si e", "end": 1758, "score": 0.6420065760612488, "start": 1732, "tag": "PASSWORD", "value": "Los Passwords no coinciden" } ]
src/cljc/orbis_grcmanager/validation.cljc
Orbisnetworkadmin/orbis-grcmanager
0
(ns orbis-grcmanager.validation (:require [bouncer.core :as b] [bouncer.validators :as v])) (defn format-validation-errors [errors] (->> errors first (map (fn [[k [v]]] [k v])) (into {}) not-empty)) (defn validate-issue [issue] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:title] "El titulo del seguimiento es requerido" [:summary] "El resumen del seguimiento es requerido" [:detail] "El detalle del seguimiento es requerido" [:tags] "El seguimiento debe tener al menos un tag"} path)) issue :title v/required :summary v/required :detail v/required :tags [v/required [v/min-count 1]]))) (defn pass-matches? [pass-confirm pass] (= pass pass-confirm)) (defn validate-create-user [user] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:screenname] "El perfil de usuario es requerido" [:pass] "Password de 8+ caracteres es requerido" [:pass-confirm] "Los Passwords no coinciden" [:is-admin] "Debe especificar si el usuario es un administrador" [:active] "Debe especificar si el usuario esta activo"} path)) user :pass [v/required [v/min-count 8]] :pass-confirm [[pass-matches? (:pass user)]] :screenname v/required :admin v/required :is-active v/required))) (defn validate-update-user [user] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:screenname] "El perfil de usuario es requerido" [:is-admin] "Debe especificar si el usuario es un administrador" [:pass-confirm] "Los Passwords no coinciden" [:active] "Debe especificar si el usuario esta activo"} path)) user :screenname v/required :admin v/required :pass-confirm [[pass-matches? (:pass user)]] :is-active v/required))) (defn validate-create [rr] (format-validation-errors (b/validate (fn [{:keys [path]}] ({ [:current-risk-register] "El riesgo continuio esta vacio o no es un numero positivo" [:residual-risk-register] "El riesgo residual esta vacio o no es un numero positivo" [:inherent-risk-register] "El riesgo inherente esta vacio o no es un numero positivo" [:description-risk-register] "La descripcion esta vacia" [:likelihood-risk-register] "La probabilidad esta vacio o no es un numero positivo" [:impact-risk-register] "El impacto esta vacio o no es un numero positivo" [:id-risk] "El riesgo padre esta vacio " [:id-risk-subtype] "El tipo de riesgo esta vacio" [:id-campaign] "La campaña esta vacia" [:status-risk-register] "El estatus del riesgo esta vacio" [:owner-risk-register] "El campo dueño esta vacio" [:efect-risk-register] "El efecto esta vacio" [:id-treatment] "El campo tratamiento esta vacio" [:location-risk-register] "El campo ubicación esta vacio" } path)) rr :current-risk-register [v/number v/positive] ;[v/number v/positive] :residual-risk-register [v/number v/positive] ;[v/number v/positive] :inherent-risk-register [v/number v/positive] ;[v/number v/positive] :description-risk-register v/required :likelihood-risk-register [v/number v/positive] ;[v/number v/positive] :impact-risk-register [v/number v/positive] :id-risk v/required :id-risk-subtype v/required :id-campaign v/required :status-risk-register v/required :owner-risk-register v/required :efect-risk-register v/required :id-treatment v/required :location-risk-register v/required )))
123047
(ns orbis-grcmanager.validation (:require [bouncer.core :as b] [bouncer.validators :as v])) (defn format-validation-errors [errors] (->> errors first (map (fn [[k [v]]] [k v])) (into {}) not-empty)) (defn validate-issue [issue] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:title] "El titulo del seguimiento es requerido" [:summary] "El resumen del seguimiento es requerido" [:detail] "El detalle del seguimiento es requerido" [:tags] "El seguimiento debe tener al menos un tag"} path)) issue :title v/required :summary v/required :detail v/required :tags [v/required [v/min-count 1]]))) (defn pass-matches? [pass-confirm pass] (= pass pass-confirm)) (defn validate-create-user [user] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:screenname] "El perfil de usuario es requerido" [:pass] "<PASSWORD>" [:pass-confirm] "<PASSWORD>" [:is-admin] "Debe especificar si el usuario es un administrador" [:active] "Debe especificar si el usuario esta activo"} path)) user :pass [v/required [v/min-count 8]] :pass-confirm [[pass-matches? (:pass user)]] :screenname v/required :admin v/required :is-active v/required))) (defn validate-update-user [user] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:screenname] "El perfil de usuario es requerido" [:is-admin] "Debe especificar si el usuario es un administrador" [:pass-confirm] "<PASSWORD>" [:active] "Debe especificar si el usuario esta activo"} path)) user :screenname v/required :admin v/required :pass-confirm [[pass-matches? (:pass user)]] :is-active v/required))) (defn validate-create [rr] (format-validation-errors (b/validate (fn [{:keys [path]}] ({ [:current-risk-register] "El riesgo continuio esta vacio o no es un numero positivo" [:residual-risk-register] "El riesgo residual esta vacio o no es un numero positivo" [:inherent-risk-register] "El riesgo inherente esta vacio o no es un numero positivo" [:description-risk-register] "La descripcion esta vacia" [:likelihood-risk-register] "La probabilidad esta vacio o no es un numero positivo" [:impact-risk-register] "El impacto esta vacio o no es un numero positivo" [:id-risk] "El riesgo padre esta vacio " [:id-risk-subtype] "El tipo de riesgo esta vacio" [:id-campaign] "La campaña esta vacia" [:status-risk-register] "El estatus del riesgo esta vacio" [:owner-risk-register] "El campo dueño esta vacio" [:efect-risk-register] "El efecto esta vacio" [:id-treatment] "El campo tratamiento esta vacio" [:location-risk-register] "El campo ubicación esta vacio" } path)) rr :current-risk-register [v/number v/positive] ;[v/number v/positive] :residual-risk-register [v/number v/positive] ;[v/number v/positive] :inherent-risk-register [v/number v/positive] ;[v/number v/positive] :description-risk-register v/required :likelihood-risk-register [v/number v/positive] ;[v/number v/positive] :impact-risk-register [v/number v/positive] :id-risk v/required :id-risk-subtype v/required :id-campaign v/required :status-risk-register v/required :owner-risk-register v/required :efect-risk-register v/required :id-treatment v/required :location-risk-register v/required )))
true
(ns orbis-grcmanager.validation (:require [bouncer.core :as b] [bouncer.validators :as v])) (defn format-validation-errors [errors] (->> errors first (map (fn [[k [v]]] [k v])) (into {}) not-empty)) (defn validate-issue [issue] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:title] "El titulo del seguimiento es requerido" [:summary] "El resumen del seguimiento es requerido" [:detail] "El detalle del seguimiento es requerido" [:tags] "El seguimiento debe tener al menos un tag"} path)) issue :title v/required :summary v/required :detail v/required :tags [v/required [v/min-count 1]]))) (defn pass-matches? [pass-confirm pass] (= pass pass-confirm)) (defn validate-create-user [user] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:screenname] "El perfil de usuario es requerido" [:pass] "PI:PASSWORD:<PASSWORD>END_PI" [:pass-confirm] "PI:PASSWORD:<PASSWORD>END_PI" [:is-admin] "Debe especificar si el usuario es un administrador" [:active] "Debe especificar si el usuario esta activo"} path)) user :pass [v/required [v/min-count 8]] :pass-confirm [[pass-matches? (:pass user)]] :screenname v/required :admin v/required :is-active v/required))) (defn validate-update-user [user] (format-validation-errors (b/validate (fn [{:keys [path]}] ({[:screenname] "El perfil de usuario es requerido" [:is-admin] "Debe especificar si el usuario es un administrador" [:pass-confirm] "PI:PASSWORD:<PASSWORD>END_PI" [:active] "Debe especificar si el usuario esta activo"} path)) user :screenname v/required :admin v/required :pass-confirm [[pass-matches? (:pass user)]] :is-active v/required))) (defn validate-create [rr] (format-validation-errors (b/validate (fn [{:keys [path]}] ({ [:current-risk-register] "El riesgo continuio esta vacio o no es un numero positivo" [:residual-risk-register] "El riesgo residual esta vacio o no es un numero positivo" [:inherent-risk-register] "El riesgo inherente esta vacio o no es un numero positivo" [:description-risk-register] "La descripcion esta vacia" [:likelihood-risk-register] "La probabilidad esta vacio o no es un numero positivo" [:impact-risk-register] "El impacto esta vacio o no es un numero positivo" [:id-risk] "El riesgo padre esta vacio " [:id-risk-subtype] "El tipo de riesgo esta vacio" [:id-campaign] "La campaña esta vacia" [:status-risk-register] "El estatus del riesgo esta vacio" [:owner-risk-register] "El campo dueño esta vacio" [:efect-risk-register] "El efecto esta vacio" [:id-treatment] "El campo tratamiento esta vacio" [:location-risk-register] "El campo ubicación esta vacio" } path)) rr :current-risk-register [v/number v/positive] ;[v/number v/positive] :residual-risk-register [v/number v/positive] ;[v/number v/positive] :inherent-risk-register [v/number v/positive] ;[v/number v/positive] :description-risk-register v/required :likelihood-risk-register [v/number v/positive] ;[v/number v/positive] :impact-risk-register [v/number v/positive] :id-risk v/required :id-risk-subtype v/required :id-campaign v/required :status-risk-register v/required :owner-risk-register v/required :efect-risk-register v/required :id-treatment v/required :location-risk-register v/required )))
[ { "context": "(def suppliers [ (Suppinfo. \"32\" -3 0 -2 false) ;Susan Windler (Supplier ID 32)\n (Suppinfo. \"101", "end": 400, "score": 0.9998506903648376, "start": 387, "tag": "NAME", "value": "Susan Windler" }, { "context": " (Suppinfo. \"101\" -3 0 -2 false) ;Togetherness Tshabalala (Supplier ID 101)\n (Suppinfo. \"21", "end": 491, "score": 0.9990484714508057, "start": 468, "tag": "NAME", "value": "Togetherness Tshabalala" }, { "context": " (Suppinfo. \"219\" 0 0.1 0 true ) ;Promise Mashangu (Supplier ID 219)\n (Suppinfo. \"20", "end": 576, "score": 0.999638557434082, "start": 560, "tag": "NAME", "value": "Promise Mashangu" }, { "context": " (Suppinfo. \"204\" 0 0.1 0 true ) ;Karel Visser (Supplier ID 204)\n ])\n\n(defrecord ", "end": 657, "score": 0.9998428225517273, "start": 645, "tag": "NAME", "value": "Karel Visser" } ]
clojure/johanvanzijl/holling/src/holling/core.clj
tobykurien/HollingBerries
1
(ns holling.core (:use [clojure.java.io :only [reader]] [clojure.data.csv :only [read-csv]] [clj-time.core :only [plus days]] [clojure.math.numeric-tower :only [ceil]] [clj-time.format :only [formatter parse unparse]] )) (defrecord Suppinfo [ suppcode sellby markup-perc markup-curr roundup ]) (def suppliers [ (Suppinfo. "32" -3 0 -2 false) ;Susan Windler (Supplier ID 32) (Suppinfo. "101" -3 0 -2 false) ;Togetherness Tshabalala (Supplier ID 101) (Suppinfo. "219" 0 0.1 0 true ) ;Promise Mashangu (Supplier ID 219) (Suppinfo. "204" 0 0.1 0 true ) ;Karel Visser (Supplier ID 204) ]) (defrecord Prodtype [codefrom codeto sellby markup]) (def prodtypes [ (Prodtype. 1000 1099 7 0.5) ;Other Fruit 1 (Prodtype. 1100 1199 14 0.4) ;Apples (Prodtype. 1200 1299 5 0.35) ;Bananas (Prodtype. 1300 1399 7 0.55) ;Berries (Prodtype. 1400 1999 7 0.5) ;Other Fruit 2 ]) (defrecord ProductRec [suppcode prodcode desc deldate cost qty] ) ;;; Define file locations and parse the file (def out-file "pricefile.txt") (defn parse-product [item] "Parses each line of the input file to a ProductRec" (ProductRec. (get item 0) ;supplier code (Integer/parseInt (get item 1)) ;parse the prodcode to int (get item 2) ;description (parse (formatter "yyyy/MM/dd") (get item 3)) ;parse delivery date (/ (Integer/parseInt (get item 4)) 100) ;parse cost (Integer/parseInt (get item 5)))) ;parse qty (def products "List of ProductRec. Reads input file" (for [ item (drop 1 ;Leave headers out. (with-open [file (reader "produce.csv")] (doall (read-csv file)))) ] (parse-product item))) (defn between? [n min max] (and (>= n min) (<= n max))) (defn get-prodtype [prodcode prodtypes] (first (for [prodtype prodtypes :when (let [{codefrom :codefrom codeto :codeto} prodtype] (between? prodcode codefrom codeto))] prodtype))) (defn get-suppinfo [suppcode suppliers] (first (filter (comp(partial = suppcode) :suppcode) suppliers))) (defn calc-product [product] (let [suppinfo (get-suppinfo (:suppcode product) suppliers) prodtype (get-prodtype (:prodcode product) prodtypes) ] ( -> product (assoc :price (if (nil? suppinfo) (* (:cost product) (+ (:markup prodtype) 1)) (let [rawprice (+ (* (:cost product) (+ (:markup prodtype) (:markup-perc suppinfo) 1)) (:markup-curr suppinfo))] (if (> rawprice 0) (if (:roundup suppinfo) (ceil rawprice) rawprice) 0 )))) (assoc :expdate (plus (:deldate product) (days (:sellby prodtype)) (when suppinfo (days (:sellby suppinfo)))))))) ;(calc-product (nth products 2)) (defn label-product [product] "Generate the label for a single product" (apply str ( repeat (:qty product) (str "R" (format "%8.2f" (double (:price product))) (unparse (formatter "yyyy/MM/dd") (:expdate product)) (subs (:desc product) 0 31) "\n")))) (defn -main [] (spit "pricefile2.txt" (doall (reduce str (for [product products] (label-product (calc-product product)))))))
124115
(ns holling.core (:use [clojure.java.io :only [reader]] [clojure.data.csv :only [read-csv]] [clj-time.core :only [plus days]] [clojure.math.numeric-tower :only [ceil]] [clj-time.format :only [formatter parse unparse]] )) (defrecord Suppinfo [ suppcode sellby markup-perc markup-curr roundup ]) (def suppliers [ (Suppinfo. "32" -3 0 -2 false) ;<NAME> (Supplier ID 32) (Suppinfo. "101" -3 0 -2 false) ;<NAME> (Supplier ID 101) (Suppinfo. "219" 0 0.1 0 true ) ;<NAME> (Supplier ID 219) (Suppinfo. "204" 0 0.1 0 true ) ;<NAME> (Supplier ID 204) ]) (defrecord Prodtype [codefrom codeto sellby markup]) (def prodtypes [ (Prodtype. 1000 1099 7 0.5) ;Other Fruit 1 (Prodtype. 1100 1199 14 0.4) ;Apples (Prodtype. 1200 1299 5 0.35) ;Bananas (Prodtype. 1300 1399 7 0.55) ;Berries (Prodtype. 1400 1999 7 0.5) ;Other Fruit 2 ]) (defrecord ProductRec [suppcode prodcode desc deldate cost qty] ) ;;; Define file locations and parse the file (def out-file "pricefile.txt") (defn parse-product [item] "Parses each line of the input file to a ProductRec" (ProductRec. (get item 0) ;supplier code (Integer/parseInt (get item 1)) ;parse the prodcode to int (get item 2) ;description (parse (formatter "yyyy/MM/dd") (get item 3)) ;parse delivery date (/ (Integer/parseInt (get item 4)) 100) ;parse cost (Integer/parseInt (get item 5)))) ;parse qty (def products "List of ProductRec. Reads input file" (for [ item (drop 1 ;Leave headers out. (with-open [file (reader "produce.csv")] (doall (read-csv file)))) ] (parse-product item))) (defn between? [n min max] (and (>= n min) (<= n max))) (defn get-prodtype [prodcode prodtypes] (first (for [prodtype prodtypes :when (let [{codefrom :codefrom codeto :codeto} prodtype] (between? prodcode codefrom codeto))] prodtype))) (defn get-suppinfo [suppcode suppliers] (first (filter (comp(partial = suppcode) :suppcode) suppliers))) (defn calc-product [product] (let [suppinfo (get-suppinfo (:suppcode product) suppliers) prodtype (get-prodtype (:prodcode product) prodtypes) ] ( -> product (assoc :price (if (nil? suppinfo) (* (:cost product) (+ (:markup prodtype) 1)) (let [rawprice (+ (* (:cost product) (+ (:markup prodtype) (:markup-perc suppinfo) 1)) (:markup-curr suppinfo))] (if (> rawprice 0) (if (:roundup suppinfo) (ceil rawprice) rawprice) 0 )))) (assoc :expdate (plus (:deldate product) (days (:sellby prodtype)) (when suppinfo (days (:sellby suppinfo)))))))) ;(calc-product (nth products 2)) (defn label-product [product] "Generate the label for a single product" (apply str ( repeat (:qty product) (str "R" (format "%8.2f" (double (:price product))) (unparse (formatter "yyyy/MM/dd") (:expdate product)) (subs (:desc product) 0 31) "\n")))) (defn -main [] (spit "pricefile2.txt" (doall (reduce str (for [product products] (label-product (calc-product product)))))))
true
(ns holling.core (:use [clojure.java.io :only [reader]] [clojure.data.csv :only [read-csv]] [clj-time.core :only [plus days]] [clojure.math.numeric-tower :only [ceil]] [clj-time.format :only [formatter parse unparse]] )) (defrecord Suppinfo [ suppcode sellby markup-perc markup-curr roundup ]) (def suppliers [ (Suppinfo. "32" -3 0 -2 false) ;PI:NAME:<NAME>END_PI (Supplier ID 32) (Suppinfo. "101" -3 0 -2 false) ;PI:NAME:<NAME>END_PI (Supplier ID 101) (Suppinfo. "219" 0 0.1 0 true ) ;PI:NAME:<NAME>END_PI (Supplier ID 219) (Suppinfo. "204" 0 0.1 0 true ) ;PI:NAME:<NAME>END_PI (Supplier ID 204) ]) (defrecord Prodtype [codefrom codeto sellby markup]) (def prodtypes [ (Prodtype. 1000 1099 7 0.5) ;Other Fruit 1 (Prodtype. 1100 1199 14 0.4) ;Apples (Prodtype. 1200 1299 5 0.35) ;Bananas (Prodtype. 1300 1399 7 0.55) ;Berries (Prodtype. 1400 1999 7 0.5) ;Other Fruit 2 ]) (defrecord ProductRec [suppcode prodcode desc deldate cost qty] ) ;;; Define file locations and parse the file (def out-file "pricefile.txt") (defn parse-product [item] "Parses each line of the input file to a ProductRec" (ProductRec. (get item 0) ;supplier code (Integer/parseInt (get item 1)) ;parse the prodcode to int (get item 2) ;description (parse (formatter "yyyy/MM/dd") (get item 3)) ;parse delivery date (/ (Integer/parseInt (get item 4)) 100) ;parse cost (Integer/parseInt (get item 5)))) ;parse qty (def products "List of ProductRec. Reads input file" (for [ item (drop 1 ;Leave headers out. (with-open [file (reader "produce.csv")] (doall (read-csv file)))) ] (parse-product item))) (defn between? [n min max] (and (>= n min) (<= n max))) (defn get-prodtype [prodcode prodtypes] (first (for [prodtype prodtypes :when (let [{codefrom :codefrom codeto :codeto} prodtype] (between? prodcode codefrom codeto))] prodtype))) (defn get-suppinfo [suppcode suppliers] (first (filter (comp(partial = suppcode) :suppcode) suppliers))) (defn calc-product [product] (let [suppinfo (get-suppinfo (:suppcode product) suppliers) prodtype (get-prodtype (:prodcode product) prodtypes) ] ( -> product (assoc :price (if (nil? suppinfo) (* (:cost product) (+ (:markup prodtype) 1)) (let [rawprice (+ (* (:cost product) (+ (:markup prodtype) (:markup-perc suppinfo) 1)) (:markup-curr suppinfo))] (if (> rawprice 0) (if (:roundup suppinfo) (ceil rawprice) rawprice) 0 )))) (assoc :expdate (plus (:deldate product) (days (:sellby prodtype)) (when suppinfo (days (:sellby suppinfo)))))))) ;(calc-product (nth products 2)) (defn label-product [product] "Generate the label for a single product" (apply str ( repeat (:qty product) (str "R" (format "%8.2f" (double (:price product))) (unparse (formatter "yyyy/MM/dd") (:expdate product)) (subs (:desc product) 0 31) "\n")))) (defn -main [] (spit "pricefile2.txt" (doall (reduce str (for [product products] (label-product (calc-product product)))))))
[ { "context": ".\n(def checks? (h/checks? num-tests))\n\n(def jane \"Doe Jane Female Purple 1/1/2000\")\n(def june \"Darla June Fe", "end": 341, "score": 0.8956639170646667, "start": 333, "tag": "NAME", "value": "Doe Jane" }, { "context": "ane \"Doe Jane Female Purple 1/1/2000\")\n(def june \"Darla June Female Orange 1/1/2000\")\n(def john \"Dean John Mal", "end": 388, "score": 0.9261638522148132, "start": 378, "tag": "NAME", "value": "Darla June" }, { "context": "e \"Darla June Female Orange 1/1/2000\")\n(def john \"Dean John Male Blue 12/31/2001\")\n(def sam \"Francis Sam Male ", "end": 436, "score": 0.9739466905593872, "start": 425, "tag": "NAME", "value": "Dean John M" }, { "context": "john \"Dean John Male Blue 12/31/2001\")\n(def sam \"Francis Sam Male Green 2/11/1994\")\n(def malformed \"Some Invalid Re", "end": 485, "score": 0.9902439713478088, "start": 469, "tag": "NAME", "value": "Francis Sam Male" }, { "context": "\"Some Invalid Record\")\n(def test-file [jane june john sam malformed])\n\n(deftest load-from-files!-test\n ", "end": 572, "score": 0.6651024222373962, "start": 569, "tag": "NAME", "value": "ohn" }, { "context": " by date of birth (then last name)\"\n (is (= [sam june jane john] (ppl/people->strs (ppl/sorted-by ", "end": 1274, "score": 0.6197834610939026, "start": 1271, "tag": "NAME", "value": "sam" }, { "context": " date of birth (then last name)\"\n (is (= [sam june jane john] (ppl/people->strs (ppl/sorted-by ::p/d", "end": 1279, "score": 0.8009073734283447, "start": 1275, "tag": "NAME", "value": "june" }, { "context": " of birth (then last name)\"\n (is (= [sam june jane john] (ppl/people->strs (ppl/sorted-by ::p/dob)))", "end": 1284, "score": 0.8349180817604065, "start": 1280, "tag": "NAME", "value": "jane" }, { "context": "irth (then last name)\"\n (is (= [sam june jane john] (ppl/people->strs (ppl/sorted-by ::p/dob)))))\n ", "end": 1289, "score": 0.7864720225334167, "start": 1285, "tag": "NAME", "value": "john" }, { "context": "(testing \"Properly sorts by gender\"\n (is (= [jane june john sam] (ppl/people->strs (ppl/sorted-by :", "end": 1395, "score": 0.6932394504547119, "start": 1391, "tag": "NAME", "value": "jane" }, { "context": "ng \"Properly sorts by gender\"\n (is (= [jane june john sam] (ppl/people->strs (ppl/sorted-by ::p/ge", "end": 1400, "score": 0.9072956442832947, "start": 1397, "tag": "NAME", "value": "une" }, { "context": "\"Properly sorts by gender\"\n (is (= [jane june john sam] (ppl/people->strs (ppl/sorted-by ::p/gender)", "end": 1405, "score": 0.8120105862617493, "start": 1401, "tag": "NAME", "value": "john" }, { "context": "erly sorts by gender\"\n (is (= [jane june john sam] (ppl/people->strs (ppl/sorted-by ::p/gender)))))", "end": 1409, "score": 0.648375391960144, "start": 1406, "tag": "NAME", "value": "sam" }, { "context": "Properly sorts by last name (desc)\"\n (is (= [sam jane john june] (ppl/people->strs (ppl/sorted-by ::p/last-name))", "end": 1542, "score": 0.9914501905441284, "start": 1524, "tag": "NAME", "value": "sam jane john june" } ]
test/sorted/people_test.clj
gekkoe/sorted
0
(ns sorted.people-test (:require [clojure.test :refer :all] [sorted.helpers :as h] [sorted.people :as ppl] [sorted.person :as p] [sorted.fileio :as file])) (def num-tests 1000) ; Increase this to run slower but more exhaustive tests. (def checks? (h/checks? num-tests)) (def jane "Doe Jane Female Purple 1/1/2000") (def june "Darla June Female Orange 1/1/2000") (def john "Dean John Male Blue 12/31/2001") (def sam "Francis Sam Male Green 2/11/1994") (def malformed "Some Invalid Record") (def test-file [jane june john sam malformed]) (deftest load-from-files!-test (testing "Conforms to spec." (is (checks? 'sorted.people/load-from-files!))) (let [result (with-redefs [file/text-read (constantly test-file) ppl/people (atom [])] (ppl/load-from-files! ["someFileName"]))] (testing "Loads expected people, ignoring bad records." (is (= (butlast test-file) (ppl/people->strs result)))))) (deftest sorted-by-test (testing "Conforms to spec." (is (checks? 'sorted.people/sorted-by))) (with-redefs [ppl/people (atom (mapv p/str->person (butlast test-file)))] (testing "Properly sorts people by date of birth (then last name)" (is (= [sam june jane john] (ppl/people->strs (ppl/sorted-by ::p/dob))))) (testing "Properly sorts by gender" (is (= [jane june john sam] (ppl/people->strs (ppl/sorted-by ::p/gender))))) (testing "Properly sorts by last name (desc)" (is (= [sam jane john june] (ppl/people->strs (ppl/sorted-by ::p/last-name)))))))
85243
(ns sorted.people-test (:require [clojure.test :refer :all] [sorted.helpers :as h] [sorted.people :as ppl] [sorted.person :as p] [sorted.fileio :as file])) (def num-tests 1000) ; Increase this to run slower but more exhaustive tests. (def checks? (h/checks? num-tests)) (def jane "<NAME> Female Purple 1/1/2000") (def june "<NAME> Female Orange 1/1/2000") (def john "<NAME>ale Blue 12/31/2001") (def sam "<NAME> Green 2/11/1994") (def malformed "Some Invalid Record") (def test-file [jane june j<NAME> sam malformed]) (deftest load-from-files!-test (testing "Conforms to spec." (is (checks? 'sorted.people/load-from-files!))) (let [result (with-redefs [file/text-read (constantly test-file) ppl/people (atom [])] (ppl/load-from-files! ["someFileName"]))] (testing "Loads expected people, ignoring bad records." (is (= (butlast test-file) (ppl/people->strs result)))))) (deftest sorted-by-test (testing "Conforms to spec." (is (checks? 'sorted.people/sorted-by))) (with-redefs [ppl/people (atom (mapv p/str->person (butlast test-file)))] (testing "Properly sorts people by date of birth (then last name)" (is (= [<NAME> <NAME> <NAME> <NAME>] (ppl/people->strs (ppl/sorted-by ::p/dob))))) (testing "Properly sorts by gender" (is (= [<NAME> j<NAME> <NAME> <NAME>] (ppl/people->strs (ppl/sorted-by ::p/gender))))) (testing "Properly sorts by last name (desc)" (is (= [<NAME>] (ppl/people->strs (ppl/sorted-by ::p/last-name)))))))
true
(ns sorted.people-test (:require [clojure.test :refer :all] [sorted.helpers :as h] [sorted.people :as ppl] [sorted.person :as p] [sorted.fileio :as file])) (def num-tests 1000) ; Increase this to run slower but more exhaustive tests. (def checks? (h/checks? num-tests)) (def jane "PI:NAME:<NAME>END_PI Female Purple 1/1/2000") (def june "PI:NAME:<NAME>END_PI Female Orange 1/1/2000") (def john "PI:NAME:<NAME>END_PIale Blue 12/31/2001") (def sam "PI:NAME:<NAME>END_PI Green 2/11/1994") (def malformed "Some Invalid Record") (def test-file [jane june jPI:NAME:<NAME>END_PI sam malformed]) (deftest load-from-files!-test (testing "Conforms to spec." (is (checks? 'sorted.people/load-from-files!))) (let [result (with-redefs [file/text-read (constantly test-file) ppl/people (atom [])] (ppl/load-from-files! ["someFileName"]))] (testing "Loads expected people, ignoring bad records." (is (= (butlast test-file) (ppl/people->strs result)))))) (deftest sorted-by-test (testing "Conforms to spec." (is (checks? 'sorted.people/sorted-by))) (with-redefs [ppl/people (atom (mapv p/str->person (butlast test-file)))] (testing "Properly sorts people by date of birth (then last name)" (is (= [PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI] (ppl/people->strs (ppl/sorted-by ::p/dob))))) (testing "Properly sorts by gender" (is (= [PI:NAME:<NAME>END_PI jPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI] (ppl/people->strs (ppl/sorted-by ::p/gender))))) (testing "Properly sorts by last name (desc)" (is (= [PI:NAME:<NAME>END_PI] (ppl/people->strs (ppl/sorted-by ::p/last-name)))))))
[ { "context": "ile is part of tempest-cljs\n;; Copyright (c) 2012, Trevor Bentley\n;; All rights reserved.\n;; See LICENSE file for d", "end": 77, "score": 0.9998540282249451, "start": 63, "tag": "NAME", "value": "Trevor Bentley" } ]
tempest/tempest.cljs
mrmekon/tempest-cljs
5
;; ;; This file is part of tempest-cljs ;; Copyright (c) 2012, Trevor Bentley ;; All rights reserved. ;; See LICENSE file for details. ;; (ns ^{:doc " Publicly exported functions to embed Tempest game in HTML. "} tempest (:require [tempest.levels :as levels] [tempest.draw :as draw] [tempest.core :as c] [goog.dom :as dom] [goog.events :as events] [goog.events.KeyHandler :as key-handler])) ;; ## Design notes: ;; ;; * Nearly everything is defined with polar coordinates (length and angle) ;; * "Entities" are players, enemies, projectiles ;; * "Entities" are defined by a path, a series of polar coordinates, that ;; are in relation to the previous point in the path. ;; * Polar coordinates are converted to cartesian coordinates shortly before ;; drawing. ;; * Levels have a number of "steps" defined, which is how many occupiable ;; points the level has (instead of allowing continuous motion). ;; * An entity's location in the level is dictated by its current segment, ;; and which step of the level it's on. ;; * An entity has a "stride", which is how many steps it moves per update. ;; The sign of the stride is direction, with positive strides moving out ;; towards the player. ;; ;; ## Obscure design oddities: ;; ;; * draw-path can optionally follow, but not draw, the first line of an ;; entity's path. There is a crazy reason for this. The 'center' of ;; an entity when drawn ends up being the first point drawn. The first ;; vertex is the one that gets centered on its location on the board. If ;; the needs to be centered around a point that is not drawn (or just ;; not its first point), the first, undrawn line given to draw-path ;; can be a line from where the entity's center should be to its first ;; drawn vertex. An example is the player's ship, whose first vertex ;; is it's "rear thruster", but who's origin when drawing must be up ;; in the front center of the ship. ;; ;; ;; ## TODO: ;; ;; * MOAR ENEMIES ;; * Jump? Is that possible with this design? I think so, easily, by ;; scaling just the first, undrawn line of player. It ends up being ;; normal to the segment's top line. ;; * Power ups. Bonus points if they're crazy swirly particle things. ;; * Browser + keyboard input stuff ;; - Any way to change repeat rate? Probably not ;; - Any way to use the mouse? ;; - I'm not above making a custom rotary controller. ;; - Two keys at the same time? Gotta swirl-n-shoot. ;; * Rate-limit bullets ;; * Frame timing, and disassociate movement speed from framerate. ;; (defn enemy-on-each-segment "List of enemies, one per segment." [level] (map #(c/build-flipper level % :step 0) (range (count (:segments level))))) (defn ^:export canvasDraw "Begins a game of tempest. 'level' specified as a string representation of an integer." [level-str] (let [document (dom/getDocument) level-idx (- (js/parseInt level-str) 1) canvas (dom/getElement "canv-fg") context (.getContext canvas "2d") bgcanvas (dom/getElement "canv-bg") bgcontext (.getContext bgcanvas "2d") handler (goog.events.KeyHandler. document true) dims {:width (.-width canvas) :height (.-height canvas)}] (events/listen handler "key" (fn [e] (c/queue-keypress e))) (let [empty-game-state (c/build-game-state) game-state (c/change-level (assoc empty-game-state :context context :bgcontext bgcontext :dims dims :anim-fn (c/animationFrameMethod) :enemy-list ) level-idx)] (c/next-game-state game-state))))
74793
;; ;; This file is part of tempest-cljs ;; Copyright (c) 2012, <NAME> ;; All rights reserved. ;; See LICENSE file for details. ;; (ns ^{:doc " Publicly exported functions to embed Tempest game in HTML. "} tempest (:require [tempest.levels :as levels] [tempest.draw :as draw] [tempest.core :as c] [goog.dom :as dom] [goog.events :as events] [goog.events.KeyHandler :as key-handler])) ;; ## Design notes: ;; ;; * Nearly everything is defined with polar coordinates (length and angle) ;; * "Entities" are players, enemies, projectiles ;; * "Entities" are defined by a path, a series of polar coordinates, that ;; are in relation to the previous point in the path. ;; * Polar coordinates are converted to cartesian coordinates shortly before ;; drawing. ;; * Levels have a number of "steps" defined, which is how many occupiable ;; points the level has (instead of allowing continuous motion). ;; * An entity's location in the level is dictated by its current segment, ;; and which step of the level it's on. ;; * An entity has a "stride", which is how many steps it moves per update. ;; The sign of the stride is direction, with positive strides moving out ;; towards the player. ;; ;; ## Obscure design oddities: ;; ;; * draw-path can optionally follow, but not draw, the first line of an ;; entity's path. There is a crazy reason for this. The 'center' of ;; an entity when drawn ends up being the first point drawn. The first ;; vertex is the one that gets centered on its location on the board. If ;; the needs to be centered around a point that is not drawn (or just ;; not its first point), the first, undrawn line given to draw-path ;; can be a line from where the entity's center should be to its first ;; drawn vertex. An example is the player's ship, whose first vertex ;; is it's "rear thruster", but who's origin when drawing must be up ;; in the front center of the ship. ;; ;; ;; ## TODO: ;; ;; * MOAR ENEMIES ;; * Jump? Is that possible with this design? I think so, easily, by ;; scaling just the first, undrawn line of player. It ends up being ;; normal to the segment's top line. ;; * Power ups. Bonus points if they're crazy swirly particle things. ;; * Browser + keyboard input stuff ;; - Any way to change repeat rate? Probably not ;; - Any way to use the mouse? ;; - I'm not above making a custom rotary controller. ;; - Two keys at the same time? Gotta swirl-n-shoot. ;; * Rate-limit bullets ;; * Frame timing, and disassociate movement speed from framerate. ;; (defn enemy-on-each-segment "List of enemies, one per segment." [level] (map #(c/build-flipper level % :step 0) (range (count (:segments level))))) (defn ^:export canvasDraw "Begins a game of tempest. 'level' specified as a string representation of an integer." [level-str] (let [document (dom/getDocument) level-idx (- (js/parseInt level-str) 1) canvas (dom/getElement "canv-fg") context (.getContext canvas "2d") bgcanvas (dom/getElement "canv-bg") bgcontext (.getContext bgcanvas "2d") handler (goog.events.KeyHandler. document true) dims {:width (.-width canvas) :height (.-height canvas)}] (events/listen handler "key" (fn [e] (c/queue-keypress e))) (let [empty-game-state (c/build-game-state) game-state (c/change-level (assoc empty-game-state :context context :bgcontext bgcontext :dims dims :anim-fn (c/animationFrameMethod) :enemy-list ) level-idx)] (c/next-game-state game-state))))
true
;; ;; This file is part of tempest-cljs ;; Copyright (c) 2012, PI:NAME:<NAME>END_PI ;; All rights reserved. ;; See LICENSE file for details. ;; (ns ^{:doc " Publicly exported functions to embed Tempest game in HTML. "} tempest (:require [tempest.levels :as levels] [tempest.draw :as draw] [tempest.core :as c] [goog.dom :as dom] [goog.events :as events] [goog.events.KeyHandler :as key-handler])) ;; ## Design notes: ;; ;; * Nearly everything is defined with polar coordinates (length and angle) ;; * "Entities" are players, enemies, projectiles ;; * "Entities" are defined by a path, a series of polar coordinates, that ;; are in relation to the previous point in the path. ;; * Polar coordinates are converted to cartesian coordinates shortly before ;; drawing. ;; * Levels have a number of "steps" defined, which is how many occupiable ;; points the level has (instead of allowing continuous motion). ;; * An entity's location in the level is dictated by its current segment, ;; and which step of the level it's on. ;; * An entity has a "stride", which is how many steps it moves per update. ;; The sign of the stride is direction, with positive strides moving out ;; towards the player. ;; ;; ## Obscure design oddities: ;; ;; * draw-path can optionally follow, but not draw, the first line of an ;; entity's path. There is a crazy reason for this. The 'center' of ;; an entity when drawn ends up being the first point drawn. The first ;; vertex is the one that gets centered on its location on the board. If ;; the needs to be centered around a point that is not drawn (or just ;; not its first point), the first, undrawn line given to draw-path ;; can be a line from where the entity's center should be to its first ;; drawn vertex. An example is the player's ship, whose first vertex ;; is it's "rear thruster", but who's origin when drawing must be up ;; in the front center of the ship. ;; ;; ;; ## TODO: ;; ;; * MOAR ENEMIES ;; * Jump? Is that possible with this design? I think so, easily, by ;; scaling just the first, undrawn line of player. It ends up being ;; normal to the segment's top line. ;; * Power ups. Bonus points if they're crazy swirly particle things. ;; * Browser + keyboard input stuff ;; - Any way to change repeat rate? Probably not ;; - Any way to use the mouse? ;; - I'm not above making a custom rotary controller. ;; - Two keys at the same time? Gotta swirl-n-shoot. ;; * Rate-limit bullets ;; * Frame timing, and disassociate movement speed from framerate. ;; (defn enemy-on-each-segment "List of enemies, one per segment." [level] (map #(c/build-flipper level % :step 0) (range (count (:segments level))))) (defn ^:export canvasDraw "Begins a game of tempest. 'level' specified as a string representation of an integer." [level-str] (let [document (dom/getDocument) level-idx (- (js/parseInt level-str) 1) canvas (dom/getElement "canv-fg") context (.getContext canvas "2d") bgcanvas (dom/getElement "canv-bg") bgcontext (.getContext bgcanvas "2d") handler (goog.events.KeyHandler. document true) dims {:width (.-width canvas) :height (.-height canvas)}] (events/listen handler "key" (fn [e] (c/queue-keypress e))) (let [empty-game-state (c/build-game-state) game-state (c/change-level (assoc empty-game-state :context context :bgcontext bgcontext :dims dims :anim-fn (c/animationFrameMethod) :enemy-list ) level-idx)] (c/next-game-state game-state))))
[ { "context": "ound the core Processing.org API.\"\n :author \"Roland Sadowski, Sam Aaron\"}\n quil.core\n (:import [processi", "end": 107, "score": 0.9997249841690063, "start": 92, "tag": "NAME", "value": "Roland Sadowski" }, { "context": "ocessing.org API.\"\n :author \"Roland Sadowski, Sam Aaron\"}\n quil.core\n (:import [processing.core PAp", "end": 118, "score": 0.9998591542243958, "start": 109, "tag": "NAME", "value": "Sam Aaron" }, { "context": "the standard\n random function. It was invented by Ken Perlin in the 1980s and\n been used since in graphical a", "end": 87073, "score": 0.9992309212684631, "start": 87063, "tag": "NAME", "value": "Ken Perlin" } ]
data/clojure/1b237a271e113898c9780b3110d8861c_core.clj
maxim5/code-inspector
5
(ns ^{:doc "Wrappers and extensions around the core Processing.org API." :author "Roland Sadowski, Sam Aaron"} quil.core (:import [processing.core PApplet PImage PGraphics PFont PConstants PShape] [java.awt.event KeyEvent]) (:require [clojure.set]) (:use [quil.version :only [QUIL-VERSION-STR]] [quil.util :only [int-like? resolve-constant-key length-of-longest-key gen-padding print-definition-list]] [quil.applet :only [current-applet applet-stop applet-state applet-start applet-close applet defapplet applet-safe-exit current-graphics *graphics*]])) (defn- current-surface "Retrieves current drawing surface. It's either current graphics or current applet if graphics is nil" [] (or (current-graphics) (current-applet))) (defn ^{:requires-bindings true :category "State" :subcategory nil :added "1.0"} state "Retrieve sketch-specific state by key. Must initially call set-state! to store state. (set-state! :foo 1) (state :foo) ;=> 1 " [key] (let [state* (:state (meta (current-applet)))] (when-not @state* (throw (Exception. "State not set - use set-state! before fetching state"))) (let [state @state*] (when-not (contains? state key) (throw (Exception. (str "Unable to find state with key: " key)))) (get state key)))) (defn ^{:requires-bindings true :category "State" :subcategory nil :added "1.0"} set-state! "Set sketch-specific state. May only be called once (ideally in the setup fn). Subsequent calls have no effect. Example: (set-state! :foo 1 :bar (atom true) :baz (/ (width) 2))" [& state-vals] (let [state* (:state (meta (current-applet)))] (when-not @state* (let [state-map (apply hash-map state-vals)] (reset! state* state-map))))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs-int "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Takes and returns an int." [n] (PApplet/abs (int n))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs-float "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Takes and returns a float." [n] (PApplet/abs (float n))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Dynamically casts to an int or float appropriately" [n] (if (int-like? n) (abs-int n) (abs-float n))) (defn ^{:requires-bindings false :processing-name "acos()" :category "Math" :subcategory "Trigonometry" :added "1.0"} acos "The inverse of cos, returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to Math/PI (3.1415927)." [n] (PApplet/acos (float n))) (defn ^{:requires-bindings true :processing-name "alpha()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} alpha "Extracts the alpha value from a color." [color] (.alpha (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient-float "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The color components set through the parameters define the reflectance. For example in the default color mode, setting x=255, y=126, z=0, would cause all the red light to reflect and half of the green light to reflect. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." ([gray] (.ambient (current-surface) (float gray))) ([x y z] (.ambient (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient-int "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The rgb color components set define the reflectance. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." [rgb] (.ambient (current-surface) (int rgb))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The color components set through the parameters define the reflectance. For example in the default color mode, setting x=255, y=126, z=0, would cause all the red light to reflect and half of the green light to reflect. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." ([rgb] (if (int-like? rgb) (ambient-int rgb) (ambient-float rgb))) ([x y z] (ambient-float x y z))) (defn ^{:requires-bindings true :processing-name "ambientLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} ambient-light "Adds an ambient light. Ambient light doesn't come from a specific direction, the rays have light have bounced around so much that objects are evenly lit from all sides. Ambient lights are almost always used in combination with other types of lights. Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop. The effect of the parameters is determined by the current color mode." ([red green blue] (.ambientLight (current-surface) (float red) (float green) (float blue))) ([red green blue x y z] (.ambientLight (current-surface) (float red) (float green) (float blue) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "applyMatrix()" :category "Transform" :subcategory nil :added "1.0"} apply-matrix "Multiplies the current matrix by the one specified through the parameters. This is very slow because it will try to calculate the inverse of the transform, so avoid it whenever possible. The equivalent function in OpenGL is glMultMatrix()." ([n00 n01 n02 n10 n11 n12] (.applyMatrix (current-surface) (float n00) (float n01) (float n02) (float n10) (float n11) (float n12))) ([n00 n01 n02 n03 n10 n11 n12 n13 n20 n21 n22 n23 n30 n31 n32 n33] (.applyMatrix (current-surface) (float n00) (float n01) (float n02) (float 03) (float n10) (float n11) (float n12) (float 13) (float n20) (float n21) (float n22) (float 23) (float n30) (float n31) (float n32) (float 33)))) (defn ^{:requires-bindings true :processing-name "arc()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} arc "Draws an arc in the display window. Arcs are drawn along the outer edge of an ellipse defined by the x, y, width and height parameters. The origin or the arc's ellipse may be changed with the ellipseMode() function. The start and stop parameters specify the angles at which to draw the arc." [x y width height start stop] (.arc (current-surface) (float x)(float y) (float width) (float height) (float start) (float stop))) (defn ^{:requires-bindings false :processing-name "asin()" :category "Math" :subcategory "Trigonometry" :added "1.0"} asin "The inverse of sin, returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2." [n] (PApplet/asin (float n))) (defn ^{:requires-bindings false :processing-name "atan()" :category "Math" :subcategory "Trigonometry" :added "1.0"} atan "The inverse of tan, returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 ." [n] (PApplet/atan (float n))) (defn ^{:requires-bindings false :processing-name "atan2()" :category "Math" :subcategory "Trigonometry" :added "1.0"} atan2 "Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2 function is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent." [y x] (PApplet/atan2 (float y) (float x))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-float "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts args to floats." ([gray] (.background (current-surface) (float gray))) ([gray alpha] (.background (current-surface) (float gray) (float alpha))) ([r g b] (.background (current-surface) (float r) (float g) (float b))) ([r g b a] (.background (current-surface) (float r) (float g) (float b) (float a)))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-int "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts rgb to an int and alpha to a float." ([rgb] (.background (current-surface) (int rgb))) ([rgb alpha] (.background (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts args to floats." ([rgb] (if (int-like? rgb) (background-int rgb) (background-float rgb))) ([rgb alpha] (if (int-like? rgb) (background-int rgb alpha) (background-float rgb alpha))) ([r g b] (background-float r g b)) ([r g b a] (background-float r g b a))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-image "Specify an image to be used as the background for a sketch. Its width and height must be the same size as the sketch window. Images used as background will ignore the current tint setting." [^PImage img] (.background (current-surface) img)) (defn ^{:requires-bindings true :processing-name "beginCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} begin-camera "Sets the matrix mode to the camera matrix so calls such as translate, rotate, apply-matrix and reset-matrix affect the camera. begin-camera should always be used with a following end-camera and pairs of begin-camera and end-camera cannot be nested. For most situations the camera function will be sufficient." [] (.beginCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "endCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} end-camera "Unsets the matrix mode from the camera matrix. See begin-camera." [] (.endCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "beginRaw()" :category "Output" :subcategory "Files" :added "1.0"} begin-raw "Enables the creation of vectors from 3D data. Requires corresponding end-raw command. These commands will grab the shape data just before it is rendered to the screen. At this stage, your entire scene is nothing but a long list of individual lines and triangles. This means that a shape created with sphere method will be made up of hundreds of triangles, rather than a single object. Or that a multi-segment line shape (such as a curve) will be rendered as individual segments." ([^PGraphics raw-gfx] (.beginRaw (current-surface) raw-gfx)) ([^String renderer ^String filename] (.beginRaw (current-applet) renderer filename))) (def ^{:private true} render-modes {:p2d PApplet/P2D :p3d PApplet/P3D :java2d PApplet/JAVA2D :opengl PApplet/OPENGL :pdf PApplet/PDF :dxf PApplet/DXF}) (defn ^{:requires-bindings true :processing-name "beginRecord()" :category "Output" :subcategory "Files" :added "1.0"} begin-record "Opens a new file and all subsequent drawing functions are echoed to this file as well as the display window. The begin-record fn requires two parameters, the first is the renderer and the second is the file name. This function is always used with end-record to stop the recording process and close the file. Note that begin-record will only pick up any settings that happen after it has been called. For instance, if you call text-font before begin-record, then that font will not be set for the file that you're recording to." [renderer filename] (let [renderer (resolve-constant-key renderer render-modes)] (println "renderer: " renderer) (.beginRecord (current-applet) (str renderer) (str filename)))) (defn ^{:requires-bindings true :processing-name "endRecord()" :category "Output" :subcategory "Files" :added "1.0"} end-record "Stops the recording process started by begin-record and closes the file." [] (.endRecord (current-applet))) (def ^{:private true} shape-modes {:points PApplet/POINTS :lines PApplet/LINES :triangles PApplet/TRIANGLES :triangle-strip PApplet/TRIANGLE_STRIP :triangle-fan PApplet/TRIANGLE_FAN :quads PApplet/QUADS :quad-strip PApplet/QUAD_STRIP}) (defn ^{:requires-bindings true :processing-name "beginShape()" :category "Shape" :subcategory "Vertex" :added "1.0"} begin-shape "Enables the creation of complex forms. begin-shape begins recording vertices for a shape and end-shape stops recording. Use the mode keyword to specify which shape create from the provided vertices. With no mode specified, the shape can be any irregular polygon. The available mode keywords are :points, :lines, :triangles, :triangle-fan, :triangle-strip, :quads, :quad-strip. After calling the begin-shape function, a series of vertex commands must follow. To stop drawing the shape, call end-shape. The vertex function with two parameters specifies a position in 2D and the vertex function with three parameters specifies a position in 3D. Each shape will be outlined with the current stroke color and filled with the fill color. Transformations such as translate, rotate, and scale do not work within begin-shape. It is also not possible to use other shapes, such as ellipse or rect within begin-shape." ([] (.beginShape (current-surface))) ([mode] (let [mode (resolve-constant-key mode shape-modes)] (.beginShape (current-surface) (int mode))))) (defn ^{:requires-bindings true :processing-name "bezier()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier "Draws a Bezier curve on the screen. These curves are defined by a series of anchor and control points. The first two parameters specify the first anchor point and the last two parameters specify the other anchor point. The middle parameters specify the control points which define the shape of the curve." ([x1 y1 cx1 cy1 cx2 cy2 x2 y2] (.bezier (current-surface) (float x1) (float y1) (float cx1) (float cy1) (float cx2) (float cy2) (float x2) (float y2))) ([x1 y1 z1 cx1 cy1 cz1 cx2 cy2 cz2 x2 y2 z2] (.bezier (current-surface) (float x1) (float y1) (float z1) (float cx1) (float cy1) (float cz1) (float cx2) (float cy2) (float cz2) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "bezierDetail()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-detail "Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the :p3d or :opengl renderer as the default (:java2d) renderer does not use this information." [detail] (.bezierDetail (current-surface) (int detail))) (defn ^{:requires-bindings true :processing-name "bezierPoint()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-point "Evaluates the Bezier at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b and c are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a bezier curve at t." [a b c d t] (.bezierPoint (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "bezierTangent()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-tangent "Calculates the tangent of a point on a Bezier curve. (See http://en.wikipedia.org/wiki/Tangent)" [a b c d t] (.bezierTangent (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "bezierVertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} bezier-vertex "Specifies vertex coordinates for Bezier curves. Each call to bezier-vertex defines the position of two control points and one anchor point of a Bezier curve, adding a new segment to a line or shape. The first time bezier-vertex is used within a begin-shape call, it must be prefaced with a call to vertex to set the first anchor point. This function must be used between begin-shape and end-shape and only when there is no parameter specified to begin-shape." ([cx1 cy1 cx2 cy2 x y] (.bezierVertex (current-surface) (float cx1) (float cy1) (float cx2) (float cy2) (float x) (float y))) ([cx1 cy1 cz1 cx2 cy2 cz2 x y z] (.bezierVertex (current-surface) (float cx1) (float cy1) (float cz1) (float cx2) (float cy2) (float cz2) (float x) (float y) (float z)))) (defn ^{:require-binding false :processing-name "binary()" :category "Data" :subcategory "Conversion" :added "1.0"} binary "Returns a string representing the binary value of an int, char or byte. When converting an int to a string, it is possible to specify the number of digits used." ([val] (PApplet/binary (if (number? val) (int val) val))) ([val num-digits] (PApplet/binary (int val) (int num-digits)))) (defn ^{:require-binding false :processing-name "unbinary()" :category "Data" :subcategory "Conversion" :added "1.0"} unbinary "Unpack a binary string to an integer. See binary for converting integers to strings." [str-val] (PApplet/unbinary (str str-val))) (def ^{:private true} blend-modes {:blend PApplet/BLEND :add PApplet/ADD :subtract PApplet/SUBTRACT :darkest PApplet/DARKEST :lightest PApplet/LIGHTEST :difference PApplet/DIFFERENCE :exclusion PApplet/EXCLUSION :multiply PApplet/MULTIPLY :screen PApplet/SCREEN :overlay PApplet/OVERLAY :hard-light PApplet/HARD_LIGHT :soft-light PApplet/SOFT_LIGHT :dodge PApplet/DODGE :burn PApplet/BURN}) (defn ^{:requires-bindings true :processing-name "blend()" :category "Color" :subcategory "Pixels" :added "1.0"} blend "Blends a region of pixels from one image into another (or in itself again) with full alpha channel support. Available blend modes are: :blend - linear interpolation of colours: C = A*factor + B :add - additive blending with white clip: C = min(A*factor + B, 255) :subtract - subtractive blending with black clip: C = max(B - A*factor, 0) :darkest - only the darkest colour succeeds: C = min(A*factor, B) :lightest - only the lightest colour succeeds: C = max(A*factor, B) :difference - subtract colors from underlying image. :exclusion - similar to :difference, but less extreme. :multiply - Multiply the colors, result will always be darker. :screen - Opposite multiply, uses inverse values of the colors. :overlay - A mix of :multiply and :screen. Multiplies dark values and screens light values. :hard-light - :screen when greater than 50% gray, :multiply when lower. :soft-light - Mix of :darkest and :lightest. Works like :overlay, but not as harsh. :dodge - Lightens light tones and increases contrast, ignores darks. Called \"Color Dodge\" in Illustrator and Photoshop. :burn - Darker areas are applied, increasing contrast, ignores lights. Called \"Color Burn\" in Illustrator and Photoshop." ([x y width height dx dy dwidth dheight mode] (let [mode (resolve-constant-key mode blend-modes)] (.blend (current-surface) (int x) (int y) (int width) (int height) (int dx) (int dy) (int dwidth) (int dheight) (int mode)))) ([^PImage src x y width height dx dy dwidth dheight mode] (let [mode (resolve-constant-key mode blend-modes)] (.blend (current-surface) src (int x) (int y) (int width) (int height) (int dx) (int dy) (int dwidth) (int dheight) (int mode))))) (defn ^{:requires-bindings false :processing-name "blendColor()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} blend-color "Blends two color values together based on the blending mode given specified with the mode keyword. Available blend modes are: :blend - linear interpolation of colours: C = A*factor + B :add - additive blending with white clip: C = min(A*factor + B, 255) :subtract - subtractive blending with black clip: C = max(B - A*factor, 0) :darkest - only the darkest colour succeeds: C = min(A*factor, B) :lightest - only the lightest colour succeeds: C = max(A*factor, B) :difference - subtract colors from underlying image. :exclusion - similar to :difference, but less extreme. :multiply - Multiply the colors, result will always be darker. :screen - Opposite multiply, uses inverse values of the colors. :overlay - A mix of :multiply and :screen. Multiplies dark values and screens light values. :hard-light - :screen when greater than 50% gray, :multiply when lower. :soft-light - Mix of :darkest and :lightest. Works like :overlay, but not as harsh. :dodge - Lightens light tones and increases contrast, ignores darks. Called \"Color Dodge\" in Illustrator and Photoshop. :burn - Darker areas are applied, increasing contrast, ignores lights. Called \"Color Burn\" in Illustrator and Photoshop." [c1 c2 mode] (let [mode (resolve-constant-key mode blend-modes)] (PApplet/blendColor (int c1) (int c2) (int mode)))) (defn ^{:requires-bindings true :processing-name "blue()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} blue "Extracts the blue value from a color, scaled to match current color-mode. Returns a float." [color] (.blue (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "box()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} box "Creates an extruded rectangle." ([size] (.box (current-surface) (float size))) ([width height depth] (.box (current-surface) (float width) (float height) (float depth)))) (defn ^{:requires-bindings true :processing-name "brightness()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} brightness "Extracts the brightness value from a color. Returns a float." [color] (.brightness (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "camera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} camera "Sets the position of the camera through setting the eye position, the center of the scene, and which axis is facing upward. Moving the eye position and the direction it is pointing (the center of the scene) allows the images to be seen from different angles. The version without any parameters sets the camera to the default position, pointing to the center of the display window with the Y axis as up. The default values are: eyeX: (/ (width) 2.0) eyeY: (/ (height) 2.0) eyeZ: (/ (/ (height) 2.0) (tan (/ (* Math/PI 60.0) 360.0))) centerX: (/ (width) 2.0) centerY: (/ (height) 2.0) centerZ: 0 upX: 0 upY: 1 upZ: 0 Similar imilar to gluLookAt() in OpenGL, but it first clears the current camera settings." ([] (.camera (current-surface))) ([eyeX eyeY eyeZ centerX centerY centerZ upX upY upZ] (.camera (current-surface) (float eyeX) (float eyeY) (float eyeZ) (float centerX) (float centerY) (float centerZ) (float upX) (float upY) (float upZ)))) (defn ^{:requires-bindings false :processing-name "ceil()" :category "Math" :subcategory "Calculation" :added "1.0"} ceil "Calculates the closest int value that is greater than or equal to the value of the parameter. For example, (ceil 9.03) returns the value 10." [n] (PApplet/ceil (float n))) (defn ^{:requires-bindings true :processing-name "color()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} color "Creates an integer representation of a color The parameters are interpreted as RGB or HSB values depending on the current color-mode. The default mode is RGB values from 0 to 255 and therefore, the function call (color 255 204 0) will return a bright yellow. Args are cast to floats. r - red or hue value g - green or saturation value b - blue or brightness value a - alpha value" ([gray] (.color (current-surface) (float gray))) ([gray alpha] (.color (current-surface) (float gray) (float alpha))) ([r g b] (.color (current-surface) (float r) (float g) (float b))) ([r g b a] (.color (current-surface) (float r) (float g) (float b) (float a)))) (def ^{:private true} color-modes {:rgb (int 1) :hsb (int 3)}) (defn ^{:requires-bindings true :processing-name "colorMode()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} color-mode "Changes the way Processing interprets color data. Available modes are :rgb and :hsb.By default, the parameters for fill, stroke, background, and color are defined by values between 0 and 255 using the :rgb color model. The color-mode fn is used to change the numerical range used for specifying colors and to switch color systems. For example, calling (color-mode :rgb 1.0) will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the parameters range1, range2, range3, and range 4." ([mode] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode)))) ([mode max] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max)))) ([mode max-x max-y max-z] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max-x) (float max-y) (float max-z)))) ([mode max-x max-y max-z max-a] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max-x) (float max-y) (float max-z) (float max-a))))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain-float "Constrains a value to not exceed a maximum and minimum value. All args are cast to floats." [amt low high] (PApplet/constrain (float amt) (float low) (float high))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain-int "Constrains a value to not exceed a maximum and minimum value. All args are cast to ints." [amt low high] (PApplet/constrain (int amt) (int low) (int high))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain "Constrains a value to not exceed a maximum and minimum value." [amt low high] (if (int-like? amt) (constrain-int amt low high) (constrain-float amt low high))) (defn ^{:requires-bindings true :processing-name "copy()" :category "Image" :subcategory "Pixels" :added "1.0"} copy "Copies a region of pixels from the display window to another area of the display window and copies a region of pixels from an image used as the src-img parameter into the display window. If the source and destination regions aren't the same size, it will automatically resize the source pixels to fit the specified target region. No alpha information is used in the process, however if the source image has an alpha channel set, it will be copied as well. " ([[sx1 sy1 sx2 sy2] [dx1 dy1 dx2 dy2]] (.copy (current-surface) (int sx1) (int sy1) (int sx2) (int sy2) (int dx1) (int dy1) (int dx2) (int dy2))) ([^PImage img [sx1 sy1 sx2 sy2] [dx1 dy1 dx2 dy2]] (.copy (current-surface) img (int sx1) (int sy1) (int sx2) (int sy2) (int dx1) (int dy1) (int dx2) (int dy2)))) (defn ^{:requires-bindings false :processing-name "cos()" :category "Math" :subcategory "Trigonometry" :added "1.0"} cos "Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to Math/PI*2). Values are returned in the range -1 to 1." [angle] (PApplet/cos (float angle))) (defn ^{:requires-bindings false :processing-name "PFont.list()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} available-fonts "A sequence of strings representing the fonts on this system available for use. Because of limitations in Java, not all fonts can be used and some might work with one operating system and not others. When sharing a sketch with other people or posting it on the web, you may need to include a .ttf or .otf version of your font in the data directory of the sketch because other people might not have the font installed on their computer. Only fonts that can legally be distributed should be included with a sketch." [] (seq (PFont/list))) (defn ^{:requires-bindings false :processing-name nil :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} font-available? "Returns true if font (specified as a string) is available on this system, false otherwise" [font-str] (if (some #{font-str} (available-fonts)) true false)) (defn ^{:requires-bindings true :processing-name "createFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} create-font "Dynamically converts a font to the format used by Processing (a PFont) from either a font name that's installed on the computer, or from a .ttf or .otf file inside the sketches 'data' folder. This function is an advanced feature for precise control. Use available-fonts to obtain the names for the fonts recognized by the computer and are compatible with this function. The size parameter states the font size you want to generate. The smooth parameter specifies if the font should be antialiased or not, and the charset parameter is an array of chars that specifies the characters to generate. This function creates a bitmapped version of a font It loads a font by name, and converts it to a series of images based on the size of the font. When possible, the text function will use a native font rather than the bitmapped version created behind the scenes with create-font. For instance, when using the default renderer setting (JAVA2D), the actual native version of the font will be employed by the sketch, improving drawing quality and performance. With the :p2d, :p3d, and :opengl renderer settings, the bitmapped version will be used. While this can drastically improve speed and appearance, results are poor when exporting if the sketch does not include the .otf or .ttf file, and the requested font is not available on the machine running the sketch." ([name size] (.createFont (current-applet) (str name) (float size))) ([name size smooth] (.createFont (current-applet) (str name) (float size) smooth)) ([name size smooth ^chars charset] (.createFont (current-applet) (str name) (float size) smooth charset))) (def ^{:private true} graphic-render-modes (select-keys render-modes [:p2d :p3d :java2d :pdf])) (defn ^{:requires-bindings true :processing-name "createGraphics()" :category "Rendering" :subcategory nil :added "1.0"} create-graphics "Creates and returns a new PGraphics object of the types :p2d, :p3d, :java2d, :pdf. Use this class if you need to draw into an off-screen graphics buffer. It's not possible to use create-graphics with the :opengl renderer, because it doesn't allow offscreen use. The :pdf renderer requires the filename parameter. It's important to call any drawing commands between begin-draw and end-draw statements. This is also true for any commands that affect drawing, such as smooth or color-mode. Unlike the main drawing surface which is completely opaque, surfaces created with create-graphics can have transparency. This makes it possible to draw into a graphics and maintain the alpha channel. By using save to write a PNG or TGA file, the transparency of the graphics object will be honored. Note that transparency levels are binary: pixels are either complete opaque or transparent. This means that text characters will be opaque blocks." ([w h renderer] (.createGraphics (current-applet) (int w) (int h) (resolve-constant-key renderer graphic-render-modes))) ([w h renderer path] (.createGraphics (current-applet) (int w) (int h) (resolve-constant-key renderer graphic-render-modes) (str path)))) (defn ^{:requires-bindings true :processing-name "createImage()" :category "Image" :subcategory nil :added "1.0"} create-image "Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play with. Set the size of the buffer with the width and height parameters. The format parameter defines how the pixels are stored. See the PImage reference for more information. Be sure to include all three parameters, specifying only the width and height (but no format) will produce a strange error. Prefer using create-image over initialising new PImage instances directly." [w h format] (.createImage (current-applet) (int w) (int h) (int format))) (defn ^{:requires-bindings true :processing-name "createInput()" :category "Input" :subcategory "Files" :added "1.0"} create-input "This is a method for advanced programmers to open a Java InputStream. The method is useful if you want to use the facilities provided by PApplet to easily open files from the data folder or from a URL, but want an InputStream object so that you can use other Java methods to take more control of how the stream is read. If the requested item doesn't exist, null is returned. If not online, this will also check to see if the user is asking for a file whose name isn't properly capitalized. If capitalization is different an error will be printed to the console. This helps prevent issues that appear when a sketch is exported to the web, where case sensitivity matters, as opposed to running from inside the Processing Development Environment on Windows or Mac OS, where case sensitivity is preserved but ignored. The filename passed in can be: - A URL, for instance (open-stream \"http://processing.org/\"; - A file in the sketch's data folder - The full path to a file to be opened locally (when running as an application) If the file ends with .gz, the stream will automatically be gzip decompressed. If you don't want the automatic decompression, use the related function create-input-raw." [filename] (.createInput (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "createInputRaw()" :category "Input" :subcategory "Files" :added "1.0"} create-input-raw "Call create-input without automatic gzip decompression." [filename] (.createInputRaw (current-applet) filename)) (defn ^{:requires-bindings true :processing-name "createOutput()" :category "Output" :subcategory "Files" :added "1.0"} create-output "Similar to create-input, this creates a Java OutputStream for a given filename or path. The file will be created in the sketch folder, or in the same folder as an exported application. If the path does not exist, intermediate folders will be created. If an exception occurs, it will be printed to the console, and null will be returned. This method is a convenience over the Java approach that requires you to 1) create a FileOutputStream object, 2) determine the exact file location, and 3) handle exceptions. Exceptions are handled internally by the function, which is more appropriate for sketch projects. If the output filename ends with .gz, the output will be automatically GZIP compressed as it is written." [filename] (.createOutput (current-applet) (str filename))) (def ^{:private true} cursor-modes {:arrow PConstants/ARROW :cross PConstants/CROSS :hand PConstants/HAND :move PConstants/MOVE :text PConstants/TEXT :wait PConstants/WAIT}) (defn ^{:requires-bindings true :processing-name "cursor()" :category "Environment" :subcategory nil :added "1.0"} cursor "Sets the cursor to a predefined symbol, an image, or makes it visible if already hidden. If you are trying to set an image as the cursor, it is recommended to make the size 16x16 or 32x32 pixels. The values for parameters x and y must be less than the dimensions of the image. Available modes: :arrow, :cross, :hand, :move, :text, :wait Setting or hiding the cursor generally does not work with 'Present' mode (when running full-screen). See cursor-image for specifying a generic image as the cursor symbol." ([] (.cursor (current-applet))) ([cursor-mode] (.cursor (current-applet) (int (resolve-constant-key cursor-mode cursor-modes))))) (defn ^{:requires-bindings true :processing-name "cursor()" :category "Environment" :subcategory nil :added "1.0"} cursor-image "Set the cursor to a predefined image. The horizontal and vertical active spots of the cursor may be specified with hx and hy" ([^PImage img] (.cursor (current-applet) img)) ([^PImage img hx hy] (.cursor (current-applet) img (int hx) (int hy)))) (defn ^{:requires-bindings true :processing-name "curve()" :category "Shape" :subcategory "Curves" :added "1.0"} curve "Draws a curved line on the screen. The first and second parameters specify the beginning control point and the last two parameters specify the ending control point. The middle parameters specify the start and stop of the curve. Longer curves can be created by putting a series of curve fns together or using curve-vertex. An additional fn called curve-tightness provides control for the visual quality of the curve. The curve fn is an implementation of Catmull-Rom splines." ([x1 y1 x2 y2 x3 y3 x4 y4] (.curve (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3) (float x4) (float y4))) ([x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y4 z4] (.curve (current-surface) (float x1) (float y1) (float z1) (float x2) (float y2) (float z2) (float x3) (float y3) (float z3) (float x4) (float y4) (float z4)))) (defn ^{:requires-bindings true :processing-name "curveDetail()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-detail "Sets the resolution at which curves display. The default value is 20. This function is only useful when using the :p3d or :opengl renderer as the default (:java2d) renderer does not use this information." [detail] (.curveDetail (current-surface) (int detail))) (defn ^{:requires-bindings true :processing-name "curvePoint()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-point "Evalutes the curve at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b c and are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a curve at t." [a b c d t] (.bezierPoint (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "curveTangent()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-tangent "Calculates the tangent of a point on a curve. See: http://en.wikipedia.org/wiki/Tangent" [a b c d t] (.curveTangent (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "curveTightness()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-tightness "Modifies the quality of forms created with curve and curve-vertex. The parameter squishy determines how the curve fits to the vertex points. The value 0.0 is the default value for squishy (this value defines the curves to be Catmull-Rom splines) and the value 1.0 connects all the points with straight lines. Values within the range -5.0 and 5.0 will deform the curves but will leave them recognizable and as values increase in magnitude, they will continue to deform." [ti] (.curveTightness (current-surface) (float ti))) (defn ^{:requires-bindings true :processing-name "curveVertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} curve-vertex "Specifies vertex coordinates for curves. This function may only be used between begin-shape and end-shape and only when there is no mode keyword specified to begin-hape. The first and last points in a series of curve-vertex lines will be used to guide the beginning and end of a the curve. A minimum of four points is required to draw a tiny curve between the second and third points. Adding a fifth point with curveVertex will draw the curve between the second, third, and fourth points. The curveVertex function is an implementation of Catmull-Rom splines." ([x y] (.curveVertex (current-surface) (float x) (float y))) ([x y z] (.curveVertex (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings false :processing-name "day()" :category "Input" :subcategory "Time & Date" :added "1.0"} day "Get the current day of the month (1 through 31)." [] (PApplet/day)) (defn ^{:requires-bindings false :processing-name "degrees()" :category "Math" :subcategory "Trigonometry" :added "1.0"} degrees "Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and (* 2 Math/PI) radians in a circle. For example, (= 90째 (/ Math/PI 2) 1.5707964). All trigonometric methods in Processing require their parameters to be specified in radians." [radians] (PApplet/degrees (float radians))) (defn ^{:requires-bindings true :processing-name "delay()" :category "Structure" :subcategory nil :added "1.0"} delay-frame "Forces the program to stop running for a specified time. Delay times are specified in thousandths of a second, therefore the function call (delay 3000) will stop the program for three seconds. Because the screen is updated only at the end of draw, the program may appear to 'freeze', because the screen will not update when the delay fn is used. This function has no affect inside setup." [freeze-ms] (.delay (current-applet) (int freeze-ms))) (defn ^{:requires-bindings true :processing-name "directionalLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} directional-light "Adds a directional light. Directional light comes from one direction and is stronger when hitting a surface squarely and weaker if it hits at a a gentle angle. After hitting a surface, a directional lights scatters in all directions. Lights need to be included in the draw fn to remain persistent in a looping program. Placing them in the setup fn of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The nx, ny, and nz parameters specify the direction the light is facing. For example, setting ny to -1 will cause the geometry to be lit from below (the light is facing directly upward)" [r g b nx ny nz] (.directionalLight (current-surface) (float r) (float g) (float b) (float nx) (float ny) (float nz))) (defn ^{:requires-bindings false :processing-name "dist()" :category "Math" :subcategory "Calculation" :added "1.0"} dist "Calculates the distance between two points" ([x1 y1 x2 y2] (PApplet/dist (float x1) (float y1) (float x2) (float y2))) ([x1 y1 z1 x2 y2 z2] (PApplet/dist (float x1) (float y1) (float z1) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "ellipse()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} ellipse "Draws an ellipse (oval) in the display window. An ellipse with an equal width and height is a circle. The origin may be changed with the ellipse-mode function" [x y width height] (.ellipse (current-surface) (float x) (float y) (float width) (float height))) (def ^{:private true} ellipse-modes {:center PApplet/CENTER :radius PApplet/RADIUS :corner PApplet/CORNER :corners PApplet/CORNERS}) (defn ^{:requires-bindings true :processing-name "ellipseMode()" :category "Shape" :subcategory "Attributes" :added "1.0"} ellipse-mode "Modifies the origin of the ellispse according to the specified mode: :center - specifies the location of the ellipse as the center of the shape. (Default). :radius - similar to center, but the width and height parameters to ellipse specify the radius of the ellipse, rather than the diameter. :corner - draws the shape from the upper-left corner of its bounding box. :corners - uses the four parameters to ellipse to set two opposing corners of the ellipse's bounding box." [mode] (let [mode (resolve-constant-key mode ellipse-modes)] (.ellipseMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive-float "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. Converts all args to floats" ([float-val] (.emissive (current-surface) (float float-val))) ([r g b] (.emissive (current-surface) (float r) (float g) (float b)))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive-int "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. Converts all args to ints" [int-val] (.emissive (current-surface) (int int-val))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. If passed one arg - it is assumed to be an int (i.e. a color), multiple args are converted to floats." ([c] (if (int-like? c) (emissive-int c) (emissive-float c))) ([r g b] (emissive-float r g b))) (defn ^{:requires-bindings true :processing-name "endRaw()" :category "Output" :subcategory "Files" :added "1.0"} end-raw "Complement to begin-raw; they must always be used together. See the begin-raw docstring for details." [] (.endRaw (current-applet))) (defn ^{:requires-bindings true :processing-name "endShape()" :category "Shape" :subcategory "Vertex" :added "1.0"} end-shape "May only be called after begin-shape. When end-shape is called, all of image data defined since the previous call to begin-shape is written into the image buffer. The keyword :close may be passed to close the shape (to connect the beginning and the end)." ([] (.endShape (current-applet))) ([mode] (when-not (= :close mode) (throw (Exception. (str "Unknown mode value: " mode ". Expected :close")))) (.endShape (current-applet) PApplet/CLOSE))) (defn ^{:requires-bindings true :processing-name "exit()" :category "Structure" :subcategory nil :added "1.0"} exit "Quits/stops/exits the program. Rather than terminating immediately, exit will cause the sketch to exit after draw has completed (or after setup completes if called during the setup method). " [] (applet-safe-exit (current-applet))) (defn ^{:requires-bindings false :processing-name "exp()" :category "Math" :subcategory "Calculation" :added "1.0"} exp "Returns Euler's number e (2.71828...) raised to the power of the value parameter." [val] (PApplet/exp (float val))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill-float "Sets the color used to fill shapes. For example, (fill 204 102 0), will specify that all subsequent shapes will be filled with orange." ([gray] (.fill (current-surface) (float gray))) ([gray alpha] (.fill (current-surface) (float gray) (float alpha))) ([r g b] (.fill (current-surface) (float r) (float g) (float b))) ([r g b alpha] (.fill (current-surface) (float r) (float g) (float b) (float alpha)))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill-int "Sets the color used to fill shapes." ([rgb] (.fill (current-surface) (int rgb))) ([rgb alpha] (.fill (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill "Sets the color used to fill shapes." ([rgb] (if (int-like? rgb) (fill-int rgb) (fill-float rgb))) ([rgb alpha] (if (int-like? rgb) (fill-int rgb alpha) (fill-float rgb alpha))) ([r g b] (fill-float r g b)) ([r g b a] (fill-float r g b a))) (def ^{:private true} filter-modes {:threshold PConstants/THRESHOLD :gray PConstants/GRAY :invert PConstants/INVERT :posterize PConstants/POSTERIZE :blur PConstants/BLUR :opaque PConstants/OPAQUE :erode PConstants/ERODE :dilate PConstants/DILATE}) (defn ^{:requires-bindings true :processing-name "filter()" :category "Image" :subcategory "Pixels" :added "1.0"} display-filter "Originally named filter in Processing Language. Filters the display window with the specified mode and level. Level defines the quality of the filter and mode may be one of the following keywords: :threshold - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. :gray - converts any colors in the image to grayscale equivalents :invert - sets each pixel to its inverse value :posterize - limits each channel of the image to the number of colors specified as the level parameter. The level parameter :blur - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1. :opaque - sets the alpha channel to entirely opaque. :erode - reduces the light areas with the amount defined by the level parameter. :dilate - increases the light areas with the amount defined by the level parameter." ([mode] (let [mode (resolve-constant-key mode filter-modes)] (.filter (current-applet) (int mode)))) ([mode level] (let [mode (resolve-constant-key mode filter-modes)] (.filter (current-applet) (int mode) (float level))))) (defn ^{:requires-bindings true :processing-name "focused" :category "Environment" :subcategory nil :added "1.0"} focused "Returns a boolean value representing whether the applet has focus." [] (.-focussed (current-applet))) (defn ^{:requires-bindings true :processing-name "frameCount" :category "Environment" :subcategory nil :added "1.0"} frame-count "The system variable frameCount contains the number of frames displayed since the program started. Inside setup() the value is 0 and and after the first iteration of draw it is 1, etc." [] (.frameCount (current-applet))) (defn ^{:requires-bindings true :processing-name "frameRate" :category "Environment" :subcategory nil :added "1.0"} current-frame-rate "Returns the current framerate" [] (.frameRate (current-applet))) (defn ^{:requires-bindings true :category "Environment" :subcategory nil :added "1.5.0"} target-frame-rate "Returns the target framerate specified with the fn frame-rate" [] @(quil.applet/target-frame-rate)) (defn ^{:requires-bindings true :processing-name "frameRate()" :category "Environment" :subcategory nil :added "1.0"} frame-rate "Specifies a new target framerate (number of frames to be displayed every second). If the processor is not fast enough to maintain the specified rate, it will not be achieved. For example, the function call (frame-rate 30) will attempt to refresh 30 times a second. It is recommended to set the frame rate within setup. The default rate is 60 frames per second." [new-rate] (.frameRate (current-applet) (float new-rate))) (defn ^{:requires-bindings true :processing-name "frustum()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} frustum "Sets a perspective matrix defined through the parameters. Works like glFrustum, except it wipes out the current perspective matrix rather than muliplying itself with it." [left right bottom top near far] (.frustum (current-surface) (float left) (float right) (float bottom) (float top) (float near) (float far))) (defn ^{:requires-bindings true :processing-name "get()" :category "Image" :subcategory "Pixels" :added "1.0"} get-pixel "Reads the color of any pixel or grabs a section of an image. If no parameters are specified, the entire image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display window by specifying an additional width and height parameter. If the pixel requested is outside of the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. For example, even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB. Getting the color of a single pixel with (get x y) is easy, but not as fast as grabbing the data directly using the pixels fn." ([] (.get (current-surface))) ([x y] (.get (current-surface) (int x) (int y))) ([x y w h] (.get (current-surface) (int x) (int y) (int w) (int h)))) (declare load-pixels) (defn ^{:requires-bindings true :processing-name "pixels[]" :category "Image" :subcategory "Pixels" :added "1.0"} pixels "Array containing the values for all the pixels in the display window. This array is therefore the size of the display window. If this array is modified, the update-pixels fn must be called to update the changes. Calls load-pixels before obtaining the pixel array. Only works with P2D and P3D renderer." [] (load-pixels) (.-pixels (current-surface))) (defn ^{:requires-bindings true :processing-name "green()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} green "Extracts the green value from a color, scaled to match current color-mode. This value is always returned as a float so be careful not to assign it to an int value." [col] (.green (current-surface) (int col))) (defn ^{:require-binding false :processing-name "hex()" :category "Data" :subcategory "Conversion"} hex "Converts a byte, char, int, or color to a String containing the equivalent hexadecimal notation. For example color(0, 102, 153) will convert to the String \"FF006699\". This function can help make your geeky debugging sessions much happier. " ([val] (PApplet/hex val)) ([val num-digits] (PApplet/hex (int val) (int num-digits)))) (defn ^{:require-binding false :processing-name "hex()" :category "Data" :subcategory "Conversion"} unhex "Converts a String representation of a hexadecimal number to its equivalent integer value." [hex-str] (PApplet/unhex (str hex-str))) (defn ^{:requires-bindings true :processing-name "height" :category "Environment" :subcategory nil :added "1.0"} height "Height of the display window. The value of height is zero until size is called." [] (.getHeight (current-applet))) (def ^{:private true} hint-options {:enable-opengl-4x-smooth PConstants/ENABLE_OPENGL_4X_SMOOTH :enable-opengl-2x-smooth PConstants/ENABLE_OPENGL_2X_SMOOTH :enable-native-fonts PConstants/ENABLE_NATIVE_FONTS :disable-native-fonts PConstants/DISABLE_NATIVE_FONTS :enable-depth-test PConstants/ENABLE_DEPTH_TEST :disable-depth-test PConstants/DISABLE_DEPTH_TEST :enable-depth-sort PConstants/ENABLE_DEPTH_SORT :disable-depth-sort PConstants/DISABLE_DEPTH_SORT :disable-opengl-error-report PConstants/DISABLE_OPENGL_ERROR_REPORT :enable-opengl-error-report PConstants/ENABLE_OPENGL_ERROR_REPORT :enable-accurate-textures PConstants/ENABLE_ACCURATE_TEXTURES :disable-accurate-textures PConstants/DISABLE_ACCURATE_TEXTURES :disable-depth-mask PConstants/DISABLE_DEPTH_MASK :enable-depth-mask PConstants/ENABLE_DEPTH_MASK}) (defn ^{:requires-bindings true :processing-name "hint()" :category "Rendering" :subcategory nil :added "1.0"} hint "Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be implemented in a consistent manner across renderers. Many options will often graduate to standard features instead of hints over time. Options: :enable-opengl-4x-smooth - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's control panel, however not all cards make this available. This hint must be called immediately after the size command because it resets the renderer, obliterating any settings and anything drawn (and like size(), re-running the code that came before it again). :disable-opengl-2x-smooth - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in earlier releases, where smooth and no-smooth could be used to enable and disable smoothing, though the quality was inferior. :enable-opengl-2x-smooth - Enables default OpenGL smoothing. :enable-native-fonts - Use the native version fonts when they are installed, rather than the bitmapped version from a .vlw file. This is useful with the default (or JAVA2D) renderer setting, as it will improve font rendering speed. This is not enabled by default, because it can be misleading while testing because the type will look great on your machine (because you have the font installed) but lousy on others' machines if the identical font is unavailable. This option can only be set per-sketch, and must be called before any use of text-font. :disable-native-fonts - Disables native font support. :disable-depth-test - Disable the zbuffer, allowing you to draw on top of everything at will. When depth testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with :enable-depth-test but note that with the depth buffer cleared, any 3D drawing that happens later in draw will ignore existing shapes on the screen. :enable-depth-test - Enables the zbuffer. :enable-depth-sort - Enable primitive z-sorting of triangles and lines in :p3d and :opengl rendering modes. This can slow performance considerably, and the algorithm is not yet perfect. :disable-depth-sort - Disables hint :enable-depth-sort :disable-opengl-error-report - Speeds up the OPENGL renderer setting by not checking for errors while running. :enable-opengl-error-report - Turns on OpenGL error checking :enable-accurate-textures :disable-accurate-textures :enable-depth-mask :disable-depth-mask" [hint-type] (let [hint-type (if (keyword? hint-type) (get hint-options hint-type) hint-type)] (.hint (current-surface) (int hint-type)))) (defn ^{:requires-bindings false :processing-name "hour()" :category "Input" :subcategory "Time & Date" :added "1.0"} hour "Returns the current hour as a value from 0 - 23." [] (PApplet/hour)) (defn ^{:requires-bindings true :processing-name "hue()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} hue "Extracts the hue value from a color." [col] (.hue (current-surface) (int col))) (defn ^{:requires-bindings true :processing-name "image()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} image "Displays images to the screen. Processing currently works with GIF, JPEG, and Targa images. The color of an image may be modified with the tint function and if a GIF has transparency, it will maintain its transparency. The img parameter specifies the image to display and the x and y parameters define the location of the image from its upper-left corner. The image is displayed at its original size unless the width and height parameters specify a different size. The image-mode fn changes the way the parameters work. A call to (image-mode :corners) will change the width and height parameters to define the x and y values of the opposite corner of the image. Starting with release 0124, when using the default (JAVA2D) renderer, smooth will also improve image quality of resized images." ([^PImage img x y] (.image (current-surface) img (float x) (float y))) ([^PImage img x y c d] (.image (current-surface) img (float x) (float y) (float c) (float d))) ([^PImage img x y c d u1 v1 u2 v2] (.image (current-surface) img (float x) (float y) (float c) (float d) (float u1) (float v1) (float u2) (float v2)))) (def ^{:private true} image-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER}) (defn ^{:requires-bindings true :processing-name "imageMode()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} image-mode "Modifies the location from which images draw. The default mode is :corner. Available modes are: :corner - specifies the location to be the upper left corner and uses the fourth and fifth parameters of image to set the image's width and height. :corners - uses the second and third parameters of image to set the location of one corner of the image and uses the fourth and fifth parameters to set the opposite corner. :center - draw images centered at the given x and y position." [mode] (let [mode (resolve-constant-key mode image-modes)] (.imageMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "lightFalloff()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} light-falloff "Sets the falloff rates for point lights, spot lights, and ambient lights. The parameters are used to determine the falloff with the following equation: d = distance from light position to vertex position falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * QUADRATIC) Like fill, it affects only the elements which are created after it in the code. The default value is (light-falloff 1.0 0.0 0.0). Thinking about an ambient light with a falloff can be tricky. It is used, for example, if you wanted a region of your scene to be lit ambiently one color and another region to be lit ambiently by another color, you would use an ambient light with location and falloff. You can think of it as a point light that doesn't care which direction a surface is facing." [constant linear quadratic] (.lightFalloff (current-surface) (float constant) (float linear) (float quadratic))) (defn ^{:requires-bindings true :processing-name "lerpColor()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} lerp-color "Calculates a color or colors between two color at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc." [c1 c2 amt] (.lerpColor (current-surface) (int c1) (int c2) (float amt))) (defn ^{:requires-bindings false :processing-name "lerp()" :category "Math" :subcategory "Calculation" :added "1.0"} lerp "Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines." [start stop amt] (PApplet/lerp (float start) (float stop) (float amt))) (defn ^{:requires-bindings true :processing-name "key" :category "Input" :subcategory "Keyboard" :added "1.0"} raw-key "Contains the value of the most recent key on the keyboard that was used (either pressed or released). For non-ASCII keys, use the keyCode variable. The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. Check for both ENTER and RETURN to make sure your program will work for all platforms." [] (.-key (current-applet))) (defn ^{:requires-bindings true :processing-name "keyCode" :category "Input" :subcategory "Keyboard" :added "1.0"} key-code "The variable keyCode is used to detect special keys such as the UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking for these keys, it's first necessary to check and see if the key is coded. This is done with the conditional (= (key) CODED). The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of key-code If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. Check for both ENTER and RETURN to make sure your program will work for all platforms. For users familiar with Java, the values for UP and DOWN are simply shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other keyCode values can be found in the Java KeyEvent reference." [] (.-keyCode (current-applet))) (defn ^{:requires-bindings true :processing-name "keyPressed" :category "Input" :subcategory "Keyboard" :added "1.0"} key-pressed? "true if any key is currently pressed, false otherwise." [] (.-keyPressed (current-applet))) (defn ^{:requires-bindings true :processing-name "lights()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} lights "Sets the default ambient light, directional light, falloff, and specular values. The defaults are: (ambient-light 128 128 128) (directional-light 128 128 128 0 0 -1) (light-falloff 1 0 0) (light-specular 0 0 0). Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop." [] (.lights (current-surface))) (defn ^{:requires-bindings true :processing-name "lightSpecular()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} light-specular "Sets the specular color for lights. Like fill, it affects only the elements which are created after it in the code. Specular refers to light which bounces off a surface in a perferred direction (rather than bouncing in all directions like a diffuse light) and is used for creating highlights. The specular quality of a light interacts with the specular material qualities set through the specular and shininess functions." [r g b] (.lightSpecular (current-surface) (float r) (float g) (float b))) (defn ^{:requires-bindings true :processing-name "line()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} line "Draws a line (a direct path between two points) to the screen. The version of line with four parameters draws the line in 2D. To color a line, use the stroke function. A line cannot be filled, therefore the fill method will not affect the color of a line. 2D lines are drawn with a width of one pixel by default, but this can be changed with the stroke-weight function. The version with six parameters allows the line to be placed anywhere within XYZ space. " ([p1 p2] (apply line (concat p1 p2))) ([x1 y1 x2 y2] (.line (current-surface) (float x1) (float y1) (float x2) (float y2))) ([x1 y1 z1 x2 y2 z2] (.line (current-surface) (float x1) (float y1) (float z1) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "loadBytes()" :category "Input" :subcategory "Files" :added "1.0"} load-bytes "Reads the contents of a file or url and places it in a byte array. The filename parameter can also be a URL to a file found online." [filename] (.loadBytes (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} load-font "Loads a font into a variable of type PFont. To load correctly, fonts must be located in the data directory of the current sketch. To create a font to use with Processing use the create-font fn. Like load-image and other methods that load data, the load-font fn should not be used inside draw, because it will slow down the sketch considerably, as the font will be re-loaded from the disk (or network) on each frame. For most renderers, Processing displays fonts using the .vlw font format, which uses images for each letter, rather than defining them through vector data. When hint :enable-native-fonts is used with the JAVA2D renderer, the native version of a font will be used if it is installed on the user's machine. Using create-font (instead of load-font) enables vector data to be used with the JAVA2D (default) renderer setting. This can be helpful when many font sizes are needed, or when using any renderer based on JAVA2D, such as the PDF library." [filename] (.loadFont (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadImage()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} load-image "Loads an image into a variable of type PImage. Four types of images ( .gif, .jpg, .tga, .png) images may be loaded. To load correctly, images must be located in the data directory of the current sketch. In most cases, load all images in setup to preload them at the start of the program. Loading images inside draw will reduce the speed of a program. The filename parameter can also be a URL to a file found online. The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to load-image. If an image is not loaded successfully, the null value is returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from load-image is nil. Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because load-image will attempt to interpret the HTML as image data." [filename] (.loadImage (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadPixels()" :category "Image" :subcategory "Pixels" :added "1.0"} load-pixels "Loads the pixel data for the display window into the pixels[] array. This function must always be called before reading from or writing to pixels. Certain renderers may or may not seem to require load-pixels or update-pixels. However, the rule is that any time you want to manipulate the pixels array, you must first call load-pixels, and after changes have been made, call updatePixels. Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change." [] (.loadPixels (current-surface))) (defn ^{:requires-bindings true :processing-name "loadShape()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} load-shape "Load a geometry from a file as a PShape." [filename] (.loadShape (current-applet) filename)) (defn ^{:requires-bindings true :processing-name "loadStrings()" :category "Input" :subcategory "Files" :added "1.0"} load-strings "Load data from a file and shove it into a String array." [filename] (.loadStrings (current-applet) filename)) (defn ^{:requires-bindings false :processing-name "log()" :category "Math" :subcategory "Calculation" :added "1.0"} log "Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the values greater than 0.0." [val] (PApplet/log (float val))) (defn ^{:requires-bindings true :processing-name "loop()" :category "Structure" :subcategory nil :added "1.0"} start-loop "Causes Processing to continuously execute the code within draw. If no-loop is called, the code in draw stops executing." [] (.loop (current-applet))) (defn ^{:requires-bindings false :processing-name "mag()" :category "Math" :subcategory "Calculation" :added "1.0"} mag "Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no start position, the magnitude of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. Therefore, mag is a shortcut for writing (dist 0 0 x y)." ([a b] (PApplet/mag (float a) (float b))) ([a b c] (PApplet/mag (float a) (float b) (float c)))) (defn ^{:requires-bindings false :processing-name "map()" :category "Math" :subcategory "Calculation" :added "1.0"} map-range "Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful." [val low1 high1 low2 high2] (PApplet/map (float val) (float low1) (float high1) (float low2) (float high2))) (defn ^{:requires-bindings false :processing-name nil :category "Image" :subcategory "Loading & Displaying" :added "1.0"} mask-image "Masks part of an image from displaying by loading another image and using it as an alpha channel. This mask image should only contain grayscale data, but only the blue color channel is used. The mask image needs to be the same size as the image to which it is applied. This method is useful for creating dynamically generated alpha masks." [^PImage img] (.mask (current-surface) img)) (defn ^{:requires-bindings true :processing-name "millis()" :category "Input" :subcategory "Time & Date" :added "1.0"} millis "Returns the number of milliseconds (thousandths of a second) since starting the sketch. This information is often used for timing animation sequences." [] (.millis (current-applet))) (defn ^{:requires-bindings false :processing-name "minute()" :category "Input" :subcategory "Time & Date" :added "1.0"} minute "Returns the current minute as a value from 0 - 59" [] (PApplet/minute)) (defn ^{:requires-bindings true :processing-name "modelX()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-x "Returns the three-dimensional x, y, z position in model space. This returns the x value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The x value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "modelY()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-y "Returns the three-dimensional x, y, z position in model space. This returns the y value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The y value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelY (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "modelZ()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-z "Returns the three-dimensional x, y, z position in model space. This returns the z value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The z value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelZ (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings false :processing-name "month()" :category "Input" :subcategory "Time & Date" :added "1.0"} month "Returns the current month as a value from 1 - 12." [] (PApplet/month)) (defn ^{:requires-bindings true :processing-name "mouseButton" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-button "The value of the system variable mouseButton is either :left, :right, or :center depending on which button is pressed." [] (let [button-code (.-mouseButton (current-applet))] (condp = button-code PConstants/LEFT :left PConstants/RIGHT :right PConstants/CENTER :center))) (defn ^{:requires-bindings true :processing-name "mousePressed" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-state "Variable storing if a mouse button is pressed. The value of the system variable mousePressed is true if a mouse button is pressed and false if a button is not pressed." [] (.-mousePressed (current-applet))) (defn ^{:requires-bindings true :processing-name "mouseX" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-x "Current horizontal coordinate of the mouse." [] (.-mouseX (current-applet))) (defn ^{:requires-bindings true :processing-name "mouseY" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-y "Current vertical coordinate of the mouse." [] (.-mouseY (current-applet))) (defn ^{:requires-bindings true :processing-name "pmouseX" :category "Input" :subcategory "Mouse" :added "1.0"} pmouse-x "Horizontal coordinate of the mouse in the previous frame" [] (.-pmouseX (current-applet))) (defn ^{:requires-bindings true :processing-name "pmouseY" :category "Input" :subcategory "Mouse" :added "1.0"} pmouse-y "Vertical coordinate of the mouse in the previous frame" [] (.-pmouseY (current-applet))) (defn ^{:requires-bindings true :processing-name "noCursor()" :category "Environment" :subcategory nil :added "1.0"} no-cursor "Hides the cursor from view. Will not work when running the in full screen (Present) mode." [] (.noCursor (current-applet))) (defn ^{:requires-bindings true :processing-name "noFill()" :category "Color" :subcategory "Setting" :added "1.0"} no-fill "Disables filling geometry. If both no-stroke and no-fill are called, nothing will be drawn to the screen." [] (.noFill (current-surface))) (defn ^{:requires-bindings true :processing-name "noise()" :category "Math" :subcategory "Random" :added "1.0"} noise "Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random function. It was invented by Ken Perlin in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. The main difference to the random function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program). The resulting value will always be between 0.0 and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The noise value can be animated by moving through the noise space and the 2nd and 3rd dimensions can also be interpreted as time. The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result. Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use." ([x] (.noise (current-applet) (float x))) ([x y] (.noise (current-applet) (float x) (float y))) ([x y z] (.noise (current-applet) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "noiseDetail()" :category "Math" :subcategory "Random" :added "1.0"} noise-detail "Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overal intensity of the noise, whereas higher octaves create finer grained details in the noise sequence. By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise. By changing these parameters, the signal created by the noise function can be adapted to fit very specific needs and characteristics." ([octaves] (.noiseDetail (current-applet) (int octaves))) ([octaves falloff] (.noiseDetail (current-applet) (int octaves) (float falloff)))) (defn ^{:requires-bindings true :processing-name "noiseSeed()" :category "Math" :subcategory "Random" :added "1.0"} noise-seed "Sets the seed value for noise. By default, noise produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run." [val] (.noiseSeed (current-applet) (int val))) (defn ^{:requires-bindings true :processing-name "noLights()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} no-lights "Disable all lighting. Lighting is turned off by default and enabled with the lights fn. This function can be used to disable lighting so that 2D geometry (which does not require lighting) can be drawn after a set of lighted 3D geometry." [] (.noLights (current-surface))) (defn ^{:requires-bindings true :processing-name "noLoop()" :category "Structure" :subcategory nil :added "1.0"} no-loop "Stops Processing from continuously executing the code within draw. If start-loop is called, the code in draw will begin to run continuously again. If using no-loop in setup, it should be the last line inside the block. When no-loop is used, it's not possible to manipulate or access the screen inside event handling functions such as mouse-pressed or key-pressed. Instead, use those functions to call redraw or loop which will run draw, which can update the screen properly. This means that when no-loop has been called, no drawing can happen, and functions like save-frame or load-pixels may not be used. Note that if the sketch is resized, redraw will be called to update the sketch, even after no-oop has been specified. Otherwise, the sketch would enter an odd state until loop was called." [] (.noLoop (current-applet))) (defn ^{:requires-bindings true :processing-name "norm()" :category "Math" :subcategory "Calculation" :added "1.0"} norm "Normalize a value to exist between 0 and 1 (inclusive)." [val start stop] (PApplet/norm (float val) (float start) (float stop))) (defn ^{:requires-bindings true :processing-name "normal()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} normal "Sets the current normal vector. This is for drawing three dimensional shapes and surfaces and specifies a vector perpendicular to the surface of the shape which determines how lighting affects it. Processing attempts to automatically assign normals to shapes, but since that's imperfect, this is a better option when you want more control. This function is identical to glNormal3f() in OpenGL." [nx ny nz] (.normal (current-surface) (float nx) (float ny) (float nz))) (defn ^{:requires-bindings true :processing-name "noSmooth()" :category "Shape" :subcategory "Attributes" :added "1.0"} no-smooth "Draws all geometry with jagged (aliased) edges." [] (.noSmooth (current-surface))) (defn ^{:requires-bindings true :processing-name "noStroke()" :category "Color" :subcategory "Setting" :added "1.0"} no-stroke "Disables drawing the stroke (outline). If both no-stroke and no-fill are called, nothing will be drawn to the screen." [] (.noStroke (current-surface))) (defn ^{:requires-bindings true :processing-name "noTint()" :category "Color" :subcategory "Loading & Displaying" :added "1.0"} no-tint "Removes the current fill value for displaying images and reverts to displaying images with their original hues." [] (.noTint (current-surface))) (defn ^{:requires-bindings true :processing-name "ortho()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} ortho "Sets an orthographic projection and defines a parallel clipping volume. All objects with the same dimension appear the same size, regardless of whether they are near or far from the camera. The parameters to this function specify the clipping volume where left and right are the minimum and maximum x values, top and bottom are the minimum and maximum y values, and near and far are the minimum and maximum z values. If no parameters are given, the default is used: ortho(0, width, 0, height, -10, 10)." ([] (.ortho (current-surface))) ([left right bottom top near far] (.ortho (current-surface) (float left) (float right) (float bottom) (float top) (float near) (float far)))) (defn ^{:requires-bindings true :processing-name "perspective()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} perspective "Sets a perspective projection applying foreshortening, making distant objects appear smaller than closer ones. The parameters define a viewing volume with the shape of truncated pyramid. Objects near to the front of the volume appear their actual size, while farther objects appear smaller. This projection simulates the perspective of the world more accurately than orthographic projection. The version of perspective without parameters sets the default perspective and the version with four parameters allows the programmer to set the area precisely. The default values are: perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));" ([] (.perspective (current-surface))) ([fovy aspect z-near z-far] (.perspective (current-surface) (float fovy) (float aspect) (float z-near) (float z-far)))) (defn ^{:requires-bindings true :processing-name "point()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} point "Draws a point, a coordinate in space at the dimension of one pixel. The first parameter is the horizontal value for the point, the second value is the vertical value for the point, and the optional third value is the depth value. Drawing this shape in 3D using the z parameter requires the :P3D or :opengl renderer to be used." ([x y] (.point (current-surface) (float x)(float y))) ([x y z] (.point (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "pointLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} point-light "Adds a point light. Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The x, y, and z parameters set the position of the light" [r g b x y z] (.pointLight (current-surface) (float r) (float g) (float b) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "popMatrix()" :category "Transform" :subcategory nil :added "1.0"} pop-matrix "Pops the current transformation matrix off the matrix stack. Understanding pushing and popping requires understanding the concept of a matrix stack. The push-matrix fn saves the current coordinate system to the stack and pop-matrix restores the prior coordinate system. push-matrix and pop-matrix are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations." [] (.popMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "popStyle()" :category "Structure" :subcategory nil :added "1.0"} pop-style "Restores the prior settings on the 'style stack'. Used in conjunction with push-style. Together they allow you to change the style settings and later return to what you had. When a new style is started with push-style, it builds on the current style information. The push-style and pop-style functions can be nested to provide more control" [] (.popStyle (current-surface))) (defn ^{:requires-bindings false :processing-name "pow()" :category "Math" :subcategory "Calculation" :added "1.0"} pow "Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocal) in large quantities. For example, (pow 3 5) is equivalent to the expression (* 3 3 3 3 3) and (pow 3 -5) is equivalent to (/ 1 (* 3 3 3 3 3))." [num exponent] (PApplet/pow (float num) (float exponent))) (defn ^{:requires-bindings true :processing-name "printCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} print-camera "Prints the current camera matrix to std out. Useful for debugging." [] (.printCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "printMatrix()" :category "Transform" :subcategory nil :added "1.0"} print-matrix "Prints the current matrix to std out. Useful for debugging." [] (.printMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "printProjection()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} print-projection "Prints the current projection matrix to std out. Useful for debugging" [] (.printProjection (current-surface))) (defn ^{:requires-bindings true :processing-name "pushMatrix()" :category "Transform" :subcategory nil :added "1.0"} push-matrix "Pushes the current transformation matrix onto the matrix stack. Understanding push-matrix and pop-matrix requires understanding the concept of a matrix stack. The push-matrix function saves the current coordinate system to the stack and pop-matrix restores the prior coordinate system. push-matrix and pop-matrix are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations." [] (.pushMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "pushStyle()" :category "Structure" :subcategory nil :added "1.0"} push-style "Saves the current style settings onto a 'style stack'. Use with pop-style which restores the prior settings. Note that these functions are always used together. They allow you to change the style settings and later return to what you had. When a new style is started with push-style, it builds on the current style information. The push-style and pop-style fns can be embedded to provide more control. The style information controlled by the following functions are included in the style: fill, stroke, tint, stroke-weight, stroke-cap, stroke-join, image-mode, rect-mode, ellipse-mode, shape-mode, color-mode, text-align, text-font, text-mode, text-size, text-leading, emissive, specular, shininess, and ambient" [] (.pushStyle (current-surface))) (defn ^{:requires-bindings true :processing-name "quad()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} quad "A quad is a quadrilateral, a four sided polygon. It is similar to a rectangle, but the angles between its edges are not constrained to be ninety degrees. The first pair of parameters (x1,y1) sets the first vertex and the subsequent pairs should proceed clockwise or counter-clockwise around the defined shape." [x1 y1 x2 y2 x3 y3 x4 y4] (.quad (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3) (float x4) (float y4))) (defn ^{:requires-bindings false :processing-name "radians()" :category "Math" :subcategory "Trigonometry" :added "1.0"} radians "Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90째 = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians." [degrees] (PApplet/radians (float degrees))) (defn ^{:requires-bindings true :processing-name "random()" :category "Math" :subcategory "Random" :added "1.0"} random "Generates random numbers. Each time the random function is called, it returns an unexpected value within the specified range. If one parameter is passed to the function it will return a float between zero and the value of the high parameter. The function call (random 5) returns values between 0 and 5 (starting at zero, up to but not including 5). If two parameters are passed, it will return a float with a value between the the parameters. The function call (random -5 10.2) returns values starting at -5 up to (but not including) 10.2." ([max] (.random (current-applet) (float max))) ([min max] (.random (current-applet) (float min) (float max)))) (defn ^{:requires-bindings true :processing-name "randomSeed()" :category "Math" :subcategory "Random" :added "1.0"} random-seed "Sets the seed value for random. By default, random produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run." [w] (.randomSeed (current-applet) (float w))) (defn ^{:requires-bindings true :processing-name "rect()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} rect "Draws a rectangle to the screen. A rectangle is a four-sided shape with every angle at ninety degrees. By default, the first two parameters set the location of the upper-left corner, the third sets the width, and the fourth sets the height. These parameters may be changed with rect-mode." [x y width height] (.rect (current-surface) (float x) (float y) (float width) (float height))) (def ^{:private true} rect-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER :radius PApplet/RADIUS}) (defn ^{:requires-bindings true :processing-name "rectMode()" :category "Shape" :subcategory "Attributes" :added "1.0"} rect-mode "Modifies the location from which rectangles draw. The default mode is :corner. Available modes are: :corner - Specifies the location to be the upper left corner of the shape and uses the third and fourth parameters of rect to specify the width and height. :corners - Uses the first and second parameters of rect to set the location of one corner and uses the third and fourth parameters to set the opposite corner. :center - Draws the image from its center point and uses the third and forth parameters of rect to specify the image's width and height. :radius - Draws the image from its center point and uses the third and forth parameters of rect() to specify half of the image's width and height." [mode] (let [mode (resolve-constant-key mode rect-modes)] (.rectMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "red()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} red "Extracts the red value from a color, scaled to match current color-mode." [c] (.red (current-surface) (int c))) (defn ^{:requires-bindings true :processing-name "redraw()" :category "Structure" :subcategory nil :added "1.0"} redraw "Executes the code within the draw fn one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mouse-pressed or key-pressed occurs. In structuring a program, it only makes sense to call redraw within events such as mouse-pressed. This is because redraw does not run draw immediately (it only sets a flag that indicates an update is needed). Calling redraw within draw has no effect because draw is continuously called anyway." [] (.redraw (current-applet))) (defn ^{:requires-bindings true :processing-name "requestImage()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} request-image "This function load images on a separate thread so that your sketch does not freeze while images load during setup. While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1. You'll know when the image has loaded properly because its width and height will be greater than 0. Asynchronous image loading (particularly when downloading from a server) can dramatically improve performance. The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to request-image." ([filename] (.requestImage (current-applet) (str filename))) ([filename extension] (.requestImage (current-applet) (str filename) (str extension)))) (defn ^{:requires-bindings true :processing-name "resetMatrix()" :category "Transform" :subcategory nil :added "1.0"} reset-matrix "Replaces the current matrix with the identity matrix. The equivalent function in OpenGL is glLoadIdentity()" [] (.resetMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "rotate()" :category "Transform" :subcategory nil :added "1.0"} rotate "Rotates a shape the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO-PI) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate HALF-PI) and then (rotate HALF-PI) is the same as (rotate PI). All tranformations are reset when draw begins again. Technically, rotate multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix." ([angle] (.rotate (current-surface) (float angle))) ([angle vx vy vz] (.rotate (current-surface) (float angle) (float vx) (float vy) (float vz)))) (defn ^{:requires-bindings true :processing-name "rotateX()" :category "Transform" :subcategory nil :added "1.0"} rotate-x "Rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-x HALF-PI) and then (rotate-x HALF-PI) is the same as (rotate-x PI). If rotate-x is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateX (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "rotateY()" :category "Transform" :subcategory nil :added "1.0"} rotate-y "Rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-y HALF-PI) and then (rotate-y HALF-PI) is the same as (rotate-y PI). If rotate-y is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateY (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "rotateZ()" :category "Transform" :subcategory nil :added "1.0"} rotate-z "Rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-z HALF-PI) and then (rotate-z HALF-PI) is the same as (rotate-z PI). If rotate-y is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateZ (current-surface) (float angle))) (defn ^{:requires-bindings false :processing-name "round()" :category "Math" :subcategory "Calculation" :added "1.0"} round "Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9." [val] (PApplet/round (float val))) (defn ^{:requires-bindings true :processing-name "saturation()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} saturation "Extracts the saturation value from a color." [c] (.saturation (current-surface) (int c))) (defn ^{:requires-bindings true :processing-name "save()" :category "Output" :subcategory "Image" :added "1.0"} save "Saves an image from the display window. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on the extension within the filename parameter. For example, image.tif will have a TIFF image and image.png will save a PNG image. If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name. All images saved from the main drawing window will be opaque. To save images without a background, use create-graphics." [filename] (.save (current-surface) (str filename))) (defn ^{:requires-bindings true :processing-name "saveFrame()" :category "Output" :subcategory "Image" :added "1.0"} save-frame "Saves an image identical to the current display window as a file. May be called multple times - each file saved will have a unique name. Name and image formate may be modified by passing a string parameter of the form \"foo-####.ext\" where foo- can be any arbitrary string, #### will be replaced with the current frame id and .ext is one of .tiff, .targa, .png, .jpeg or .jpg Examples: (save-frame) (save-frame \"pretty-pic-####.jpg\")" ([] (.saveFrame (current-applet))) ([name] (.saveFrame (current-applet) (str name)))) (defn ^{:requires-bindings true :processing-name "scale()" :category "Transform" :subcategory nil :added "1.0"} scale "Increases or decreases the size of a shape by expanding and contracting vertices. Objects always scale from their relative origin to the coordinate system. Scale values are specified as decimal percentages. For example, the function call (scale 2) increases the dimension of a shape by 200%. Transformations apply to everything that happens after and subsequent calls to the function multiply the effect. For example, calling (scale 2) and then (scale 1.5) is the same as (scale 3). If scale is called within draw, the transformation is reset when the loop begins again. Using this fuction with the z parameter requires specfying :p3d or :opengl as the renderer. This function can be further controlled by push-matrix and pop-matrix." ([s] (.scale (current-surface) (float s))) ([sx sy] (.scale (current-surface) (float sx) (float sy)))) (defn- current-screen [] (let [default-toolkit (java.awt.Toolkit/getDefaultToolkit)] (.getScreenSize default-toolkit))) (def ^{:private true} orig-screen-width (let [screen (current-screen)] (.width screen))) (defn ^{:requires-bindings false :processing-name "screen.width" :category "Environment" :subcategory nil :added "1.0"} screen-width "Returns the width of the main screen in pixels." [] orig-screen-width) (def ^{:private true} orig-screen-height (let [screen (current-screen)] (.height screen))) (defn ^{:requires-bindings false :processing-name "screen.height" :category "Environment" :subcategory nil :added "1.0"} screen-height "Returns the height of the main screen in pixels." [] orig-screen-height) (defn ^{:requires-bindings true :processing-name "screenX()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-x "Takes a three-dimensional x, y, z position and returns the x value for where it will appear on a (two-dimensional) screen, once affected by translate, scale or any other transformations" [x y z] (.screenX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "screenY()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-y "Takes a three-dimensional x, y, z position and returns the y value for where it will appear on a (two-dimensional) screen, once affected by translate, scale or any other transformations" [x y z] (.screenY (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "screenZ()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-z "Given an x, y, z coordinate, returns its z value. This value can be used to determine if an x, y, z coordinate is in front or in back of another (x, y, z) coordinate. The units are based on how the zbuffer is set up, and don't relate to anything 'real'. They're only useful for in comparison to another value obtained from screen-z, or directly out of the zbuffer" [x y z] (.screenX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings false :processing-name "seconds()" :category "Input" :subcategory "Time & Date" :added "1.0"} seconds "Returns the current second as a value from 0 - 59." [] (PApplet/second)) (defn ^{:requires-bindings true :processing-name "set()" :category "Image" :subcategory "Pixels" :added "1.0"} set-pixel "Changes the color of any pixel in the display window. The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). Setting the color of a single pixel with (set x, y) is easy, but not as fast as putting the data directly into pixels[]. This function ignores imageMode(). Due to what appears to be a bug in Apple's Java implementation, the point() and set() methods are extremely slow in some circumstances when used with the default renderer. Using :p2d or :p3d will fix the problem. Grouping many calls to point or set-pixel together can also help. (Bug 1094)" [x y c] (.set (current-surface) (int x) (int y) (int c))) (defn ^{:requires-bindings true :processing-name "set()" :category "Image" :subcategory "Pixels" :added "1.0"} set-image "Writes an image directly into the display window. The x and y parameters define the coordinates for the upper-left corner of the image." [x y ^PImage src] (.set (current-surface) (int x) (int y) src)) (defn ^{:requires-bindings true :processing-name "shape()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} shape "Displays shapes to the screen. The shapes must have been loaded with load-shape. Processing currently works with SVG shapes only. The sh parameter specifies the shape to display and the x and y parameters define the location of the shape from its upper-left corner. The shape is displayed at its original size unless the width and height parameters specify a different size. The shape-mode fn changes the way the parameters work. A call to (shape-mode :corners), for example, will change the width and height parameters to define the x and y values of the opposite corner of the shape. Note complex shapes may draw awkwardly with the renderers :p2d, :p3d, and :opengl. Those renderers do not yet support shapes that have holes or complicated breaks." ([^PShape sh] (.shape (current-surface) sh)) ([^PShape sh x y] (.shape (current-surface) sh (float x) (float y))) ([^PShape sh x y width height] (.shape (current-surface) sh (float x) (float y) (float width) (float height)))) (defn ^{:requires-bindings true :processing-name "shearX()" :category "Transform" :subcategory nil :added "1.0"} shear-x "Shears a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. Objects are always sheared around their relative position to the origin and positive numbers shear objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (shear-x (/ PI 2)) and then (shear-x (/ PI 2)) is the same as (shear-x PI). If shear-x is called within the draw fn, the transformation is reset when the loop begins again. This function works in P2D or JAVA2D mode. Technically, shear-x multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix fns." [angle] (.shearX (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "shearY()" :category "Transform" :subcategory nil :added "1.0"} shear-y "Shears a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. Objects are always sheared around their relative position to the origin and positive numbers shear objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (shear-y (/ PI 2)) and then (shear-y (/ PI 2)) is the same as (shear-y PI). If shear-y is called within the draw fn, the transformation is reset when the loop begins again. This function works in P2D or JAVA2D mode. Technically, shear-y multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix fns." [angle] (.shearY (current-surface) (float angle))) (def ^{:private true} p-shape-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER}) (defn ^{:requires-bindings true :processing-name "shapeMode()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} shape-mode "Modifies the location from which shapes draw. Available modes are :corner, :corners and :center. Default is :corner. :corner - specifies the location to be the upper left corner of the shape and uses the third and fourth parameters of shape to specify the width and height. :corners - uses the first and second parameters of shape to set the location of one corner and uses the third and fourth parameters to set the opposite corner. :center - draws the shape from its center point and uses the third and forth parameters of shape to specify the width and height. " [mode] (let [mode (resolve-constant-key mode p-shape-modes)] (.shapeMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "shininess()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} shininess "Sets the amount of gloss in the surface of shapes. Used in combination with ambient, specular, and emissive in setting the material properties of shapes." [shine] (.shininess (current-surface) (float shine))) (defn ^{:requires-bindings false :processing-name "sin()" :category "Math" :subcategory "Trigonometry" :added "1.0"} sin "Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to 6.28). A float within the range -1 to 1 is returned." [angle] (PApplet/sin (float angle))) (defn size "Not supported. Use :size key in applet or defapplet" [& args] (println "Deprecated - size should be specified as a :size key to applet or defapplet") nil) (defn ^{:requires-bindings true :processing-name "smooth()" :category "Shape" :subcategory "Attributes" :added "1.0"} smooth "Draws all geometry with smooth (anti-aliased) edges. This will slow down the frame rate of the application, but will enhance the visual refinement. Note that smooth will also improve image quality of resized images." [] (.smooth (current-surface))) (defn ^{:requires-bindings true :processing-name "specular()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} specular "Sets the specular color of the materials used for shapes drawn to the screen, which sets the color of hightlights. Specular refers to light which bounces off a surface in a perferred direction (rather than bouncing in all directions like a diffuse light). Used in combination with emissive, ambient, and shininess in setting the material properties of shapes." ([gray] (.specular (current-surface) (float gray))) ([gray alpha] (.specular (current-surface) (float gray) (float alpha))) ([x y z] (.specular (current-surface) (float x) (float y) (float z))) ([x y z a] (.specular (current-surface) (float x) (float y) (float z) (float a)))) (defn ^{:requires-bindings true :processing-name "sphere()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} sphere "Genarates a hollow ball made from tessellated triangles." [radius] (.sphere (current-surface) (float radius))) (defn ^{:requires-bindings true :processing-name "sphereDetail()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} sphere-detail "Controls the detail used to render a sphere by adjusting the number of vertices of the sphere mesh. The default resolution is 30, which creates a fairly detailed sphere definition with vertices every 360/30 = 12 degrees. If you're going to render a great number of spheres per frame, it is advised to reduce the level of detail using this function. The setting stays active until sphere-detail is called again with a new parameter and so should not be called prior to every sphere statement, unless you wish to render spheres with different settings, e.g. using less detail for smaller spheres or ones further away from the camera. To controla the detail of the horizontal and vertical resolution independently, use the version of the functions with two parameters." ([res] (.sphereDetail (current-surface) (int res))) ([ures vres] (.sphereDetail (current-surface) (int ures) (int vres)))) (defn ^{:requires-bindings true :processing-name "spotLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} spot-light "Adds a spot light. Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The x, y, and z parameters specify the position of the light and nx, ny, nz specify the direction or light. The angle parameter affects angle of the spotlight cone." ([r g b x y z nx ny nz angle concentration] (.spotLight (current-surface) r g b x y z nx ny nz angle concentration)) ([[r g b] [x y z] [nx ny nz] angle concentration] (.spotLight (current-surface) r g b x y z nx ny nz angle concentration))) (defn ^{:requires-bindings false :processing-name "sq()" :category "Math" :subcategory "Calculation" :added "1.0"} sq "Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1." [a] (PApplet/sq (float a))) (defn ^{:requires-bindings false :processing-name "sqrt()" :category "Math" :subcategory "Calculation" :added "1.0"} sqrt "Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that (= a (* s s)) . It is the opposite of squaring." [a] (PApplet/sqrt (float a))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke-float "Sets the color used to draw lines and borders around shapes. Converts all args to floats" ([gray] (.stroke (current-surface) (float gray))) ([gray alpha] (.stroke (current-surface) (float gray) (float alpha))) ([x y z] (.stroke (current-surface) (float x) (float y) (float z))) ([x y z a] (.stroke (current-surface) (float x) (float y) (float z) (float a)))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke-int "Sets the color used to draw lines and borders around shapes. Converts rgb to int and alpha to a float." ([rgb] (.stroke (current-surface) (int rgb))) ([rgb alpha] (.stroke (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke "Sets the color used to draw lines and borders around shapes. This color is either specified in terms of the RGB or HSB color depending on the current color-mode (the default color space is RGB, with each value in the range from 0 to 255)." ([rgb] (if (int-like? rgb) (stroke-int rgb) (stroke-float rgb))) ([rgb alpha] (if (int-like? rgb) (stroke-int rgb alpha) (stroke-float rgb alpha))) ([x y z] (stroke-float x y z)) ([x y z a] (stroke-float x y z a))) (def ^{:private true} stroke-cap-modes {:square PApplet/SQUARE :round PApplet/ROUND :project PApplet/PROJECT :model PApplet/MODEL}) (defn ^{:requires-bindings true :processing-name "strokeCap()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-cap "Sets the style for rendering line endings. These ends are either squared, extended, or rounded and specified with the corresponding parameters :square, :project, and :round. The default cap is :round." [cap-mode] (let [cap-mode (resolve-constant-key cap-mode stroke-cap-modes)] (.strokeCap (current-surface) (int cap-mode)))) (def ^{:private true} stroke-join-modes {:miter PConstants/MITER :bevel PConstants/BEVEL :round PConstants/ROUND}) (defn ^{:requires-bindings true :processing-name "strokeJoin()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-join "Sets the style of the joints which connect line segments. These joints are either mitered, beveled, or rounded and specified with the corresponding parameters :miter, :bevel, and :round. The default joint is :miter. This function is not available with the :p2d, :p3d, or :opengl renderers." [join-mode] (let [join-mode (resolve-constant-key join-mode stroke-join-modes)] (.strokeJoin (current-surface) (int join-mode)))) (defn ^{:requires-bindings true :processing-name "strokeWeight()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-weight "Sets the width of the stroke used for lines, points, and the border around shapes. All widths are set in units of pixels. " [weight] (.strokeWeight (current-surface) (float weight))) (defn ^{:requires-bindings false :processing-name "tan()" :category "Math" :subcategory "Trigonometry" :added "1.0"} tan "Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity." [angle] (PApplet/tan (float angle))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-char "Draws a char to the screen in the specified position. See text fn for more details." ([c] (.text (current-surface) (char c))) ([c x y] (.text (current-surface) (char c) (float x) (float y))) ([c x y z] (.text (current-surface) (char c) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-num "Draws a number to the screen in the specified position. See text fn for more details." ([num x y] (.text (current-surface) (float num) (float x) (float y))) ([num x y z] (.text (current-surface) (float num) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text "Draws text to the screen in the position specified by the x and y parameters and the optional z parameter. A default font will be used unless a font is set with the text-font fn. Change the color of the text with the fill fn. The text displays in relation to the text-align fn, which gives the option to draw to the left, right, and center of the coordinates. The x1, y1, x2 and y2 (and optional z) parameters define a rectangular area to display within and may only be used with string data. For text drawn inside a rectangle, the coordinates are interpreted based on the current rect-mode setting. Use the text-mode function with the :screen parameter to display text in 2D at the surface of the window." ([^String s] (.text (current-surface) s)) ([^String s x y] (.text (current-surface) s (float x) (float y))) ([^String s x y z] (.text (current-surface) s (float x) (float y) (float z))) ([^String s x1 y1 x2 y2] (.text (current-surface) s (float x1) (float y1) (float x2) (float y2))) ([^String s x1 y1 x2 y2 z] (.text (current-surface) s (float x1) (float y1) (float x2) (float y2) (float z)))) (def ^{:private true} horizontal-alignment-modes {:left PApplet/LEFT :center PApplet/CENTER :right PApplet/RIGHT}) (def ^{:private true} vertical-alignment-modes {:top PApplet/TOP :bottom PApplet/BOTTOM :center PApplet/CENTER :baseline PApplet/BASELINE}) (defn ^{:requires-bindings true :processing-name "textAlign()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-align "Sets the current alignment for drawing text. Available modes are: horizontal - :left, :center, and :right vertical - :top, :bottom, :center, and :baseline An optional second parameter specifies the vertical alignment mode. :baseline is the default. The :top and :center parameters are straightforward. The :bottom parameter offsets the line based on the current text-descent. For multiple lines, the final line will be aligned to the bottom, with the previous lines appearing above it. When using text with width and height parameters, :baseline is ignored, and treated as :top. (Otherwise, text would by default draw outside the box, since :baseline is the default setting. :baseline is not a useful drawing mode for text drawn in a rectangle.) The vertical alignment is based on the value of text-ascent, which many fonts do not specify correctly. It may be necessary to use a hack and offset by a few pixels by hand so that the offset looks correct. To do this as less of a hack, use some percentage of text-ascent or text-descent so that the hack works even if you change the size of the font." ([align] (let [align (resolve-constant-key align horizontal-alignment-modes)] (.textAlign (current-surface) (int align)))) ([align-x align-y] (let [align-x (resolve-constant-key align-x horizontal-alignment-modes) align-y (resolve-constant-key align-y vertical-alignment-modes)] (.textAlign (current-surface) (int align-x) (int align-y))))) (defn ^{:requires-bindings true :processing-name "textAscent()" :category "Typography" :subcategory "Metrics" :added "1.0"} text-ascent "Returns the ascent of the current font at its current size. This information is useful for determining the height of the font above the baseline. For example, adding the text-ascent and text-descent values will give you the total height of the line." [] (.textAscent (current-surface))) (defn ^{:requires-bindings true :processing-name "textDescent()" :category "Typography" :subcategory "Metrics" :added "1.0"} text-descent "Returns descent of the current font at its current size. This information is useful for determining the height of the font below the baseline. For example, adding the text-ascent and text-descent values will give you the total height of the line." [] (.textDescent (current-surface))) (defn ^{:requires-bindings true :processing-name "textFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-font "Sets the current font that will be drawn with the text function. Fonts must be loaded with load-font before it can be used. This font will be used in all subsequent calls to the text function. If no size parameter is input, the font will appear at its original size until it is changed with text-size. Because fonts are usually bitmaped, you should create fonts at the sizes that will be used most commonly. Using textFont without the size parameter will result in the cleanest-looking text. With the default (JAVA2D) and PDF renderers, it's also possible to enable the use of native fonts via the command (hint :enable-native-fonts). This will produce vector text in JAVA2D sketches and PDF output in cases where the vector data is available: when the font is still installed, or the font is created via the create-font fn" ([^PFont font] (.textFont (current-surface) font)) ([^PFont font size] (.textFont (current-surface) font (int size)))) (defn ^{:requires-bindings true :processing-name "textLeading()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-leading "Sets the spacing between lines of text in units of pixels. This setting will be used in all subsequent calls to the text function." [leading] (.textLeading (current-surface) (float leading))) (def ^{:private true} text-modes {:model PConstants/MODEL :shape PConstants/SHAPE :screen PConstants/SCREEN}) (defn ^{:requires-bindings true :processing-name "textMode()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-mode "Sets the way text draws to the screen - available modes are :model, :shape and :screen In the default configuration (the :model mode), it's possible to rotate, scale, and place letters in two and three dimensional space. Changing to :screen mode draws letters directly to the front of the window and greatly increases rendering quality and speed when used with the :p2d and :p3d renderers. :screen with :opengl and :java2d (the default) renderers will generally be slower, though pixel accurate with :p2d and :p3d. With :screen, the letters draw at the actual size of the font (in pixels) and therefore calls to text-size will not affect the size of the letters. To create a font at the size you desire, use create-font. When using :screen, any z-coordinate passed to a text command will be ignored, because your computer screen is...flat! The :shape mode draws text using the the glyph outlines of individual characters rather than as textures. This mode is only only supported with the PDF and OPENGL renderer settings. With the PDF renderer, you must specify the :shape text-mode before any other drawing occurs. If the outlines are not available, then :shape will be ignored and :model will be used instead. The :shape option in OPENGL mode can be combined with begin-raw to write vector-accurate text to 2D and 3D output files, for instance DXF or PDF. :shape is not currently optimized for OPENGL, so if recording shape data, use :model until you're ready to capture the geometry with begin-raw." [mode] (let [mode (resolve-constant-key mode text-modes)] (.textMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "textSize()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-size "Sets the current font size. This size will be used in all subsequent calls to the text fn. Font size is measured in units of pixels." [size] (.textSize (current-surface) (float size))) (defn ^{:requires-bindings true :processing-name "texture()" :category "Shape" :subcategory "Vertex" :added "1.0"} texture "Sets a texture to be applied to vertex points. The texture fn must be called between begin-shape and end-shape and before any calls to vertex. When textures are in use, the fill color is ignored. Instead, use tint to specify the color of the texture as it is applied to the shape." [^PImage img] (.texture (current-surface) img)) (def ^{:private true} texture-modes {:image PApplet/IMAGE :normalized PApplet/NORMALIZED}) (defn ^{:requires-bindings true :processing-name "textureMode()" :category "Shape" :subcategory "Vertex" :added "1.0"} texture-mode "Sets the coordinate space for texture mapping. There are two options, :image and :normalized. :image refers to the actual coordinates of the image and :normalized refers to a normalized space of values ranging from 0 to 1. The default mode is :image. In :image, if an image is 100 x 200 pixels, mapping the image onto the entire size of a quad would require the points (0,0) (0,100) (100,200) (0,200). The same mapping in NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1)." [mode] (let [mode (resolve-constant-key mode texture-modes)] (.textureMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "textWidth()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-width "Calculates and returns the width of any character or text string." [data] (let [data (if (= (class data) (class \a)) (char data) (str data))] (.textWidth (current-surface) data))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint-float "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([gray] (.tint (current-surface) (float gray))) ([gray alpha] (.tint (current-surface) (float gray) (float alpha))) ([r g b] (.tint (current-surface) (float r)(float g) (float b))) ([r g b a] (.tint (current-surface) (float g) (float g) (float b) (float a)))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint-int "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([rgb] (.tint (current-surface) (int rgb))) ([rgb alpha] (.tint (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([rgb] (if (int-like? rgb) (tint-int rgb) (tint-float rgb))) ([rgb alpha] (if (int-like? rgb) (tint-int rgb alpha) (tint-float rgb alpha))) ([r g b] (tint-float r g b)) ([r g b a] (tint-float r g b a))) (defn ^{:requires-bindings true :processing-name "translate()" :category "Transform" :subcategory nil :added "1.0"} translate "Specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (translate 50 0) and then (translate 20, 0) is the same as (translate 70, 0). If translate is called within draw, the transformation is reset when the loop begins again. This function can be further controlled by the push-matrix and pop-matrix." ([v] (apply translate v)) ([tx ty] (.translate (current-surface) (float tx) (float ty))) ([tx ty tz] (.translate (current-surface) (float tx) (float ty) (float tz)))) (defn ^{:requires-bindings true :processing-name "triangle()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} triangle "A triangle is a plane created by connecting three points. The first two arguments specify the first point, the middle two arguments specify the second point, and the last two arguments specify the third point." [x1 y1 x2 y2 x3 y3] (.triangle (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3))) (defn ^{:requires-bindings true :processing-name "updatePixels()" :category "Image" :subcategory "Pixels" :added "1.0"} update-pixels "Updates the display window with the data in the pixels array. Use in conjunction with load-pixels. If you're only reading pixels from the array, there's no need to call update-pixels unless there are changes. Certain renderers may or may not seem to require load-pixels or update-pixels. However, the rule is that any time you want to manipulate the pixels array, you must first call load-pixels, and after changes have been made, call update-pixels. Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change." [] (.updatePixels (current-surface))) (defn ^{:requires-bindings true :processing-name "vertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} vertex "All shapes are constructed by connecting a series of vertices. vertex is used to specify the vertex coordinates for points, lines, triangles, quads, and polygons and is used exclusively within the begin-shape and end-shape fns. Drawing a vertex in 3D using the z parameter requires the :p3d or :opengl renderers to be used. This function is also used to map a texture onto the geometry. The texture fn declares the texture to apply to the geometry and the u and v coordinates set define the mapping of this texture to the form. By default, the coordinates used for u and v are specified in relation to the image's size in pixels, but this relation can be changed with texture-mode." ([x y] (.vertex (current-surface) (float x) (float y))) ([x y z] (.vertex (current-surface) (float x) (float y) (float z))) ([x y u v] (.vertex (current-surface) (float x) (float y) (float u) (float v))) ([x y z u v] (.vertex (current-surface) (float x) (float y) (float z) (float u) (float v)))) (defn ^{:requires-bindings false :processing-name "year()" :category "Input" :subcategory "Time & Date" :added "1.0"} year "Returns the current year as an integer (2003, 2004, 2005, etc)." [] (PApplet/year)) (defn ^{:requires-bindings true :processing-name "width" :category "Environment" :subcategory nil :added "1.0"} width "Width of the display window. The value of width is zero until size is called." [] (.getWidth (current-applet))) (defmacro ^{:requires-bindings true :processing-name nil :category "Transform" :subcategory "Utility Macros"} with-translation "Performs body with translation, restores current transformation on exit." [translation-vector & body] `(let [tr# ~translation-vector] (push-matrix) (translate tr#) ~@body (pop-matrix))) (defmacro ^{:requires-bindings true :processing-name nil :category "Transform" :subcategory "Utility Macros"} with-rotation "Performs body with rotation, restores current transformation on exit. Accepts a vector [angle] or [angle x-axis y-axis z-axis]. Example: (with-rotation [angle] (vertex 1 2))" [rotation & body] `(let [tr# ~rotation] (push-matrix) (apply rotate tr#) ~@body (pop-matrix))) ;;; version number (defn quil-version [] QUIL-VERSION-STR) ;;; doc utils (def ^{:private true} processing-fn-metas "Returns a seq of metadata maps for all fns related to the original Processing API (but may not have a direct Processing API equivalent)." (map #(-> % second meta) (ns-publics *ns*))) (defn- processing-fn-metas-with-orig-method-name "Returns a seq of metadata maps for all fns with a corresponding Processing API method." [] (filter :processing-name processing-fn-metas)) (defn- matching-processing-methods "Takes a string representing the start of a method name in the original Processing API and returns a map of orig/new-name pairs" [orig-name] (let [metas (processing-fn-metas-with-orig-method-name) matches (filter #(.startsWith (:processing-name %) orig-name) metas)] (into {} (map (fn [{:keys [name processing-name]}] [(str processing-name) (str name)]) matches)))) (defn- find-categories [] (let [metas processing-fn-metas cats (into (sorted-set) (map :category metas))] (clojure.set/difference cats #{nil}))) (defn- find-subcategories [category] (let [metas processing-fn-metas in-cat (filter #(= category (:category %)) metas) res (into (sorted-set) (map :subcategory in-cat))] (clojure.set/difference res #{nil}))) (defn- find-fns "Find the names of fns in category cat that don't also belong to a subcategory" [cat subcat] (let [metas processing-fn-metas res (filter (fn [m] (and (= cat (:category m)) (= subcat (:subcategory m)))) metas)] (sort (map :name res)))) (defn- subcategory-map [cat cat-idx] (let [subcats (find-subcategories cat) idxs (map inc (range)) idxd-subcats (map (fn [idx subcat] [(str cat-idx "." idx) subcat]) idxs subcats)] (into {} (map (fn [[idx subcat]] [idx {:name subcat :fns (find-fns cat subcat)}]) idxd-subcats)))) (defn- sorted-category-map [] (let [cats (find-categories) idxs (map inc (range)) idxd-cats (into {} (map (fn [idx cat] [idx cat]) idxs cats))] (into (sorted-map) (map (fn [[idx cat]] [idx {:name cat :fns (find-fns cat nil) :subcategories (subcategory-map cat idx)}]) idxd-cats)))) (defn- all-category-map [] (reduce (fn [sum [k v]] (merge sum (:subcategories v))) (into {} (map (fn [[k v]] [(str k) v]) (sorted-category-map))) (sorted-category-map))) (defn show-cats "Print out a list of all the categories and subcategories, associated index nums and fn count (in parens)." [] (let [cats (sorted-category-map)] (dorun (map (fn [[cat-idx cat]] (println cat-idx (:name cat) (str "(" (count (find-fns (:name cat) nil)) ")")) (dorun (map (fn [[subcat-idx subcat]] (println " " subcat-idx (:name subcat) (str "(" (count (find-fns (:name cat) (:name subcat))) ")"))) (:subcategories cat)))) cats)))) (defn- wrap-lines "Split a list of words in lists (lines) not longer than width chars each, space between words included." [width words] (letfn [(wrap-lines-rec [ws accum-lns] (if (empty? ws) accum-lns (let [lens (map count ws) cumlens (reduce (fn [sums len] (conj sums (if (empty? sums) len (+ (last sums) len 1)))) [] lens) [line other] (split-with #(> width %) cumlens) [line other] (split-at (count line) ws)] (recur other (conj accum-lns line)))))] (wrap-lines-rec words []))) (defn- pprint-wrapped-lines "Pretty print words across several lines by wrapping lines at word boundary." [words & {:keys [fromcolumn width] :or {fromcolumn 0 width 80}}] (let [w (- width fromcolumn) wordss (wrap-lines w words) indent (apply str (repeat fromcolumn \space)) lines (map #(apply str indent (interpose " " %)) wordss)] (doseq [l lines] (println l)))) (defn show-fns "If given a number, print all the functions within category or subcategory specified by the category index (use show-cats to see a list of index nums). If given a string or a regular expression, print all the functions whose name or category name contains that string. If a category is specified, it will not print out the fns in any of cat's subcategories." [q] (letfn [(list-category [cid c & {:keys [only]}] (let [category-fns (:fns c) display-fns (if (nil? only) category-fns (clojure.set/intersection (set only) (set category-fns))) names (sort (map str display-fns))] (if (not (empty? names)) (do (println cid (:name c)) (pprint-wrapped-lines names :fromcolumn 4))))) (show-fns-by-cat-idx [cat-idx] (let [c (get (all-category-map) (str cat-idx))] (list-category cat-idx c))) (show-fns-by-name-regex [re] (doseq [[cid c] (sort-by key (all-category-map))] (let [in-cat-name? (re-find re (:name c)) matching-fns (filter #(re-find re (str %)) (:fns c)) in-fn-names? (not (empty? matching-fns))] (cond in-cat-name? (list-category cid c) ;; print an entire category in-fn-names? (list-category cid c :only matching-fns)))))] (cond (string? q) (show-fns-by-name-regex (re-pattern (str "(?i)" q))) (isa? (type q) java.util.regex.Pattern) (show-fns-by-name-regex q) :else (show-fns-by-cat-idx q)))) (defn show-meths "Takes a string representing the start of a method name in the original Processing API and prints out all matches alongside the Processing-core equivalent." [orig-name] (let [res (matching-processing-methods orig-name)] (print-definition-list res)) nil) ;;; Useful trig constants (def PI (float Math/PI)) (def HALF-PI (/ PI (float 2.0))) (def THIRD-PI (/ PI (float 3.0))) (def QUARTER-PI (/ PI (float 4.0))) (def TWO-PI (* PI (float 2.0))) (def DEG-TO-RAD (/ PI (float 180.0))) (def RAD-TO-DEG (/ (float 180.0) PI)) ;; Sketch control (defn sketch-stop "Stop/pause the sketch (restart with sketch-start)" [sketch] (applet-stop sketch)) (defn sketch-state "Fetch an element of state from within the sketch" [sketch k] (applet-state sketch k)) (defn sketch-start "Restart the sketch (if it has been stopped with sketch-stop)" [sketch] (applet-start sketch)) (defn sketch-close "Stop the sketch and close the window" [sketch] (applet-close sketch)) ;; Sketch creation (defn sketch "Create and start a new visualisation applet. :size - a vector of width and height for the sketch. Defaults to [500 300]. :renderer - Specify the renderer type. One of :p2d, :java2d, :opengl, :pdf or :dxf). Defaults to :java2d. If :pdf or :dxf is selected, :target is forced to :none. :output-file - Specify an output file path. Only used in :pdf and :dxf render modes. :title - a string which will be displayed at the top of the sketch window. :target - Specify the target. One of :frame, :perm-frame or :none. Ignored if :pdf or :dxf renderer is used. :decor - Specify if the window should have OS frame decorations. Only honoured with :frame or :perm-frame targets. :setup - a fn to be called once when setting the sketch up. :draw - a fn to be repeatedly called at most n times per second where n is the target frame-rate set for the visualisation. :focus-gained - Called when the sketch gains focus. :focus-lost - Called when the sketch loses focus. :mouse-entered - Called when the mouse enters the sketch window. :mouse-exited - Called when the mouse leaves the sketch window :mouse-pressed - Called every time a mouse button is pressed. :mouse-released - Called every time a mouse button is released. :mouse-clicked - called once after a mouse button has been pressed and then released. :mouse-moved - Called every time the mouse moves and a button is not pressed. :mouse-dragged - Called every time the mouse moves and a button is pressed. :key-pressed - Called every time any key is pressed. :key-released - Called every time any key is released. :key-typed - Called once every time non-modifier keys are pressed. :safe-draw-fn - Catches and prints exceptions in the draw fn. Default is true. :on-close - Called once, when sketch is closed" [& opts] (apply applet opts)) (defmacro defsketch "Define and start a sketch and bind it to a var with the symbol app-name. If any of the options to the various callbacks are symbols, it wraps them in a call to var to ensure they aren't inlined and that redefinitions to the original fns are reflected in the visualisation. See sketch for the available options." [app-name & opts] `(defapplet ~app-name ~@opts)) (defmacro with-graphics "All subsequent calls of any drawing function will draw on given graphics." [graphics & body] `(binding [*graphics* ~graphics] (.beginDraw ~graphics) ~@body (.endDraw ~graphics))) (defn ^{:requires-bindings false :processing-name nil :category "Input" :subcategory "Keyboard" :added "1.6"} key-coded? "Returns true if char c is a 'coded' char i.e. it is necessary to fetch the key-code as an integer and use that to determine the specific key pressed. See key-keyword." [c] (= PConstants/CODED (int c))) (def ^{:private true} KEY-CODES {KeyEvent/VK_UP :up KeyEvent/VK_DOWN :down KeyEvent/VK_LEFT :left KeyEvent/VK_RIGHT :right KeyEvent/VK_ALT :alt KeyEvent/VK_CONTROL :control KeyEvent/VK_SHIFT :shift KeyEvent/VK_WINDOWS :command KeyEvent/VK_META :command KeyEvent/VK_F1 :f1 KeyEvent/VK_F2 :f2 KeyEvent/VK_F3 :f3 KeyEvent/VK_F4 :f4 KeyEvent/VK_F5 :f5 KeyEvent/VK_F6 :f6 KeyEvent/VK_F7 :f7 KeyEvent/VK_F8 :f8 KeyEvent/VK_F9 :f9 KeyEvent/VK_F10 :f10 KeyEvent/VK_F11 :f11 KeyEvent/VK_F12 :f12 KeyEvent/VK_F13 :f13 KeyEvent/VK_F14 :f14 KeyEvent/VK_F15 :f15 KeyEvent/VK_F16 :f16 KeyEvent/VK_F17 :f17 KeyEvent/VK_F18 :f18 KeyEvent/VK_F19 :f19 KeyEvent/VK_F20 :f20 KeyEvent/VK_F21 :f21 KeyEvent/VK_F22 :f22 KeyEvent/VK_F23 :f23 KeyEvent/VK_F24 :f24}) (defn ^{:requires-bindings true :processing-name nil :category "Input" :subcategory "Keyboard" :added "1.6"} key-as-keyword "Returns a keyword representing the currently pressed key. Modifier keys are represented as: :up, :down, :left, :right, :alt, :control, :shift, :command, :f1-24" [] (let [key-char (raw-key) code (key-code)] (if (key-coded? key-char) (get KEY-CODES code :unknown-key) (keyword (str key-char))))) (defn ^{:requires-bindings false :processing-name nil :category "Debugging" :added "1.6"} debug "Prints msg and then sleeps the current thread for delay-ms. Useful for debugging live running sketches. delay-ms defaults to 300. " ([msg] (debug msg 300)) ([msg delay-ms] (println msg) (Thread/sleep delay-ms)))
116090
(ns ^{:doc "Wrappers and extensions around the core Processing.org API." :author "<NAME>, <NAME>"} quil.core (:import [processing.core PApplet PImage PGraphics PFont PConstants PShape] [java.awt.event KeyEvent]) (:require [clojure.set]) (:use [quil.version :only [QUIL-VERSION-STR]] [quil.util :only [int-like? resolve-constant-key length-of-longest-key gen-padding print-definition-list]] [quil.applet :only [current-applet applet-stop applet-state applet-start applet-close applet defapplet applet-safe-exit current-graphics *graphics*]])) (defn- current-surface "Retrieves current drawing surface. It's either current graphics or current applet if graphics is nil" [] (or (current-graphics) (current-applet))) (defn ^{:requires-bindings true :category "State" :subcategory nil :added "1.0"} state "Retrieve sketch-specific state by key. Must initially call set-state! to store state. (set-state! :foo 1) (state :foo) ;=> 1 " [key] (let [state* (:state (meta (current-applet)))] (when-not @state* (throw (Exception. "State not set - use set-state! before fetching state"))) (let [state @state*] (when-not (contains? state key) (throw (Exception. (str "Unable to find state with key: " key)))) (get state key)))) (defn ^{:requires-bindings true :category "State" :subcategory nil :added "1.0"} set-state! "Set sketch-specific state. May only be called once (ideally in the setup fn). Subsequent calls have no effect. Example: (set-state! :foo 1 :bar (atom true) :baz (/ (width) 2))" [& state-vals] (let [state* (:state (meta (current-applet)))] (when-not @state* (let [state-map (apply hash-map state-vals)] (reset! state* state-map))))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs-int "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Takes and returns an int." [n] (PApplet/abs (int n))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs-float "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Takes and returns a float." [n] (PApplet/abs (float n))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Dynamically casts to an int or float appropriately" [n] (if (int-like? n) (abs-int n) (abs-float n))) (defn ^{:requires-bindings false :processing-name "acos()" :category "Math" :subcategory "Trigonometry" :added "1.0"} acos "The inverse of cos, returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to Math/PI (3.1415927)." [n] (PApplet/acos (float n))) (defn ^{:requires-bindings true :processing-name "alpha()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} alpha "Extracts the alpha value from a color." [color] (.alpha (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient-float "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The color components set through the parameters define the reflectance. For example in the default color mode, setting x=255, y=126, z=0, would cause all the red light to reflect and half of the green light to reflect. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." ([gray] (.ambient (current-surface) (float gray))) ([x y z] (.ambient (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient-int "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The rgb color components set define the reflectance. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." [rgb] (.ambient (current-surface) (int rgb))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The color components set through the parameters define the reflectance. For example in the default color mode, setting x=255, y=126, z=0, would cause all the red light to reflect and half of the green light to reflect. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." ([rgb] (if (int-like? rgb) (ambient-int rgb) (ambient-float rgb))) ([x y z] (ambient-float x y z))) (defn ^{:requires-bindings true :processing-name "ambientLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} ambient-light "Adds an ambient light. Ambient light doesn't come from a specific direction, the rays have light have bounced around so much that objects are evenly lit from all sides. Ambient lights are almost always used in combination with other types of lights. Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop. The effect of the parameters is determined by the current color mode." ([red green blue] (.ambientLight (current-surface) (float red) (float green) (float blue))) ([red green blue x y z] (.ambientLight (current-surface) (float red) (float green) (float blue) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "applyMatrix()" :category "Transform" :subcategory nil :added "1.0"} apply-matrix "Multiplies the current matrix by the one specified through the parameters. This is very slow because it will try to calculate the inverse of the transform, so avoid it whenever possible. The equivalent function in OpenGL is glMultMatrix()." ([n00 n01 n02 n10 n11 n12] (.applyMatrix (current-surface) (float n00) (float n01) (float n02) (float n10) (float n11) (float n12))) ([n00 n01 n02 n03 n10 n11 n12 n13 n20 n21 n22 n23 n30 n31 n32 n33] (.applyMatrix (current-surface) (float n00) (float n01) (float n02) (float 03) (float n10) (float n11) (float n12) (float 13) (float n20) (float n21) (float n22) (float 23) (float n30) (float n31) (float n32) (float 33)))) (defn ^{:requires-bindings true :processing-name "arc()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} arc "Draws an arc in the display window. Arcs are drawn along the outer edge of an ellipse defined by the x, y, width and height parameters. The origin or the arc's ellipse may be changed with the ellipseMode() function. The start and stop parameters specify the angles at which to draw the arc." [x y width height start stop] (.arc (current-surface) (float x)(float y) (float width) (float height) (float start) (float stop))) (defn ^{:requires-bindings false :processing-name "asin()" :category "Math" :subcategory "Trigonometry" :added "1.0"} asin "The inverse of sin, returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2." [n] (PApplet/asin (float n))) (defn ^{:requires-bindings false :processing-name "atan()" :category "Math" :subcategory "Trigonometry" :added "1.0"} atan "The inverse of tan, returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 ." [n] (PApplet/atan (float n))) (defn ^{:requires-bindings false :processing-name "atan2()" :category "Math" :subcategory "Trigonometry" :added "1.0"} atan2 "Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2 function is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent." [y x] (PApplet/atan2 (float y) (float x))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-float "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts args to floats." ([gray] (.background (current-surface) (float gray))) ([gray alpha] (.background (current-surface) (float gray) (float alpha))) ([r g b] (.background (current-surface) (float r) (float g) (float b))) ([r g b a] (.background (current-surface) (float r) (float g) (float b) (float a)))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-int "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts rgb to an int and alpha to a float." ([rgb] (.background (current-surface) (int rgb))) ([rgb alpha] (.background (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts args to floats." ([rgb] (if (int-like? rgb) (background-int rgb) (background-float rgb))) ([rgb alpha] (if (int-like? rgb) (background-int rgb alpha) (background-float rgb alpha))) ([r g b] (background-float r g b)) ([r g b a] (background-float r g b a))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-image "Specify an image to be used as the background for a sketch. Its width and height must be the same size as the sketch window. Images used as background will ignore the current tint setting." [^PImage img] (.background (current-surface) img)) (defn ^{:requires-bindings true :processing-name "beginCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} begin-camera "Sets the matrix mode to the camera matrix so calls such as translate, rotate, apply-matrix and reset-matrix affect the camera. begin-camera should always be used with a following end-camera and pairs of begin-camera and end-camera cannot be nested. For most situations the camera function will be sufficient." [] (.beginCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "endCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} end-camera "Unsets the matrix mode from the camera matrix. See begin-camera." [] (.endCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "beginRaw()" :category "Output" :subcategory "Files" :added "1.0"} begin-raw "Enables the creation of vectors from 3D data. Requires corresponding end-raw command. These commands will grab the shape data just before it is rendered to the screen. At this stage, your entire scene is nothing but a long list of individual lines and triangles. This means that a shape created with sphere method will be made up of hundreds of triangles, rather than a single object. Or that a multi-segment line shape (such as a curve) will be rendered as individual segments." ([^PGraphics raw-gfx] (.beginRaw (current-surface) raw-gfx)) ([^String renderer ^String filename] (.beginRaw (current-applet) renderer filename))) (def ^{:private true} render-modes {:p2d PApplet/P2D :p3d PApplet/P3D :java2d PApplet/JAVA2D :opengl PApplet/OPENGL :pdf PApplet/PDF :dxf PApplet/DXF}) (defn ^{:requires-bindings true :processing-name "beginRecord()" :category "Output" :subcategory "Files" :added "1.0"} begin-record "Opens a new file and all subsequent drawing functions are echoed to this file as well as the display window. The begin-record fn requires two parameters, the first is the renderer and the second is the file name. This function is always used with end-record to stop the recording process and close the file. Note that begin-record will only pick up any settings that happen after it has been called. For instance, if you call text-font before begin-record, then that font will not be set for the file that you're recording to." [renderer filename] (let [renderer (resolve-constant-key renderer render-modes)] (println "renderer: " renderer) (.beginRecord (current-applet) (str renderer) (str filename)))) (defn ^{:requires-bindings true :processing-name "endRecord()" :category "Output" :subcategory "Files" :added "1.0"} end-record "Stops the recording process started by begin-record and closes the file." [] (.endRecord (current-applet))) (def ^{:private true} shape-modes {:points PApplet/POINTS :lines PApplet/LINES :triangles PApplet/TRIANGLES :triangle-strip PApplet/TRIANGLE_STRIP :triangle-fan PApplet/TRIANGLE_FAN :quads PApplet/QUADS :quad-strip PApplet/QUAD_STRIP}) (defn ^{:requires-bindings true :processing-name "beginShape()" :category "Shape" :subcategory "Vertex" :added "1.0"} begin-shape "Enables the creation of complex forms. begin-shape begins recording vertices for a shape and end-shape stops recording. Use the mode keyword to specify which shape create from the provided vertices. With no mode specified, the shape can be any irregular polygon. The available mode keywords are :points, :lines, :triangles, :triangle-fan, :triangle-strip, :quads, :quad-strip. After calling the begin-shape function, a series of vertex commands must follow. To stop drawing the shape, call end-shape. The vertex function with two parameters specifies a position in 2D and the vertex function with three parameters specifies a position in 3D. Each shape will be outlined with the current stroke color and filled with the fill color. Transformations such as translate, rotate, and scale do not work within begin-shape. It is also not possible to use other shapes, such as ellipse or rect within begin-shape." ([] (.beginShape (current-surface))) ([mode] (let [mode (resolve-constant-key mode shape-modes)] (.beginShape (current-surface) (int mode))))) (defn ^{:requires-bindings true :processing-name "bezier()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier "Draws a Bezier curve on the screen. These curves are defined by a series of anchor and control points. The first two parameters specify the first anchor point and the last two parameters specify the other anchor point. The middle parameters specify the control points which define the shape of the curve." ([x1 y1 cx1 cy1 cx2 cy2 x2 y2] (.bezier (current-surface) (float x1) (float y1) (float cx1) (float cy1) (float cx2) (float cy2) (float x2) (float y2))) ([x1 y1 z1 cx1 cy1 cz1 cx2 cy2 cz2 x2 y2 z2] (.bezier (current-surface) (float x1) (float y1) (float z1) (float cx1) (float cy1) (float cz1) (float cx2) (float cy2) (float cz2) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "bezierDetail()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-detail "Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the :p3d or :opengl renderer as the default (:java2d) renderer does not use this information." [detail] (.bezierDetail (current-surface) (int detail))) (defn ^{:requires-bindings true :processing-name "bezierPoint()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-point "Evaluates the Bezier at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b and c are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a bezier curve at t." [a b c d t] (.bezierPoint (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "bezierTangent()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-tangent "Calculates the tangent of a point on a Bezier curve. (See http://en.wikipedia.org/wiki/Tangent)" [a b c d t] (.bezierTangent (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "bezierVertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} bezier-vertex "Specifies vertex coordinates for Bezier curves. Each call to bezier-vertex defines the position of two control points and one anchor point of a Bezier curve, adding a new segment to a line or shape. The first time bezier-vertex is used within a begin-shape call, it must be prefaced with a call to vertex to set the first anchor point. This function must be used between begin-shape and end-shape and only when there is no parameter specified to begin-shape." ([cx1 cy1 cx2 cy2 x y] (.bezierVertex (current-surface) (float cx1) (float cy1) (float cx2) (float cy2) (float x) (float y))) ([cx1 cy1 cz1 cx2 cy2 cz2 x y z] (.bezierVertex (current-surface) (float cx1) (float cy1) (float cz1) (float cx2) (float cy2) (float cz2) (float x) (float y) (float z)))) (defn ^{:require-binding false :processing-name "binary()" :category "Data" :subcategory "Conversion" :added "1.0"} binary "Returns a string representing the binary value of an int, char or byte. When converting an int to a string, it is possible to specify the number of digits used." ([val] (PApplet/binary (if (number? val) (int val) val))) ([val num-digits] (PApplet/binary (int val) (int num-digits)))) (defn ^{:require-binding false :processing-name "unbinary()" :category "Data" :subcategory "Conversion" :added "1.0"} unbinary "Unpack a binary string to an integer. See binary for converting integers to strings." [str-val] (PApplet/unbinary (str str-val))) (def ^{:private true} blend-modes {:blend PApplet/BLEND :add PApplet/ADD :subtract PApplet/SUBTRACT :darkest PApplet/DARKEST :lightest PApplet/LIGHTEST :difference PApplet/DIFFERENCE :exclusion PApplet/EXCLUSION :multiply PApplet/MULTIPLY :screen PApplet/SCREEN :overlay PApplet/OVERLAY :hard-light PApplet/HARD_LIGHT :soft-light PApplet/SOFT_LIGHT :dodge PApplet/DODGE :burn PApplet/BURN}) (defn ^{:requires-bindings true :processing-name "blend()" :category "Color" :subcategory "Pixels" :added "1.0"} blend "Blends a region of pixels from one image into another (or in itself again) with full alpha channel support. Available blend modes are: :blend - linear interpolation of colours: C = A*factor + B :add - additive blending with white clip: C = min(A*factor + B, 255) :subtract - subtractive blending with black clip: C = max(B - A*factor, 0) :darkest - only the darkest colour succeeds: C = min(A*factor, B) :lightest - only the lightest colour succeeds: C = max(A*factor, B) :difference - subtract colors from underlying image. :exclusion - similar to :difference, but less extreme. :multiply - Multiply the colors, result will always be darker. :screen - Opposite multiply, uses inverse values of the colors. :overlay - A mix of :multiply and :screen. Multiplies dark values and screens light values. :hard-light - :screen when greater than 50% gray, :multiply when lower. :soft-light - Mix of :darkest and :lightest. Works like :overlay, but not as harsh. :dodge - Lightens light tones and increases contrast, ignores darks. Called \"Color Dodge\" in Illustrator and Photoshop. :burn - Darker areas are applied, increasing contrast, ignores lights. Called \"Color Burn\" in Illustrator and Photoshop." ([x y width height dx dy dwidth dheight mode] (let [mode (resolve-constant-key mode blend-modes)] (.blend (current-surface) (int x) (int y) (int width) (int height) (int dx) (int dy) (int dwidth) (int dheight) (int mode)))) ([^PImage src x y width height dx dy dwidth dheight mode] (let [mode (resolve-constant-key mode blend-modes)] (.blend (current-surface) src (int x) (int y) (int width) (int height) (int dx) (int dy) (int dwidth) (int dheight) (int mode))))) (defn ^{:requires-bindings false :processing-name "blendColor()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} blend-color "Blends two color values together based on the blending mode given specified with the mode keyword. Available blend modes are: :blend - linear interpolation of colours: C = A*factor + B :add - additive blending with white clip: C = min(A*factor + B, 255) :subtract - subtractive blending with black clip: C = max(B - A*factor, 0) :darkest - only the darkest colour succeeds: C = min(A*factor, B) :lightest - only the lightest colour succeeds: C = max(A*factor, B) :difference - subtract colors from underlying image. :exclusion - similar to :difference, but less extreme. :multiply - Multiply the colors, result will always be darker. :screen - Opposite multiply, uses inverse values of the colors. :overlay - A mix of :multiply and :screen. Multiplies dark values and screens light values. :hard-light - :screen when greater than 50% gray, :multiply when lower. :soft-light - Mix of :darkest and :lightest. Works like :overlay, but not as harsh. :dodge - Lightens light tones and increases contrast, ignores darks. Called \"Color Dodge\" in Illustrator and Photoshop. :burn - Darker areas are applied, increasing contrast, ignores lights. Called \"Color Burn\" in Illustrator and Photoshop." [c1 c2 mode] (let [mode (resolve-constant-key mode blend-modes)] (PApplet/blendColor (int c1) (int c2) (int mode)))) (defn ^{:requires-bindings true :processing-name "blue()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} blue "Extracts the blue value from a color, scaled to match current color-mode. Returns a float." [color] (.blue (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "box()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} box "Creates an extruded rectangle." ([size] (.box (current-surface) (float size))) ([width height depth] (.box (current-surface) (float width) (float height) (float depth)))) (defn ^{:requires-bindings true :processing-name "brightness()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} brightness "Extracts the brightness value from a color. Returns a float." [color] (.brightness (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "camera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} camera "Sets the position of the camera through setting the eye position, the center of the scene, and which axis is facing upward. Moving the eye position and the direction it is pointing (the center of the scene) allows the images to be seen from different angles. The version without any parameters sets the camera to the default position, pointing to the center of the display window with the Y axis as up. The default values are: eyeX: (/ (width) 2.0) eyeY: (/ (height) 2.0) eyeZ: (/ (/ (height) 2.0) (tan (/ (* Math/PI 60.0) 360.0))) centerX: (/ (width) 2.0) centerY: (/ (height) 2.0) centerZ: 0 upX: 0 upY: 1 upZ: 0 Similar imilar to gluLookAt() in OpenGL, but it first clears the current camera settings." ([] (.camera (current-surface))) ([eyeX eyeY eyeZ centerX centerY centerZ upX upY upZ] (.camera (current-surface) (float eyeX) (float eyeY) (float eyeZ) (float centerX) (float centerY) (float centerZ) (float upX) (float upY) (float upZ)))) (defn ^{:requires-bindings false :processing-name "ceil()" :category "Math" :subcategory "Calculation" :added "1.0"} ceil "Calculates the closest int value that is greater than or equal to the value of the parameter. For example, (ceil 9.03) returns the value 10." [n] (PApplet/ceil (float n))) (defn ^{:requires-bindings true :processing-name "color()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} color "Creates an integer representation of a color The parameters are interpreted as RGB or HSB values depending on the current color-mode. The default mode is RGB values from 0 to 255 and therefore, the function call (color 255 204 0) will return a bright yellow. Args are cast to floats. r - red or hue value g - green or saturation value b - blue or brightness value a - alpha value" ([gray] (.color (current-surface) (float gray))) ([gray alpha] (.color (current-surface) (float gray) (float alpha))) ([r g b] (.color (current-surface) (float r) (float g) (float b))) ([r g b a] (.color (current-surface) (float r) (float g) (float b) (float a)))) (def ^{:private true} color-modes {:rgb (int 1) :hsb (int 3)}) (defn ^{:requires-bindings true :processing-name "colorMode()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} color-mode "Changes the way Processing interprets color data. Available modes are :rgb and :hsb.By default, the parameters for fill, stroke, background, and color are defined by values between 0 and 255 using the :rgb color model. The color-mode fn is used to change the numerical range used for specifying colors and to switch color systems. For example, calling (color-mode :rgb 1.0) will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the parameters range1, range2, range3, and range 4." ([mode] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode)))) ([mode max] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max)))) ([mode max-x max-y max-z] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max-x) (float max-y) (float max-z)))) ([mode max-x max-y max-z max-a] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max-x) (float max-y) (float max-z) (float max-a))))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain-float "Constrains a value to not exceed a maximum and minimum value. All args are cast to floats." [amt low high] (PApplet/constrain (float amt) (float low) (float high))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain-int "Constrains a value to not exceed a maximum and minimum value. All args are cast to ints." [amt low high] (PApplet/constrain (int amt) (int low) (int high))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain "Constrains a value to not exceed a maximum and minimum value." [amt low high] (if (int-like? amt) (constrain-int amt low high) (constrain-float amt low high))) (defn ^{:requires-bindings true :processing-name "copy()" :category "Image" :subcategory "Pixels" :added "1.0"} copy "Copies a region of pixels from the display window to another area of the display window and copies a region of pixels from an image used as the src-img parameter into the display window. If the source and destination regions aren't the same size, it will automatically resize the source pixels to fit the specified target region. No alpha information is used in the process, however if the source image has an alpha channel set, it will be copied as well. " ([[sx1 sy1 sx2 sy2] [dx1 dy1 dx2 dy2]] (.copy (current-surface) (int sx1) (int sy1) (int sx2) (int sy2) (int dx1) (int dy1) (int dx2) (int dy2))) ([^PImage img [sx1 sy1 sx2 sy2] [dx1 dy1 dx2 dy2]] (.copy (current-surface) img (int sx1) (int sy1) (int sx2) (int sy2) (int dx1) (int dy1) (int dx2) (int dy2)))) (defn ^{:requires-bindings false :processing-name "cos()" :category "Math" :subcategory "Trigonometry" :added "1.0"} cos "Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to Math/PI*2). Values are returned in the range -1 to 1." [angle] (PApplet/cos (float angle))) (defn ^{:requires-bindings false :processing-name "PFont.list()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} available-fonts "A sequence of strings representing the fonts on this system available for use. Because of limitations in Java, not all fonts can be used and some might work with one operating system and not others. When sharing a sketch with other people or posting it on the web, you may need to include a .ttf or .otf version of your font in the data directory of the sketch because other people might not have the font installed on their computer. Only fonts that can legally be distributed should be included with a sketch." [] (seq (PFont/list))) (defn ^{:requires-bindings false :processing-name nil :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} font-available? "Returns true if font (specified as a string) is available on this system, false otherwise" [font-str] (if (some #{font-str} (available-fonts)) true false)) (defn ^{:requires-bindings true :processing-name "createFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} create-font "Dynamically converts a font to the format used by Processing (a PFont) from either a font name that's installed on the computer, or from a .ttf or .otf file inside the sketches 'data' folder. This function is an advanced feature for precise control. Use available-fonts to obtain the names for the fonts recognized by the computer and are compatible with this function. The size parameter states the font size you want to generate. The smooth parameter specifies if the font should be antialiased or not, and the charset parameter is an array of chars that specifies the characters to generate. This function creates a bitmapped version of a font It loads a font by name, and converts it to a series of images based on the size of the font. When possible, the text function will use a native font rather than the bitmapped version created behind the scenes with create-font. For instance, when using the default renderer setting (JAVA2D), the actual native version of the font will be employed by the sketch, improving drawing quality and performance. With the :p2d, :p3d, and :opengl renderer settings, the bitmapped version will be used. While this can drastically improve speed and appearance, results are poor when exporting if the sketch does not include the .otf or .ttf file, and the requested font is not available on the machine running the sketch." ([name size] (.createFont (current-applet) (str name) (float size))) ([name size smooth] (.createFont (current-applet) (str name) (float size) smooth)) ([name size smooth ^chars charset] (.createFont (current-applet) (str name) (float size) smooth charset))) (def ^{:private true} graphic-render-modes (select-keys render-modes [:p2d :p3d :java2d :pdf])) (defn ^{:requires-bindings true :processing-name "createGraphics()" :category "Rendering" :subcategory nil :added "1.0"} create-graphics "Creates and returns a new PGraphics object of the types :p2d, :p3d, :java2d, :pdf. Use this class if you need to draw into an off-screen graphics buffer. It's not possible to use create-graphics with the :opengl renderer, because it doesn't allow offscreen use. The :pdf renderer requires the filename parameter. It's important to call any drawing commands between begin-draw and end-draw statements. This is also true for any commands that affect drawing, such as smooth or color-mode. Unlike the main drawing surface which is completely opaque, surfaces created with create-graphics can have transparency. This makes it possible to draw into a graphics and maintain the alpha channel. By using save to write a PNG or TGA file, the transparency of the graphics object will be honored. Note that transparency levels are binary: pixels are either complete opaque or transparent. This means that text characters will be opaque blocks." ([w h renderer] (.createGraphics (current-applet) (int w) (int h) (resolve-constant-key renderer graphic-render-modes))) ([w h renderer path] (.createGraphics (current-applet) (int w) (int h) (resolve-constant-key renderer graphic-render-modes) (str path)))) (defn ^{:requires-bindings true :processing-name "createImage()" :category "Image" :subcategory nil :added "1.0"} create-image "Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play with. Set the size of the buffer with the width and height parameters. The format parameter defines how the pixels are stored. See the PImage reference for more information. Be sure to include all three parameters, specifying only the width and height (but no format) will produce a strange error. Prefer using create-image over initialising new PImage instances directly." [w h format] (.createImage (current-applet) (int w) (int h) (int format))) (defn ^{:requires-bindings true :processing-name "createInput()" :category "Input" :subcategory "Files" :added "1.0"} create-input "This is a method for advanced programmers to open a Java InputStream. The method is useful if you want to use the facilities provided by PApplet to easily open files from the data folder or from a URL, but want an InputStream object so that you can use other Java methods to take more control of how the stream is read. If the requested item doesn't exist, null is returned. If not online, this will also check to see if the user is asking for a file whose name isn't properly capitalized. If capitalization is different an error will be printed to the console. This helps prevent issues that appear when a sketch is exported to the web, where case sensitivity matters, as opposed to running from inside the Processing Development Environment on Windows or Mac OS, where case sensitivity is preserved but ignored. The filename passed in can be: - A URL, for instance (open-stream \"http://processing.org/\"; - A file in the sketch's data folder - The full path to a file to be opened locally (when running as an application) If the file ends with .gz, the stream will automatically be gzip decompressed. If you don't want the automatic decompression, use the related function create-input-raw." [filename] (.createInput (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "createInputRaw()" :category "Input" :subcategory "Files" :added "1.0"} create-input-raw "Call create-input without automatic gzip decompression." [filename] (.createInputRaw (current-applet) filename)) (defn ^{:requires-bindings true :processing-name "createOutput()" :category "Output" :subcategory "Files" :added "1.0"} create-output "Similar to create-input, this creates a Java OutputStream for a given filename or path. The file will be created in the sketch folder, or in the same folder as an exported application. If the path does not exist, intermediate folders will be created. If an exception occurs, it will be printed to the console, and null will be returned. This method is a convenience over the Java approach that requires you to 1) create a FileOutputStream object, 2) determine the exact file location, and 3) handle exceptions. Exceptions are handled internally by the function, which is more appropriate for sketch projects. If the output filename ends with .gz, the output will be automatically GZIP compressed as it is written." [filename] (.createOutput (current-applet) (str filename))) (def ^{:private true} cursor-modes {:arrow PConstants/ARROW :cross PConstants/CROSS :hand PConstants/HAND :move PConstants/MOVE :text PConstants/TEXT :wait PConstants/WAIT}) (defn ^{:requires-bindings true :processing-name "cursor()" :category "Environment" :subcategory nil :added "1.0"} cursor "Sets the cursor to a predefined symbol, an image, or makes it visible if already hidden. If you are trying to set an image as the cursor, it is recommended to make the size 16x16 or 32x32 pixels. The values for parameters x and y must be less than the dimensions of the image. Available modes: :arrow, :cross, :hand, :move, :text, :wait Setting or hiding the cursor generally does not work with 'Present' mode (when running full-screen). See cursor-image for specifying a generic image as the cursor symbol." ([] (.cursor (current-applet))) ([cursor-mode] (.cursor (current-applet) (int (resolve-constant-key cursor-mode cursor-modes))))) (defn ^{:requires-bindings true :processing-name "cursor()" :category "Environment" :subcategory nil :added "1.0"} cursor-image "Set the cursor to a predefined image. The horizontal and vertical active spots of the cursor may be specified with hx and hy" ([^PImage img] (.cursor (current-applet) img)) ([^PImage img hx hy] (.cursor (current-applet) img (int hx) (int hy)))) (defn ^{:requires-bindings true :processing-name "curve()" :category "Shape" :subcategory "Curves" :added "1.0"} curve "Draws a curved line on the screen. The first and second parameters specify the beginning control point and the last two parameters specify the ending control point. The middle parameters specify the start and stop of the curve. Longer curves can be created by putting a series of curve fns together or using curve-vertex. An additional fn called curve-tightness provides control for the visual quality of the curve. The curve fn is an implementation of Catmull-Rom splines." ([x1 y1 x2 y2 x3 y3 x4 y4] (.curve (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3) (float x4) (float y4))) ([x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y4 z4] (.curve (current-surface) (float x1) (float y1) (float z1) (float x2) (float y2) (float z2) (float x3) (float y3) (float z3) (float x4) (float y4) (float z4)))) (defn ^{:requires-bindings true :processing-name "curveDetail()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-detail "Sets the resolution at which curves display. The default value is 20. This function is only useful when using the :p3d or :opengl renderer as the default (:java2d) renderer does not use this information." [detail] (.curveDetail (current-surface) (int detail))) (defn ^{:requires-bindings true :processing-name "curvePoint()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-point "Evalutes the curve at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b c and are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a curve at t." [a b c d t] (.bezierPoint (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "curveTangent()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-tangent "Calculates the tangent of a point on a curve. See: http://en.wikipedia.org/wiki/Tangent" [a b c d t] (.curveTangent (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "curveTightness()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-tightness "Modifies the quality of forms created with curve and curve-vertex. The parameter squishy determines how the curve fits to the vertex points. The value 0.0 is the default value for squishy (this value defines the curves to be Catmull-Rom splines) and the value 1.0 connects all the points with straight lines. Values within the range -5.0 and 5.0 will deform the curves but will leave them recognizable and as values increase in magnitude, they will continue to deform." [ti] (.curveTightness (current-surface) (float ti))) (defn ^{:requires-bindings true :processing-name "curveVertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} curve-vertex "Specifies vertex coordinates for curves. This function may only be used between begin-shape and end-shape and only when there is no mode keyword specified to begin-hape. The first and last points in a series of curve-vertex lines will be used to guide the beginning and end of a the curve. A minimum of four points is required to draw a tiny curve between the second and third points. Adding a fifth point with curveVertex will draw the curve between the second, third, and fourth points. The curveVertex function is an implementation of Catmull-Rom splines." ([x y] (.curveVertex (current-surface) (float x) (float y))) ([x y z] (.curveVertex (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings false :processing-name "day()" :category "Input" :subcategory "Time & Date" :added "1.0"} day "Get the current day of the month (1 through 31)." [] (PApplet/day)) (defn ^{:requires-bindings false :processing-name "degrees()" :category "Math" :subcategory "Trigonometry" :added "1.0"} degrees "Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and (* 2 Math/PI) radians in a circle. For example, (= 90째 (/ Math/PI 2) 1.5707964). All trigonometric methods in Processing require their parameters to be specified in radians." [radians] (PApplet/degrees (float radians))) (defn ^{:requires-bindings true :processing-name "delay()" :category "Structure" :subcategory nil :added "1.0"} delay-frame "Forces the program to stop running for a specified time. Delay times are specified in thousandths of a second, therefore the function call (delay 3000) will stop the program for three seconds. Because the screen is updated only at the end of draw, the program may appear to 'freeze', because the screen will not update when the delay fn is used. This function has no affect inside setup." [freeze-ms] (.delay (current-applet) (int freeze-ms))) (defn ^{:requires-bindings true :processing-name "directionalLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} directional-light "Adds a directional light. Directional light comes from one direction and is stronger when hitting a surface squarely and weaker if it hits at a a gentle angle. After hitting a surface, a directional lights scatters in all directions. Lights need to be included in the draw fn to remain persistent in a looping program. Placing them in the setup fn of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The nx, ny, and nz parameters specify the direction the light is facing. For example, setting ny to -1 will cause the geometry to be lit from below (the light is facing directly upward)" [r g b nx ny nz] (.directionalLight (current-surface) (float r) (float g) (float b) (float nx) (float ny) (float nz))) (defn ^{:requires-bindings false :processing-name "dist()" :category "Math" :subcategory "Calculation" :added "1.0"} dist "Calculates the distance between two points" ([x1 y1 x2 y2] (PApplet/dist (float x1) (float y1) (float x2) (float y2))) ([x1 y1 z1 x2 y2 z2] (PApplet/dist (float x1) (float y1) (float z1) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "ellipse()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} ellipse "Draws an ellipse (oval) in the display window. An ellipse with an equal width and height is a circle. The origin may be changed with the ellipse-mode function" [x y width height] (.ellipse (current-surface) (float x) (float y) (float width) (float height))) (def ^{:private true} ellipse-modes {:center PApplet/CENTER :radius PApplet/RADIUS :corner PApplet/CORNER :corners PApplet/CORNERS}) (defn ^{:requires-bindings true :processing-name "ellipseMode()" :category "Shape" :subcategory "Attributes" :added "1.0"} ellipse-mode "Modifies the origin of the ellispse according to the specified mode: :center - specifies the location of the ellipse as the center of the shape. (Default). :radius - similar to center, but the width and height parameters to ellipse specify the radius of the ellipse, rather than the diameter. :corner - draws the shape from the upper-left corner of its bounding box. :corners - uses the four parameters to ellipse to set two opposing corners of the ellipse's bounding box." [mode] (let [mode (resolve-constant-key mode ellipse-modes)] (.ellipseMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive-float "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. Converts all args to floats" ([float-val] (.emissive (current-surface) (float float-val))) ([r g b] (.emissive (current-surface) (float r) (float g) (float b)))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive-int "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. Converts all args to ints" [int-val] (.emissive (current-surface) (int int-val))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. If passed one arg - it is assumed to be an int (i.e. a color), multiple args are converted to floats." ([c] (if (int-like? c) (emissive-int c) (emissive-float c))) ([r g b] (emissive-float r g b))) (defn ^{:requires-bindings true :processing-name "endRaw()" :category "Output" :subcategory "Files" :added "1.0"} end-raw "Complement to begin-raw; they must always be used together. See the begin-raw docstring for details." [] (.endRaw (current-applet))) (defn ^{:requires-bindings true :processing-name "endShape()" :category "Shape" :subcategory "Vertex" :added "1.0"} end-shape "May only be called after begin-shape. When end-shape is called, all of image data defined since the previous call to begin-shape is written into the image buffer. The keyword :close may be passed to close the shape (to connect the beginning and the end)." ([] (.endShape (current-applet))) ([mode] (when-not (= :close mode) (throw (Exception. (str "Unknown mode value: " mode ". Expected :close")))) (.endShape (current-applet) PApplet/CLOSE))) (defn ^{:requires-bindings true :processing-name "exit()" :category "Structure" :subcategory nil :added "1.0"} exit "Quits/stops/exits the program. Rather than terminating immediately, exit will cause the sketch to exit after draw has completed (or after setup completes if called during the setup method). " [] (applet-safe-exit (current-applet))) (defn ^{:requires-bindings false :processing-name "exp()" :category "Math" :subcategory "Calculation" :added "1.0"} exp "Returns Euler's number e (2.71828...) raised to the power of the value parameter." [val] (PApplet/exp (float val))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill-float "Sets the color used to fill shapes. For example, (fill 204 102 0), will specify that all subsequent shapes will be filled with orange." ([gray] (.fill (current-surface) (float gray))) ([gray alpha] (.fill (current-surface) (float gray) (float alpha))) ([r g b] (.fill (current-surface) (float r) (float g) (float b))) ([r g b alpha] (.fill (current-surface) (float r) (float g) (float b) (float alpha)))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill-int "Sets the color used to fill shapes." ([rgb] (.fill (current-surface) (int rgb))) ([rgb alpha] (.fill (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill "Sets the color used to fill shapes." ([rgb] (if (int-like? rgb) (fill-int rgb) (fill-float rgb))) ([rgb alpha] (if (int-like? rgb) (fill-int rgb alpha) (fill-float rgb alpha))) ([r g b] (fill-float r g b)) ([r g b a] (fill-float r g b a))) (def ^{:private true} filter-modes {:threshold PConstants/THRESHOLD :gray PConstants/GRAY :invert PConstants/INVERT :posterize PConstants/POSTERIZE :blur PConstants/BLUR :opaque PConstants/OPAQUE :erode PConstants/ERODE :dilate PConstants/DILATE}) (defn ^{:requires-bindings true :processing-name "filter()" :category "Image" :subcategory "Pixels" :added "1.0"} display-filter "Originally named filter in Processing Language. Filters the display window with the specified mode and level. Level defines the quality of the filter and mode may be one of the following keywords: :threshold - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. :gray - converts any colors in the image to grayscale equivalents :invert - sets each pixel to its inverse value :posterize - limits each channel of the image to the number of colors specified as the level parameter. The level parameter :blur - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1. :opaque - sets the alpha channel to entirely opaque. :erode - reduces the light areas with the amount defined by the level parameter. :dilate - increases the light areas with the amount defined by the level parameter." ([mode] (let [mode (resolve-constant-key mode filter-modes)] (.filter (current-applet) (int mode)))) ([mode level] (let [mode (resolve-constant-key mode filter-modes)] (.filter (current-applet) (int mode) (float level))))) (defn ^{:requires-bindings true :processing-name "focused" :category "Environment" :subcategory nil :added "1.0"} focused "Returns a boolean value representing whether the applet has focus." [] (.-focussed (current-applet))) (defn ^{:requires-bindings true :processing-name "frameCount" :category "Environment" :subcategory nil :added "1.0"} frame-count "The system variable frameCount contains the number of frames displayed since the program started. Inside setup() the value is 0 and and after the first iteration of draw it is 1, etc." [] (.frameCount (current-applet))) (defn ^{:requires-bindings true :processing-name "frameRate" :category "Environment" :subcategory nil :added "1.0"} current-frame-rate "Returns the current framerate" [] (.frameRate (current-applet))) (defn ^{:requires-bindings true :category "Environment" :subcategory nil :added "1.5.0"} target-frame-rate "Returns the target framerate specified with the fn frame-rate" [] @(quil.applet/target-frame-rate)) (defn ^{:requires-bindings true :processing-name "frameRate()" :category "Environment" :subcategory nil :added "1.0"} frame-rate "Specifies a new target framerate (number of frames to be displayed every second). If the processor is not fast enough to maintain the specified rate, it will not be achieved. For example, the function call (frame-rate 30) will attempt to refresh 30 times a second. It is recommended to set the frame rate within setup. The default rate is 60 frames per second." [new-rate] (.frameRate (current-applet) (float new-rate))) (defn ^{:requires-bindings true :processing-name "frustum()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} frustum "Sets a perspective matrix defined through the parameters. Works like glFrustum, except it wipes out the current perspective matrix rather than muliplying itself with it." [left right bottom top near far] (.frustum (current-surface) (float left) (float right) (float bottom) (float top) (float near) (float far))) (defn ^{:requires-bindings true :processing-name "get()" :category "Image" :subcategory "Pixels" :added "1.0"} get-pixel "Reads the color of any pixel or grabs a section of an image. If no parameters are specified, the entire image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display window by specifying an additional width and height parameter. If the pixel requested is outside of the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. For example, even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB. Getting the color of a single pixel with (get x y) is easy, but not as fast as grabbing the data directly using the pixels fn." ([] (.get (current-surface))) ([x y] (.get (current-surface) (int x) (int y))) ([x y w h] (.get (current-surface) (int x) (int y) (int w) (int h)))) (declare load-pixels) (defn ^{:requires-bindings true :processing-name "pixels[]" :category "Image" :subcategory "Pixels" :added "1.0"} pixels "Array containing the values for all the pixels in the display window. This array is therefore the size of the display window. If this array is modified, the update-pixels fn must be called to update the changes. Calls load-pixels before obtaining the pixel array. Only works with P2D and P3D renderer." [] (load-pixels) (.-pixels (current-surface))) (defn ^{:requires-bindings true :processing-name "green()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} green "Extracts the green value from a color, scaled to match current color-mode. This value is always returned as a float so be careful not to assign it to an int value." [col] (.green (current-surface) (int col))) (defn ^{:require-binding false :processing-name "hex()" :category "Data" :subcategory "Conversion"} hex "Converts a byte, char, int, or color to a String containing the equivalent hexadecimal notation. For example color(0, 102, 153) will convert to the String \"FF006699\". This function can help make your geeky debugging sessions much happier. " ([val] (PApplet/hex val)) ([val num-digits] (PApplet/hex (int val) (int num-digits)))) (defn ^{:require-binding false :processing-name "hex()" :category "Data" :subcategory "Conversion"} unhex "Converts a String representation of a hexadecimal number to its equivalent integer value." [hex-str] (PApplet/unhex (str hex-str))) (defn ^{:requires-bindings true :processing-name "height" :category "Environment" :subcategory nil :added "1.0"} height "Height of the display window. The value of height is zero until size is called." [] (.getHeight (current-applet))) (def ^{:private true} hint-options {:enable-opengl-4x-smooth PConstants/ENABLE_OPENGL_4X_SMOOTH :enable-opengl-2x-smooth PConstants/ENABLE_OPENGL_2X_SMOOTH :enable-native-fonts PConstants/ENABLE_NATIVE_FONTS :disable-native-fonts PConstants/DISABLE_NATIVE_FONTS :enable-depth-test PConstants/ENABLE_DEPTH_TEST :disable-depth-test PConstants/DISABLE_DEPTH_TEST :enable-depth-sort PConstants/ENABLE_DEPTH_SORT :disable-depth-sort PConstants/DISABLE_DEPTH_SORT :disable-opengl-error-report PConstants/DISABLE_OPENGL_ERROR_REPORT :enable-opengl-error-report PConstants/ENABLE_OPENGL_ERROR_REPORT :enable-accurate-textures PConstants/ENABLE_ACCURATE_TEXTURES :disable-accurate-textures PConstants/DISABLE_ACCURATE_TEXTURES :disable-depth-mask PConstants/DISABLE_DEPTH_MASK :enable-depth-mask PConstants/ENABLE_DEPTH_MASK}) (defn ^{:requires-bindings true :processing-name "hint()" :category "Rendering" :subcategory nil :added "1.0"} hint "Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be implemented in a consistent manner across renderers. Many options will often graduate to standard features instead of hints over time. Options: :enable-opengl-4x-smooth - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's control panel, however not all cards make this available. This hint must be called immediately after the size command because it resets the renderer, obliterating any settings and anything drawn (and like size(), re-running the code that came before it again). :disable-opengl-2x-smooth - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in earlier releases, where smooth and no-smooth could be used to enable and disable smoothing, though the quality was inferior. :enable-opengl-2x-smooth - Enables default OpenGL smoothing. :enable-native-fonts - Use the native version fonts when they are installed, rather than the bitmapped version from a .vlw file. This is useful with the default (or JAVA2D) renderer setting, as it will improve font rendering speed. This is not enabled by default, because it can be misleading while testing because the type will look great on your machine (because you have the font installed) but lousy on others' machines if the identical font is unavailable. This option can only be set per-sketch, and must be called before any use of text-font. :disable-native-fonts - Disables native font support. :disable-depth-test - Disable the zbuffer, allowing you to draw on top of everything at will. When depth testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with :enable-depth-test but note that with the depth buffer cleared, any 3D drawing that happens later in draw will ignore existing shapes on the screen. :enable-depth-test - Enables the zbuffer. :enable-depth-sort - Enable primitive z-sorting of triangles and lines in :p3d and :opengl rendering modes. This can slow performance considerably, and the algorithm is not yet perfect. :disable-depth-sort - Disables hint :enable-depth-sort :disable-opengl-error-report - Speeds up the OPENGL renderer setting by not checking for errors while running. :enable-opengl-error-report - Turns on OpenGL error checking :enable-accurate-textures :disable-accurate-textures :enable-depth-mask :disable-depth-mask" [hint-type] (let [hint-type (if (keyword? hint-type) (get hint-options hint-type) hint-type)] (.hint (current-surface) (int hint-type)))) (defn ^{:requires-bindings false :processing-name "hour()" :category "Input" :subcategory "Time & Date" :added "1.0"} hour "Returns the current hour as a value from 0 - 23." [] (PApplet/hour)) (defn ^{:requires-bindings true :processing-name "hue()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} hue "Extracts the hue value from a color." [col] (.hue (current-surface) (int col))) (defn ^{:requires-bindings true :processing-name "image()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} image "Displays images to the screen. Processing currently works with GIF, JPEG, and Targa images. The color of an image may be modified with the tint function and if a GIF has transparency, it will maintain its transparency. The img parameter specifies the image to display and the x and y parameters define the location of the image from its upper-left corner. The image is displayed at its original size unless the width and height parameters specify a different size. The image-mode fn changes the way the parameters work. A call to (image-mode :corners) will change the width and height parameters to define the x and y values of the opposite corner of the image. Starting with release 0124, when using the default (JAVA2D) renderer, smooth will also improve image quality of resized images." ([^PImage img x y] (.image (current-surface) img (float x) (float y))) ([^PImage img x y c d] (.image (current-surface) img (float x) (float y) (float c) (float d))) ([^PImage img x y c d u1 v1 u2 v2] (.image (current-surface) img (float x) (float y) (float c) (float d) (float u1) (float v1) (float u2) (float v2)))) (def ^{:private true} image-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER}) (defn ^{:requires-bindings true :processing-name "imageMode()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} image-mode "Modifies the location from which images draw. The default mode is :corner. Available modes are: :corner - specifies the location to be the upper left corner and uses the fourth and fifth parameters of image to set the image's width and height. :corners - uses the second and third parameters of image to set the location of one corner of the image and uses the fourth and fifth parameters to set the opposite corner. :center - draw images centered at the given x and y position." [mode] (let [mode (resolve-constant-key mode image-modes)] (.imageMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "lightFalloff()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} light-falloff "Sets the falloff rates for point lights, spot lights, and ambient lights. The parameters are used to determine the falloff with the following equation: d = distance from light position to vertex position falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * QUADRATIC) Like fill, it affects only the elements which are created after it in the code. The default value is (light-falloff 1.0 0.0 0.0). Thinking about an ambient light with a falloff can be tricky. It is used, for example, if you wanted a region of your scene to be lit ambiently one color and another region to be lit ambiently by another color, you would use an ambient light with location and falloff. You can think of it as a point light that doesn't care which direction a surface is facing." [constant linear quadratic] (.lightFalloff (current-surface) (float constant) (float linear) (float quadratic))) (defn ^{:requires-bindings true :processing-name "lerpColor()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} lerp-color "Calculates a color or colors between two color at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc." [c1 c2 amt] (.lerpColor (current-surface) (int c1) (int c2) (float amt))) (defn ^{:requires-bindings false :processing-name "lerp()" :category "Math" :subcategory "Calculation" :added "1.0"} lerp "Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines." [start stop amt] (PApplet/lerp (float start) (float stop) (float amt))) (defn ^{:requires-bindings true :processing-name "key" :category "Input" :subcategory "Keyboard" :added "1.0"} raw-key "Contains the value of the most recent key on the keyboard that was used (either pressed or released). For non-ASCII keys, use the keyCode variable. The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. Check for both ENTER and RETURN to make sure your program will work for all platforms." [] (.-key (current-applet))) (defn ^{:requires-bindings true :processing-name "keyCode" :category "Input" :subcategory "Keyboard" :added "1.0"} key-code "The variable keyCode is used to detect special keys such as the UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking for these keys, it's first necessary to check and see if the key is coded. This is done with the conditional (= (key) CODED). The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of key-code If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. Check for both ENTER and RETURN to make sure your program will work for all platforms. For users familiar with Java, the values for UP and DOWN are simply shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other keyCode values can be found in the Java KeyEvent reference." [] (.-keyCode (current-applet))) (defn ^{:requires-bindings true :processing-name "keyPressed" :category "Input" :subcategory "Keyboard" :added "1.0"} key-pressed? "true if any key is currently pressed, false otherwise." [] (.-keyPressed (current-applet))) (defn ^{:requires-bindings true :processing-name "lights()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} lights "Sets the default ambient light, directional light, falloff, and specular values. The defaults are: (ambient-light 128 128 128) (directional-light 128 128 128 0 0 -1) (light-falloff 1 0 0) (light-specular 0 0 0). Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop." [] (.lights (current-surface))) (defn ^{:requires-bindings true :processing-name "lightSpecular()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} light-specular "Sets the specular color for lights. Like fill, it affects only the elements which are created after it in the code. Specular refers to light which bounces off a surface in a perferred direction (rather than bouncing in all directions like a diffuse light) and is used for creating highlights. The specular quality of a light interacts with the specular material qualities set through the specular and shininess functions." [r g b] (.lightSpecular (current-surface) (float r) (float g) (float b))) (defn ^{:requires-bindings true :processing-name "line()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} line "Draws a line (a direct path between two points) to the screen. The version of line with four parameters draws the line in 2D. To color a line, use the stroke function. A line cannot be filled, therefore the fill method will not affect the color of a line. 2D lines are drawn with a width of one pixel by default, but this can be changed with the stroke-weight function. The version with six parameters allows the line to be placed anywhere within XYZ space. " ([p1 p2] (apply line (concat p1 p2))) ([x1 y1 x2 y2] (.line (current-surface) (float x1) (float y1) (float x2) (float y2))) ([x1 y1 z1 x2 y2 z2] (.line (current-surface) (float x1) (float y1) (float z1) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "loadBytes()" :category "Input" :subcategory "Files" :added "1.0"} load-bytes "Reads the contents of a file or url and places it in a byte array. The filename parameter can also be a URL to a file found online." [filename] (.loadBytes (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} load-font "Loads a font into a variable of type PFont. To load correctly, fonts must be located in the data directory of the current sketch. To create a font to use with Processing use the create-font fn. Like load-image and other methods that load data, the load-font fn should not be used inside draw, because it will slow down the sketch considerably, as the font will be re-loaded from the disk (or network) on each frame. For most renderers, Processing displays fonts using the .vlw font format, which uses images for each letter, rather than defining them through vector data. When hint :enable-native-fonts is used with the JAVA2D renderer, the native version of a font will be used if it is installed on the user's machine. Using create-font (instead of load-font) enables vector data to be used with the JAVA2D (default) renderer setting. This can be helpful when many font sizes are needed, or when using any renderer based on JAVA2D, such as the PDF library." [filename] (.loadFont (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadImage()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} load-image "Loads an image into a variable of type PImage. Four types of images ( .gif, .jpg, .tga, .png) images may be loaded. To load correctly, images must be located in the data directory of the current sketch. In most cases, load all images in setup to preload them at the start of the program. Loading images inside draw will reduce the speed of a program. The filename parameter can also be a URL to a file found online. The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to load-image. If an image is not loaded successfully, the null value is returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from load-image is nil. Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because load-image will attempt to interpret the HTML as image data." [filename] (.loadImage (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadPixels()" :category "Image" :subcategory "Pixels" :added "1.0"} load-pixels "Loads the pixel data for the display window into the pixels[] array. This function must always be called before reading from or writing to pixels. Certain renderers may or may not seem to require load-pixels or update-pixels. However, the rule is that any time you want to manipulate the pixels array, you must first call load-pixels, and after changes have been made, call updatePixels. Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change." [] (.loadPixels (current-surface))) (defn ^{:requires-bindings true :processing-name "loadShape()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} load-shape "Load a geometry from a file as a PShape." [filename] (.loadShape (current-applet) filename)) (defn ^{:requires-bindings true :processing-name "loadStrings()" :category "Input" :subcategory "Files" :added "1.0"} load-strings "Load data from a file and shove it into a String array." [filename] (.loadStrings (current-applet) filename)) (defn ^{:requires-bindings false :processing-name "log()" :category "Math" :subcategory "Calculation" :added "1.0"} log "Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the values greater than 0.0." [val] (PApplet/log (float val))) (defn ^{:requires-bindings true :processing-name "loop()" :category "Structure" :subcategory nil :added "1.0"} start-loop "Causes Processing to continuously execute the code within draw. If no-loop is called, the code in draw stops executing." [] (.loop (current-applet))) (defn ^{:requires-bindings false :processing-name "mag()" :category "Math" :subcategory "Calculation" :added "1.0"} mag "Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no start position, the magnitude of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. Therefore, mag is a shortcut for writing (dist 0 0 x y)." ([a b] (PApplet/mag (float a) (float b))) ([a b c] (PApplet/mag (float a) (float b) (float c)))) (defn ^{:requires-bindings false :processing-name "map()" :category "Math" :subcategory "Calculation" :added "1.0"} map-range "Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful." [val low1 high1 low2 high2] (PApplet/map (float val) (float low1) (float high1) (float low2) (float high2))) (defn ^{:requires-bindings false :processing-name nil :category "Image" :subcategory "Loading & Displaying" :added "1.0"} mask-image "Masks part of an image from displaying by loading another image and using it as an alpha channel. This mask image should only contain grayscale data, but only the blue color channel is used. The mask image needs to be the same size as the image to which it is applied. This method is useful for creating dynamically generated alpha masks." [^PImage img] (.mask (current-surface) img)) (defn ^{:requires-bindings true :processing-name "millis()" :category "Input" :subcategory "Time & Date" :added "1.0"} millis "Returns the number of milliseconds (thousandths of a second) since starting the sketch. This information is often used for timing animation sequences." [] (.millis (current-applet))) (defn ^{:requires-bindings false :processing-name "minute()" :category "Input" :subcategory "Time & Date" :added "1.0"} minute "Returns the current minute as a value from 0 - 59" [] (PApplet/minute)) (defn ^{:requires-bindings true :processing-name "modelX()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-x "Returns the three-dimensional x, y, z position in model space. This returns the x value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The x value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "modelY()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-y "Returns the three-dimensional x, y, z position in model space. This returns the y value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The y value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelY (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "modelZ()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-z "Returns the three-dimensional x, y, z position in model space. This returns the z value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The z value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelZ (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings false :processing-name "month()" :category "Input" :subcategory "Time & Date" :added "1.0"} month "Returns the current month as a value from 1 - 12." [] (PApplet/month)) (defn ^{:requires-bindings true :processing-name "mouseButton" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-button "The value of the system variable mouseButton is either :left, :right, or :center depending on which button is pressed." [] (let [button-code (.-mouseButton (current-applet))] (condp = button-code PConstants/LEFT :left PConstants/RIGHT :right PConstants/CENTER :center))) (defn ^{:requires-bindings true :processing-name "mousePressed" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-state "Variable storing if a mouse button is pressed. The value of the system variable mousePressed is true if a mouse button is pressed and false if a button is not pressed." [] (.-mousePressed (current-applet))) (defn ^{:requires-bindings true :processing-name "mouseX" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-x "Current horizontal coordinate of the mouse." [] (.-mouseX (current-applet))) (defn ^{:requires-bindings true :processing-name "mouseY" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-y "Current vertical coordinate of the mouse." [] (.-mouseY (current-applet))) (defn ^{:requires-bindings true :processing-name "pmouseX" :category "Input" :subcategory "Mouse" :added "1.0"} pmouse-x "Horizontal coordinate of the mouse in the previous frame" [] (.-pmouseX (current-applet))) (defn ^{:requires-bindings true :processing-name "pmouseY" :category "Input" :subcategory "Mouse" :added "1.0"} pmouse-y "Vertical coordinate of the mouse in the previous frame" [] (.-pmouseY (current-applet))) (defn ^{:requires-bindings true :processing-name "noCursor()" :category "Environment" :subcategory nil :added "1.0"} no-cursor "Hides the cursor from view. Will not work when running the in full screen (Present) mode." [] (.noCursor (current-applet))) (defn ^{:requires-bindings true :processing-name "noFill()" :category "Color" :subcategory "Setting" :added "1.0"} no-fill "Disables filling geometry. If both no-stroke and no-fill are called, nothing will be drawn to the screen." [] (.noFill (current-surface))) (defn ^{:requires-bindings true :processing-name "noise()" :category "Math" :subcategory "Random" :added "1.0"} noise "Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random function. It was invented by <NAME> in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. The main difference to the random function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program). The resulting value will always be between 0.0 and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The noise value can be animated by moving through the noise space and the 2nd and 3rd dimensions can also be interpreted as time. The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result. Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use." ([x] (.noise (current-applet) (float x))) ([x y] (.noise (current-applet) (float x) (float y))) ([x y z] (.noise (current-applet) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "noiseDetail()" :category "Math" :subcategory "Random" :added "1.0"} noise-detail "Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overal intensity of the noise, whereas higher octaves create finer grained details in the noise sequence. By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise. By changing these parameters, the signal created by the noise function can be adapted to fit very specific needs and characteristics." ([octaves] (.noiseDetail (current-applet) (int octaves))) ([octaves falloff] (.noiseDetail (current-applet) (int octaves) (float falloff)))) (defn ^{:requires-bindings true :processing-name "noiseSeed()" :category "Math" :subcategory "Random" :added "1.0"} noise-seed "Sets the seed value for noise. By default, noise produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run." [val] (.noiseSeed (current-applet) (int val))) (defn ^{:requires-bindings true :processing-name "noLights()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} no-lights "Disable all lighting. Lighting is turned off by default and enabled with the lights fn. This function can be used to disable lighting so that 2D geometry (which does not require lighting) can be drawn after a set of lighted 3D geometry." [] (.noLights (current-surface))) (defn ^{:requires-bindings true :processing-name "noLoop()" :category "Structure" :subcategory nil :added "1.0"} no-loop "Stops Processing from continuously executing the code within draw. If start-loop is called, the code in draw will begin to run continuously again. If using no-loop in setup, it should be the last line inside the block. When no-loop is used, it's not possible to manipulate or access the screen inside event handling functions such as mouse-pressed or key-pressed. Instead, use those functions to call redraw or loop which will run draw, which can update the screen properly. This means that when no-loop has been called, no drawing can happen, and functions like save-frame or load-pixels may not be used. Note that if the sketch is resized, redraw will be called to update the sketch, even after no-oop has been specified. Otherwise, the sketch would enter an odd state until loop was called." [] (.noLoop (current-applet))) (defn ^{:requires-bindings true :processing-name "norm()" :category "Math" :subcategory "Calculation" :added "1.0"} norm "Normalize a value to exist between 0 and 1 (inclusive)." [val start stop] (PApplet/norm (float val) (float start) (float stop))) (defn ^{:requires-bindings true :processing-name "normal()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} normal "Sets the current normal vector. This is for drawing three dimensional shapes and surfaces and specifies a vector perpendicular to the surface of the shape which determines how lighting affects it. Processing attempts to automatically assign normals to shapes, but since that's imperfect, this is a better option when you want more control. This function is identical to glNormal3f() in OpenGL." [nx ny nz] (.normal (current-surface) (float nx) (float ny) (float nz))) (defn ^{:requires-bindings true :processing-name "noSmooth()" :category "Shape" :subcategory "Attributes" :added "1.0"} no-smooth "Draws all geometry with jagged (aliased) edges." [] (.noSmooth (current-surface))) (defn ^{:requires-bindings true :processing-name "noStroke()" :category "Color" :subcategory "Setting" :added "1.0"} no-stroke "Disables drawing the stroke (outline). If both no-stroke and no-fill are called, nothing will be drawn to the screen." [] (.noStroke (current-surface))) (defn ^{:requires-bindings true :processing-name "noTint()" :category "Color" :subcategory "Loading & Displaying" :added "1.0"} no-tint "Removes the current fill value for displaying images and reverts to displaying images with their original hues." [] (.noTint (current-surface))) (defn ^{:requires-bindings true :processing-name "ortho()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} ortho "Sets an orthographic projection and defines a parallel clipping volume. All objects with the same dimension appear the same size, regardless of whether they are near or far from the camera. The parameters to this function specify the clipping volume where left and right are the minimum and maximum x values, top and bottom are the minimum and maximum y values, and near and far are the minimum and maximum z values. If no parameters are given, the default is used: ortho(0, width, 0, height, -10, 10)." ([] (.ortho (current-surface))) ([left right bottom top near far] (.ortho (current-surface) (float left) (float right) (float bottom) (float top) (float near) (float far)))) (defn ^{:requires-bindings true :processing-name "perspective()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} perspective "Sets a perspective projection applying foreshortening, making distant objects appear smaller than closer ones. The parameters define a viewing volume with the shape of truncated pyramid. Objects near to the front of the volume appear their actual size, while farther objects appear smaller. This projection simulates the perspective of the world more accurately than orthographic projection. The version of perspective without parameters sets the default perspective and the version with four parameters allows the programmer to set the area precisely. The default values are: perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));" ([] (.perspective (current-surface))) ([fovy aspect z-near z-far] (.perspective (current-surface) (float fovy) (float aspect) (float z-near) (float z-far)))) (defn ^{:requires-bindings true :processing-name "point()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} point "Draws a point, a coordinate in space at the dimension of one pixel. The first parameter is the horizontal value for the point, the second value is the vertical value for the point, and the optional third value is the depth value. Drawing this shape in 3D using the z parameter requires the :P3D or :opengl renderer to be used." ([x y] (.point (current-surface) (float x)(float y))) ([x y z] (.point (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "pointLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} point-light "Adds a point light. Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The x, y, and z parameters set the position of the light" [r g b x y z] (.pointLight (current-surface) (float r) (float g) (float b) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "popMatrix()" :category "Transform" :subcategory nil :added "1.0"} pop-matrix "Pops the current transformation matrix off the matrix stack. Understanding pushing and popping requires understanding the concept of a matrix stack. The push-matrix fn saves the current coordinate system to the stack and pop-matrix restores the prior coordinate system. push-matrix and pop-matrix are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations." [] (.popMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "popStyle()" :category "Structure" :subcategory nil :added "1.0"} pop-style "Restores the prior settings on the 'style stack'. Used in conjunction with push-style. Together they allow you to change the style settings and later return to what you had. When a new style is started with push-style, it builds on the current style information. The push-style and pop-style functions can be nested to provide more control" [] (.popStyle (current-surface))) (defn ^{:requires-bindings false :processing-name "pow()" :category "Math" :subcategory "Calculation" :added "1.0"} pow "Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocal) in large quantities. For example, (pow 3 5) is equivalent to the expression (* 3 3 3 3 3) and (pow 3 -5) is equivalent to (/ 1 (* 3 3 3 3 3))." [num exponent] (PApplet/pow (float num) (float exponent))) (defn ^{:requires-bindings true :processing-name "printCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} print-camera "Prints the current camera matrix to std out. Useful for debugging." [] (.printCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "printMatrix()" :category "Transform" :subcategory nil :added "1.0"} print-matrix "Prints the current matrix to std out. Useful for debugging." [] (.printMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "printProjection()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} print-projection "Prints the current projection matrix to std out. Useful for debugging" [] (.printProjection (current-surface))) (defn ^{:requires-bindings true :processing-name "pushMatrix()" :category "Transform" :subcategory nil :added "1.0"} push-matrix "Pushes the current transformation matrix onto the matrix stack. Understanding push-matrix and pop-matrix requires understanding the concept of a matrix stack. The push-matrix function saves the current coordinate system to the stack and pop-matrix restores the prior coordinate system. push-matrix and pop-matrix are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations." [] (.pushMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "pushStyle()" :category "Structure" :subcategory nil :added "1.0"} push-style "Saves the current style settings onto a 'style stack'. Use with pop-style which restores the prior settings. Note that these functions are always used together. They allow you to change the style settings and later return to what you had. When a new style is started with push-style, it builds on the current style information. The push-style and pop-style fns can be embedded to provide more control. The style information controlled by the following functions are included in the style: fill, stroke, tint, stroke-weight, stroke-cap, stroke-join, image-mode, rect-mode, ellipse-mode, shape-mode, color-mode, text-align, text-font, text-mode, text-size, text-leading, emissive, specular, shininess, and ambient" [] (.pushStyle (current-surface))) (defn ^{:requires-bindings true :processing-name "quad()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} quad "A quad is a quadrilateral, a four sided polygon. It is similar to a rectangle, but the angles between its edges are not constrained to be ninety degrees. The first pair of parameters (x1,y1) sets the first vertex and the subsequent pairs should proceed clockwise or counter-clockwise around the defined shape." [x1 y1 x2 y2 x3 y3 x4 y4] (.quad (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3) (float x4) (float y4))) (defn ^{:requires-bindings false :processing-name "radians()" :category "Math" :subcategory "Trigonometry" :added "1.0"} radians "Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90째 = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians." [degrees] (PApplet/radians (float degrees))) (defn ^{:requires-bindings true :processing-name "random()" :category "Math" :subcategory "Random" :added "1.0"} random "Generates random numbers. Each time the random function is called, it returns an unexpected value within the specified range. If one parameter is passed to the function it will return a float between zero and the value of the high parameter. The function call (random 5) returns values between 0 and 5 (starting at zero, up to but not including 5). If two parameters are passed, it will return a float with a value between the the parameters. The function call (random -5 10.2) returns values starting at -5 up to (but not including) 10.2." ([max] (.random (current-applet) (float max))) ([min max] (.random (current-applet) (float min) (float max)))) (defn ^{:requires-bindings true :processing-name "randomSeed()" :category "Math" :subcategory "Random" :added "1.0"} random-seed "Sets the seed value for random. By default, random produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run." [w] (.randomSeed (current-applet) (float w))) (defn ^{:requires-bindings true :processing-name "rect()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} rect "Draws a rectangle to the screen. A rectangle is a four-sided shape with every angle at ninety degrees. By default, the first two parameters set the location of the upper-left corner, the third sets the width, and the fourth sets the height. These parameters may be changed with rect-mode." [x y width height] (.rect (current-surface) (float x) (float y) (float width) (float height))) (def ^{:private true} rect-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER :radius PApplet/RADIUS}) (defn ^{:requires-bindings true :processing-name "rectMode()" :category "Shape" :subcategory "Attributes" :added "1.0"} rect-mode "Modifies the location from which rectangles draw. The default mode is :corner. Available modes are: :corner - Specifies the location to be the upper left corner of the shape and uses the third and fourth parameters of rect to specify the width and height. :corners - Uses the first and second parameters of rect to set the location of one corner and uses the third and fourth parameters to set the opposite corner. :center - Draws the image from its center point and uses the third and forth parameters of rect to specify the image's width and height. :radius - Draws the image from its center point and uses the third and forth parameters of rect() to specify half of the image's width and height." [mode] (let [mode (resolve-constant-key mode rect-modes)] (.rectMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "red()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} red "Extracts the red value from a color, scaled to match current color-mode." [c] (.red (current-surface) (int c))) (defn ^{:requires-bindings true :processing-name "redraw()" :category "Structure" :subcategory nil :added "1.0"} redraw "Executes the code within the draw fn one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mouse-pressed or key-pressed occurs. In structuring a program, it only makes sense to call redraw within events such as mouse-pressed. This is because redraw does not run draw immediately (it only sets a flag that indicates an update is needed). Calling redraw within draw has no effect because draw is continuously called anyway." [] (.redraw (current-applet))) (defn ^{:requires-bindings true :processing-name "requestImage()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} request-image "This function load images on a separate thread so that your sketch does not freeze while images load during setup. While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1. You'll know when the image has loaded properly because its width and height will be greater than 0. Asynchronous image loading (particularly when downloading from a server) can dramatically improve performance. The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to request-image." ([filename] (.requestImage (current-applet) (str filename))) ([filename extension] (.requestImage (current-applet) (str filename) (str extension)))) (defn ^{:requires-bindings true :processing-name "resetMatrix()" :category "Transform" :subcategory nil :added "1.0"} reset-matrix "Replaces the current matrix with the identity matrix. The equivalent function in OpenGL is glLoadIdentity()" [] (.resetMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "rotate()" :category "Transform" :subcategory nil :added "1.0"} rotate "Rotates a shape the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO-PI) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate HALF-PI) and then (rotate HALF-PI) is the same as (rotate PI). All tranformations are reset when draw begins again. Technically, rotate multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix." ([angle] (.rotate (current-surface) (float angle))) ([angle vx vy vz] (.rotate (current-surface) (float angle) (float vx) (float vy) (float vz)))) (defn ^{:requires-bindings true :processing-name "rotateX()" :category "Transform" :subcategory nil :added "1.0"} rotate-x "Rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-x HALF-PI) and then (rotate-x HALF-PI) is the same as (rotate-x PI). If rotate-x is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateX (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "rotateY()" :category "Transform" :subcategory nil :added "1.0"} rotate-y "Rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-y HALF-PI) and then (rotate-y HALF-PI) is the same as (rotate-y PI). If rotate-y is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateY (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "rotateZ()" :category "Transform" :subcategory nil :added "1.0"} rotate-z "Rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-z HALF-PI) and then (rotate-z HALF-PI) is the same as (rotate-z PI). If rotate-y is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateZ (current-surface) (float angle))) (defn ^{:requires-bindings false :processing-name "round()" :category "Math" :subcategory "Calculation" :added "1.0"} round "Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9." [val] (PApplet/round (float val))) (defn ^{:requires-bindings true :processing-name "saturation()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} saturation "Extracts the saturation value from a color." [c] (.saturation (current-surface) (int c))) (defn ^{:requires-bindings true :processing-name "save()" :category "Output" :subcategory "Image" :added "1.0"} save "Saves an image from the display window. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on the extension within the filename parameter. For example, image.tif will have a TIFF image and image.png will save a PNG image. If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name. All images saved from the main drawing window will be opaque. To save images without a background, use create-graphics." [filename] (.save (current-surface) (str filename))) (defn ^{:requires-bindings true :processing-name "saveFrame()" :category "Output" :subcategory "Image" :added "1.0"} save-frame "Saves an image identical to the current display window as a file. May be called multple times - each file saved will have a unique name. Name and image formate may be modified by passing a string parameter of the form \"foo-####.ext\" where foo- can be any arbitrary string, #### will be replaced with the current frame id and .ext is one of .tiff, .targa, .png, .jpeg or .jpg Examples: (save-frame) (save-frame \"pretty-pic-####.jpg\")" ([] (.saveFrame (current-applet))) ([name] (.saveFrame (current-applet) (str name)))) (defn ^{:requires-bindings true :processing-name "scale()" :category "Transform" :subcategory nil :added "1.0"} scale "Increases or decreases the size of a shape by expanding and contracting vertices. Objects always scale from their relative origin to the coordinate system. Scale values are specified as decimal percentages. For example, the function call (scale 2) increases the dimension of a shape by 200%. Transformations apply to everything that happens after and subsequent calls to the function multiply the effect. For example, calling (scale 2) and then (scale 1.5) is the same as (scale 3). If scale is called within draw, the transformation is reset when the loop begins again. Using this fuction with the z parameter requires specfying :p3d or :opengl as the renderer. This function can be further controlled by push-matrix and pop-matrix." ([s] (.scale (current-surface) (float s))) ([sx sy] (.scale (current-surface) (float sx) (float sy)))) (defn- current-screen [] (let [default-toolkit (java.awt.Toolkit/getDefaultToolkit)] (.getScreenSize default-toolkit))) (def ^{:private true} orig-screen-width (let [screen (current-screen)] (.width screen))) (defn ^{:requires-bindings false :processing-name "screen.width" :category "Environment" :subcategory nil :added "1.0"} screen-width "Returns the width of the main screen in pixels." [] orig-screen-width) (def ^{:private true} orig-screen-height (let [screen (current-screen)] (.height screen))) (defn ^{:requires-bindings false :processing-name "screen.height" :category "Environment" :subcategory nil :added "1.0"} screen-height "Returns the height of the main screen in pixels." [] orig-screen-height) (defn ^{:requires-bindings true :processing-name "screenX()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-x "Takes a three-dimensional x, y, z position and returns the x value for where it will appear on a (two-dimensional) screen, once affected by translate, scale or any other transformations" [x y z] (.screenX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "screenY()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-y "Takes a three-dimensional x, y, z position and returns the y value for where it will appear on a (two-dimensional) screen, once affected by translate, scale or any other transformations" [x y z] (.screenY (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "screenZ()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-z "Given an x, y, z coordinate, returns its z value. This value can be used to determine if an x, y, z coordinate is in front or in back of another (x, y, z) coordinate. The units are based on how the zbuffer is set up, and don't relate to anything 'real'. They're only useful for in comparison to another value obtained from screen-z, or directly out of the zbuffer" [x y z] (.screenX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings false :processing-name "seconds()" :category "Input" :subcategory "Time & Date" :added "1.0"} seconds "Returns the current second as a value from 0 - 59." [] (PApplet/second)) (defn ^{:requires-bindings true :processing-name "set()" :category "Image" :subcategory "Pixels" :added "1.0"} set-pixel "Changes the color of any pixel in the display window. The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). Setting the color of a single pixel with (set x, y) is easy, but not as fast as putting the data directly into pixels[]. This function ignores imageMode(). Due to what appears to be a bug in Apple's Java implementation, the point() and set() methods are extremely slow in some circumstances when used with the default renderer. Using :p2d or :p3d will fix the problem. Grouping many calls to point or set-pixel together can also help. (Bug 1094)" [x y c] (.set (current-surface) (int x) (int y) (int c))) (defn ^{:requires-bindings true :processing-name "set()" :category "Image" :subcategory "Pixels" :added "1.0"} set-image "Writes an image directly into the display window. The x and y parameters define the coordinates for the upper-left corner of the image." [x y ^PImage src] (.set (current-surface) (int x) (int y) src)) (defn ^{:requires-bindings true :processing-name "shape()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} shape "Displays shapes to the screen. The shapes must have been loaded with load-shape. Processing currently works with SVG shapes only. The sh parameter specifies the shape to display and the x and y parameters define the location of the shape from its upper-left corner. The shape is displayed at its original size unless the width and height parameters specify a different size. The shape-mode fn changes the way the parameters work. A call to (shape-mode :corners), for example, will change the width and height parameters to define the x and y values of the opposite corner of the shape. Note complex shapes may draw awkwardly with the renderers :p2d, :p3d, and :opengl. Those renderers do not yet support shapes that have holes or complicated breaks." ([^PShape sh] (.shape (current-surface) sh)) ([^PShape sh x y] (.shape (current-surface) sh (float x) (float y))) ([^PShape sh x y width height] (.shape (current-surface) sh (float x) (float y) (float width) (float height)))) (defn ^{:requires-bindings true :processing-name "shearX()" :category "Transform" :subcategory nil :added "1.0"} shear-x "Shears a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. Objects are always sheared around their relative position to the origin and positive numbers shear objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (shear-x (/ PI 2)) and then (shear-x (/ PI 2)) is the same as (shear-x PI). If shear-x is called within the draw fn, the transformation is reset when the loop begins again. This function works in P2D or JAVA2D mode. Technically, shear-x multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix fns." [angle] (.shearX (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "shearY()" :category "Transform" :subcategory nil :added "1.0"} shear-y "Shears a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. Objects are always sheared around their relative position to the origin and positive numbers shear objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (shear-y (/ PI 2)) and then (shear-y (/ PI 2)) is the same as (shear-y PI). If shear-y is called within the draw fn, the transformation is reset when the loop begins again. This function works in P2D or JAVA2D mode. Technically, shear-y multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix fns." [angle] (.shearY (current-surface) (float angle))) (def ^{:private true} p-shape-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER}) (defn ^{:requires-bindings true :processing-name "shapeMode()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} shape-mode "Modifies the location from which shapes draw. Available modes are :corner, :corners and :center. Default is :corner. :corner - specifies the location to be the upper left corner of the shape and uses the third and fourth parameters of shape to specify the width and height. :corners - uses the first and second parameters of shape to set the location of one corner and uses the third and fourth parameters to set the opposite corner. :center - draws the shape from its center point and uses the third and forth parameters of shape to specify the width and height. " [mode] (let [mode (resolve-constant-key mode p-shape-modes)] (.shapeMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "shininess()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} shininess "Sets the amount of gloss in the surface of shapes. Used in combination with ambient, specular, and emissive in setting the material properties of shapes." [shine] (.shininess (current-surface) (float shine))) (defn ^{:requires-bindings false :processing-name "sin()" :category "Math" :subcategory "Trigonometry" :added "1.0"} sin "Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to 6.28). A float within the range -1 to 1 is returned." [angle] (PApplet/sin (float angle))) (defn size "Not supported. Use :size key in applet or defapplet" [& args] (println "Deprecated - size should be specified as a :size key to applet or defapplet") nil) (defn ^{:requires-bindings true :processing-name "smooth()" :category "Shape" :subcategory "Attributes" :added "1.0"} smooth "Draws all geometry with smooth (anti-aliased) edges. This will slow down the frame rate of the application, but will enhance the visual refinement. Note that smooth will also improve image quality of resized images." [] (.smooth (current-surface))) (defn ^{:requires-bindings true :processing-name "specular()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} specular "Sets the specular color of the materials used for shapes drawn to the screen, which sets the color of hightlights. Specular refers to light which bounces off a surface in a perferred direction (rather than bouncing in all directions like a diffuse light). Used in combination with emissive, ambient, and shininess in setting the material properties of shapes." ([gray] (.specular (current-surface) (float gray))) ([gray alpha] (.specular (current-surface) (float gray) (float alpha))) ([x y z] (.specular (current-surface) (float x) (float y) (float z))) ([x y z a] (.specular (current-surface) (float x) (float y) (float z) (float a)))) (defn ^{:requires-bindings true :processing-name "sphere()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} sphere "Genarates a hollow ball made from tessellated triangles." [radius] (.sphere (current-surface) (float radius))) (defn ^{:requires-bindings true :processing-name "sphereDetail()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} sphere-detail "Controls the detail used to render a sphere by adjusting the number of vertices of the sphere mesh. The default resolution is 30, which creates a fairly detailed sphere definition with vertices every 360/30 = 12 degrees. If you're going to render a great number of spheres per frame, it is advised to reduce the level of detail using this function. The setting stays active until sphere-detail is called again with a new parameter and so should not be called prior to every sphere statement, unless you wish to render spheres with different settings, e.g. using less detail for smaller spheres or ones further away from the camera. To controla the detail of the horizontal and vertical resolution independently, use the version of the functions with two parameters." ([res] (.sphereDetail (current-surface) (int res))) ([ures vres] (.sphereDetail (current-surface) (int ures) (int vres)))) (defn ^{:requires-bindings true :processing-name "spotLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} spot-light "Adds a spot light. Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The x, y, and z parameters specify the position of the light and nx, ny, nz specify the direction or light. The angle parameter affects angle of the spotlight cone." ([r g b x y z nx ny nz angle concentration] (.spotLight (current-surface) r g b x y z nx ny nz angle concentration)) ([[r g b] [x y z] [nx ny nz] angle concentration] (.spotLight (current-surface) r g b x y z nx ny nz angle concentration))) (defn ^{:requires-bindings false :processing-name "sq()" :category "Math" :subcategory "Calculation" :added "1.0"} sq "Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1." [a] (PApplet/sq (float a))) (defn ^{:requires-bindings false :processing-name "sqrt()" :category "Math" :subcategory "Calculation" :added "1.0"} sqrt "Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that (= a (* s s)) . It is the opposite of squaring." [a] (PApplet/sqrt (float a))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke-float "Sets the color used to draw lines and borders around shapes. Converts all args to floats" ([gray] (.stroke (current-surface) (float gray))) ([gray alpha] (.stroke (current-surface) (float gray) (float alpha))) ([x y z] (.stroke (current-surface) (float x) (float y) (float z))) ([x y z a] (.stroke (current-surface) (float x) (float y) (float z) (float a)))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke-int "Sets the color used to draw lines and borders around shapes. Converts rgb to int and alpha to a float." ([rgb] (.stroke (current-surface) (int rgb))) ([rgb alpha] (.stroke (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke "Sets the color used to draw lines and borders around shapes. This color is either specified in terms of the RGB or HSB color depending on the current color-mode (the default color space is RGB, with each value in the range from 0 to 255)." ([rgb] (if (int-like? rgb) (stroke-int rgb) (stroke-float rgb))) ([rgb alpha] (if (int-like? rgb) (stroke-int rgb alpha) (stroke-float rgb alpha))) ([x y z] (stroke-float x y z)) ([x y z a] (stroke-float x y z a))) (def ^{:private true} stroke-cap-modes {:square PApplet/SQUARE :round PApplet/ROUND :project PApplet/PROJECT :model PApplet/MODEL}) (defn ^{:requires-bindings true :processing-name "strokeCap()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-cap "Sets the style for rendering line endings. These ends are either squared, extended, or rounded and specified with the corresponding parameters :square, :project, and :round. The default cap is :round." [cap-mode] (let [cap-mode (resolve-constant-key cap-mode stroke-cap-modes)] (.strokeCap (current-surface) (int cap-mode)))) (def ^{:private true} stroke-join-modes {:miter PConstants/MITER :bevel PConstants/BEVEL :round PConstants/ROUND}) (defn ^{:requires-bindings true :processing-name "strokeJoin()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-join "Sets the style of the joints which connect line segments. These joints are either mitered, beveled, or rounded and specified with the corresponding parameters :miter, :bevel, and :round. The default joint is :miter. This function is not available with the :p2d, :p3d, or :opengl renderers." [join-mode] (let [join-mode (resolve-constant-key join-mode stroke-join-modes)] (.strokeJoin (current-surface) (int join-mode)))) (defn ^{:requires-bindings true :processing-name "strokeWeight()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-weight "Sets the width of the stroke used for lines, points, and the border around shapes. All widths are set in units of pixels. " [weight] (.strokeWeight (current-surface) (float weight))) (defn ^{:requires-bindings false :processing-name "tan()" :category "Math" :subcategory "Trigonometry" :added "1.0"} tan "Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity." [angle] (PApplet/tan (float angle))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-char "Draws a char to the screen in the specified position. See text fn for more details." ([c] (.text (current-surface) (char c))) ([c x y] (.text (current-surface) (char c) (float x) (float y))) ([c x y z] (.text (current-surface) (char c) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-num "Draws a number to the screen in the specified position. See text fn for more details." ([num x y] (.text (current-surface) (float num) (float x) (float y))) ([num x y z] (.text (current-surface) (float num) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text "Draws text to the screen in the position specified by the x and y parameters and the optional z parameter. A default font will be used unless a font is set with the text-font fn. Change the color of the text with the fill fn. The text displays in relation to the text-align fn, which gives the option to draw to the left, right, and center of the coordinates. The x1, y1, x2 and y2 (and optional z) parameters define a rectangular area to display within and may only be used with string data. For text drawn inside a rectangle, the coordinates are interpreted based on the current rect-mode setting. Use the text-mode function with the :screen parameter to display text in 2D at the surface of the window." ([^String s] (.text (current-surface) s)) ([^String s x y] (.text (current-surface) s (float x) (float y))) ([^String s x y z] (.text (current-surface) s (float x) (float y) (float z))) ([^String s x1 y1 x2 y2] (.text (current-surface) s (float x1) (float y1) (float x2) (float y2))) ([^String s x1 y1 x2 y2 z] (.text (current-surface) s (float x1) (float y1) (float x2) (float y2) (float z)))) (def ^{:private true} horizontal-alignment-modes {:left PApplet/LEFT :center PApplet/CENTER :right PApplet/RIGHT}) (def ^{:private true} vertical-alignment-modes {:top PApplet/TOP :bottom PApplet/BOTTOM :center PApplet/CENTER :baseline PApplet/BASELINE}) (defn ^{:requires-bindings true :processing-name "textAlign()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-align "Sets the current alignment for drawing text. Available modes are: horizontal - :left, :center, and :right vertical - :top, :bottom, :center, and :baseline An optional second parameter specifies the vertical alignment mode. :baseline is the default. The :top and :center parameters are straightforward. The :bottom parameter offsets the line based on the current text-descent. For multiple lines, the final line will be aligned to the bottom, with the previous lines appearing above it. When using text with width and height parameters, :baseline is ignored, and treated as :top. (Otherwise, text would by default draw outside the box, since :baseline is the default setting. :baseline is not a useful drawing mode for text drawn in a rectangle.) The vertical alignment is based on the value of text-ascent, which many fonts do not specify correctly. It may be necessary to use a hack and offset by a few pixels by hand so that the offset looks correct. To do this as less of a hack, use some percentage of text-ascent or text-descent so that the hack works even if you change the size of the font." ([align] (let [align (resolve-constant-key align horizontal-alignment-modes)] (.textAlign (current-surface) (int align)))) ([align-x align-y] (let [align-x (resolve-constant-key align-x horizontal-alignment-modes) align-y (resolve-constant-key align-y vertical-alignment-modes)] (.textAlign (current-surface) (int align-x) (int align-y))))) (defn ^{:requires-bindings true :processing-name "textAscent()" :category "Typography" :subcategory "Metrics" :added "1.0"} text-ascent "Returns the ascent of the current font at its current size. This information is useful for determining the height of the font above the baseline. For example, adding the text-ascent and text-descent values will give you the total height of the line." [] (.textAscent (current-surface))) (defn ^{:requires-bindings true :processing-name "textDescent()" :category "Typography" :subcategory "Metrics" :added "1.0"} text-descent "Returns descent of the current font at its current size. This information is useful for determining the height of the font below the baseline. For example, adding the text-ascent and text-descent values will give you the total height of the line." [] (.textDescent (current-surface))) (defn ^{:requires-bindings true :processing-name "textFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-font "Sets the current font that will be drawn with the text function. Fonts must be loaded with load-font before it can be used. This font will be used in all subsequent calls to the text function. If no size parameter is input, the font will appear at its original size until it is changed with text-size. Because fonts are usually bitmaped, you should create fonts at the sizes that will be used most commonly. Using textFont without the size parameter will result in the cleanest-looking text. With the default (JAVA2D) and PDF renderers, it's also possible to enable the use of native fonts via the command (hint :enable-native-fonts). This will produce vector text in JAVA2D sketches and PDF output in cases where the vector data is available: when the font is still installed, or the font is created via the create-font fn" ([^PFont font] (.textFont (current-surface) font)) ([^PFont font size] (.textFont (current-surface) font (int size)))) (defn ^{:requires-bindings true :processing-name "textLeading()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-leading "Sets the spacing between lines of text in units of pixels. This setting will be used in all subsequent calls to the text function." [leading] (.textLeading (current-surface) (float leading))) (def ^{:private true} text-modes {:model PConstants/MODEL :shape PConstants/SHAPE :screen PConstants/SCREEN}) (defn ^{:requires-bindings true :processing-name "textMode()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-mode "Sets the way text draws to the screen - available modes are :model, :shape and :screen In the default configuration (the :model mode), it's possible to rotate, scale, and place letters in two and three dimensional space. Changing to :screen mode draws letters directly to the front of the window and greatly increases rendering quality and speed when used with the :p2d and :p3d renderers. :screen with :opengl and :java2d (the default) renderers will generally be slower, though pixel accurate with :p2d and :p3d. With :screen, the letters draw at the actual size of the font (in pixels) and therefore calls to text-size will not affect the size of the letters. To create a font at the size you desire, use create-font. When using :screen, any z-coordinate passed to a text command will be ignored, because your computer screen is...flat! The :shape mode draws text using the the glyph outlines of individual characters rather than as textures. This mode is only only supported with the PDF and OPENGL renderer settings. With the PDF renderer, you must specify the :shape text-mode before any other drawing occurs. If the outlines are not available, then :shape will be ignored and :model will be used instead. The :shape option in OPENGL mode can be combined with begin-raw to write vector-accurate text to 2D and 3D output files, for instance DXF or PDF. :shape is not currently optimized for OPENGL, so if recording shape data, use :model until you're ready to capture the geometry with begin-raw." [mode] (let [mode (resolve-constant-key mode text-modes)] (.textMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "textSize()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-size "Sets the current font size. This size will be used in all subsequent calls to the text fn. Font size is measured in units of pixels." [size] (.textSize (current-surface) (float size))) (defn ^{:requires-bindings true :processing-name "texture()" :category "Shape" :subcategory "Vertex" :added "1.0"} texture "Sets a texture to be applied to vertex points. The texture fn must be called between begin-shape and end-shape and before any calls to vertex. When textures are in use, the fill color is ignored. Instead, use tint to specify the color of the texture as it is applied to the shape." [^PImage img] (.texture (current-surface) img)) (def ^{:private true} texture-modes {:image PApplet/IMAGE :normalized PApplet/NORMALIZED}) (defn ^{:requires-bindings true :processing-name "textureMode()" :category "Shape" :subcategory "Vertex" :added "1.0"} texture-mode "Sets the coordinate space for texture mapping. There are two options, :image and :normalized. :image refers to the actual coordinates of the image and :normalized refers to a normalized space of values ranging from 0 to 1. The default mode is :image. In :image, if an image is 100 x 200 pixels, mapping the image onto the entire size of a quad would require the points (0,0) (0,100) (100,200) (0,200). The same mapping in NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1)." [mode] (let [mode (resolve-constant-key mode texture-modes)] (.textureMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "textWidth()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-width "Calculates and returns the width of any character or text string." [data] (let [data (if (= (class data) (class \a)) (char data) (str data))] (.textWidth (current-surface) data))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint-float "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([gray] (.tint (current-surface) (float gray))) ([gray alpha] (.tint (current-surface) (float gray) (float alpha))) ([r g b] (.tint (current-surface) (float r)(float g) (float b))) ([r g b a] (.tint (current-surface) (float g) (float g) (float b) (float a)))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint-int "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([rgb] (.tint (current-surface) (int rgb))) ([rgb alpha] (.tint (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([rgb] (if (int-like? rgb) (tint-int rgb) (tint-float rgb))) ([rgb alpha] (if (int-like? rgb) (tint-int rgb alpha) (tint-float rgb alpha))) ([r g b] (tint-float r g b)) ([r g b a] (tint-float r g b a))) (defn ^{:requires-bindings true :processing-name "translate()" :category "Transform" :subcategory nil :added "1.0"} translate "Specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (translate 50 0) and then (translate 20, 0) is the same as (translate 70, 0). If translate is called within draw, the transformation is reset when the loop begins again. This function can be further controlled by the push-matrix and pop-matrix." ([v] (apply translate v)) ([tx ty] (.translate (current-surface) (float tx) (float ty))) ([tx ty tz] (.translate (current-surface) (float tx) (float ty) (float tz)))) (defn ^{:requires-bindings true :processing-name "triangle()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} triangle "A triangle is a plane created by connecting three points. The first two arguments specify the first point, the middle two arguments specify the second point, and the last two arguments specify the third point." [x1 y1 x2 y2 x3 y3] (.triangle (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3))) (defn ^{:requires-bindings true :processing-name "updatePixels()" :category "Image" :subcategory "Pixels" :added "1.0"} update-pixels "Updates the display window with the data in the pixels array. Use in conjunction with load-pixels. If you're only reading pixels from the array, there's no need to call update-pixels unless there are changes. Certain renderers may or may not seem to require load-pixels or update-pixels. However, the rule is that any time you want to manipulate the pixels array, you must first call load-pixels, and after changes have been made, call update-pixels. Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change." [] (.updatePixels (current-surface))) (defn ^{:requires-bindings true :processing-name "vertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} vertex "All shapes are constructed by connecting a series of vertices. vertex is used to specify the vertex coordinates for points, lines, triangles, quads, and polygons and is used exclusively within the begin-shape and end-shape fns. Drawing a vertex in 3D using the z parameter requires the :p3d or :opengl renderers to be used. This function is also used to map a texture onto the geometry. The texture fn declares the texture to apply to the geometry and the u and v coordinates set define the mapping of this texture to the form. By default, the coordinates used for u and v are specified in relation to the image's size in pixels, but this relation can be changed with texture-mode." ([x y] (.vertex (current-surface) (float x) (float y))) ([x y z] (.vertex (current-surface) (float x) (float y) (float z))) ([x y u v] (.vertex (current-surface) (float x) (float y) (float u) (float v))) ([x y z u v] (.vertex (current-surface) (float x) (float y) (float z) (float u) (float v)))) (defn ^{:requires-bindings false :processing-name "year()" :category "Input" :subcategory "Time & Date" :added "1.0"} year "Returns the current year as an integer (2003, 2004, 2005, etc)." [] (PApplet/year)) (defn ^{:requires-bindings true :processing-name "width" :category "Environment" :subcategory nil :added "1.0"} width "Width of the display window. The value of width is zero until size is called." [] (.getWidth (current-applet))) (defmacro ^{:requires-bindings true :processing-name nil :category "Transform" :subcategory "Utility Macros"} with-translation "Performs body with translation, restores current transformation on exit." [translation-vector & body] `(let [tr# ~translation-vector] (push-matrix) (translate tr#) ~@body (pop-matrix))) (defmacro ^{:requires-bindings true :processing-name nil :category "Transform" :subcategory "Utility Macros"} with-rotation "Performs body with rotation, restores current transformation on exit. Accepts a vector [angle] or [angle x-axis y-axis z-axis]. Example: (with-rotation [angle] (vertex 1 2))" [rotation & body] `(let [tr# ~rotation] (push-matrix) (apply rotate tr#) ~@body (pop-matrix))) ;;; version number (defn quil-version [] QUIL-VERSION-STR) ;;; doc utils (def ^{:private true} processing-fn-metas "Returns a seq of metadata maps for all fns related to the original Processing API (but may not have a direct Processing API equivalent)." (map #(-> % second meta) (ns-publics *ns*))) (defn- processing-fn-metas-with-orig-method-name "Returns a seq of metadata maps for all fns with a corresponding Processing API method." [] (filter :processing-name processing-fn-metas)) (defn- matching-processing-methods "Takes a string representing the start of a method name in the original Processing API and returns a map of orig/new-name pairs" [orig-name] (let [metas (processing-fn-metas-with-orig-method-name) matches (filter #(.startsWith (:processing-name %) orig-name) metas)] (into {} (map (fn [{:keys [name processing-name]}] [(str processing-name) (str name)]) matches)))) (defn- find-categories [] (let [metas processing-fn-metas cats (into (sorted-set) (map :category metas))] (clojure.set/difference cats #{nil}))) (defn- find-subcategories [category] (let [metas processing-fn-metas in-cat (filter #(= category (:category %)) metas) res (into (sorted-set) (map :subcategory in-cat))] (clojure.set/difference res #{nil}))) (defn- find-fns "Find the names of fns in category cat that don't also belong to a subcategory" [cat subcat] (let [metas processing-fn-metas res (filter (fn [m] (and (= cat (:category m)) (= subcat (:subcategory m)))) metas)] (sort (map :name res)))) (defn- subcategory-map [cat cat-idx] (let [subcats (find-subcategories cat) idxs (map inc (range)) idxd-subcats (map (fn [idx subcat] [(str cat-idx "." idx) subcat]) idxs subcats)] (into {} (map (fn [[idx subcat]] [idx {:name subcat :fns (find-fns cat subcat)}]) idxd-subcats)))) (defn- sorted-category-map [] (let [cats (find-categories) idxs (map inc (range)) idxd-cats (into {} (map (fn [idx cat] [idx cat]) idxs cats))] (into (sorted-map) (map (fn [[idx cat]] [idx {:name cat :fns (find-fns cat nil) :subcategories (subcategory-map cat idx)}]) idxd-cats)))) (defn- all-category-map [] (reduce (fn [sum [k v]] (merge sum (:subcategories v))) (into {} (map (fn [[k v]] [(str k) v]) (sorted-category-map))) (sorted-category-map))) (defn show-cats "Print out a list of all the categories and subcategories, associated index nums and fn count (in parens)." [] (let [cats (sorted-category-map)] (dorun (map (fn [[cat-idx cat]] (println cat-idx (:name cat) (str "(" (count (find-fns (:name cat) nil)) ")")) (dorun (map (fn [[subcat-idx subcat]] (println " " subcat-idx (:name subcat) (str "(" (count (find-fns (:name cat) (:name subcat))) ")"))) (:subcategories cat)))) cats)))) (defn- wrap-lines "Split a list of words in lists (lines) not longer than width chars each, space between words included." [width words] (letfn [(wrap-lines-rec [ws accum-lns] (if (empty? ws) accum-lns (let [lens (map count ws) cumlens (reduce (fn [sums len] (conj sums (if (empty? sums) len (+ (last sums) len 1)))) [] lens) [line other] (split-with #(> width %) cumlens) [line other] (split-at (count line) ws)] (recur other (conj accum-lns line)))))] (wrap-lines-rec words []))) (defn- pprint-wrapped-lines "Pretty print words across several lines by wrapping lines at word boundary." [words & {:keys [fromcolumn width] :or {fromcolumn 0 width 80}}] (let [w (- width fromcolumn) wordss (wrap-lines w words) indent (apply str (repeat fromcolumn \space)) lines (map #(apply str indent (interpose " " %)) wordss)] (doseq [l lines] (println l)))) (defn show-fns "If given a number, print all the functions within category or subcategory specified by the category index (use show-cats to see a list of index nums). If given a string or a regular expression, print all the functions whose name or category name contains that string. If a category is specified, it will not print out the fns in any of cat's subcategories." [q] (letfn [(list-category [cid c & {:keys [only]}] (let [category-fns (:fns c) display-fns (if (nil? only) category-fns (clojure.set/intersection (set only) (set category-fns))) names (sort (map str display-fns))] (if (not (empty? names)) (do (println cid (:name c)) (pprint-wrapped-lines names :fromcolumn 4))))) (show-fns-by-cat-idx [cat-idx] (let [c (get (all-category-map) (str cat-idx))] (list-category cat-idx c))) (show-fns-by-name-regex [re] (doseq [[cid c] (sort-by key (all-category-map))] (let [in-cat-name? (re-find re (:name c)) matching-fns (filter #(re-find re (str %)) (:fns c)) in-fn-names? (not (empty? matching-fns))] (cond in-cat-name? (list-category cid c) ;; print an entire category in-fn-names? (list-category cid c :only matching-fns)))))] (cond (string? q) (show-fns-by-name-regex (re-pattern (str "(?i)" q))) (isa? (type q) java.util.regex.Pattern) (show-fns-by-name-regex q) :else (show-fns-by-cat-idx q)))) (defn show-meths "Takes a string representing the start of a method name in the original Processing API and prints out all matches alongside the Processing-core equivalent." [orig-name] (let [res (matching-processing-methods orig-name)] (print-definition-list res)) nil) ;;; Useful trig constants (def PI (float Math/PI)) (def HALF-PI (/ PI (float 2.0))) (def THIRD-PI (/ PI (float 3.0))) (def QUARTER-PI (/ PI (float 4.0))) (def TWO-PI (* PI (float 2.0))) (def DEG-TO-RAD (/ PI (float 180.0))) (def RAD-TO-DEG (/ (float 180.0) PI)) ;; Sketch control (defn sketch-stop "Stop/pause the sketch (restart with sketch-start)" [sketch] (applet-stop sketch)) (defn sketch-state "Fetch an element of state from within the sketch" [sketch k] (applet-state sketch k)) (defn sketch-start "Restart the sketch (if it has been stopped with sketch-stop)" [sketch] (applet-start sketch)) (defn sketch-close "Stop the sketch and close the window" [sketch] (applet-close sketch)) ;; Sketch creation (defn sketch "Create and start a new visualisation applet. :size - a vector of width and height for the sketch. Defaults to [500 300]. :renderer - Specify the renderer type. One of :p2d, :java2d, :opengl, :pdf or :dxf). Defaults to :java2d. If :pdf or :dxf is selected, :target is forced to :none. :output-file - Specify an output file path. Only used in :pdf and :dxf render modes. :title - a string which will be displayed at the top of the sketch window. :target - Specify the target. One of :frame, :perm-frame or :none. Ignored if :pdf or :dxf renderer is used. :decor - Specify if the window should have OS frame decorations. Only honoured with :frame or :perm-frame targets. :setup - a fn to be called once when setting the sketch up. :draw - a fn to be repeatedly called at most n times per second where n is the target frame-rate set for the visualisation. :focus-gained - Called when the sketch gains focus. :focus-lost - Called when the sketch loses focus. :mouse-entered - Called when the mouse enters the sketch window. :mouse-exited - Called when the mouse leaves the sketch window :mouse-pressed - Called every time a mouse button is pressed. :mouse-released - Called every time a mouse button is released. :mouse-clicked - called once after a mouse button has been pressed and then released. :mouse-moved - Called every time the mouse moves and a button is not pressed. :mouse-dragged - Called every time the mouse moves and a button is pressed. :key-pressed - Called every time any key is pressed. :key-released - Called every time any key is released. :key-typed - Called once every time non-modifier keys are pressed. :safe-draw-fn - Catches and prints exceptions in the draw fn. Default is true. :on-close - Called once, when sketch is closed" [& opts] (apply applet opts)) (defmacro defsketch "Define and start a sketch and bind it to a var with the symbol app-name. If any of the options to the various callbacks are symbols, it wraps them in a call to var to ensure they aren't inlined and that redefinitions to the original fns are reflected in the visualisation. See sketch for the available options." [app-name & opts] `(defapplet ~app-name ~@opts)) (defmacro with-graphics "All subsequent calls of any drawing function will draw on given graphics." [graphics & body] `(binding [*graphics* ~graphics] (.beginDraw ~graphics) ~@body (.endDraw ~graphics))) (defn ^{:requires-bindings false :processing-name nil :category "Input" :subcategory "Keyboard" :added "1.6"} key-coded? "Returns true if char c is a 'coded' char i.e. it is necessary to fetch the key-code as an integer and use that to determine the specific key pressed. See key-keyword." [c] (= PConstants/CODED (int c))) (def ^{:private true} KEY-CODES {KeyEvent/VK_UP :up KeyEvent/VK_DOWN :down KeyEvent/VK_LEFT :left KeyEvent/VK_RIGHT :right KeyEvent/VK_ALT :alt KeyEvent/VK_CONTROL :control KeyEvent/VK_SHIFT :shift KeyEvent/VK_WINDOWS :command KeyEvent/VK_META :command KeyEvent/VK_F1 :f1 KeyEvent/VK_F2 :f2 KeyEvent/VK_F3 :f3 KeyEvent/VK_F4 :f4 KeyEvent/VK_F5 :f5 KeyEvent/VK_F6 :f6 KeyEvent/VK_F7 :f7 KeyEvent/VK_F8 :f8 KeyEvent/VK_F9 :f9 KeyEvent/VK_F10 :f10 KeyEvent/VK_F11 :f11 KeyEvent/VK_F12 :f12 KeyEvent/VK_F13 :f13 KeyEvent/VK_F14 :f14 KeyEvent/VK_F15 :f15 KeyEvent/VK_F16 :f16 KeyEvent/VK_F17 :f17 KeyEvent/VK_F18 :f18 KeyEvent/VK_F19 :f19 KeyEvent/VK_F20 :f20 KeyEvent/VK_F21 :f21 KeyEvent/VK_F22 :f22 KeyEvent/VK_F23 :f23 KeyEvent/VK_F24 :f24}) (defn ^{:requires-bindings true :processing-name nil :category "Input" :subcategory "Keyboard" :added "1.6"} key-as-keyword "Returns a keyword representing the currently pressed key. Modifier keys are represented as: :up, :down, :left, :right, :alt, :control, :shift, :command, :f1-24" [] (let [key-char (raw-key) code (key-code)] (if (key-coded? key-char) (get KEY-CODES code :unknown-key) (keyword (str key-char))))) (defn ^{:requires-bindings false :processing-name nil :category "Debugging" :added "1.6"} debug "Prints msg and then sleeps the current thread for delay-ms. Useful for debugging live running sketches. delay-ms defaults to 300. " ([msg] (debug msg 300)) ([msg delay-ms] (println msg) (Thread/sleep delay-ms)))
true
(ns ^{:doc "Wrappers and extensions around the core Processing.org API." :author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"} quil.core (:import [processing.core PApplet PImage PGraphics PFont PConstants PShape] [java.awt.event KeyEvent]) (:require [clojure.set]) (:use [quil.version :only [QUIL-VERSION-STR]] [quil.util :only [int-like? resolve-constant-key length-of-longest-key gen-padding print-definition-list]] [quil.applet :only [current-applet applet-stop applet-state applet-start applet-close applet defapplet applet-safe-exit current-graphics *graphics*]])) (defn- current-surface "Retrieves current drawing surface. It's either current graphics or current applet if graphics is nil" [] (or (current-graphics) (current-applet))) (defn ^{:requires-bindings true :category "State" :subcategory nil :added "1.0"} state "Retrieve sketch-specific state by key. Must initially call set-state! to store state. (set-state! :foo 1) (state :foo) ;=> 1 " [key] (let [state* (:state (meta (current-applet)))] (when-not @state* (throw (Exception. "State not set - use set-state! before fetching state"))) (let [state @state*] (when-not (contains? state key) (throw (Exception. (str "Unable to find state with key: " key)))) (get state key)))) (defn ^{:requires-bindings true :category "State" :subcategory nil :added "1.0"} set-state! "Set sketch-specific state. May only be called once (ideally in the setup fn). Subsequent calls have no effect. Example: (set-state! :foo 1 :bar (atom true) :baz (/ (width) 2))" [& state-vals] (let [state* (:state (meta (current-applet)))] (when-not @state* (let [state-map (apply hash-map state-vals)] (reset! state* state-map))))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs-int "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Takes and returns an int." [n] (PApplet/abs (int n))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs-float "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Takes and returns a float." [n] (PApplet/abs (float n))) (defn ^{:requires-bindings false :processing-name "abs()" :category "Math" :subcategory "Calculation" :added "1.0"} abs "Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. Dynamically casts to an int or float appropriately" [n] (if (int-like? n) (abs-int n) (abs-float n))) (defn ^{:requires-bindings false :processing-name "acos()" :category "Math" :subcategory "Trigonometry" :added "1.0"} acos "The inverse of cos, returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to Math/PI (3.1415927)." [n] (PApplet/acos (float n))) (defn ^{:requires-bindings true :processing-name "alpha()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} alpha "Extracts the alpha value from a color." [color] (.alpha (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient-float "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The color components set through the parameters define the reflectance. For example in the default color mode, setting x=255, y=126, z=0, would cause all the red light to reflect and half of the green light to reflect. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." ([gray] (.ambient (current-surface) (float gray))) ([x y z] (.ambient (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient-int "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The rgb color components set define the reflectance. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." [rgb] (.ambient (current-surface) (int rgb))) (defn ^{:requires-bindings true :processing-name "ambient()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} ambient "Sets the ambient reflectance for shapes drawn to the screen. This is combined with the ambient light component of environment. The color components set through the parameters define the reflectance. For example in the default color mode, setting x=255, y=126, z=0, would cause all the red light to reflect and half of the green light to reflect. Used in combination with emissive, specular, and shininess in setting the material properties of shapes." ([rgb] (if (int-like? rgb) (ambient-int rgb) (ambient-float rgb))) ([x y z] (ambient-float x y z))) (defn ^{:requires-bindings true :processing-name "ambientLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} ambient-light "Adds an ambient light. Ambient light doesn't come from a specific direction, the rays have light have bounced around so much that objects are evenly lit from all sides. Ambient lights are almost always used in combination with other types of lights. Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop. The effect of the parameters is determined by the current color mode." ([red green blue] (.ambientLight (current-surface) (float red) (float green) (float blue))) ([red green blue x y z] (.ambientLight (current-surface) (float red) (float green) (float blue) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "applyMatrix()" :category "Transform" :subcategory nil :added "1.0"} apply-matrix "Multiplies the current matrix by the one specified through the parameters. This is very slow because it will try to calculate the inverse of the transform, so avoid it whenever possible. The equivalent function in OpenGL is glMultMatrix()." ([n00 n01 n02 n10 n11 n12] (.applyMatrix (current-surface) (float n00) (float n01) (float n02) (float n10) (float n11) (float n12))) ([n00 n01 n02 n03 n10 n11 n12 n13 n20 n21 n22 n23 n30 n31 n32 n33] (.applyMatrix (current-surface) (float n00) (float n01) (float n02) (float 03) (float n10) (float n11) (float n12) (float 13) (float n20) (float n21) (float n22) (float 23) (float n30) (float n31) (float n32) (float 33)))) (defn ^{:requires-bindings true :processing-name "arc()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} arc "Draws an arc in the display window. Arcs are drawn along the outer edge of an ellipse defined by the x, y, width and height parameters. The origin or the arc's ellipse may be changed with the ellipseMode() function. The start and stop parameters specify the angles at which to draw the arc." [x y width height start stop] (.arc (current-surface) (float x)(float y) (float width) (float height) (float start) (float stop))) (defn ^{:requires-bindings false :processing-name "asin()" :category "Math" :subcategory "Trigonometry" :added "1.0"} asin "The inverse of sin, returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2." [n] (PApplet/asin (float n))) (defn ^{:requires-bindings false :processing-name "atan()" :category "Math" :subcategory "Trigonometry" :added "1.0"} atan "The inverse of tan, returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 ." [n] (PApplet/atan (float n))) (defn ^{:requires-bindings false :processing-name "atan2()" :category "Math" :subcategory "Trigonometry" :added "1.0"} atan2 "Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2 function is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent." [y x] (PApplet/atan2 (float y) (float x))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-float "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts args to floats." ([gray] (.background (current-surface) (float gray))) ([gray alpha] (.background (current-surface) (float gray) (float alpha))) ([r g b] (.background (current-surface) (float r) (float g) (float b))) ([r g b a] (.background (current-surface) (float r) (float g) (float b) (float a)))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-int "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts rgb to an int and alpha to a float." ([rgb] (.background (current-surface) (int rgb))) ([rgb alpha] (.background (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background "Sets the color used for the background of the Processing window. The default background is light gray. In the draw function, the background color is used to clear the display window at the beginning of each frame. It is not possible to use transparency (alpha) in background colors with the main drawing surface, however they will work properly with create-graphics. Converts args to floats." ([rgb] (if (int-like? rgb) (background-int rgb) (background-float rgb))) ([rgb alpha] (if (int-like? rgb) (background-int rgb alpha) (background-float rgb alpha))) ([r g b] (background-float r g b)) ([r g b a] (background-float r g b a))) (defn ^{:requires-bindings true :processing-name "background()" :category "Color" :subcategory "Setting" :added "1.0"} background-image "Specify an image to be used as the background for a sketch. Its width and height must be the same size as the sketch window. Images used as background will ignore the current tint setting." [^PImage img] (.background (current-surface) img)) (defn ^{:requires-bindings true :processing-name "beginCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} begin-camera "Sets the matrix mode to the camera matrix so calls such as translate, rotate, apply-matrix and reset-matrix affect the camera. begin-camera should always be used with a following end-camera and pairs of begin-camera and end-camera cannot be nested. For most situations the camera function will be sufficient." [] (.beginCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "endCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} end-camera "Unsets the matrix mode from the camera matrix. See begin-camera." [] (.endCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "beginRaw()" :category "Output" :subcategory "Files" :added "1.0"} begin-raw "Enables the creation of vectors from 3D data. Requires corresponding end-raw command. These commands will grab the shape data just before it is rendered to the screen. At this stage, your entire scene is nothing but a long list of individual lines and triangles. This means that a shape created with sphere method will be made up of hundreds of triangles, rather than a single object. Or that a multi-segment line shape (such as a curve) will be rendered as individual segments." ([^PGraphics raw-gfx] (.beginRaw (current-surface) raw-gfx)) ([^String renderer ^String filename] (.beginRaw (current-applet) renderer filename))) (def ^{:private true} render-modes {:p2d PApplet/P2D :p3d PApplet/P3D :java2d PApplet/JAVA2D :opengl PApplet/OPENGL :pdf PApplet/PDF :dxf PApplet/DXF}) (defn ^{:requires-bindings true :processing-name "beginRecord()" :category "Output" :subcategory "Files" :added "1.0"} begin-record "Opens a new file and all subsequent drawing functions are echoed to this file as well as the display window. The begin-record fn requires two parameters, the first is the renderer and the second is the file name. This function is always used with end-record to stop the recording process and close the file. Note that begin-record will only pick up any settings that happen after it has been called. For instance, if you call text-font before begin-record, then that font will not be set for the file that you're recording to." [renderer filename] (let [renderer (resolve-constant-key renderer render-modes)] (println "renderer: " renderer) (.beginRecord (current-applet) (str renderer) (str filename)))) (defn ^{:requires-bindings true :processing-name "endRecord()" :category "Output" :subcategory "Files" :added "1.0"} end-record "Stops the recording process started by begin-record and closes the file." [] (.endRecord (current-applet))) (def ^{:private true} shape-modes {:points PApplet/POINTS :lines PApplet/LINES :triangles PApplet/TRIANGLES :triangle-strip PApplet/TRIANGLE_STRIP :triangle-fan PApplet/TRIANGLE_FAN :quads PApplet/QUADS :quad-strip PApplet/QUAD_STRIP}) (defn ^{:requires-bindings true :processing-name "beginShape()" :category "Shape" :subcategory "Vertex" :added "1.0"} begin-shape "Enables the creation of complex forms. begin-shape begins recording vertices for a shape and end-shape stops recording. Use the mode keyword to specify which shape create from the provided vertices. With no mode specified, the shape can be any irregular polygon. The available mode keywords are :points, :lines, :triangles, :triangle-fan, :triangle-strip, :quads, :quad-strip. After calling the begin-shape function, a series of vertex commands must follow. To stop drawing the shape, call end-shape. The vertex function with two parameters specifies a position in 2D and the vertex function with three parameters specifies a position in 3D. Each shape will be outlined with the current stroke color and filled with the fill color. Transformations such as translate, rotate, and scale do not work within begin-shape. It is also not possible to use other shapes, such as ellipse or rect within begin-shape." ([] (.beginShape (current-surface))) ([mode] (let [mode (resolve-constant-key mode shape-modes)] (.beginShape (current-surface) (int mode))))) (defn ^{:requires-bindings true :processing-name "bezier()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier "Draws a Bezier curve on the screen. These curves are defined by a series of anchor and control points. The first two parameters specify the first anchor point and the last two parameters specify the other anchor point. The middle parameters specify the control points which define the shape of the curve." ([x1 y1 cx1 cy1 cx2 cy2 x2 y2] (.bezier (current-surface) (float x1) (float y1) (float cx1) (float cy1) (float cx2) (float cy2) (float x2) (float y2))) ([x1 y1 z1 cx1 cy1 cz1 cx2 cy2 cz2 x2 y2 z2] (.bezier (current-surface) (float x1) (float y1) (float z1) (float cx1) (float cy1) (float cz1) (float cx2) (float cy2) (float cz2) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "bezierDetail()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-detail "Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the :p3d or :opengl renderer as the default (:java2d) renderer does not use this information." [detail] (.bezierDetail (current-surface) (int detail))) (defn ^{:requires-bindings true :processing-name "bezierPoint()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-point "Evaluates the Bezier at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b and c are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a bezier curve at t." [a b c d t] (.bezierPoint (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "bezierTangent()" :category "Shape" :subcategory "Curves" :added "1.0"} bezier-tangent "Calculates the tangent of a point on a Bezier curve. (See http://en.wikipedia.org/wiki/Tangent)" [a b c d t] (.bezierTangent (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "bezierVertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} bezier-vertex "Specifies vertex coordinates for Bezier curves. Each call to bezier-vertex defines the position of two control points and one anchor point of a Bezier curve, adding a new segment to a line or shape. The first time bezier-vertex is used within a begin-shape call, it must be prefaced with a call to vertex to set the first anchor point. This function must be used between begin-shape and end-shape and only when there is no parameter specified to begin-shape." ([cx1 cy1 cx2 cy2 x y] (.bezierVertex (current-surface) (float cx1) (float cy1) (float cx2) (float cy2) (float x) (float y))) ([cx1 cy1 cz1 cx2 cy2 cz2 x y z] (.bezierVertex (current-surface) (float cx1) (float cy1) (float cz1) (float cx2) (float cy2) (float cz2) (float x) (float y) (float z)))) (defn ^{:require-binding false :processing-name "binary()" :category "Data" :subcategory "Conversion" :added "1.0"} binary "Returns a string representing the binary value of an int, char or byte. When converting an int to a string, it is possible to specify the number of digits used." ([val] (PApplet/binary (if (number? val) (int val) val))) ([val num-digits] (PApplet/binary (int val) (int num-digits)))) (defn ^{:require-binding false :processing-name "unbinary()" :category "Data" :subcategory "Conversion" :added "1.0"} unbinary "Unpack a binary string to an integer. See binary for converting integers to strings." [str-val] (PApplet/unbinary (str str-val))) (def ^{:private true} blend-modes {:blend PApplet/BLEND :add PApplet/ADD :subtract PApplet/SUBTRACT :darkest PApplet/DARKEST :lightest PApplet/LIGHTEST :difference PApplet/DIFFERENCE :exclusion PApplet/EXCLUSION :multiply PApplet/MULTIPLY :screen PApplet/SCREEN :overlay PApplet/OVERLAY :hard-light PApplet/HARD_LIGHT :soft-light PApplet/SOFT_LIGHT :dodge PApplet/DODGE :burn PApplet/BURN}) (defn ^{:requires-bindings true :processing-name "blend()" :category "Color" :subcategory "Pixels" :added "1.0"} blend "Blends a region of pixels from one image into another (or in itself again) with full alpha channel support. Available blend modes are: :blend - linear interpolation of colours: C = A*factor + B :add - additive blending with white clip: C = min(A*factor + B, 255) :subtract - subtractive blending with black clip: C = max(B - A*factor, 0) :darkest - only the darkest colour succeeds: C = min(A*factor, B) :lightest - only the lightest colour succeeds: C = max(A*factor, B) :difference - subtract colors from underlying image. :exclusion - similar to :difference, but less extreme. :multiply - Multiply the colors, result will always be darker. :screen - Opposite multiply, uses inverse values of the colors. :overlay - A mix of :multiply and :screen. Multiplies dark values and screens light values. :hard-light - :screen when greater than 50% gray, :multiply when lower. :soft-light - Mix of :darkest and :lightest. Works like :overlay, but not as harsh. :dodge - Lightens light tones and increases contrast, ignores darks. Called \"Color Dodge\" in Illustrator and Photoshop. :burn - Darker areas are applied, increasing contrast, ignores lights. Called \"Color Burn\" in Illustrator and Photoshop." ([x y width height dx dy dwidth dheight mode] (let [mode (resolve-constant-key mode blend-modes)] (.blend (current-surface) (int x) (int y) (int width) (int height) (int dx) (int dy) (int dwidth) (int dheight) (int mode)))) ([^PImage src x y width height dx dy dwidth dheight mode] (let [mode (resolve-constant-key mode blend-modes)] (.blend (current-surface) src (int x) (int y) (int width) (int height) (int dx) (int dy) (int dwidth) (int dheight) (int mode))))) (defn ^{:requires-bindings false :processing-name "blendColor()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} blend-color "Blends two color values together based on the blending mode given specified with the mode keyword. Available blend modes are: :blend - linear interpolation of colours: C = A*factor + B :add - additive blending with white clip: C = min(A*factor + B, 255) :subtract - subtractive blending with black clip: C = max(B - A*factor, 0) :darkest - only the darkest colour succeeds: C = min(A*factor, B) :lightest - only the lightest colour succeeds: C = max(A*factor, B) :difference - subtract colors from underlying image. :exclusion - similar to :difference, but less extreme. :multiply - Multiply the colors, result will always be darker. :screen - Opposite multiply, uses inverse values of the colors. :overlay - A mix of :multiply and :screen. Multiplies dark values and screens light values. :hard-light - :screen when greater than 50% gray, :multiply when lower. :soft-light - Mix of :darkest and :lightest. Works like :overlay, but not as harsh. :dodge - Lightens light tones and increases contrast, ignores darks. Called \"Color Dodge\" in Illustrator and Photoshop. :burn - Darker areas are applied, increasing contrast, ignores lights. Called \"Color Burn\" in Illustrator and Photoshop." [c1 c2 mode] (let [mode (resolve-constant-key mode blend-modes)] (PApplet/blendColor (int c1) (int c2) (int mode)))) (defn ^{:requires-bindings true :processing-name "blue()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} blue "Extracts the blue value from a color, scaled to match current color-mode. Returns a float." [color] (.blue (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "box()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} box "Creates an extruded rectangle." ([size] (.box (current-surface) (float size))) ([width height depth] (.box (current-surface) (float width) (float height) (float depth)))) (defn ^{:requires-bindings true :processing-name "brightness()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} brightness "Extracts the brightness value from a color. Returns a float." [color] (.brightness (current-surface) (int color))) (defn ^{:requires-bindings true :processing-name "camera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} camera "Sets the position of the camera through setting the eye position, the center of the scene, and which axis is facing upward. Moving the eye position and the direction it is pointing (the center of the scene) allows the images to be seen from different angles. The version without any parameters sets the camera to the default position, pointing to the center of the display window with the Y axis as up. The default values are: eyeX: (/ (width) 2.0) eyeY: (/ (height) 2.0) eyeZ: (/ (/ (height) 2.0) (tan (/ (* Math/PI 60.0) 360.0))) centerX: (/ (width) 2.0) centerY: (/ (height) 2.0) centerZ: 0 upX: 0 upY: 1 upZ: 0 Similar imilar to gluLookAt() in OpenGL, but it first clears the current camera settings." ([] (.camera (current-surface))) ([eyeX eyeY eyeZ centerX centerY centerZ upX upY upZ] (.camera (current-surface) (float eyeX) (float eyeY) (float eyeZ) (float centerX) (float centerY) (float centerZ) (float upX) (float upY) (float upZ)))) (defn ^{:requires-bindings false :processing-name "ceil()" :category "Math" :subcategory "Calculation" :added "1.0"} ceil "Calculates the closest int value that is greater than or equal to the value of the parameter. For example, (ceil 9.03) returns the value 10." [n] (PApplet/ceil (float n))) (defn ^{:requires-bindings true :processing-name "color()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} color "Creates an integer representation of a color The parameters are interpreted as RGB or HSB values depending on the current color-mode. The default mode is RGB values from 0 to 255 and therefore, the function call (color 255 204 0) will return a bright yellow. Args are cast to floats. r - red or hue value g - green or saturation value b - blue or brightness value a - alpha value" ([gray] (.color (current-surface) (float gray))) ([gray alpha] (.color (current-surface) (float gray) (float alpha))) ([r g b] (.color (current-surface) (float r) (float g) (float b))) ([r g b a] (.color (current-surface) (float r) (float g) (float b) (float a)))) (def ^{:private true} color-modes {:rgb (int 1) :hsb (int 3)}) (defn ^{:requires-bindings true :processing-name "colorMode()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} color-mode "Changes the way Processing interprets color data. Available modes are :rgb and :hsb.By default, the parameters for fill, stroke, background, and color are defined by values between 0 and 255 using the :rgb color model. The color-mode fn is used to change the numerical range used for specifying colors and to switch color systems. For example, calling (color-mode :rgb 1.0) will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the parameters range1, range2, range3, and range 4." ([mode] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode)))) ([mode max] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max)))) ([mode max-x max-y max-z] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max-x) (float max-y) (float max-z)))) ([mode max-x max-y max-z max-a] (let [mode (resolve-constant-key mode color-modes)] (.colorMode (current-surface) (int mode) (float max-x) (float max-y) (float max-z) (float max-a))))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain-float "Constrains a value to not exceed a maximum and minimum value. All args are cast to floats." [amt low high] (PApplet/constrain (float amt) (float low) (float high))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain-int "Constrains a value to not exceed a maximum and minimum value. All args are cast to ints." [amt low high] (PApplet/constrain (int amt) (int low) (int high))) (defn ^{:requires-bindings false :processing-name "constrain()" :category "Math" :subcategory "Calculation" :added "1.0"} constrain "Constrains a value to not exceed a maximum and minimum value." [amt low high] (if (int-like? amt) (constrain-int amt low high) (constrain-float amt low high))) (defn ^{:requires-bindings true :processing-name "copy()" :category "Image" :subcategory "Pixels" :added "1.0"} copy "Copies a region of pixels from the display window to another area of the display window and copies a region of pixels from an image used as the src-img parameter into the display window. If the source and destination regions aren't the same size, it will automatically resize the source pixels to fit the specified target region. No alpha information is used in the process, however if the source image has an alpha channel set, it will be copied as well. " ([[sx1 sy1 sx2 sy2] [dx1 dy1 dx2 dy2]] (.copy (current-surface) (int sx1) (int sy1) (int sx2) (int sy2) (int dx1) (int dy1) (int dx2) (int dy2))) ([^PImage img [sx1 sy1 sx2 sy2] [dx1 dy1 dx2 dy2]] (.copy (current-surface) img (int sx1) (int sy1) (int sx2) (int sy2) (int dx1) (int dy1) (int dx2) (int dy2)))) (defn ^{:requires-bindings false :processing-name "cos()" :category "Math" :subcategory "Trigonometry" :added "1.0"} cos "Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to Math/PI*2). Values are returned in the range -1 to 1." [angle] (PApplet/cos (float angle))) (defn ^{:requires-bindings false :processing-name "PFont.list()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} available-fonts "A sequence of strings representing the fonts on this system available for use. Because of limitations in Java, not all fonts can be used and some might work with one operating system and not others. When sharing a sketch with other people or posting it on the web, you may need to include a .ttf or .otf version of your font in the data directory of the sketch because other people might not have the font installed on their computer. Only fonts that can legally be distributed should be included with a sketch." [] (seq (PFont/list))) (defn ^{:requires-bindings false :processing-name nil :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} font-available? "Returns true if font (specified as a string) is available on this system, false otherwise" [font-str] (if (some #{font-str} (available-fonts)) true false)) (defn ^{:requires-bindings true :processing-name "createFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} create-font "Dynamically converts a font to the format used by Processing (a PFont) from either a font name that's installed on the computer, or from a .ttf or .otf file inside the sketches 'data' folder. This function is an advanced feature for precise control. Use available-fonts to obtain the names for the fonts recognized by the computer and are compatible with this function. The size parameter states the font size you want to generate. The smooth parameter specifies if the font should be antialiased or not, and the charset parameter is an array of chars that specifies the characters to generate. This function creates a bitmapped version of a font It loads a font by name, and converts it to a series of images based on the size of the font. When possible, the text function will use a native font rather than the bitmapped version created behind the scenes with create-font. For instance, when using the default renderer setting (JAVA2D), the actual native version of the font will be employed by the sketch, improving drawing quality and performance. With the :p2d, :p3d, and :opengl renderer settings, the bitmapped version will be used. While this can drastically improve speed and appearance, results are poor when exporting if the sketch does not include the .otf or .ttf file, and the requested font is not available on the machine running the sketch." ([name size] (.createFont (current-applet) (str name) (float size))) ([name size smooth] (.createFont (current-applet) (str name) (float size) smooth)) ([name size smooth ^chars charset] (.createFont (current-applet) (str name) (float size) smooth charset))) (def ^{:private true} graphic-render-modes (select-keys render-modes [:p2d :p3d :java2d :pdf])) (defn ^{:requires-bindings true :processing-name "createGraphics()" :category "Rendering" :subcategory nil :added "1.0"} create-graphics "Creates and returns a new PGraphics object of the types :p2d, :p3d, :java2d, :pdf. Use this class if you need to draw into an off-screen graphics buffer. It's not possible to use create-graphics with the :opengl renderer, because it doesn't allow offscreen use. The :pdf renderer requires the filename parameter. It's important to call any drawing commands between begin-draw and end-draw statements. This is also true for any commands that affect drawing, such as smooth or color-mode. Unlike the main drawing surface which is completely opaque, surfaces created with create-graphics can have transparency. This makes it possible to draw into a graphics and maintain the alpha channel. By using save to write a PNG or TGA file, the transparency of the graphics object will be honored. Note that transparency levels are binary: pixels are either complete opaque or transparent. This means that text characters will be opaque blocks." ([w h renderer] (.createGraphics (current-applet) (int w) (int h) (resolve-constant-key renderer graphic-render-modes))) ([w h renderer path] (.createGraphics (current-applet) (int w) (int h) (resolve-constant-key renderer graphic-render-modes) (str path)))) (defn ^{:requires-bindings true :processing-name "createImage()" :category "Image" :subcategory nil :added "1.0"} create-image "Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play with. Set the size of the buffer with the width and height parameters. The format parameter defines how the pixels are stored. See the PImage reference for more information. Be sure to include all three parameters, specifying only the width and height (but no format) will produce a strange error. Prefer using create-image over initialising new PImage instances directly." [w h format] (.createImage (current-applet) (int w) (int h) (int format))) (defn ^{:requires-bindings true :processing-name "createInput()" :category "Input" :subcategory "Files" :added "1.0"} create-input "This is a method for advanced programmers to open a Java InputStream. The method is useful if you want to use the facilities provided by PApplet to easily open files from the data folder or from a URL, but want an InputStream object so that you can use other Java methods to take more control of how the stream is read. If the requested item doesn't exist, null is returned. If not online, this will also check to see if the user is asking for a file whose name isn't properly capitalized. If capitalization is different an error will be printed to the console. This helps prevent issues that appear when a sketch is exported to the web, where case sensitivity matters, as opposed to running from inside the Processing Development Environment on Windows or Mac OS, where case sensitivity is preserved but ignored. The filename passed in can be: - A URL, for instance (open-stream \"http://processing.org/\"; - A file in the sketch's data folder - The full path to a file to be opened locally (when running as an application) If the file ends with .gz, the stream will automatically be gzip decompressed. If you don't want the automatic decompression, use the related function create-input-raw." [filename] (.createInput (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "createInputRaw()" :category "Input" :subcategory "Files" :added "1.0"} create-input-raw "Call create-input without automatic gzip decompression." [filename] (.createInputRaw (current-applet) filename)) (defn ^{:requires-bindings true :processing-name "createOutput()" :category "Output" :subcategory "Files" :added "1.0"} create-output "Similar to create-input, this creates a Java OutputStream for a given filename or path. The file will be created in the sketch folder, or in the same folder as an exported application. If the path does not exist, intermediate folders will be created. If an exception occurs, it will be printed to the console, and null will be returned. This method is a convenience over the Java approach that requires you to 1) create a FileOutputStream object, 2) determine the exact file location, and 3) handle exceptions. Exceptions are handled internally by the function, which is more appropriate for sketch projects. If the output filename ends with .gz, the output will be automatically GZIP compressed as it is written." [filename] (.createOutput (current-applet) (str filename))) (def ^{:private true} cursor-modes {:arrow PConstants/ARROW :cross PConstants/CROSS :hand PConstants/HAND :move PConstants/MOVE :text PConstants/TEXT :wait PConstants/WAIT}) (defn ^{:requires-bindings true :processing-name "cursor()" :category "Environment" :subcategory nil :added "1.0"} cursor "Sets the cursor to a predefined symbol, an image, or makes it visible if already hidden. If you are trying to set an image as the cursor, it is recommended to make the size 16x16 or 32x32 pixels. The values for parameters x and y must be less than the dimensions of the image. Available modes: :arrow, :cross, :hand, :move, :text, :wait Setting or hiding the cursor generally does not work with 'Present' mode (when running full-screen). See cursor-image for specifying a generic image as the cursor symbol." ([] (.cursor (current-applet))) ([cursor-mode] (.cursor (current-applet) (int (resolve-constant-key cursor-mode cursor-modes))))) (defn ^{:requires-bindings true :processing-name "cursor()" :category "Environment" :subcategory nil :added "1.0"} cursor-image "Set the cursor to a predefined image. The horizontal and vertical active spots of the cursor may be specified with hx and hy" ([^PImage img] (.cursor (current-applet) img)) ([^PImage img hx hy] (.cursor (current-applet) img (int hx) (int hy)))) (defn ^{:requires-bindings true :processing-name "curve()" :category "Shape" :subcategory "Curves" :added "1.0"} curve "Draws a curved line on the screen. The first and second parameters specify the beginning control point and the last two parameters specify the ending control point. The middle parameters specify the start and stop of the curve. Longer curves can be created by putting a series of curve fns together or using curve-vertex. An additional fn called curve-tightness provides control for the visual quality of the curve. The curve fn is an implementation of Catmull-Rom splines." ([x1 y1 x2 y2 x3 y3 x4 y4] (.curve (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3) (float x4) (float y4))) ([x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y4 z4] (.curve (current-surface) (float x1) (float y1) (float z1) (float x2) (float y2) (float z2) (float x3) (float y3) (float z3) (float x4) (float y4) (float z4)))) (defn ^{:requires-bindings true :processing-name "curveDetail()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-detail "Sets the resolution at which curves display. The default value is 20. This function is only useful when using the :p3d or :opengl renderer as the default (:java2d) renderer does not use this information." [detail] (.curveDetail (current-surface) (int detail))) (defn ^{:requires-bindings true :processing-name "curvePoint()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-point "Evalutes the curve at point t for points a, b, c, d. The parameter t varies between 0 and 1, a and d are points on the curve, and b c and are the control points. This can be done once with the x coordinates and a second time with the y coordinates to get the location of a curve at t." [a b c d t] (.bezierPoint (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "curveTangent()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-tangent "Calculates the tangent of a point on a curve. See: http://en.wikipedia.org/wiki/Tangent" [a b c d t] (.curveTangent (current-surface) (float a) (float b) (float c) (float d) (float t))) (defn ^{:requires-bindings true :processing-name "curveTightness()" :category "Shape" :subcategory "Curves" :added "1.0"} curve-tightness "Modifies the quality of forms created with curve and curve-vertex. The parameter squishy determines how the curve fits to the vertex points. The value 0.0 is the default value for squishy (this value defines the curves to be Catmull-Rom splines) and the value 1.0 connects all the points with straight lines. Values within the range -5.0 and 5.0 will deform the curves but will leave them recognizable and as values increase in magnitude, they will continue to deform." [ti] (.curveTightness (current-surface) (float ti))) (defn ^{:requires-bindings true :processing-name "curveVertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} curve-vertex "Specifies vertex coordinates for curves. This function may only be used between begin-shape and end-shape and only when there is no mode keyword specified to begin-hape. The first and last points in a series of curve-vertex lines will be used to guide the beginning and end of a the curve. A minimum of four points is required to draw a tiny curve between the second and third points. Adding a fifth point with curveVertex will draw the curve between the second, third, and fourth points. The curveVertex function is an implementation of Catmull-Rom splines." ([x y] (.curveVertex (current-surface) (float x) (float y))) ([x y z] (.curveVertex (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings false :processing-name "day()" :category "Input" :subcategory "Time & Date" :added "1.0"} day "Get the current day of the month (1 through 31)." [] (PApplet/day)) (defn ^{:requires-bindings false :processing-name "degrees()" :category "Math" :subcategory "Trigonometry" :added "1.0"} degrees "Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and (* 2 Math/PI) radians in a circle. For example, (= 90째 (/ Math/PI 2) 1.5707964). All trigonometric methods in Processing require their parameters to be specified in radians." [radians] (PApplet/degrees (float radians))) (defn ^{:requires-bindings true :processing-name "delay()" :category "Structure" :subcategory nil :added "1.0"} delay-frame "Forces the program to stop running for a specified time. Delay times are specified in thousandths of a second, therefore the function call (delay 3000) will stop the program for three seconds. Because the screen is updated only at the end of draw, the program may appear to 'freeze', because the screen will not update when the delay fn is used. This function has no affect inside setup." [freeze-ms] (.delay (current-applet) (int freeze-ms))) (defn ^{:requires-bindings true :processing-name "directionalLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} directional-light "Adds a directional light. Directional light comes from one direction and is stronger when hitting a surface squarely and weaker if it hits at a a gentle angle. After hitting a surface, a directional lights scatters in all directions. Lights need to be included in the draw fn to remain persistent in a looping program. Placing them in the setup fn of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The nx, ny, and nz parameters specify the direction the light is facing. For example, setting ny to -1 will cause the geometry to be lit from below (the light is facing directly upward)" [r g b nx ny nz] (.directionalLight (current-surface) (float r) (float g) (float b) (float nx) (float ny) (float nz))) (defn ^{:requires-bindings false :processing-name "dist()" :category "Math" :subcategory "Calculation" :added "1.0"} dist "Calculates the distance between two points" ([x1 y1 x2 y2] (PApplet/dist (float x1) (float y1) (float x2) (float y2))) ([x1 y1 z1 x2 y2 z2] (PApplet/dist (float x1) (float y1) (float z1) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "ellipse()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} ellipse "Draws an ellipse (oval) in the display window. An ellipse with an equal width and height is a circle. The origin may be changed with the ellipse-mode function" [x y width height] (.ellipse (current-surface) (float x) (float y) (float width) (float height))) (def ^{:private true} ellipse-modes {:center PApplet/CENTER :radius PApplet/RADIUS :corner PApplet/CORNER :corners PApplet/CORNERS}) (defn ^{:requires-bindings true :processing-name "ellipseMode()" :category "Shape" :subcategory "Attributes" :added "1.0"} ellipse-mode "Modifies the origin of the ellispse according to the specified mode: :center - specifies the location of the ellipse as the center of the shape. (Default). :radius - similar to center, but the width and height parameters to ellipse specify the radius of the ellipse, rather than the diameter. :corner - draws the shape from the upper-left corner of its bounding box. :corners - uses the four parameters to ellipse to set two opposing corners of the ellipse's bounding box." [mode] (let [mode (resolve-constant-key mode ellipse-modes)] (.ellipseMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive-float "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. Converts all args to floats" ([float-val] (.emissive (current-surface) (float float-val))) ([r g b] (.emissive (current-surface) (float r) (float g) (float b)))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive-int "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. Converts all args to ints" [int-val] (.emissive (current-surface) (int int-val))) (defn ^{:requires-bindings true :processing-name "emissive()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} emissive "Sets the emissive color of the material used for drawing shapes drawn to the screen. Used in combination with ambient, specular, and shininess in setting the material properties of shapes. If passed one arg - it is assumed to be an int (i.e. a color), multiple args are converted to floats." ([c] (if (int-like? c) (emissive-int c) (emissive-float c))) ([r g b] (emissive-float r g b))) (defn ^{:requires-bindings true :processing-name "endRaw()" :category "Output" :subcategory "Files" :added "1.0"} end-raw "Complement to begin-raw; they must always be used together. See the begin-raw docstring for details." [] (.endRaw (current-applet))) (defn ^{:requires-bindings true :processing-name "endShape()" :category "Shape" :subcategory "Vertex" :added "1.0"} end-shape "May only be called after begin-shape. When end-shape is called, all of image data defined since the previous call to begin-shape is written into the image buffer. The keyword :close may be passed to close the shape (to connect the beginning and the end)." ([] (.endShape (current-applet))) ([mode] (when-not (= :close mode) (throw (Exception. (str "Unknown mode value: " mode ". Expected :close")))) (.endShape (current-applet) PApplet/CLOSE))) (defn ^{:requires-bindings true :processing-name "exit()" :category "Structure" :subcategory nil :added "1.0"} exit "Quits/stops/exits the program. Rather than terminating immediately, exit will cause the sketch to exit after draw has completed (or after setup completes if called during the setup method). " [] (applet-safe-exit (current-applet))) (defn ^{:requires-bindings false :processing-name "exp()" :category "Math" :subcategory "Calculation" :added "1.0"} exp "Returns Euler's number e (2.71828...) raised to the power of the value parameter." [val] (PApplet/exp (float val))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill-float "Sets the color used to fill shapes. For example, (fill 204 102 0), will specify that all subsequent shapes will be filled with orange." ([gray] (.fill (current-surface) (float gray))) ([gray alpha] (.fill (current-surface) (float gray) (float alpha))) ([r g b] (.fill (current-surface) (float r) (float g) (float b))) ([r g b alpha] (.fill (current-surface) (float r) (float g) (float b) (float alpha)))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill-int "Sets the color used to fill shapes." ([rgb] (.fill (current-surface) (int rgb))) ([rgb alpha] (.fill (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "fill()" :category "Color" :subcategory "Setting" :added "1.0"} fill "Sets the color used to fill shapes." ([rgb] (if (int-like? rgb) (fill-int rgb) (fill-float rgb))) ([rgb alpha] (if (int-like? rgb) (fill-int rgb alpha) (fill-float rgb alpha))) ([r g b] (fill-float r g b)) ([r g b a] (fill-float r g b a))) (def ^{:private true} filter-modes {:threshold PConstants/THRESHOLD :gray PConstants/GRAY :invert PConstants/INVERT :posterize PConstants/POSTERIZE :blur PConstants/BLUR :opaque PConstants/OPAQUE :erode PConstants/ERODE :dilate PConstants/DILATE}) (defn ^{:requires-bindings true :processing-name "filter()" :category "Image" :subcategory "Pixels" :added "1.0"} display-filter "Originally named filter in Processing Language. Filters the display window with the specified mode and level. Level defines the quality of the filter and mode may be one of the following keywords: :threshold - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. :gray - converts any colors in the image to grayscale equivalents :invert - sets each pixel to its inverse value :posterize - limits each channel of the image to the number of colors specified as the level parameter. The level parameter :blur - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1. :opaque - sets the alpha channel to entirely opaque. :erode - reduces the light areas with the amount defined by the level parameter. :dilate - increases the light areas with the amount defined by the level parameter." ([mode] (let [mode (resolve-constant-key mode filter-modes)] (.filter (current-applet) (int mode)))) ([mode level] (let [mode (resolve-constant-key mode filter-modes)] (.filter (current-applet) (int mode) (float level))))) (defn ^{:requires-bindings true :processing-name "focused" :category "Environment" :subcategory nil :added "1.0"} focused "Returns a boolean value representing whether the applet has focus." [] (.-focussed (current-applet))) (defn ^{:requires-bindings true :processing-name "frameCount" :category "Environment" :subcategory nil :added "1.0"} frame-count "The system variable frameCount contains the number of frames displayed since the program started. Inside setup() the value is 0 and and after the first iteration of draw it is 1, etc." [] (.frameCount (current-applet))) (defn ^{:requires-bindings true :processing-name "frameRate" :category "Environment" :subcategory nil :added "1.0"} current-frame-rate "Returns the current framerate" [] (.frameRate (current-applet))) (defn ^{:requires-bindings true :category "Environment" :subcategory nil :added "1.5.0"} target-frame-rate "Returns the target framerate specified with the fn frame-rate" [] @(quil.applet/target-frame-rate)) (defn ^{:requires-bindings true :processing-name "frameRate()" :category "Environment" :subcategory nil :added "1.0"} frame-rate "Specifies a new target framerate (number of frames to be displayed every second). If the processor is not fast enough to maintain the specified rate, it will not be achieved. For example, the function call (frame-rate 30) will attempt to refresh 30 times a second. It is recommended to set the frame rate within setup. The default rate is 60 frames per second." [new-rate] (.frameRate (current-applet) (float new-rate))) (defn ^{:requires-bindings true :processing-name "frustum()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} frustum "Sets a perspective matrix defined through the parameters. Works like glFrustum, except it wipes out the current perspective matrix rather than muliplying itself with it." [left right bottom top near far] (.frustum (current-surface) (float left) (float right) (float bottom) (float top) (float near) (float far))) (defn ^{:requires-bindings true :processing-name "get()" :category "Image" :subcategory "Pixels" :added "1.0"} get-pixel "Reads the color of any pixel or grabs a section of an image. If no parameters are specified, the entire image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display window by specifying an additional width and height parameter. If the pixel requested is outside of the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. For example, even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB. Getting the color of a single pixel with (get x y) is easy, but not as fast as grabbing the data directly using the pixels fn." ([] (.get (current-surface))) ([x y] (.get (current-surface) (int x) (int y))) ([x y w h] (.get (current-surface) (int x) (int y) (int w) (int h)))) (declare load-pixels) (defn ^{:requires-bindings true :processing-name "pixels[]" :category "Image" :subcategory "Pixels" :added "1.0"} pixels "Array containing the values for all the pixels in the display window. This array is therefore the size of the display window. If this array is modified, the update-pixels fn must be called to update the changes. Calls load-pixels before obtaining the pixel array. Only works with P2D and P3D renderer." [] (load-pixels) (.-pixels (current-surface))) (defn ^{:requires-bindings true :processing-name "green()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} green "Extracts the green value from a color, scaled to match current color-mode. This value is always returned as a float so be careful not to assign it to an int value." [col] (.green (current-surface) (int col))) (defn ^{:require-binding false :processing-name "hex()" :category "Data" :subcategory "Conversion"} hex "Converts a byte, char, int, or color to a String containing the equivalent hexadecimal notation. For example color(0, 102, 153) will convert to the String \"FF006699\". This function can help make your geeky debugging sessions much happier. " ([val] (PApplet/hex val)) ([val num-digits] (PApplet/hex (int val) (int num-digits)))) (defn ^{:require-binding false :processing-name "hex()" :category "Data" :subcategory "Conversion"} unhex "Converts a String representation of a hexadecimal number to its equivalent integer value." [hex-str] (PApplet/unhex (str hex-str))) (defn ^{:requires-bindings true :processing-name "height" :category "Environment" :subcategory nil :added "1.0"} height "Height of the display window. The value of height is zero until size is called." [] (.getHeight (current-applet))) (def ^{:private true} hint-options {:enable-opengl-4x-smooth PConstants/ENABLE_OPENGL_4X_SMOOTH :enable-opengl-2x-smooth PConstants/ENABLE_OPENGL_2X_SMOOTH :enable-native-fonts PConstants/ENABLE_NATIVE_FONTS :disable-native-fonts PConstants/DISABLE_NATIVE_FONTS :enable-depth-test PConstants/ENABLE_DEPTH_TEST :disable-depth-test PConstants/DISABLE_DEPTH_TEST :enable-depth-sort PConstants/ENABLE_DEPTH_SORT :disable-depth-sort PConstants/DISABLE_DEPTH_SORT :disable-opengl-error-report PConstants/DISABLE_OPENGL_ERROR_REPORT :enable-opengl-error-report PConstants/ENABLE_OPENGL_ERROR_REPORT :enable-accurate-textures PConstants/ENABLE_ACCURATE_TEXTURES :disable-accurate-textures PConstants/DISABLE_ACCURATE_TEXTURES :disable-depth-mask PConstants/DISABLE_DEPTH_MASK :enable-depth-mask PConstants/ENABLE_DEPTH_MASK}) (defn ^{:requires-bindings true :processing-name "hint()" :category "Rendering" :subcategory nil :added "1.0"} hint "Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be implemented in a consistent manner across renderers. Many options will often graduate to standard features instead of hints over time. Options: :enable-opengl-4x-smooth - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's control panel, however not all cards make this available. This hint must be called immediately after the size command because it resets the renderer, obliterating any settings and anything drawn (and like size(), re-running the code that came before it again). :disable-opengl-2x-smooth - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in earlier releases, where smooth and no-smooth could be used to enable and disable smoothing, though the quality was inferior. :enable-opengl-2x-smooth - Enables default OpenGL smoothing. :enable-native-fonts - Use the native version fonts when they are installed, rather than the bitmapped version from a .vlw file. This is useful with the default (or JAVA2D) renderer setting, as it will improve font rendering speed. This is not enabled by default, because it can be misleading while testing because the type will look great on your machine (because you have the font installed) but lousy on others' machines if the identical font is unavailable. This option can only be set per-sketch, and must be called before any use of text-font. :disable-native-fonts - Disables native font support. :disable-depth-test - Disable the zbuffer, allowing you to draw on top of everything at will. When depth testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with :enable-depth-test but note that with the depth buffer cleared, any 3D drawing that happens later in draw will ignore existing shapes on the screen. :enable-depth-test - Enables the zbuffer. :enable-depth-sort - Enable primitive z-sorting of triangles and lines in :p3d and :opengl rendering modes. This can slow performance considerably, and the algorithm is not yet perfect. :disable-depth-sort - Disables hint :enable-depth-sort :disable-opengl-error-report - Speeds up the OPENGL renderer setting by not checking for errors while running. :enable-opengl-error-report - Turns on OpenGL error checking :enable-accurate-textures :disable-accurate-textures :enable-depth-mask :disable-depth-mask" [hint-type] (let [hint-type (if (keyword? hint-type) (get hint-options hint-type) hint-type)] (.hint (current-surface) (int hint-type)))) (defn ^{:requires-bindings false :processing-name "hour()" :category "Input" :subcategory "Time & Date" :added "1.0"} hour "Returns the current hour as a value from 0 - 23." [] (PApplet/hour)) (defn ^{:requires-bindings true :processing-name "hue()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} hue "Extracts the hue value from a color." [col] (.hue (current-surface) (int col))) (defn ^{:requires-bindings true :processing-name "image()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} image "Displays images to the screen. Processing currently works with GIF, JPEG, and Targa images. The color of an image may be modified with the tint function and if a GIF has transparency, it will maintain its transparency. The img parameter specifies the image to display and the x and y parameters define the location of the image from its upper-left corner. The image is displayed at its original size unless the width and height parameters specify a different size. The image-mode fn changes the way the parameters work. A call to (image-mode :corners) will change the width and height parameters to define the x and y values of the opposite corner of the image. Starting with release 0124, when using the default (JAVA2D) renderer, smooth will also improve image quality of resized images." ([^PImage img x y] (.image (current-surface) img (float x) (float y))) ([^PImage img x y c d] (.image (current-surface) img (float x) (float y) (float c) (float d))) ([^PImage img x y c d u1 v1 u2 v2] (.image (current-surface) img (float x) (float y) (float c) (float d) (float u1) (float v1) (float u2) (float v2)))) (def ^{:private true} image-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER}) (defn ^{:requires-bindings true :processing-name "imageMode()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} image-mode "Modifies the location from which images draw. The default mode is :corner. Available modes are: :corner - specifies the location to be the upper left corner and uses the fourth and fifth parameters of image to set the image's width and height. :corners - uses the second and third parameters of image to set the location of one corner of the image and uses the fourth and fifth parameters to set the opposite corner. :center - draw images centered at the given x and y position." [mode] (let [mode (resolve-constant-key mode image-modes)] (.imageMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "lightFalloff()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} light-falloff "Sets the falloff rates for point lights, spot lights, and ambient lights. The parameters are used to determine the falloff with the following equation: d = distance from light position to vertex position falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * QUADRATIC) Like fill, it affects only the elements which are created after it in the code. The default value is (light-falloff 1.0 0.0 0.0). Thinking about an ambient light with a falloff can be tricky. It is used, for example, if you wanted a region of your scene to be lit ambiently one color and another region to be lit ambiently by another color, you would use an ambient light with location and falloff. You can think of it as a point light that doesn't care which direction a surface is facing." [constant linear quadratic] (.lightFalloff (current-surface) (float constant) (float linear) (float quadratic))) (defn ^{:requires-bindings true :processing-name "lerpColor()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} lerp-color "Calculates a color or colors between two color at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc." [c1 c2 amt] (.lerpColor (current-surface) (int c1) (int c2) (float amt))) (defn ^{:requires-bindings false :processing-name "lerp()" :category "Math" :subcategory "Calculation" :added "1.0"} lerp "Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines." [start stop amt] (PApplet/lerp (float start) (float stop) (float amt))) (defn ^{:requires-bindings true :processing-name "key" :category "Input" :subcategory "Keyboard" :added "1.0"} raw-key "Contains the value of the most recent key on the keyboard that was used (either pressed or released). For non-ASCII keys, use the keyCode variable. The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of keyCode If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. Check for both ENTER and RETURN to make sure your program will work for all platforms." [] (.-key (current-applet))) (defn ^{:requires-bindings true :processing-name "keyCode" :category "Input" :subcategory "Keyboard" :added "1.0"} key-code "The variable keyCode is used to detect special keys such as the UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking for these keys, it's first necessary to check and see if the key is coded. This is done with the conditional (= (key) CODED). The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the key variable instead of key-code If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh. Check for both ENTER and RETURN to make sure your program will work for all platforms. For users familiar with Java, the values for UP and DOWN are simply shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other keyCode values can be found in the Java KeyEvent reference." [] (.-keyCode (current-applet))) (defn ^{:requires-bindings true :processing-name "keyPressed" :category "Input" :subcategory "Keyboard" :added "1.0"} key-pressed? "true if any key is currently pressed, false otherwise." [] (.-keyPressed (current-applet))) (defn ^{:requires-bindings true :processing-name "lights()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} lights "Sets the default ambient light, directional light, falloff, and specular values. The defaults are: (ambient-light 128 128 128) (directional-light 128 128 128 0 0 -1) (light-falloff 1 0 0) (light-specular 0 0 0). Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop." [] (.lights (current-surface))) (defn ^{:requires-bindings true :processing-name "lightSpecular()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} light-specular "Sets the specular color for lights. Like fill, it affects only the elements which are created after it in the code. Specular refers to light which bounces off a surface in a perferred direction (rather than bouncing in all directions like a diffuse light) and is used for creating highlights. The specular quality of a light interacts with the specular material qualities set through the specular and shininess functions." [r g b] (.lightSpecular (current-surface) (float r) (float g) (float b))) (defn ^{:requires-bindings true :processing-name "line()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} line "Draws a line (a direct path between two points) to the screen. The version of line with four parameters draws the line in 2D. To color a line, use the stroke function. A line cannot be filled, therefore the fill method will not affect the color of a line. 2D lines are drawn with a width of one pixel by default, but this can be changed with the stroke-weight function. The version with six parameters allows the line to be placed anywhere within XYZ space. " ([p1 p2] (apply line (concat p1 p2))) ([x1 y1 x2 y2] (.line (current-surface) (float x1) (float y1) (float x2) (float y2))) ([x1 y1 z1 x2 y2 z2] (.line (current-surface) (float x1) (float y1) (float z1) (float x2) (float y2) (float z2)))) (defn ^{:requires-bindings true :processing-name "loadBytes()" :category "Input" :subcategory "Files" :added "1.0"} load-bytes "Reads the contents of a file or url and places it in a byte array. The filename parameter can also be a URL to a file found online." [filename] (.loadBytes (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} load-font "Loads a font into a variable of type PFont. To load correctly, fonts must be located in the data directory of the current sketch. To create a font to use with Processing use the create-font fn. Like load-image and other methods that load data, the load-font fn should not be used inside draw, because it will slow down the sketch considerably, as the font will be re-loaded from the disk (or network) on each frame. For most renderers, Processing displays fonts using the .vlw font format, which uses images for each letter, rather than defining them through vector data. When hint :enable-native-fonts is used with the JAVA2D renderer, the native version of a font will be used if it is installed on the user's machine. Using create-font (instead of load-font) enables vector data to be used with the JAVA2D (default) renderer setting. This can be helpful when many font sizes are needed, or when using any renderer based on JAVA2D, such as the PDF library." [filename] (.loadFont (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadImage()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} load-image "Loads an image into a variable of type PImage. Four types of images ( .gif, .jpg, .tga, .png) images may be loaded. To load correctly, images must be located in the data directory of the current sketch. In most cases, load all images in setup to preload them at the start of the program. Loading images inside draw will reduce the speed of a program. The filename parameter can also be a URL to a file found online. The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to load-image. If an image is not loaded successfully, the null value is returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned from load-image is nil. Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because load-image will attempt to interpret the HTML as image data." [filename] (.loadImage (current-applet) (str filename))) (defn ^{:requires-bindings true :processing-name "loadPixels()" :category "Image" :subcategory "Pixels" :added "1.0"} load-pixels "Loads the pixel data for the display window into the pixels[] array. This function must always be called before reading from or writing to pixels. Certain renderers may or may not seem to require load-pixels or update-pixels. However, the rule is that any time you want to manipulate the pixels array, you must first call load-pixels, and after changes have been made, call updatePixels. Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change." [] (.loadPixels (current-surface))) (defn ^{:requires-bindings true :processing-name "loadShape()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} load-shape "Load a geometry from a file as a PShape." [filename] (.loadShape (current-applet) filename)) (defn ^{:requires-bindings true :processing-name "loadStrings()" :category "Input" :subcategory "Files" :added "1.0"} load-strings "Load data from a file and shove it into a String array." [filename] (.loadStrings (current-applet) filename)) (defn ^{:requires-bindings false :processing-name "log()" :category "Math" :subcategory "Calculation" :added "1.0"} log "Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the values greater than 0.0." [val] (PApplet/log (float val))) (defn ^{:requires-bindings true :processing-name "loop()" :category "Structure" :subcategory nil :added "1.0"} start-loop "Causes Processing to continuously execute the code within draw. If no-loop is called, the code in draw stops executing." [] (.loop (current-applet))) (defn ^{:requires-bindings false :processing-name "mag()" :category "Math" :subcategory "Calculation" :added "1.0"} mag "Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no start position, the magnitude of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. Therefore, mag is a shortcut for writing (dist 0 0 x y)." ([a b] (PApplet/mag (float a) (float b))) ([a b c] (PApplet/mag (float a) (float b) (float c)))) (defn ^{:requires-bindings false :processing-name "map()" :category "Math" :subcategory "Calculation" :added "1.0"} map-range "Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful." [val low1 high1 low2 high2] (PApplet/map (float val) (float low1) (float high1) (float low2) (float high2))) (defn ^{:requires-bindings false :processing-name nil :category "Image" :subcategory "Loading & Displaying" :added "1.0"} mask-image "Masks part of an image from displaying by loading another image and using it as an alpha channel. This mask image should only contain grayscale data, but only the blue color channel is used. The mask image needs to be the same size as the image to which it is applied. This method is useful for creating dynamically generated alpha masks." [^PImage img] (.mask (current-surface) img)) (defn ^{:requires-bindings true :processing-name "millis()" :category "Input" :subcategory "Time & Date" :added "1.0"} millis "Returns the number of milliseconds (thousandths of a second) since starting the sketch. This information is often used for timing animation sequences." [] (.millis (current-applet))) (defn ^{:requires-bindings false :processing-name "minute()" :category "Input" :subcategory "Time & Date" :added "1.0"} minute "Returns the current minute as a value from 0 - 59" [] (PApplet/minute)) (defn ^{:requires-bindings true :processing-name "modelX()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-x "Returns the three-dimensional x, y, z position in model space. This returns the x value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The x value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "modelY()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-y "Returns the three-dimensional x, y, z position in model space. This returns the y value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The y value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelY (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "modelZ()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} model-z "Returns the three-dimensional x, y, z position in model space. This returns the z value for a given coordinate based on the current set of transformations (scale, rotate, translate, etc.) The z value can be used to place an object in space relative to the location of the original point once the transformations are no longer in use." [x y z] (.modelZ (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings false :processing-name "month()" :category "Input" :subcategory "Time & Date" :added "1.0"} month "Returns the current month as a value from 1 - 12." [] (PApplet/month)) (defn ^{:requires-bindings true :processing-name "mouseButton" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-button "The value of the system variable mouseButton is either :left, :right, or :center depending on which button is pressed." [] (let [button-code (.-mouseButton (current-applet))] (condp = button-code PConstants/LEFT :left PConstants/RIGHT :right PConstants/CENTER :center))) (defn ^{:requires-bindings true :processing-name "mousePressed" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-state "Variable storing if a mouse button is pressed. The value of the system variable mousePressed is true if a mouse button is pressed and false if a button is not pressed." [] (.-mousePressed (current-applet))) (defn ^{:requires-bindings true :processing-name "mouseX" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-x "Current horizontal coordinate of the mouse." [] (.-mouseX (current-applet))) (defn ^{:requires-bindings true :processing-name "mouseY" :category "Input" :subcategory "Mouse" :added "1.0"} mouse-y "Current vertical coordinate of the mouse." [] (.-mouseY (current-applet))) (defn ^{:requires-bindings true :processing-name "pmouseX" :category "Input" :subcategory "Mouse" :added "1.0"} pmouse-x "Horizontal coordinate of the mouse in the previous frame" [] (.-pmouseX (current-applet))) (defn ^{:requires-bindings true :processing-name "pmouseY" :category "Input" :subcategory "Mouse" :added "1.0"} pmouse-y "Vertical coordinate of the mouse in the previous frame" [] (.-pmouseY (current-applet))) (defn ^{:requires-bindings true :processing-name "noCursor()" :category "Environment" :subcategory nil :added "1.0"} no-cursor "Hides the cursor from view. Will not work when running the in full screen (Present) mode." [] (.noCursor (current-applet))) (defn ^{:requires-bindings true :processing-name "noFill()" :category "Color" :subcategory "Setting" :added "1.0"} no-fill "Disables filling geometry. If both no-stroke and no-fill are called, nothing will be drawn to the screen." [] (.noFill (current-surface))) (defn ^{:requires-bindings true :processing-name "noise()" :category "Math" :subcategory "Random" :added "1.0"} noise "Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random function. It was invented by PI:NAME:<NAME>END_PI in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. The main difference to the random function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program). The resulting value will always be between 0.0 and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The noise value can be animated by moving through the noise space and the 2nd and 3rd dimensions can also be interpreted as time. The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result. Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use." ([x] (.noise (current-applet) (float x))) ([x y] (.noise (current-applet) (float x) (float y))) ([x y z] (.noise (current-applet) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "noiseDetail()" :category "Math" :subcategory "Random" :added "1.0"} noise-detail "Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overal intensity of the noise, whereas higher octaves create finer grained details in the noise sequence. By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise. By changing these parameters, the signal created by the noise function can be adapted to fit very specific needs and characteristics." ([octaves] (.noiseDetail (current-applet) (int octaves))) ([octaves falloff] (.noiseDetail (current-applet) (int octaves) (float falloff)))) (defn ^{:requires-bindings true :processing-name "noiseSeed()" :category "Math" :subcategory "Random" :added "1.0"} noise-seed "Sets the seed value for noise. By default, noise produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run." [val] (.noiseSeed (current-applet) (int val))) (defn ^{:requires-bindings true :processing-name "noLights()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} no-lights "Disable all lighting. Lighting is turned off by default and enabled with the lights fn. This function can be used to disable lighting so that 2D geometry (which does not require lighting) can be drawn after a set of lighted 3D geometry." [] (.noLights (current-surface))) (defn ^{:requires-bindings true :processing-name "noLoop()" :category "Structure" :subcategory nil :added "1.0"} no-loop "Stops Processing from continuously executing the code within draw. If start-loop is called, the code in draw will begin to run continuously again. If using no-loop in setup, it should be the last line inside the block. When no-loop is used, it's not possible to manipulate or access the screen inside event handling functions such as mouse-pressed or key-pressed. Instead, use those functions to call redraw or loop which will run draw, which can update the screen properly. This means that when no-loop has been called, no drawing can happen, and functions like save-frame or load-pixels may not be used. Note that if the sketch is resized, redraw will be called to update the sketch, even after no-oop has been specified. Otherwise, the sketch would enter an odd state until loop was called." [] (.noLoop (current-applet))) (defn ^{:requires-bindings true :processing-name "norm()" :category "Math" :subcategory "Calculation" :added "1.0"} norm "Normalize a value to exist between 0 and 1 (inclusive)." [val start stop] (PApplet/norm (float val) (float start) (float stop))) (defn ^{:requires-bindings true :processing-name "normal()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} normal "Sets the current normal vector. This is for drawing three dimensional shapes and surfaces and specifies a vector perpendicular to the surface of the shape which determines how lighting affects it. Processing attempts to automatically assign normals to shapes, but since that's imperfect, this is a better option when you want more control. This function is identical to glNormal3f() in OpenGL." [nx ny nz] (.normal (current-surface) (float nx) (float ny) (float nz))) (defn ^{:requires-bindings true :processing-name "noSmooth()" :category "Shape" :subcategory "Attributes" :added "1.0"} no-smooth "Draws all geometry with jagged (aliased) edges." [] (.noSmooth (current-surface))) (defn ^{:requires-bindings true :processing-name "noStroke()" :category "Color" :subcategory "Setting" :added "1.0"} no-stroke "Disables drawing the stroke (outline). If both no-stroke and no-fill are called, nothing will be drawn to the screen." [] (.noStroke (current-surface))) (defn ^{:requires-bindings true :processing-name "noTint()" :category "Color" :subcategory "Loading & Displaying" :added "1.0"} no-tint "Removes the current fill value for displaying images and reverts to displaying images with their original hues." [] (.noTint (current-surface))) (defn ^{:requires-bindings true :processing-name "ortho()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} ortho "Sets an orthographic projection and defines a parallel clipping volume. All objects with the same dimension appear the same size, regardless of whether they are near or far from the camera. The parameters to this function specify the clipping volume where left and right are the minimum and maximum x values, top and bottom are the minimum and maximum y values, and near and far are the minimum and maximum z values. If no parameters are given, the default is used: ortho(0, width, 0, height, -10, 10)." ([] (.ortho (current-surface))) ([left right bottom top near far] (.ortho (current-surface) (float left) (float right) (float bottom) (float top) (float near) (float far)))) (defn ^{:requires-bindings true :processing-name "perspective()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} perspective "Sets a perspective projection applying foreshortening, making distant objects appear smaller than closer ones. The parameters define a viewing volume with the shape of truncated pyramid. Objects near to the front of the volume appear their actual size, while farther objects appear smaller. This projection simulates the perspective of the world more accurately than orthographic projection. The version of perspective without parameters sets the default perspective and the version with four parameters allows the programmer to set the area precisely. The default values are: perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));" ([] (.perspective (current-surface))) ([fovy aspect z-near z-far] (.perspective (current-surface) (float fovy) (float aspect) (float z-near) (float z-far)))) (defn ^{:requires-bindings true :processing-name "point()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} point "Draws a point, a coordinate in space at the dimension of one pixel. The first parameter is the horizontal value for the point, the second value is the vertical value for the point, and the optional third value is the depth value. Drawing this shape in 3D using the z parameter requires the :P3D or :opengl renderer to be used." ([x y] (.point (current-surface) (float x)(float y))) ([x y z] (.point (current-surface) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "pointLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} point-light "Adds a point light. Lights need to be included in the draw() to remain persistent in a looping program. Placing them in the setup() of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The x, y, and z parameters set the position of the light" [r g b x y z] (.pointLight (current-surface) (float r) (float g) (float b) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "popMatrix()" :category "Transform" :subcategory nil :added "1.0"} pop-matrix "Pops the current transformation matrix off the matrix stack. Understanding pushing and popping requires understanding the concept of a matrix stack. The push-matrix fn saves the current coordinate system to the stack and pop-matrix restores the prior coordinate system. push-matrix and pop-matrix are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations." [] (.popMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "popStyle()" :category "Structure" :subcategory nil :added "1.0"} pop-style "Restores the prior settings on the 'style stack'. Used in conjunction with push-style. Together they allow you to change the style settings and later return to what you had. When a new style is started with push-style, it builds on the current style information. The push-style and pop-style functions can be nested to provide more control" [] (.popStyle (current-surface))) (defn ^{:requires-bindings false :processing-name "pow()" :category "Math" :subcategory "Calculation" :added "1.0"} pow "Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocal) in large quantities. For example, (pow 3 5) is equivalent to the expression (* 3 3 3 3 3) and (pow 3 -5) is equivalent to (/ 1 (* 3 3 3 3 3))." [num exponent] (PApplet/pow (float num) (float exponent))) (defn ^{:requires-bindings true :processing-name "printCamera()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} print-camera "Prints the current camera matrix to std out. Useful for debugging." [] (.printCamera (current-surface))) (defn ^{:requires-bindings true :processing-name "printMatrix()" :category "Transform" :subcategory nil :added "1.0"} print-matrix "Prints the current matrix to std out. Useful for debugging." [] (.printMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "printProjection()" :category "Lights, Camera" :subcategory "Camera" :added "1.0"} print-projection "Prints the current projection matrix to std out. Useful for debugging" [] (.printProjection (current-surface))) (defn ^{:requires-bindings true :processing-name "pushMatrix()" :category "Transform" :subcategory nil :added "1.0"} push-matrix "Pushes the current transformation matrix onto the matrix stack. Understanding push-matrix and pop-matrix requires understanding the concept of a matrix stack. The push-matrix function saves the current coordinate system to the stack and pop-matrix restores the prior coordinate system. push-matrix and pop-matrix are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations." [] (.pushMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "pushStyle()" :category "Structure" :subcategory nil :added "1.0"} push-style "Saves the current style settings onto a 'style stack'. Use with pop-style which restores the prior settings. Note that these functions are always used together. They allow you to change the style settings and later return to what you had. When a new style is started with push-style, it builds on the current style information. The push-style and pop-style fns can be embedded to provide more control. The style information controlled by the following functions are included in the style: fill, stroke, tint, stroke-weight, stroke-cap, stroke-join, image-mode, rect-mode, ellipse-mode, shape-mode, color-mode, text-align, text-font, text-mode, text-size, text-leading, emissive, specular, shininess, and ambient" [] (.pushStyle (current-surface))) (defn ^{:requires-bindings true :processing-name "quad()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} quad "A quad is a quadrilateral, a four sided polygon. It is similar to a rectangle, but the angles between its edges are not constrained to be ninety degrees. The first pair of parameters (x1,y1) sets the first vertex and the subsequent pairs should proceed clockwise or counter-clockwise around the defined shape." [x1 y1 x2 y2 x3 y3 x4 y4] (.quad (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3) (float x4) (float y4))) (defn ^{:requires-bindings false :processing-name "radians()" :category "Math" :subcategory "Trigonometry" :added "1.0"} radians "Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90째 = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians." [degrees] (PApplet/radians (float degrees))) (defn ^{:requires-bindings true :processing-name "random()" :category "Math" :subcategory "Random" :added "1.0"} random "Generates random numbers. Each time the random function is called, it returns an unexpected value within the specified range. If one parameter is passed to the function it will return a float between zero and the value of the high parameter. The function call (random 5) returns values between 0 and 5 (starting at zero, up to but not including 5). If two parameters are passed, it will return a float with a value between the the parameters. The function call (random -5 10.2) returns values starting at -5 up to (but not including) 10.2." ([max] (.random (current-applet) (float max))) ([min max] (.random (current-applet) (float min) (float max)))) (defn ^{:requires-bindings true :processing-name "randomSeed()" :category "Math" :subcategory "Random" :added "1.0"} random-seed "Sets the seed value for random. By default, random produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run." [w] (.randomSeed (current-applet) (float w))) (defn ^{:requires-bindings true :processing-name "rect()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} rect "Draws a rectangle to the screen. A rectangle is a four-sided shape with every angle at ninety degrees. By default, the first two parameters set the location of the upper-left corner, the third sets the width, and the fourth sets the height. These parameters may be changed with rect-mode." [x y width height] (.rect (current-surface) (float x) (float y) (float width) (float height))) (def ^{:private true} rect-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER :radius PApplet/RADIUS}) (defn ^{:requires-bindings true :processing-name "rectMode()" :category "Shape" :subcategory "Attributes" :added "1.0"} rect-mode "Modifies the location from which rectangles draw. The default mode is :corner. Available modes are: :corner - Specifies the location to be the upper left corner of the shape and uses the third and fourth parameters of rect to specify the width and height. :corners - Uses the first and second parameters of rect to set the location of one corner and uses the third and fourth parameters to set the opposite corner. :center - Draws the image from its center point and uses the third and forth parameters of rect to specify the image's width and height. :radius - Draws the image from its center point and uses the third and forth parameters of rect() to specify half of the image's width and height." [mode] (let [mode (resolve-constant-key mode rect-modes)] (.rectMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "red()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} red "Extracts the red value from a color, scaled to match current color-mode." [c] (.red (current-surface) (int c))) (defn ^{:requires-bindings true :processing-name "redraw()" :category "Structure" :subcategory nil :added "1.0"} redraw "Executes the code within the draw fn one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mouse-pressed or key-pressed occurs. In structuring a program, it only makes sense to call redraw within events such as mouse-pressed. This is because redraw does not run draw immediately (it only sets a flag that indicates an update is needed). Calling redraw within draw has no effect because draw is continuously called anyway." [] (.redraw (current-applet))) (defn ^{:requires-bindings true :processing-name "requestImage()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} request-image "This function load images on a separate thread so that your sketch does not freeze while images load during setup. While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1. You'll know when the image has loaded properly because its width and height will be greater than 0. Asynchronous image loading (particularly when downloading from a server) can dramatically improve performance. The extension parameter is used to determine the image type in cases where the image filename does not end with a proper extension. Specify the extension as the second parameter to request-image." ([filename] (.requestImage (current-applet) (str filename))) ([filename extension] (.requestImage (current-applet) (str filename) (str extension)))) (defn ^{:requires-bindings true :processing-name "resetMatrix()" :category "Transform" :subcategory nil :added "1.0"} reset-matrix "Replaces the current matrix with the identity matrix. The equivalent function in OpenGL is glLoadIdentity()" [] (.resetMatrix (current-surface))) (defn ^{:requires-bindings true :processing-name "rotate()" :category "Transform" :subcategory nil :added "1.0"} rotate "Rotates a shape the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO-PI) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate HALF-PI) and then (rotate HALF-PI) is the same as (rotate PI). All tranformations are reset when draw begins again. Technically, rotate multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix." ([angle] (.rotate (current-surface) (float angle))) ([angle vx vy vz] (.rotate (current-surface) (float angle) (float vx) (float vy) (float vz)))) (defn ^{:requires-bindings true :processing-name "rotateX()" :category "Transform" :subcategory nil :added "1.0"} rotate-x "Rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-x HALF-PI) and then (rotate-x HALF-PI) is the same as (rotate-x PI). If rotate-x is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateX (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "rotateY()" :category "Transform" :subcategory nil :added "1.0"} rotate-y "Rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-y HALF-PI) and then (rotate-y HALF-PI) is the same as (rotate-y PI). If rotate-y is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateY (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "rotateZ()" :category "Transform" :subcategory nil :added "1.0"} rotate-z "Rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to (* PI 2)) or converted to radians with the radians function. Objects are always rotated around their relative position to the origin and positive numbers rotate objects in a counterclockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (rotate-z HALF-PI) and then (rotate-z HALF-PI) is the same as (rotate-z PI). If rotate-y is called within the draw fn, the transformation is reset when the loop begins again. This function requires either the :p3d or :opengl renderer." [angle] (.rotateZ (current-surface) (float angle))) (defn ^{:requires-bindings false :processing-name "round()" :category "Math" :subcategory "Calculation" :added "1.0"} round "Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9." [val] (PApplet/round (float val))) (defn ^{:requires-bindings true :processing-name "saturation()" :category "Color" :subcategory "Creating & Reading" :added "1.0"} saturation "Extracts the saturation value from a color." [c] (.saturation (current-surface) (int c))) (defn ^{:requires-bindings true :processing-name "save()" :category "Output" :subcategory "Image" :added "1.0"} save "Saves an image from the display window. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on the extension within the filename parameter. For example, image.tif will have a TIFF image and image.png will save a PNG image. If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name. All images saved from the main drawing window will be opaque. To save images without a background, use create-graphics." [filename] (.save (current-surface) (str filename))) (defn ^{:requires-bindings true :processing-name "saveFrame()" :category "Output" :subcategory "Image" :added "1.0"} save-frame "Saves an image identical to the current display window as a file. May be called multple times - each file saved will have a unique name. Name and image formate may be modified by passing a string parameter of the form \"foo-####.ext\" where foo- can be any arbitrary string, #### will be replaced with the current frame id and .ext is one of .tiff, .targa, .png, .jpeg or .jpg Examples: (save-frame) (save-frame \"pretty-pic-####.jpg\")" ([] (.saveFrame (current-applet))) ([name] (.saveFrame (current-applet) (str name)))) (defn ^{:requires-bindings true :processing-name "scale()" :category "Transform" :subcategory nil :added "1.0"} scale "Increases or decreases the size of a shape by expanding and contracting vertices. Objects always scale from their relative origin to the coordinate system. Scale values are specified as decimal percentages. For example, the function call (scale 2) increases the dimension of a shape by 200%. Transformations apply to everything that happens after and subsequent calls to the function multiply the effect. For example, calling (scale 2) and then (scale 1.5) is the same as (scale 3). If scale is called within draw, the transformation is reset when the loop begins again. Using this fuction with the z parameter requires specfying :p3d or :opengl as the renderer. This function can be further controlled by push-matrix and pop-matrix." ([s] (.scale (current-surface) (float s))) ([sx sy] (.scale (current-surface) (float sx) (float sy)))) (defn- current-screen [] (let [default-toolkit (java.awt.Toolkit/getDefaultToolkit)] (.getScreenSize default-toolkit))) (def ^{:private true} orig-screen-width (let [screen (current-screen)] (.width screen))) (defn ^{:requires-bindings false :processing-name "screen.width" :category "Environment" :subcategory nil :added "1.0"} screen-width "Returns the width of the main screen in pixels." [] orig-screen-width) (def ^{:private true} orig-screen-height (let [screen (current-screen)] (.height screen))) (defn ^{:requires-bindings false :processing-name "screen.height" :category "Environment" :subcategory nil :added "1.0"} screen-height "Returns the height of the main screen in pixels." [] orig-screen-height) (defn ^{:requires-bindings true :processing-name "screenX()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-x "Takes a three-dimensional x, y, z position and returns the x value for where it will appear on a (two-dimensional) screen, once affected by translate, scale or any other transformations" [x y z] (.screenX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "screenY()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-y "Takes a three-dimensional x, y, z position and returns the y value for where it will appear on a (two-dimensional) screen, once affected by translate, scale or any other transformations" [x y z] (.screenY (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings true :processing-name "screenZ()" :category "Lights, Camera" :subcategory "Coordinates" :added "1.0"} screen-z "Given an x, y, z coordinate, returns its z value. This value can be used to determine if an x, y, z coordinate is in front or in back of another (x, y, z) coordinate. The units are based on how the zbuffer is set up, and don't relate to anything 'real'. They're only useful for in comparison to another value obtained from screen-z, or directly out of the zbuffer" [x y z] (.screenX (current-surface) (float x) (float y) (float z))) (defn ^{:requires-bindings false :processing-name "seconds()" :category "Input" :subcategory "Time & Date" :added "1.0"} seconds "Returns the current second as a value from 0 - 59." [] (PApplet/second)) (defn ^{:requires-bindings true :processing-name "set()" :category "Image" :subcategory "Pixels" :added "1.0"} set-pixel "Changes the color of any pixel in the display window. The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). Setting the color of a single pixel with (set x, y) is easy, but not as fast as putting the data directly into pixels[]. This function ignores imageMode(). Due to what appears to be a bug in Apple's Java implementation, the point() and set() methods are extremely slow in some circumstances when used with the default renderer. Using :p2d or :p3d will fix the problem. Grouping many calls to point or set-pixel together can also help. (Bug 1094)" [x y c] (.set (current-surface) (int x) (int y) (int c))) (defn ^{:requires-bindings true :processing-name "set()" :category "Image" :subcategory "Pixels" :added "1.0"} set-image "Writes an image directly into the display window. The x and y parameters define the coordinates for the upper-left corner of the image." [x y ^PImage src] (.set (current-surface) (int x) (int y) src)) (defn ^{:requires-bindings true :processing-name "shape()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} shape "Displays shapes to the screen. The shapes must have been loaded with load-shape. Processing currently works with SVG shapes only. The sh parameter specifies the shape to display and the x and y parameters define the location of the shape from its upper-left corner. The shape is displayed at its original size unless the width and height parameters specify a different size. The shape-mode fn changes the way the parameters work. A call to (shape-mode :corners), for example, will change the width and height parameters to define the x and y values of the opposite corner of the shape. Note complex shapes may draw awkwardly with the renderers :p2d, :p3d, and :opengl. Those renderers do not yet support shapes that have holes or complicated breaks." ([^PShape sh] (.shape (current-surface) sh)) ([^PShape sh x y] (.shape (current-surface) sh (float x) (float y))) ([^PShape sh x y width height] (.shape (current-surface) sh (float x) (float y) (float width) (float height)))) (defn ^{:requires-bindings true :processing-name "shearX()" :category "Transform" :subcategory nil :added "1.0"} shear-x "Shears a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. Objects are always sheared around their relative position to the origin and positive numbers shear objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (shear-x (/ PI 2)) and then (shear-x (/ PI 2)) is the same as (shear-x PI). If shear-x is called within the draw fn, the transformation is reset when the loop begins again. This function works in P2D or JAVA2D mode. Technically, shear-x multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix fns." [angle] (.shearX (current-surface) (float angle))) (defn ^{:requires-bindings true :processing-name "shearY()" :category "Transform" :subcategory nil :added "1.0"} shear-y "Shears a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. Objects are always sheared around their relative position to the origin and positive numbers shear objects in a clockwise direction. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (shear-y (/ PI 2)) and then (shear-y (/ PI 2)) is the same as (shear-y PI). If shear-y is called within the draw fn, the transformation is reset when the loop begins again. This function works in P2D or JAVA2D mode. Technically, shear-y multiplies the current transformation matrix by a rotation matrix. This function can be further controlled by the push-matrix and pop-matrix fns." [angle] (.shearY (current-surface) (float angle))) (def ^{:private true} p-shape-modes {:corner PApplet/CORNER :corners PApplet/CORNERS :center PApplet/CENTER}) (defn ^{:requires-bindings true :processing-name "shapeMode()" :category "Shape" :subcategory "Loading & Displaying" :added "1.0"} shape-mode "Modifies the location from which shapes draw. Available modes are :corner, :corners and :center. Default is :corner. :corner - specifies the location to be the upper left corner of the shape and uses the third and fourth parameters of shape to specify the width and height. :corners - uses the first and second parameters of shape to set the location of one corner and uses the third and fourth parameters to set the opposite corner. :center - draws the shape from its center point and uses the third and forth parameters of shape to specify the width and height. " [mode] (let [mode (resolve-constant-key mode p-shape-modes)] (.shapeMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "shininess()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} shininess "Sets the amount of gloss in the surface of shapes. Used in combination with ambient, specular, and emissive in setting the material properties of shapes." [shine] (.shininess (current-surface) (float shine))) (defn ^{:requires-bindings false :processing-name "sin()" :category "Math" :subcategory "Trigonometry" :added "1.0"} sin "Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to 6.28). A float within the range -1 to 1 is returned." [angle] (PApplet/sin (float angle))) (defn size "Not supported. Use :size key in applet or defapplet" [& args] (println "Deprecated - size should be specified as a :size key to applet or defapplet") nil) (defn ^{:requires-bindings true :processing-name "smooth()" :category "Shape" :subcategory "Attributes" :added "1.0"} smooth "Draws all geometry with smooth (anti-aliased) edges. This will slow down the frame rate of the application, but will enhance the visual refinement. Note that smooth will also improve image quality of resized images." [] (.smooth (current-surface))) (defn ^{:requires-bindings true :processing-name "specular()" :category "Lights, Camera" :subcategory "Material Properties" :added "1.0"} specular "Sets the specular color of the materials used for shapes drawn to the screen, which sets the color of hightlights. Specular refers to light which bounces off a surface in a perferred direction (rather than bouncing in all directions like a diffuse light). Used in combination with emissive, ambient, and shininess in setting the material properties of shapes." ([gray] (.specular (current-surface) (float gray))) ([gray alpha] (.specular (current-surface) (float gray) (float alpha))) ([x y z] (.specular (current-surface) (float x) (float y) (float z))) ([x y z a] (.specular (current-surface) (float x) (float y) (float z) (float a)))) (defn ^{:requires-bindings true :processing-name "sphere()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} sphere "Genarates a hollow ball made from tessellated triangles." [radius] (.sphere (current-surface) (float radius))) (defn ^{:requires-bindings true :processing-name "sphereDetail()" :category "Shape" :subcategory "3D Primitives" :added "1.0"} sphere-detail "Controls the detail used to render a sphere by adjusting the number of vertices of the sphere mesh. The default resolution is 30, which creates a fairly detailed sphere definition with vertices every 360/30 = 12 degrees. If you're going to render a great number of spheres per frame, it is advised to reduce the level of detail using this function. The setting stays active until sphere-detail is called again with a new parameter and so should not be called prior to every sphere statement, unless you wish to render spheres with different settings, e.g. using less detail for smaller spheres or ones further away from the camera. To controla the detail of the horizontal and vertical resolution independently, use the version of the functions with two parameters." ([res] (.sphereDetail (current-surface) (int res))) ([ures vres] (.sphereDetail (current-surface) (int ures) (int vres)))) (defn ^{:requires-bindings true :processing-name "spotLight()" :category "Lights, Camera" :subcategory "Lights" :added "1.0"} spot-light "Adds a spot light. Lights need to be included in the draw to remain persistent in a looping program. Placing them in the setup of a looping program will cause them to only have an effect the first time through the loop. The affect of the r, g, and b parameters is determined by the current color mode. The x, y, and z parameters specify the position of the light and nx, ny, nz specify the direction or light. The angle parameter affects angle of the spotlight cone." ([r g b x y z nx ny nz angle concentration] (.spotLight (current-surface) r g b x y z nx ny nz angle concentration)) ([[r g b] [x y z] [nx ny nz] angle concentration] (.spotLight (current-surface) r g b x y z nx ny nz angle concentration))) (defn ^{:requires-bindings false :processing-name "sq()" :category "Math" :subcategory "Calculation" :added "1.0"} sq "Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1." [a] (PApplet/sq (float a))) (defn ^{:requires-bindings false :processing-name "sqrt()" :category "Math" :subcategory "Calculation" :added "1.0"} sqrt "Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that (= a (* s s)) . It is the opposite of squaring." [a] (PApplet/sqrt (float a))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke-float "Sets the color used to draw lines and borders around shapes. Converts all args to floats" ([gray] (.stroke (current-surface) (float gray))) ([gray alpha] (.stroke (current-surface) (float gray) (float alpha))) ([x y z] (.stroke (current-surface) (float x) (float y) (float z))) ([x y z a] (.stroke (current-surface) (float x) (float y) (float z) (float a)))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke-int "Sets the color used to draw lines and borders around shapes. Converts rgb to int and alpha to a float." ([rgb] (.stroke (current-surface) (int rgb))) ([rgb alpha] (.stroke (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "stroke()" :category "Color" :subcategory "Setting" :added "1.0"} stroke "Sets the color used to draw lines and borders around shapes. This color is either specified in terms of the RGB or HSB color depending on the current color-mode (the default color space is RGB, with each value in the range from 0 to 255)." ([rgb] (if (int-like? rgb) (stroke-int rgb) (stroke-float rgb))) ([rgb alpha] (if (int-like? rgb) (stroke-int rgb alpha) (stroke-float rgb alpha))) ([x y z] (stroke-float x y z)) ([x y z a] (stroke-float x y z a))) (def ^{:private true} stroke-cap-modes {:square PApplet/SQUARE :round PApplet/ROUND :project PApplet/PROJECT :model PApplet/MODEL}) (defn ^{:requires-bindings true :processing-name "strokeCap()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-cap "Sets the style for rendering line endings. These ends are either squared, extended, or rounded and specified with the corresponding parameters :square, :project, and :round. The default cap is :round." [cap-mode] (let [cap-mode (resolve-constant-key cap-mode stroke-cap-modes)] (.strokeCap (current-surface) (int cap-mode)))) (def ^{:private true} stroke-join-modes {:miter PConstants/MITER :bevel PConstants/BEVEL :round PConstants/ROUND}) (defn ^{:requires-bindings true :processing-name "strokeJoin()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-join "Sets the style of the joints which connect line segments. These joints are either mitered, beveled, or rounded and specified with the corresponding parameters :miter, :bevel, and :round. The default joint is :miter. This function is not available with the :p2d, :p3d, or :opengl renderers." [join-mode] (let [join-mode (resolve-constant-key join-mode stroke-join-modes)] (.strokeJoin (current-surface) (int join-mode)))) (defn ^{:requires-bindings true :processing-name "strokeWeight()" :category "Shape" :subcategory "Attributes" :added "1.0"} stroke-weight "Sets the width of the stroke used for lines, points, and the border around shapes. All widths are set in units of pixels. " [weight] (.strokeWeight (current-surface) (float weight))) (defn ^{:requires-bindings false :processing-name "tan()" :category "Math" :subcategory "Trigonometry" :added "1.0"} tan "Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity." [angle] (PApplet/tan (float angle))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-char "Draws a char to the screen in the specified position. See text fn for more details." ([c] (.text (current-surface) (char c))) ([c x y] (.text (current-surface) (char c) (float x) (float y))) ([c x y z] (.text (current-surface) (char c) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-num "Draws a number to the screen in the specified position. See text fn for more details." ([num x y] (.text (current-surface) (float num) (float x) (float y))) ([num x y z] (.text (current-surface) (float num) (float x) (float y) (float z)))) (defn ^{:requires-bindings true :processing-name "text()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text "Draws text to the screen in the position specified by the x and y parameters and the optional z parameter. A default font will be used unless a font is set with the text-font fn. Change the color of the text with the fill fn. The text displays in relation to the text-align fn, which gives the option to draw to the left, right, and center of the coordinates. The x1, y1, x2 and y2 (and optional z) parameters define a rectangular area to display within and may only be used with string data. For text drawn inside a rectangle, the coordinates are interpreted based on the current rect-mode setting. Use the text-mode function with the :screen parameter to display text in 2D at the surface of the window." ([^String s] (.text (current-surface) s)) ([^String s x y] (.text (current-surface) s (float x) (float y))) ([^String s x y z] (.text (current-surface) s (float x) (float y) (float z))) ([^String s x1 y1 x2 y2] (.text (current-surface) s (float x1) (float y1) (float x2) (float y2))) ([^String s x1 y1 x2 y2 z] (.text (current-surface) s (float x1) (float y1) (float x2) (float y2) (float z)))) (def ^{:private true} horizontal-alignment-modes {:left PApplet/LEFT :center PApplet/CENTER :right PApplet/RIGHT}) (def ^{:private true} vertical-alignment-modes {:top PApplet/TOP :bottom PApplet/BOTTOM :center PApplet/CENTER :baseline PApplet/BASELINE}) (defn ^{:requires-bindings true :processing-name "textAlign()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-align "Sets the current alignment for drawing text. Available modes are: horizontal - :left, :center, and :right vertical - :top, :bottom, :center, and :baseline An optional second parameter specifies the vertical alignment mode. :baseline is the default. The :top and :center parameters are straightforward. The :bottom parameter offsets the line based on the current text-descent. For multiple lines, the final line will be aligned to the bottom, with the previous lines appearing above it. When using text with width and height parameters, :baseline is ignored, and treated as :top. (Otherwise, text would by default draw outside the box, since :baseline is the default setting. :baseline is not a useful drawing mode for text drawn in a rectangle.) The vertical alignment is based on the value of text-ascent, which many fonts do not specify correctly. It may be necessary to use a hack and offset by a few pixels by hand so that the offset looks correct. To do this as less of a hack, use some percentage of text-ascent or text-descent so that the hack works even if you change the size of the font." ([align] (let [align (resolve-constant-key align horizontal-alignment-modes)] (.textAlign (current-surface) (int align)))) ([align-x align-y] (let [align-x (resolve-constant-key align-x horizontal-alignment-modes) align-y (resolve-constant-key align-y vertical-alignment-modes)] (.textAlign (current-surface) (int align-x) (int align-y))))) (defn ^{:requires-bindings true :processing-name "textAscent()" :category "Typography" :subcategory "Metrics" :added "1.0"} text-ascent "Returns the ascent of the current font at its current size. This information is useful for determining the height of the font above the baseline. For example, adding the text-ascent and text-descent values will give you the total height of the line." [] (.textAscent (current-surface))) (defn ^{:requires-bindings true :processing-name "textDescent()" :category "Typography" :subcategory "Metrics" :added "1.0"} text-descent "Returns descent of the current font at its current size. This information is useful for determining the height of the font below the baseline. For example, adding the text-ascent and text-descent values will give you the total height of the line." [] (.textDescent (current-surface))) (defn ^{:requires-bindings true :processing-name "textFont()" :category "Typography" :subcategory "Loading & Displaying" :added "1.0"} text-font "Sets the current font that will be drawn with the text function. Fonts must be loaded with load-font before it can be used. This font will be used in all subsequent calls to the text function. If no size parameter is input, the font will appear at its original size until it is changed with text-size. Because fonts are usually bitmaped, you should create fonts at the sizes that will be used most commonly. Using textFont without the size parameter will result in the cleanest-looking text. With the default (JAVA2D) and PDF renderers, it's also possible to enable the use of native fonts via the command (hint :enable-native-fonts). This will produce vector text in JAVA2D sketches and PDF output in cases where the vector data is available: when the font is still installed, or the font is created via the create-font fn" ([^PFont font] (.textFont (current-surface) font)) ([^PFont font size] (.textFont (current-surface) font (int size)))) (defn ^{:requires-bindings true :processing-name "textLeading()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-leading "Sets the spacing between lines of text in units of pixels. This setting will be used in all subsequent calls to the text function." [leading] (.textLeading (current-surface) (float leading))) (def ^{:private true} text-modes {:model PConstants/MODEL :shape PConstants/SHAPE :screen PConstants/SCREEN}) (defn ^{:requires-bindings true :processing-name "textMode()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-mode "Sets the way text draws to the screen - available modes are :model, :shape and :screen In the default configuration (the :model mode), it's possible to rotate, scale, and place letters in two and three dimensional space. Changing to :screen mode draws letters directly to the front of the window and greatly increases rendering quality and speed when used with the :p2d and :p3d renderers. :screen with :opengl and :java2d (the default) renderers will generally be slower, though pixel accurate with :p2d and :p3d. With :screen, the letters draw at the actual size of the font (in pixels) and therefore calls to text-size will not affect the size of the letters. To create a font at the size you desire, use create-font. When using :screen, any z-coordinate passed to a text command will be ignored, because your computer screen is...flat! The :shape mode draws text using the the glyph outlines of individual characters rather than as textures. This mode is only only supported with the PDF and OPENGL renderer settings. With the PDF renderer, you must specify the :shape text-mode before any other drawing occurs. If the outlines are not available, then :shape will be ignored and :model will be used instead. The :shape option in OPENGL mode can be combined with begin-raw to write vector-accurate text to 2D and 3D output files, for instance DXF or PDF. :shape is not currently optimized for OPENGL, so if recording shape data, use :model until you're ready to capture the geometry with begin-raw." [mode] (let [mode (resolve-constant-key mode text-modes)] (.textMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "textSize()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-size "Sets the current font size. This size will be used in all subsequent calls to the text fn. Font size is measured in units of pixels." [size] (.textSize (current-surface) (float size))) (defn ^{:requires-bindings true :processing-name "texture()" :category "Shape" :subcategory "Vertex" :added "1.0"} texture "Sets a texture to be applied to vertex points. The texture fn must be called between begin-shape and end-shape and before any calls to vertex. When textures are in use, the fill color is ignored. Instead, use tint to specify the color of the texture as it is applied to the shape." [^PImage img] (.texture (current-surface) img)) (def ^{:private true} texture-modes {:image PApplet/IMAGE :normalized PApplet/NORMALIZED}) (defn ^{:requires-bindings true :processing-name "textureMode()" :category "Shape" :subcategory "Vertex" :added "1.0"} texture-mode "Sets the coordinate space for texture mapping. There are two options, :image and :normalized. :image refers to the actual coordinates of the image and :normalized refers to a normalized space of values ranging from 0 to 1. The default mode is :image. In :image, if an image is 100 x 200 pixels, mapping the image onto the entire size of a quad would require the points (0,0) (0,100) (100,200) (0,200). The same mapping in NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1)." [mode] (let [mode (resolve-constant-key mode texture-modes)] (.textureMode (current-surface) (int mode)))) (defn ^{:requires-bindings true :processing-name "textWidth()" :category "Typography" :subcategory "Attributes" :added "1.0"} text-width "Calculates and returns the width of any character or text string." [data] (let [data (if (= (class data) (class \a)) (char data) (str data))] (.textWidth (current-surface) data))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint-float "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([gray] (.tint (current-surface) (float gray))) ([gray alpha] (.tint (current-surface) (float gray) (float alpha))) ([r g b] (.tint (current-surface) (float r)(float g) (float b))) ([r g b a] (.tint (current-surface) (float g) (float g) (float b) (float a)))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint-int "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([rgb] (.tint (current-surface) (int rgb))) ([rgb alpha] (.tint (current-surface) (int rgb) (float alpha)))) (defn ^{:requires-bindings true :processing-name "tint()" :category "Image" :subcategory "Loading & Displaying" :added "1.0"} tint "Sets the fill value for displaying images. Images can be tinted to specified colors or made transparent by setting the alpha. To make an image transparent, but not change it's color, use white as the tint color and specify an alpha value. For instance, tint(255, 128) will make an image 50% transparent (unless colorMode() has been used). The value for the parameter gray must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. Also used to control the coloring of textures in 3D." ([rgb] (if (int-like? rgb) (tint-int rgb) (tint-float rgb))) ([rgb alpha] (if (int-like? rgb) (tint-int rgb alpha) (tint-float rgb alpha))) ([r g b] (tint-float r g b)) ([r g b a] (tint-float r g b a))) (defn ^{:requires-bindings true :processing-name "translate()" :category "Transform" :subcategory nil :added "1.0"} translate "Specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling (translate 50 0) and then (translate 20, 0) is the same as (translate 70, 0). If translate is called within draw, the transformation is reset when the loop begins again. This function can be further controlled by the push-matrix and pop-matrix." ([v] (apply translate v)) ([tx ty] (.translate (current-surface) (float tx) (float ty))) ([tx ty tz] (.translate (current-surface) (float tx) (float ty) (float tz)))) (defn ^{:requires-bindings true :processing-name "triangle()" :category "Shape" :subcategory "2D Primitives" :added "1.0"} triangle "A triangle is a plane created by connecting three points. The first two arguments specify the first point, the middle two arguments specify the second point, and the last two arguments specify the third point." [x1 y1 x2 y2 x3 y3] (.triangle (current-surface) (float x1) (float y1) (float x2) (float y2) (float x3) (float y3))) (defn ^{:requires-bindings true :processing-name "updatePixels()" :category "Image" :subcategory "Pixels" :added "1.0"} update-pixels "Updates the display window with the data in the pixels array. Use in conjunction with load-pixels. If you're only reading pixels from the array, there's no need to call update-pixels unless there are changes. Certain renderers may or may not seem to require load-pixels or update-pixels. However, the rule is that any time you want to manipulate the pixels array, you must first call load-pixels, and after changes have been made, call update-pixels. Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change." [] (.updatePixels (current-surface))) (defn ^{:requires-bindings true :processing-name "vertex()" :category "Shape" :subcategory "Vertex" :added "1.0"} vertex "All shapes are constructed by connecting a series of vertices. vertex is used to specify the vertex coordinates for points, lines, triangles, quads, and polygons and is used exclusively within the begin-shape and end-shape fns. Drawing a vertex in 3D using the z parameter requires the :p3d or :opengl renderers to be used. This function is also used to map a texture onto the geometry. The texture fn declares the texture to apply to the geometry and the u and v coordinates set define the mapping of this texture to the form. By default, the coordinates used for u and v are specified in relation to the image's size in pixels, but this relation can be changed with texture-mode." ([x y] (.vertex (current-surface) (float x) (float y))) ([x y z] (.vertex (current-surface) (float x) (float y) (float z))) ([x y u v] (.vertex (current-surface) (float x) (float y) (float u) (float v))) ([x y z u v] (.vertex (current-surface) (float x) (float y) (float z) (float u) (float v)))) (defn ^{:requires-bindings false :processing-name "year()" :category "Input" :subcategory "Time & Date" :added "1.0"} year "Returns the current year as an integer (2003, 2004, 2005, etc)." [] (PApplet/year)) (defn ^{:requires-bindings true :processing-name "width" :category "Environment" :subcategory nil :added "1.0"} width "Width of the display window. The value of width is zero until size is called." [] (.getWidth (current-applet))) (defmacro ^{:requires-bindings true :processing-name nil :category "Transform" :subcategory "Utility Macros"} with-translation "Performs body with translation, restores current transformation on exit." [translation-vector & body] `(let [tr# ~translation-vector] (push-matrix) (translate tr#) ~@body (pop-matrix))) (defmacro ^{:requires-bindings true :processing-name nil :category "Transform" :subcategory "Utility Macros"} with-rotation "Performs body with rotation, restores current transformation on exit. Accepts a vector [angle] or [angle x-axis y-axis z-axis]. Example: (with-rotation [angle] (vertex 1 2))" [rotation & body] `(let [tr# ~rotation] (push-matrix) (apply rotate tr#) ~@body (pop-matrix))) ;;; version number (defn quil-version [] QUIL-VERSION-STR) ;;; doc utils (def ^{:private true} processing-fn-metas "Returns a seq of metadata maps for all fns related to the original Processing API (but may not have a direct Processing API equivalent)." (map #(-> % second meta) (ns-publics *ns*))) (defn- processing-fn-metas-with-orig-method-name "Returns a seq of metadata maps for all fns with a corresponding Processing API method." [] (filter :processing-name processing-fn-metas)) (defn- matching-processing-methods "Takes a string representing the start of a method name in the original Processing API and returns a map of orig/new-name pairs" [orig-name] (let [metas (processing-fn-metas-with-orig-method-name) matches (filter #(.startsWith (:processing-name %) orig-name) metas)] (into {} (map (fn [{:keys [name processing-name]}] [(str processing-name) (str name)]) matches)))) (defn- find-categories [] (let [metas processing-fn-metas cats (into (sorted-set) (map :category metas))] (clojure.set/difference cats #{nil}))) (defn- find-subcategories [category] (let [metas processing-fn-metas in-cat (filter #(= category (:category %)) metas) res (into (sorted-set) (map :subcategory in-cat))] (clojure.set/difference res #{nil}))) (defn- find-fns "Find the names of fns in category cat that don't also belong to a subcategory" [cat subcat] (let [metas processing-fn-metas res (filter (fn [m] (and (= cat (:category m)) (= subcat (:subcategory m)))) metas)] (sort (map :name res)))) (defn- subcategory-map [cat cat-idx] (let [subcats (find-subcategories cat) idxs (map inc (range)) idxd-subcats (map (fn [idx subcat] [(str cat-idx "." idx) subcat]) idxs subcats)] (into {} (map (fn [[idx subcat]] [idx {:name subcat :fns (find-fns cat subcat)}]) idxd-subcats)))) (defn- sorted-category-map [] (let [cats (find-categories) idxs (map inc (range)) idxd-cats (into {} (map (fn [idx cat] [idx cat]) idxs cats))] (into (sorted-map) (map (fn [[idx cat]] [idx {:name cat :fns (find-fns cat nil) :subcategories (subcategory-map cat idx)}]) idxd-cats)))) (defn- all-category-map [] (reduce (fn [sum [k v]] (merge sum (:subcategories v))) (into {} (map (fn [[k v]] [(str k) v]) (sorted-category-map))) (sorted-category-map))) (defn show-cats "Print out a list of all the categories and subcategories, associated index nums and fn count (in parens)." [] (let [cats (sorted-category-map)] (dorun (map (fn [[cat-idx cat]] (println cat-idx (:name cat) (str "(" (count (find-fns (:name cat) nil)) ")")) (dorun (map (fn [[subcat-idx subcat]] (println " " subcat-idx (:name subcat) (str "(" (count (find-fns (:name cat) (:name subcat))) ")"))) (:subcategories cat)))) cats)))) (defn- wrap-lines "Split a list of words in lists (lines) not longer than width chars each, space between words included." [width words] (letfn [(wrap-lines-rec [ws accum-lns] (if (empty? ws) accum-lns (let [lens (map count ws) cumlens (reduce (fn [sums len] (conj sums (if (empty? sums) len (+ (last sums) len 1)))) [] lens) [line other] (split-with #(> width %) cumlens) [line other] (split-at (count line) ws)] (recur other (conj accum-lns line)))))] (wrap-lines-rec words []))) (defn- pprint-wrapped-lines "Pretty print words across several lines by wrapping lines at word boundary." [words & {:keys [fromcolumn width] :or {fromcolumn 0 width 80}}] (let [w (- width fromcolumn) wordss (wrap-lines w words) indent (apply str (repeat fromcolumn \space)) lines (map #(apply str indent (interpose " " %)) wordss)] (doseq [l lines] (println l)))) (defn show-fns "If given a number, print all the functions within category or subcategory specified by the category index (use show-cats to see a list of index nums). If given a string or a regular expression, print all the functions whose name or category name contains that string. If a category is specified, it will not print out the fns in any of cat's subcategories." [q] (letfn [(list-category [cid c & {:keys [only]}] (let [category-fns (:fns c) display-fns (if (nil? only) category-fns (clojure.set/intersection (set only) (set category-fns))) names (sort (map str display-fns))] (if (not (empty? names)) (do (println cid (:name c)) (pprint-wrapped-lines names :fromcolumn 4))))) (show-fns-by-cat-idx [cat-idx] (let [c (get (all-category-map) (str cat-idx))] (list-category cat-idx c))) (show-fns-by-name-regex [re] (doseq [[cid c] (sort-by key (all-category-map))] (let [in-cat-name? (re-find re (:name c)) matching-fns (filter #(re-find re (str %)) (:fns c)) in-fn-names? (not (empty? matching-fns))] (cond in-cat-name? (list-category cid c) ;; print an entire category in-fn-names? (list-category cid c :only matching-fns)))))] (cond (string? q) (show-fns-by-name-regex (re-pattern (str "(?i)" q))) (isa? (type q) java.util.regex.Pattern) (show-fns-by-name-regex q) :else (show-fns-by-cat-idx q)))) (defn show-meths "Takes a string representing the start of a method name in the original Processing API and prints out all matches alongside the Processing-core equivalent." [orig-name] (let [res (matching-processing-methods orig-name)] (print-definition-list res)) nil) ;;; Useful trig constants (def PI (float Math/PI)) (def HALF-PI (/ PI (float 2.0))) (def THIRD-PI (/ PI (float 3.0))) (def QUARTER-PI (/ PI (float 4.0))) (def TWO-PI (* PI (float 2.0))) (def DEG-TO-RAD (/ PI (float 180.0))) (def RAD-TO-DEG (/ (float 180.0) PI)) ;; Sketch control (defn sketch-stop "Stop/pause the sketch (restart with sketch-start)" [sketch] (applet-stop sketch)) (defn sketch-state "Fetch an element of state from within the sketch" [sketch k] (applet-state sketch k)) (defn sketch-start "Restart the sketch (if it has been stopped with sketch-stop)" [sketch] (applet-start sketch)) (defn sketch-close "Stop the sketch and close the window" [sketch] (applet-close sketch)) ;; Sketch creation (defn sketch "Create and start a new visualisation applet. :size - a vector of width and height for the sketch. Defaults to [500 300]. :renderer - Specify the renderer type. One of :p2d, :java2d, :opengl, :pdf or :dxf). Defaults to :java2d. If :pdf or :dxf is selected, :target is forced to :none. :output-file - Specify an output file path. Only used in :pdf and :dxf render modes. :title - a string which will be displayed at the top of the sketch window. :target - Specify the target. One of :frame, :perm-frame or :none. Ignored if :pdf or :dxf renderer is used. :decor - Specify if the window should have OS frame decorations. Only honoured with :frame or :perm-frame targets. :setup - a fn to be called once when setting the sketch up. :draw - a fn to be repeatedly called at most n times per second where n is the target frame-rate set for the visualisation. :focus-gained - Called when the sketch gains focus. :focus-lost - Called when the sketch loses focus. :mouse-entered - Called when the mouse enters the sketch window. :mouse-exited - Called when the mouse leaves the sketch window :mouse-pressed - Called every time a mouse button is pressed. :mouse-released - Called every time a mouse button is released. :mouse-clicked - called once after a mouse button has been pressed and then released. :mouse-moved - Called every time the mouse moves and a button is not pressed. :mouse-dragged - Called every time the mouse moves and a button is pressed. :key-pressed - Called every time any key is pressed. :key-released - Called every time any key is released. :key-typed - Called once every time non-modifier keys are pressed. :safe-draw-fn - Catches and prints exceptions in the draw fn. Default is true. :on-close - Called once, when sketch is closed" [& opts] (apply applet opts)) (defmacro defsketch "Define and start a sketch and bind it to a var with the symbol app-name. If any of the options to the various callbacks are symbols, it wraps them in a call to var to ensure they aren't inlined and that redefinitions to the original fns are reflected in the visualisation. See sketch for the available options." [app-name & opts] `(defapplet ~app-name ~@opts)) (defmacro with-graphics "All subsequent calls of any drawing function will draw on given graphics." [graphics & body] `(binding [*graphics* ~graphics] (.beginDraw ~graphics) ~@body (.endDraw ~graphics))) (defn ^{:requires-bindings false :processing-name nil :category "Input" :subcategory "Keyboard" :added "1.6"} key-coded? "Returns true if char c is a 'coded' char i.e. it is necessary to fetch the key-code as an integer and use that to determine the specific key pressed. See key-keyword." [c] (= PConstants/CODED (int c))) (def ^{:private true} KEY-CODES {KeyEvent/VK_UP :up KeyEvent/VK_DOWN :down KeyEvent/VK_LEFT :left KeyEvent/VK_RIGHT :right KeyEvent/VK_ALT :alt KeyEvent/VK_CONTROL :control KeyEvent/VK_SHIFT :shift KeyEvent/VK_WINDOWS :command KeyEvent/VK_META :command KeyEvent/VK_F1 :f1 KeyEvent/VK_F2 :f2 KeyEvent/VK_F3 :f3 KeyEvent/VK_F4 :f4 KeyEvent/VK_F5 :f5 KeyEvent/VK_F6 :f6 KeyEvent/VK_F7 :f7 KeyEvent/VK_F8 :f8 KeyEvent/VK_F9 :f9 KeyEvent/VK_F10 :f10 KeyEvent/VK_F11 :f11 KeyEvent/VK_F12 :f12 KeyEvent/VK_F13 :f13 KeyEvent/VK_F14 :f14 KeyEvent/VK_F15 :f15 KeyEvent/VK_F16 :f16 KeyEvent/VK_F17 :f17 KeyEvent/VK_F18 :f18 KeyEvent/VK_F19 :f19 KeyEvent/VK_F20 :f20 KeyEvent/VK_F21 :f21 KeyEvent/VK_F22 :f22 KeyEvent/VK_F23 :f23 KeyEvent/VK_F24 :f24}) (defn ^{:requires-bindings true :processing-name nil :category "Input" :subcategory "Keyboard" :added "1.6"} key-as-keyword "Returns a keyword representing the currently pressed key. Modifier keys are represented as: :up, :down, :left, :right, :alt, :control, :shift, :command, :f1-24" [] (let [key-char (raw-key) code (key-code)] (if (key-coded? key-char) (get KEY-CODES code :unknown-key) (keyword (str key-char))))) (defn ^{:requires-bindings false :processing-name nil :category "Debugging" :added "1.6"} debug "Prints msg and then sleeps the current thread for delay-ms. Useful for debugging live running sketches. delay-ms defaults to 300. " ([msg] (debug msg 300)) ([msg delay-ms] (println msg) (Thread/sleep delay-ms)))
[ { "context": ";; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team\n;;\n;; The", "end": 45, "score": 0.9998461604118347, "start": 27, "tag": "NAME", "value": "Michael S. Klishin" }, { "context": ";; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team\n;;\n;; The use and dist", "end": 58, "score": 0.9998098015785217, "start": 47, "tag": "NAME", "value": "Alex Petrov" } ]
src/clojure/pantomime/web.clj
dthadi3/pantomime
119
;; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team ;; ;; 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 pantomime.web "Contains the same functions as pantomime.mime but is Web-oriented. Apache Tika as of April 2012 cannot detect PNG, JPEG and other image bytes for byte arrays. However, it is not uncommon to see broken Web frameworks, apps and servers that serve, say, PDF files claiming that they are text/html. pantomime.web attempts to improve the situation by providing special MIME type detection functions that can use content-based detection and Content-Type header at the same time." (:require [pantomime.internal :refer :all]) (:require [pantomime.mime :as mime]) (:import [java.io File InputStream] [java.net URL] [org.apache.tika Tika] [org.apache.tika.mime MediaType MimeType])) (def ^Tika detector (Tika.)) (def ^{:private true :const true} default-mime-type "application/octet-stream") (defn ^{:private true} pick-preference [body-content-type headers-content-type] (if (= default-mime-type body-content-type) (or headers-content-type default-mime-type) body-content-type)) ;; ;; API ;; (defprotocol MIMETypeDetection (mime-type-of [body headers] "Returns MIME type of given response body, headers and url. Detection will try content-based detection (magic bytes, tag detection for XML-based formats, etc) for response body as well as Content-Type header.")) (extend-protocol MIMETypeDetection String (mime-type-of [^String body {content-type "content-type"}] (pick-preference (mime/mime-type-of (.getBytes body)) content-type)) InputStream (mime-type-of [^InputStream body {content-type "content-type"}] (pick-preference (mime/mime-type-of body) content-type))) (extend byte-array-type MIMETypeDetection {:mime-type-of (fn [^bytes body {content-type "content-type"}] (let [bct (mime/mime-type-of body)] (pick-preference bct content-type))) })
62367
;; Copyright (c) 2011-2014 <NAME>, <NAME>, and the ClojureWerkz Team ;; ;; 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 pantomime.web "Contains the same functions as pantomime.mime but is Web-oriented. Apache Tika as of April 2012 cannot detect PNG, JPEG and other image bytes for byte arrays. However, it is not uncommon to see broken Web frameworks, apps and servers that serve, say, PDF files claiming that they are text/html. pantomime.web attempts to improve the situation by providing special MIME type detection functions that can use content-based detection and Content-Type header at the same time." (:require [pantomime.internal :refer :all]) (:require [pantomime.mime :as mime]) (:import [java.io File InputStream] [java.net URL] [org.apache.tika Tika] [org.apache.tika.mime MediaType MimeType])) (def ^Tika detector (Tika.)) (def ^{:private true :const true} default-mime-type "application/octet-stream") (defn ^{:private true} pick-preference [body-content-type headers-content-type] (if (= default-mime-type body-content-type) (or headers-content-type default-mime-type) body-content-type)) ;; ;; API ;; (defprotocol MIMETypeDetection (mime-type-of [body headers] "Returns MIME type of given response body, headers and url. Detection will try content-based detection (magic bytes, tag detection for XML-based formats, etc) for response body as well as Content-Type header.")) (extend-protocol MIMETypeDetection String (mime-type-of [^String body {content-type "content-type"}] (pick-preference (mime/mime-type-of (.getBytes body)) content-type)) InputStream (mime-type-of [^InputStream body {content-type "content-type"}] (pick-preference (mime/mime-type-of body) content-type))) (extend byte-array-type MIMETypeDetection {:mime-type-of (fn [^bytes body {content-type "content-type"}] (let [bct (mime/mime-type-of body)] (pick-preference bct content-type))) })
true
;; Copyright (c) 2011-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and the ClojureWerkz Team ;; ;; 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 pantomime.web "Contains the same functions as pantomime.mime but is Web-oriented. Apache Tika as of April 2012 cannot detect PNG, JPEG and other image bytes for byte arrays. However, it is not uncommon to see broken Web frameworks, apps and servers that serve, say, PDF files claiming that they are text/html. pantomime.web attempts to improve the situation by providing special MIME type detection functions that can use content-based detection and Content-Type header at the same time." (:require [pantomime.internal :refer :all]) (:require [pantomime.mime :as mime]) (:import [java.io File InputStream] [java.net URL] [org.apache.tika Tika] [org.apache.tika.mime MediaType MimeType])) (def ^Tika detector (Tika.)) (def ^{:private true :const true} default-mime-type "application/octet-stream") (defn ^{:private true} pick-preference [body-content-type headers-content-type] (if (= default-mime-type body-content-type) (or headers-content-type default-mime-type) body-content-type)) ;; ;; API ;; (defprotocol MIMETypeDetection (mime-type-of [body headers] "Returns MIME type of given response body, headers and url. Detection will try content-based detection (magic bytes, tag detection for XML-based formats, etc) for response body as well as Content-Type header.")) (extend-protocol MIMETypeDetection String (mime-type-of [^String body {content-type "content-type"}] (pick-preference (mime/mime-type-of (.getBytes body)) content-type)) InputStream (mime-type-of [^InputStream body {content-type "content-type"}] (pick-preference (mime/mime-type-of body) content-type))) (extend byte-array-type MIMETypeDetection {:mime-type-of (fn [^bytes body {content-type "content-type"}] (let [bct (mime/mime-type-of body)] (pick-preference bct content-type))) })
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998096227645874, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
ext/clojure-clojurescript-bef56a7/bin/cljsc.clj
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. (require '[cljs.closure :as closure]) (defn transform-cl-args [args] (let [source (first args) opts-string (apply str (interpose " " (rest args))) options (when (> (count opts-string) 1) (try (read-string opts-string) (catch Exception e (println e))))] {:source source :options (merge {:output-to :print} options)})) (let [args (transform-cl-args *command-line-args*)] (closure/build (:source args) (:options args)))
89516
; 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. (require '[cljs.closure :as closure]) (defn transform-cl-args [args] (let [source (first args) opts-string (apply str (interpose " " (rest args))) options (when (> (count opts-string) 1) (try (read-string opts-string) (catch Exception e (println e))))] {:source source :options (merge {:output-to :print} options)})) (let [args (transform-cl-args *command-line-args*)] (closure/build (:source args) (:options args)))
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. (require '[cljs.closure :as closure]) (defn transform-cl-args [args] (let [source (first args) opts-string (apply str (interpose " " (rest args))) options (when (> (count opts-string) 1) (try (read-string opts-string) (catch Exception e (println e))))] {:source source :options (merge {:output-to :print} options)})) (let [args (transform-cl-args *command-line-args*)] (closure/build (:source args) (:options args)))
[ { "context": "ing!, $password: String!) {\n login(username: $username, password: $password)\n }\")\n\n(defrecord Login [p", "end": 609, "score": 0.5702123045921326, "start": 601, "tag": "USERNAME", "value": "username" }, { "context": "ng!) {\n login(username: $username, password: $password)\n }\")\n\n(defrecord Login [params on-error]\n ptk", "end": 630, "score": 0.718970775604248, "start": 622, "tag": "PASSWORD", "value": "password" } ]
src/front/mee6/events.cljs
mgdelacroix/mee6
2
(ns mee6.events (:require [potok.core :as ptk] [beicon.core :as rx] [mee6.graphql :as gql] [mee6.store :as st] [mee6.util.router :as rt])) ;; --- Helpers (defn- index-by [coll getter] (reduce #(assoc %1 (getter %2) %2) {} coll)) ;; --- Auth Events (defrecord LoggedIn [data] ptk/UpdateEvent (update [_ state] (assoc state :token (:login data))) ptk/WatchEvent (watch [_ state stream] (rx/of (rt/navigate :home)))) (def ^:private +login-query+ "mutation Login($username: String!, $password: String!) { login(username: $username, password: $password) }") (defrecord Login [params on-error] ptk/WatchEvent (watch [_ state stream] (letfn [(handle-error [{:keys [type] :as error}] (if (= type "wrong-credentials") (do (on-error error) (rx/empty)) (rx/throw error)))] (->> (gql/query +login-query+ params) (rx/catch handle-error) (rx/map ->LoggedIn))))) (defrecord LoggedOut [] ptk/UpdateEvent (update [_ state] (dissoc state :token)) ptk/WatchEvent (watch [_ state stream] (rx/of (rt/navigate :login)))) (defrecord Logout [] ptk/WatchEvent (watch [_ state stream] (->> (gql/query "mutation Logout {logout}") (rx/map ->LoggedOut)))) ;; --- Checks Events (defrecord ChecksRetrieved [checks] ptk/UpdateEvent (update [_ state] (->> (index-by checks :id) (assoc state :checks)))) (def ^:private +checks-query+ "query RetrieveCheccks($outputFormat: String!) { checks { id, name, host, cron, status, tags, config, error, updatedAt output(format: $outputFormat) } }") (defrecord RetrieveChecks [] ptk/WatchEvent (watch [_ state stream] (->> (gql/query +checks-query+ {:outputFormat "yaml"}) (rx/map :checks) (rx/map ->ChecksRetrieved)))) (defrecord UpdateSelectedTag [tag] ptk/UpdateEvent (update [_ {:keys [selected-tag] :as state}] (if (= tag selected-tag) (dissoc state :selected-tag) (assoc state :selected-tag tag))))
91537
(ns mee6.events (:require [potok.core :as ptk] [beicon.core :as rx] [mee6.graphql :as gql] [mee6.store :as st] [mee6.util.router :as rt])) ;; --- Helpers (defn- index-by [coll getter] (reduce #(assoc %1 (getter %2) %2) {} coll)) ;; --- Auth Events (defrecord LoggedIn [data] ptk/UpdateEvent (update [_ state] (assoc state :token (:login data))) ptk/WatchEvent (watch [_ state stream] (rx/of (rt/navigate :home)))) (def ^:private +login-query+ "mutation Login($username: String!, $password: String!) { login(username: $username, password: $<PASSWORD>) }") (defrecord Login [params on-error] ptk/WatchEvent (watch [_ state stream] (letfn [(handle-error [{:keys [type] :as error}] (if (= type "wrong-credentials") (do (on-error error) (rx/empty)) (rx/throw error)))] (->> (gql/query +login-query+ params) (rx/catch handle-error) (rx/map ->LoggedIn))))) (defrecord LoggedOut [] ptk/UpdateEvent (update [_ state] (dissoc state :token)) ptk/WatchEvent (watch [_ state stream] (rx/of (rt/navigate :login)))) (defrecord Logout [] ptk/WatchEvent (watch [_ state stream] (->> (gql/query "mutation Logout {logout}") (rx/map ->LoggedOut)))) ;; --- Checks Events (defrecord ChecksRetrieved [checks] ptk/UpdateEvent (update [_ state] (->> (index-by checks :id) (assoc state :checks)))) (def ^:private +checks-query+ "query RetrieveCheccks($outputFormat: String!) { checks { id, name, host, cron, status, tags, config, error, updatedAt output(format: $outputFormat) } }") (defrecord RetrieveChecks [] ptk/WatchEvent (watch [_ state stream] (->> (gql/query +checks-query+ {:outputFormat "yaml"}) (rx/map :checks) (rx/map ->ChecksRetrieved)))) (defrecord UpdateSelectedTag [tag] ptk/UpdateEvent (update [_ {:keys [selected-tag] :as state}] (if (= tag selected-tag) (dissoc state :selected-tag) (assoc state :selected-tag tag))))
true
(ns mee6.events (:require [potok.core :as ptk] [beicon.core :as rx] [mee6.graphql :as gql] [mee6.store :as st] [mee6.util.router :as rt])) ;; --- Helpers (defn- index-by [coll getter] (reduce #(assoc %1 (getter %2) %2) {} coll)) ;; --- Auth Events (defrecord LoggedIn [data] ptk/UpdateEvent (update [_ state] (assoc state :token (:login data))) ptk/WatchEvent (watch [_ state stream] (rx/of (rt/navigate :home)))) (def ^:private +login-query+ "mutation Login($username: String!, $password: String!) { login(username: $username, password: $PI:PASSWORD:<PASSWORD>END_PI) }") (defrecord Login [params on-error] ptk/WatchEvent (watch [_ state stream] (letfn [(handle-error [{:keys [type] :as error}] (if (= type "wrong-credentials") (do (on-error error) (rx/empty)) (rx/throw error)))] (->> (gql/query +login-query+ params) (rx/catch handle-error) (rx/map ->LoggedIn))))) (defrecord LoggedOut [] ptk/UpdateEvent (update [_ state] (dissoc state :token)) ptk/WatchEvent (watch [_ state stream] (rx/of (rt/navigate :login)))) (defrecord Logout [] ptk/WatchEvent (watch [_ state stream] (->> (gql/query "mutation Logout {logout}") (rx/map ->LoggedOut)))) ;; --- Checks Events (defrecord ChecksRetrieved [checks] ptk/UpdateEvent (update [_ state] (->> (index-by checks :id) (assoc state :checks)))) (def ^:private +checks-query+ "query RetrieveCheccks($outputFormat: String!) { checks { id, name, host, cron, status, tags, config, error, updatedAt output(format: $outputFormat) } }") (defrecord RetrieveChecks [] ptk/WatchEvent (watch [_ state stream] (->> (gql/query +checks-query+ {:outputFormat "yaml"}) (rx/map :checks) (rx/map ->ChecksRetrieved)))) (defrecord UpdateSelectedTag [tag] ptk/UpdateEvent (update [_ {:keys [selected-tag] :as state}] (if (= tag selected-tag) (dissoc state :selected-tag) (assoc state :selected-tag tag))))
[ { "context": "the reconstruction probability,\n as described in An & Cho, 2015\n - Variational Autoencoder based A", "end": 17785, "score": 0.9086015224456787, "start": 17783, "tag": "NAME", "value": "An" } ]
src/dl4clj/nn/api/layer_specific_fns.clj
ghosthamlet/dl4clj
62
(ns ^{:doc "see https://deeplearning4j.org/doc/org/deeplearning4j/nn/conf/layers/Layer.html and https://deeplearning4j.org/doc/org/deeplearning4j/nn/conf/layers/package-frame.html"} dl4clj.nn.api.layer-specific-fns (:import [org.deeplearning4j.nn.conf.layers BaseOutputLayer CenterLossOutputLayer SubsamplingLayer] [org.deeplearning4j.nn.layers BasePretrainNetwork FrozenLayer LossLayer] [org.deeplearning4j.nn.layers.feedforward.autoencoder AutoEncoder] [org.deeplearning4j.nn.layers.feedforward.rbm RBM] [org.deeplearning4j.nn.layers.normalization BatchNormalization] [org.deeplearning4j.nn.layers.variational VariationalAutoencoder] [org.deeplearning4j.nn.api.layers RecurrentLayer] [org.deeplearning4j.nn.api.layers IOutputLayer]) (:require [nd4clj.linalg.factory.nd4j :refer [vec-or-matrix->indarray]] [dl4clj.utils :refer [contains-many? obj-or-code? eval-if-code]] [clojure.core.match :refer [match]] [dl4clj.constants :as enum])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From BaseOutputlayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-loss-fn [output-layer & {:keys [as-code?] :or {as-code? true}}] (match [output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getLossFn ~output-layer)) :else (.getLossFn output-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From CenterLossOutputLayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-alpha [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getAlpha ~center-loss-output-layer)) :else (.getAlpha center-loss-output-layer))) (defn get-gradient-check [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getGradientCheck ~center-loss-output-layer)) :else (.getGradientCheck center-loss-output-layer))) (defn get-lambda [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getLambda ~center-loss-output-layer)) :else (.getLambda center-loss-output-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From SubsamplingLayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-eps [subsampling-layer & {:keys [as-code?] :or {as-code? true}}] (match [subsampling-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getEps ~subsampling-layer)) :else (.getEps subsampling-layer))) (defn get-pnorm [subsampling-layer & {:keys [as-code?] :or {as-code? true}}] (match [subsampling-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getPnorm ~subsampling-layer)) :else (.getPnorm subsampling-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; output layers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compute-score "Compute score after labels and input have been set. output-layer is the output layer in question full-network-l1 (double) is the l1 regularization term for the model the layer is apart of full-network-l2 (double) is the l2 regularization term for the model the layer is aprt of -note: it is okay for L1 and L2 to be set to 0.0 if regularization was not used training? (boolean) are we traing the model or testing it?" [& {:keys [output-layer full-network-l1 full-network-l2 training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :full-network-l1 (:or (_ :guard number?) (_ :guard seq?)) :full-network-l2 (:or (_ :guard number?) (_ :guard seq?)) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.computeScore ~output-layer (double ~full-network-l1) (double ~full-network-l2) ~training?)) :else (let [[o-l n-l1 n-l2 t?] (eval-if-code [output-layer seq?] [full-network-l1 seq? number?] [full-network-l2 seq? number?] [training? seq? boolean?])] (.computeScore o-l n-l1 n-l2 t?)))) (defn compute-score-for-examples "Compute the score for each example individually, after labels and input have been set. output-layer is the output layer in question full-network-l1 (double) is the l1 regularization term for the model the layer is apart of full-network-l2 (double) is the l2 regularization term for the model the layer is aprt of -note: it is okay for L1 and L2 to be set to 0.0 if regularization was not used" [& {:keys [output-layer full-network-l1 full-network-l2 as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :full-network-l1 (:or (_ :guard number?) (_ :guard seq?)) :full-network-l2 (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.computeScoreForExamples ~output-layer (double ~full-network-l1) (double ~full-network-l2))) :else (let [[n-l1 n-l2] (eval-if-code [full-network-l1 seq? number?] [full-network-l2 seq? number?])] (.computeScoreForExamples output-layer n-l1 n-l2)))) (defn set-labels! "Set the labels array for this output layer and returns the layer labels is an INDArray or vec of labels" [& {:keys [output-layer labels as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :labels (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(doto ~output-layer (.setLabels (vec-or-matrix->indarray ~labels)))) :else (let [[o-layer l] (eval-if-code [output-layer seq?] [labels seq?])] (doto o-layer (.setLabels (vec-or-matrix->indarray l)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; base pretrain layer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-corrupted-input "Corrupts the given input by doing a binomial sampling given the corruption level :features is an INDArray or vector of input features to the network :corruption-level (double) amount of corruption to apply." [& {:keys [base-pretrain-network features corruption-level as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :features (:or (_ :guard seq?) (_ :guard vector?)) :corruption-level (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.getCorruptedInput ~base-pretrain-network (vec-or-matrix->indarray ~features) (double ~corruption-level))) :else (let [[f c-lvl bpn] (eval-if-code [features seq?] [corruption-level seq? number?] [base-pretrain-network seq?])] (.getCorruptedInput bpn (vec-or-matrix->indarray f) c-lvl)))) (defn sample-hidden-given-visible "Sample the hidden distribution given the visible :visible is an INDArray or vector of the visibile distribution" [& {:keys [base-pretrain-network visible as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :visible (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.sampleHiddenGivenVisible ~base-pretrain-network (vec-or-matrix->indarray ~visible))) :else (let [[v bpn] (eval-if-code [visible seq?] [base-pretrain-network seq?])] (.sampleHiddenGivenVisible bpn (vec-or-matrix->indarray v))))) (defn sample-visible-given-hidden "Sample the visible distribution given the hidden :hidden is an INDArray or vector of the hidden distribution" [& {:keys [base-pretrain-network hidden as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :hidden (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.sampleVisibleGivenHidden ~base-pretrain-network (vec-or-matrix->indarray ~hidden))) :else (let [[h bpn] (eval-if-code [hidden seq?] [base-pretrain-network seq?])] (.sampleVisibleGivenHidden bpn (vec-or-matrix->indarray h))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; autoencoders ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn decode "decodes an encoded output of an autoencoder" [& {:keys [autoencoder layer-output as-code?] :or {as-code? true} :as opts}] (match [opts] [{:autoencoder (_ :guard seq?) :layer-output (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.decode ~autoencoder (vec-or-matrix->indarray ~layer-output))) :else (let [[l-o a] (eval-if-code [layer-output seq?] [autoencoder seq?])] (.decode a (vec-or-matrix->indarray l-o))))) (defn encode "encodes an input to be passed to an autoencoder" [& {:keys [autoencoder input training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:autoencoder (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?)) :training (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.encode ~autoencoder (vec-or-matrix->indarray ~input) ~training?)) :else (let [[i t? a] (eval-if-code [input seq?] [training? seq? boolean?] [autoencoder seq?])] (.encode a (vec-or-matrix->indarray i) t?)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rbm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gibbs-sampling-step "Gibbs sampling step: hidden ---> visible ---> hidden returns the expected values and samples of both the visible samples given the hidden and the new hidden input and expected values" [& {:keys [rbm hidden-input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :hidden-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.gibbhVh ~rbm (vec-or-matrix->indarray ~hidden-input))) :else (let [[h-i rbm-model] (eval-if-code [hidden-input seq?] [rbm seq?])] (.gibbhVh rbm-model (vec-or-matrix->indarray h-i))))) (defn prop-up "Calculates the activation of the visible : sigmoid(v * W + hbias)" [& {:keys [rbm visible-input training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :visible-input (:or (_ :guard seq?) (_ :guard vector?)) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.propUp ~rbm (vec-or-matrix->indarray ~visible-input) ~training?)) [{:rbm _ :visible-input _ :training? _}] (let [[v-i t? rbm-model] (eval-if-code [visible-input seq?] [training? seq? boolean?] [rbm seq?])] (.propUp rbm-model (vec-or-matrix->indarray v-i) t?)) [{:rbm (_ :guard seq?) :visible-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? (obj-or-code? as-code? `(.propUp ~rbm (vec-or-matrix->indarray ~visible-input)))) :else (let [[v-i rbm-model] (eval-if-code [visible-input seq?] [rbm seq?])] (.propUp rbm-model (vec-or-matrix->indarray v-i))))) (defn prop-up-derivative "derivative of the prop-up activation" [& {:keys [rbm prop-up-vals as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :prop-up-vals (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.propUpDerivative ~rbm (vec-or-matrix->indarray ~prop-up-vals))) :else (let [[p-up rbm-model] (eval-if-code [prop-up-vals seq?] [rbm seq?])] (.propUpDerivative rbm-model (vec-or-matrix->indarray p-up))))) (defn prop-down "Calculates the activation of the hidden: (activation (h * W + vbias))" [& {:keys [rbm hidden-input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :hidden-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.propDown ~rbm (vec-or-matrix->indarray ~hidden-input))) :else (let [[h-i rbm-model] (eval-if-code [hidden-input seq?] [rbm seq?])] (.propDown rbm-model (vec-or-matrix->indarray h-i))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; frozen layer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn log-test-mode ":training? (boolean) training or testing? :training-mode (keyword) one of :training or :testing" [& {:keys [frozen-layer training? training-mode as-code?] :or {as-code? true} :as opts}] (match [opts] [{:frozen-layer (_ :guard seq?) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~frozen-layer (.logTestMode ~training?))) [{:frozen-layer _ :training? _}] (let [[t?] (eval-if-code [training? seq? boolean?])] (doto frozen-layer (.logTestMode t?))) [{:frozen-layer (_ :guard seq?) :training-mode (:or (_ :guard keyword?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~frozen-layer (.logTestMode (enum/value-of {:layer-training-mode ~training-mode})))) [{:frozen-layer _ :training-mode _}] (let [[t-mode] (eval-if-code [training-mode seq? keyword?])] (doto frozen-layer (.logTestMode (enum/value-of {:layer-training-mode t-mode})))))) (defn get-inside-layer [frozen-layer & {:keys [as-code?] :or {as-code? true}}] (match [frozen-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getInsideLayer ~frozen-layer)) :else (.getInsideLayer frozen-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; batch normalization ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-shape "returns an integer array of the shape after passing through the normalization layer" [& {:keys [batch-norm features as-code?] :or {as-code? true} :as opts}] (match [opts] [{:batch-norm (_ :guard seq?) :features (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.getShape ~batch-norm (vec-or-matrix->indarray ~features))) :else (let [[f b-norm] (eval-if-code [features seq?] [batch-norm seq?])] (.getShape b-norm (vec-or-matrix->indarray f))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; vae ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-pretrain-param? "checks to see if the supplied param can be pretrained :param (string), name of the paramter" [& {:keys [vae param as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :param (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.isPretrainParam ~vae ~param)) :else (let [[p] (eval-if-code [param seq? string?])] (.isPretrainParam vae p)))) (defn reconstruction-probability "Calculate the reconstruction probability, as described in An & Cho, 2015 - Variational Autoencoder based Anomaly Detection using Reconstruction Probability - (Algorithm 4) The authors describe it as follows: - This is essentially the probability of the data being generated from a given latent variable drawn from the approximate posterior distribution. Specifically, for each example x in the input, calculate p(x). Note however that p(x) is a stochastic (Monte-Carlo) estimate of the true p(x), based on the specified number of samples. More samples will produce a more accurate (lower variance) estimate of the true p(x) for the current model parameters. The returned array is a column vector of reconstruction probabilities, for each example. Thus, reconstruction probabilities can (and should, for efficiency) be calculated in a batched manner. under the hood, this fn calls reconstructionLogProbability in dl4j land. :data (INDArray or vec), the data to calculate the reconstruction probability for :num-samples (int), Number of samples with which to base the reconstruction probability on." [& {:keys [vae data num-samples as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?)) :num-samples (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.reconstructionProbability ~vae (vec-or-matrix->indarray ~data) (int ~num-samples))) :else (let [[d n-samples model] (eval-if-code [data seq?] [num-samples seq? number?] [vae seq?])] (.reconstructionProbability model (vec-or-matrix->indarray d) n-samples)))) (defn reconstruction-log-probability "Return the log reconstruction probability given the specified number of samples. the docs in reconstruction-probability also apply to this fn." [& {:keys [vae data num-samples as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?)) :num-samples (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.reconstructionLogProbability ~vae (vec-or-matrix->indarray ~data) (int ~num-samples))) :else (let [[d n-samples model] (eval-if-code [data seq?] [num-samples seq? number?] [vae seq?])] (.reconstructionLogProbability model (vec-or-matrix->indarray d) n-samples)))) (defn generate-random-given-z "Given a specified values for the latent space as input (latent space being z in p(z|data)), randomly generate output x, where x ~ P(x|z) :latent-space-values (INDArray or vec), Values for the latent space. - size(1) must equal nOut configuration parameter :vae (layer), is the variational autoencoder" [& {:keys [vae latent-space-values as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :latent-space-values (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.generateRandomGivenZ ~vae (vec-or-matrix->indarray ~latent-space-values))) :else (let [[lsv model] (eval-if-code [latent-space-values seq?] [vae seq?])] (.generateRandomGivenZ model (vec-or-matrix->indarray lsv))))) (defn generate-at-mean-given-z "Given a specified values for the latent space as input (latent space being z in p(z|data)), generate output from P(x|z), where x = E[P(x|z)] - i.e., return the mean value for the distribution P(x|z) :latent-space-values (INDArray or vec), Values for the latent space. - size(1) must equal nOut configuration parameter :vae (layer), is the variational autoencoder" [& {:keys [vae latent-space-values as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :latent-space-values (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.generateAtMeanGivenZ ~vae (vec-or-matrix->indarray ~latent-space-values))) :else (let [[lsv model] (eval-if-code [latent-space-values seq?] [vae seq?])] (.generateAtMeanGivenZ model (vec-or-matrix->indarray lsv))))) (defn has-loss-fn? "Does the reconstruction distribution have a loss function (such as mean squared error) or is it a standard probabilistic reconstruction distribution?" [vae & {:keys [as-code?] :or {as-code? true}}] (match [vae] [(_ :guard seq?)] (obj-or-code? as-code? `(.hasLossFunction ~vae)) :else (.hasLossFunction vae))) (defn reconstruction-error "Return the reconstruction error for this variational autoencoder. This method is used ONLY for VAEs that have a standard neural network loss function (i.e., an ILossFunction instance such as mean squared error) instead of using a probabilistic reconstruction distribution P(x|z) for the reconstructions (as presented in the VAE architecture by Kingma and Welling). reconstruction error is a simple deterministic function :vae (layer), is the variational autoencoder :data (INDArray or vec), the data to calc the reconstruction error on" [& {:keys [vae data as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.reconstructionError ~vae (vec-or-matrix->indarray ~data))) :else (let [[d model] (eval-if-code [data seq?] [vae seq?])] (.reconstructionError model (vec-or-matrix->indarray d))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; recurrent layers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rnn-activate-using-stored-state "Similar to rnnTimeStep, this method is used for activations using the state stored in the stateMap as the initialization. input (INDArray or vec) of input values to the layer store-last-for-tbptt? (boolean), save state to be used in tbptt training? (boolean) is the model currently in training or not?" [& {:keys [rnn-layer input training? store-last-for-tbptt? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?)) :training? (:or (_ :guard seq?) (_ :guard boolean?)) :store-last-for-tbptt? (:or (_ :guard seq?) (_ :guard boolean?))}] (obj-or-code? as-code? `(.rnnActivateUsingStoredState rnn-layer (vec-or-matrix->indarray input) training? store-last-for-tbptt?)) :else (let [[rnn i t? store?] (eval-if-code [rnn-layer seq?] [input seq?] [training? seq? boolean?] [store-last-for-tbptt? seq? boolean?])] (.rnnActivateUsingStoredState rnn (vec-or-matrix->indarray i) t? store?)))) (defn rnn-clear-previous-state! "Reset/clear the stateMap for rnn-time-step and tBpttStateMap for rnn-activate-using-stored-state returns the rnn-layer" [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnClearPreviousState))) :else (doto rnn-layer (.rnnClearPreviousState)))) (defn rnn-layer-get-prev-state "Returns a shallow copy of the RNN stateMap (that contains the stored history for use in fns such as rnn-time-step" [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.rnnGetPreviousState ~rnn-layer)) :else (.rnnGetPreviousState rnn-layer))) (defn rnn-get-tbptt-state "Get the RNN truncated backpropagations through time (TBPTT) state for the recurrent layer." [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.rnnGetTBPTTState ~rnn-layer)) :else (.rnnGetTBPTTState rnn-layer))) (defn rnn-set-tbptt-state! "Set the RNN truncated backpropagations through time (TBPTT) state for the recurrent layer. and returns the layer state is a map of {string (indArray or code for creating one)}" [& {:keys [rnn-layer state as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :state (:or (_ :guard map?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnSetTBPTTState ~state))) :else (let [[s] (eval-if-code [state seq? map?])] (doto rnn-layer (.rnnSetTBPTTState s))))) (defn rnn-layer-set-prev-state! "Set the stateMap (stored history) and return the layer. state is a map of {string (indArray or code for creating one)} - where seq is the code for creating an indArray There is no validation for whats in the state map" [& {:keys [rnn-layer state as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :state (:or (_ :guard seq?) (_ :guard map?))}] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnSetPreviousState ~state))) :else (let [[s] (eval-if-code [state seq? map?])] (doto rnn-layer (.rnnSetPreviousState s))))) (defn rnn-layer-time-step "Do one or more time steps using the previous time step state stored in stateMap. Can be used to efficiently do forward pass one or n-steps at a time (instead of doing forward pass always from t=0) If stateMap is empty, default initialization (usually zeros) is used Implementations also update stateMap at the end of this method input should be an INDArray or vector of input values to the layer" [& {:keys [rnn-layer input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.rnnTimeStep ~rnn-layer (vec-or-matrix->indarray ~input))) :else (let [[rnn i] (eval-if-code [rnn-layer seq?] [input seq?])] (.rnnTimeStep rnn (vec-or-matrix->indarray i))))) (defn tbptt-backprop-gradient "Returns the Truncated BPTT gradient epsilon should be an INDArray or vec tbptt-back-length is an integer" [& {:keys [rnn-layer epsilon tbptt-back-length as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :epsilon (:or (_ :guard seq?) (_ :guard vector?)) :tbptt-back-length (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.tbpttBackpropGradient ~rnn-layer (vec-or-matrix->indarray ~epsilon) (int ~tbptt-back-length))) :else (let [[rnn e length] (eval-if-code [rnn-layer seq?] [epsilon seq?] [tbptt-back-length seq? number?])] (.tbpttBackpropGradient rnn (vec-or-matrix->indarray e) length))))
81839
(ns ^{:doc "see https://deeplearning4j.org/doc/org/deeplearning4j/nn/conf/layers/Layer.html and https://deeplearning4j.org/doc/org/deeplearning4j/nn/conf/layers/package-frame.html"} dl4clj.nn.api.layer-specific-fns (:import [org.deeplearning4j.nn.conf.layers BaseOutputLayer CenterLossOutputLayer SubsamplingLayer] [org.deeplearning4j.nn.layers BasePretrainNetwork FrozenLayer LossLayer] [org.deeplearning4j.nn.layers.feedforward.autoencoder AutoEncoder] [org.deeplearning4j.nn.layers.feedforward.rbm RBM] [org.deeplearning4j.nn.layers.normalization BatchNormalization] [org.deeplearning4j.nn.layers.variational VariationalAutoencoder] [org.deeplearning4j.nn.api.layers RecurrentLayer] [org.deeplearning4j.nn.api.layers IOutputLayer]) (:require [nd4clj.linalg.factory.nd4j :refer [vec-or-matrix->indarray]] [dl4clj.utils :refer [contains-many? obj-or-code? eval-if-code]] [clojure.core.match :refer [match]] [dl4clj.constants :as enum])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From BaseOutputlayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-loss-fn [output-layer & {:keys [as-code?] :or {as-code? true}}] (match [output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getLossFn ~output-layer)) :else (.getLossFn output-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From CenterLossOutputLayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-alpha [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getAlpha ~center-loss-output-layer)) :else (.getAlpha center-loss-output-layer))) (defn get-gradient-check [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getGradientCheck ~center-loss-output-layer)) :else (.getGradientCheck center-loss-output-layer))) (defn get-lambda [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getLambda ~center-loss-output-layer)) :else (.getLambda center-loss-output-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From SubsamplingLayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-eps [subsampling-layer & {:keys [as-code?] :or {as-code? true}}] (match [subsampling-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getEps ~subsampling-layer)) :else (.getEps subsampling-layer))) (defn get-pnorm [subsampling-layer & {:keys [as-code?] :or {as-code? true}}] (match [subsampling-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getPnorm ~subsampling-layer)) :else (.getPnorm subsampling-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; output layers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compute-score "Compute score after labels and input have been set. output-layer is the output layer in question full-network-l1 (double) is the l1 regularization term for the model the layer is apart of full-network-l2 (double) is the l2 regularization term for the model the layer is aprt of -note: it is okay for L1 and L2 to be set to 0.0 if regularization was not used training? (boolean) are we traing the model or testing it?" [& {:keys [output-layer full-network-l1 full-network-l2 training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :full-network-l1 (:or (_ :guard number?) (_ :guard seq?)) :full-network-l2 (:or (_ :guard number?) (_ :guard seq?)) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.computeScore ~output-layer (double ~full-network-l1) (double ~full-network-l2) ~training?)) :else (let [[o-l n-l1 n-l2 t?] (eval-if-code [output-layer seq?] [full-network-l1 seq? number?] [full-network-l2 seq? number?] [training? seq? boolean?])] (.computeScore o-l n-l1 n-l2 t?)))) (defn compute-score-for-examples "Compute the score for each example individually, after labels and input have been set. output-layer is the output layer in question full-network-l1 (double) is the l1 regularization term for the model the layer is apart of full-network-l2 (double) is the l2 regularization term for the model the layer is aprt of -note: it is okay for L1 and L2 to be set to 0.0 if regularization was not used" [& {:keys [output-layer full-network-l1 full-network-l2 as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :full-network-l1 (:or (_ :guard number?) (_ :guard seq?)) :full-network-l2 (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.computeScoreForExamples ~output-layer (double ~full-network-l1) (double ~full-network-l2))) :else (let [[n-l1 n-l2] (eval-if-code [full-network-l1 seq? number?] [full-network-l2 seq? number?])] (.computeScoreForExamples output-layer n-l1 n-l2)))) (defn set-labels! "Set the labels array for this output layer and returns the layer labels is an INDArray or vec of labels" [& {:keys [output-layer labels as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :labels (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(doto ~output-layer (.setLabels (vec-or-matrix->indarray ~labels)))) :else (let [[o-layer l] (eval-if-code [output-layer seq?] [labels seq?])] (doto o-layer (.setLabels (vec-or-matrix->indarray l)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; base pretrain layer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-corrupted-input "Corrupts the given input by doing a binomial sampling given the corruption level :features is an INDArray or vector of input features to the network :corruption-level (double) amount of corruption to apply." [& {:keys [base-pretrain-network features corruption-level as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :features (:or (_ :guard seq?) (_ :guard vector?)) :corruption-level (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.getCorruptedInput ~base-pretrain-network (vec-or-matrix->indarray ~features) (double ~corruption-level))) :else (let [[f c-lvl bpn] (eval-if-code [features seq?] [corruption-level seq? number?] [base-pretrain-network seq?])] (.getCorruptedInput bpn (vec-or-matrix->indarray f) c-lvl)))) (defn sample-hidden-given-visible "Sample the hidden distribution given the visible :visible is an INDArray or vector of the visibile distribution" [& {:keys [base-pretrain-network visible as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :visible (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.sampleHiddenGivenVisible ~base-pretrain-network (vec-or-matrix->indarray ~visible))) :else (let [[v bpn] (eval-if-code [visible seq?] [base-pretrain-network seq?])] (.sampleHiddenGivenVisible bpn (vec-or-matrix->indarray v))))) (defn sample-visible-given-hidden "Sample the visible distribution given the hidden :hidden is an INDArray or vector of the hidden distribution" [& {:keys [base-pretrain-network hidden as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :hidden (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.sampleVisibleGivenHidden ~base-pretrain-network (vec-or-matrix->indarray ~hidden))) :else (let [[h bpn] (eval-if-code [hidden seq?] [base-pretrain-network seq?])] (.sampleVisibleGivenHidden bpn (vec-or-matrix->indarray h))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; autoencoders ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn decode "decodes an encoded output of an autoencoder" [& {:keys [autoencoder layer-output as-code?] :or {as-code? true} :as opts}] (match [opts] [{:autoencoder (_ :guard seq?) :layer-output (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.decode ~autoencoder (vec-or-matrix->indarray ~layer-output))) :else (let [[l-o a] (eval-if-code [layer-output seq?] [autoencoder seq?])] (.decode a (vec-or-matrix->indarray l-o))))) (defn encode "encodes an input to be passed to an autoencoder" [& {:keys [autoencoder input training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:autoencoder (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?)) :training (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.encode ~autoencoder (vec-or-matrix->indarray ~input) ~training?)) :else (let [[i t? a] (eval-if-code [input seq?] [training? seq? boolean?] [autoencoder seq?])] (.encode a (vec-or-matrix->indarray i) t?)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rbm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gibbs-sampling-step "Gibbs sampling step: hidden ---> visible ---> hidden returns the expected values and samples of both the visible samples given the hidden and the new hidden input and expected values" [& {:keys [rbm hidden-input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :hidden-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.gibbhVh ~rbm (vec-or-matrix->indarray ~hidden-input))) :else (let [[h-i rbm-model] (eval-if-code [hidden-input seq?] [rbm seq?])] (.gibbhVh rbm-model (vec-or-matrix->indarray h-i))))) (defn prop-up "Calculates the activation of the visible : sigmoid(v * W + hbias)" [& {:keys [rbm visible-input training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :visible-input (:or (_ :guard seq?) (_ :guard vector?)) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.propUp ~rbm (vec-or-matrix->indarray ~visible-input) ~training?)) [{:rbm _ :visible-input _ :training? _}] (let [[v-i t? rbm-model] (eval-if-code [visible-input seq?] [training? seq? boolean?] [rbm seq?])] (.propUp rbm-model (vec-or-matrix->indarray v-i) t?)) [{:rbm (_ :guard seq?) :visible-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? (obj-or-code? as-code? `(.propUp ~rbm (vec-or-matrix->indarray ~visible-input)))) :else (let [[v-i rbm-model] (eval-if-code [visible-input seq?] [rbm seq?])] (.propUp rbm-model (vec-or-matrix->indarray v-i))))) (defn prop-up-derivative "derivative of the prop-up activation" [& {:keys [rbm prop-up-vals as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :prop-up-vals (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.propUpDerivative ~rbm (vec-or-matrix->indarray ~prop-up-vals))) :else (let [[p-up rbm-model] (eval-if-code [prop-up-vals seq?] [rbm seq?])] (.propUpDerivative rbm-model (vec-or-matrix->indarray p-up))))) (defn prop-down "Calculates the activation of the hidden: (activation (h * W + vbias))" [& {:keys [rbm hidden-input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :hidden-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.propDown ~rbm (vec-or-matrix->indarray ~hidden-input))) :else (let [[h-i rbm-model] (eval-if-code [hidden-input seq?] [rbm seq?])] (.propDown rbm-model (vec-or-matrix->indarray h-i))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; frozen layer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn log-test-mode ":training? (boolean) training or testing? :training-mode (keyword) one of :training or :testing" [& {:keys [frozen-layer training? training-mode as-code?] :or {as-code? true} :as opts}] (match [opts] [{:frozen-layer (_ :guard seq?) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~frozen-layer (.logTestMode ~training?))) [{:frozen-layer _ :training? _}] (let [[t?] (eval-if-code [training? seq? boolean?])] (doto frozen-layer (.logTestMode t?))) [{:frozen-layer (_ :guard seq?) :training-mode (:or (_ :guard keyword?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~frozen-layer (.logTestMode (enum/value-of {:layer-training-mode ~training-mode})))) [{:frozen-layer _ :training-mode _}] (let [[t-mode] (eval-if-code [training-mode seq? keyword?])] (doto frozen-layer (.logTestMode (enum/value-of {:layer-training-mode t-mode})))))) (defn get-inside-layer [frozen-layer & {:keys [as-code?] :or {as-code? true}}] (match [frozen-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getInsideLayer ~frozen-layer)) :else (.getInsideLayer frozen-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; batch normalization ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-shape "returns an integer array of the shape after passing through the normalization layer" [& {:keys [batch-norm features as-code?] :or {as-code? true} :as opts}] (match [opts] [{:batch-norm (_ :guard seq?) :features (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.getShape ~batch-norm (vec-or-matrix->indarray ~features))) :else (let [[f b-norm] (eval-if-code [features seq?] [batch-norm seq?])] (.getShape b-norm (vec-or-matrix->indarray f))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; vae ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-pretrain-param? "checks to see if the supplied param can be pretrained :param (string), name of the paramter" [& {:keys [vae param as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :param (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.isPretrainParam ~vae ~param)) :else (let [[p] (eval-if-code [param seq? string?])] (.isPretrainParam vae p)))) (defn reconstruction-probability "Calculate the reconstruction probability, as described in <NAME> & Cho, 2015 - Variational Autoencoder based Anomaly Detection using Reconstruction Probability - (Algorithm 4) The authors describe it as follows: - This is essentially the probability of the data being generated from a given latent variable drawn from the approximate posterior distribution. Specifically, for each example x in the input, calculate p(x). Note however that p(x) is a stochastic (Monte-Carlo) estimate of the true p(x), based on the specified number of samples. More samples will produce a more accurate (lower variance) estimate of the true p(x) for the current model parameters. The returned array is a column vector of reconstruction probabilities, for each example. Thus, reconstruction probabilities can (and should, for efficiency) be calculated in a batched manner. under the hood, this fn calls reconstructionLogProbability in dl4j land. :data (INDArray or vec), the data to calculate the reconstruction probability for :num-samples (int), Number of samples with which to base the reconstruction probability on." [& {:keys [vae data num-samples as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?)) :num-samples (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.reconstructionProbability ~vae (vec-or-matrix->indarray ~data) (int ~num-samples))) :else (let [[d n-samples model] (eval-if-code [data seq?] [num-samples seq? number?] [vae seq?])] (.reconstructionProbability model (vec-or-matrix->indarray d) n-samples)))) (defn reconstruction-log-probability "Return the log reconstruction probability given the specified number of samples. the docs in reconstruction-probability also apply to this fn." [& {:keys [vae data num-samples as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?)) :num-samples (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.reconstructionLogProbability ~vae (vec-or-matrix->indarray ~data) (int ~num-samples))) :else (let [[d n-samples model] (eval-if-code [data seq?] [num-samples seq? number?] [vae seq?])] (.reconstructionLogProbability model (vec-or-matrix->indarray d) n-samples)))) (defn generate-random-given-z "Given a specified values for the latent space as input (latent space being z in p(z|data)), randomly generate output x, where x ~ P(x|z) :latent-space-values (INDArray or vec), Values for the latent space. - size(1) must equal nOut configuration parameter :vae (layer), is the variational autoencoder" [& {:keys [vae latent-space-values as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :latent-space-values (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.generateRandomGivenZ ~vae (vec-or-matrix->indarray ~latent-space-values))) :else (let [[lsv model] (eval-if-code [latent-space-values seq?] [vae seq?])] (.generateRandomGivenZ model (vec-or-matrix->indarray lsv))))) (defn generate-at-mean-given-z "Given a specified values for the latent space as input (latent space being z in p(z|data)), generate output from P(x|z), where x = E[P(x|z)] - i.e., return the mean value for the distribution P(x|z) :latent-space-values (INDArray or vec), Values for the latent space. - size(1) must equal nOut configuration parameter :vae (layer), is the variational autoencoder" [& {:keys [vae latent-space-values as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :latent-space-values (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.generateAtMeanGivenZ ~vae (vec-or-matrix->indarray ~latent-space-values))) :else (let [[lsv model] (eval-if-code [latent-space-values seq?] [vae seq?])] (.generateAtMeanGivenZ model (vec-or-matrix->indarray lsv))))) (defn has-loss-fn? "Does the reconstruction distribution have a loss function (such as mean squared error) or is it a standard probabilistic reconstruction distribution?" [vae & {:keys [as-code?] :or {as-code? true}}] (match [vae] [(_ :guard seq?)] (obj-or-code? as-code? `(.hasLossFunction ~vae)) :else (.hasLossFunction vae))) (defn reconstruction-error "Return the reconstruction error for this variational autoencoder. This method is used ONLY for VAEs that have a standard neural network loss function (i.e., an ILossFunction instance such as mean squared error) instead of using a probabilistic reconstruction distribution P(x|z) for the reconstructions (as presented in the VAE architecture by Kingma and Welling). reconstruction error is a simple deterministic function :vae (layer), is the variational autoencoder :data (INDArray or vec), the data to calc the reconstruction error on" [& {:keys [vae data as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.reconstructionError ~vae (vec-or-matrix->indarray ~data))) :else (let [[d model] (eval-if-code [data seq?] [vae seq?])] (.reconstructionError model (vec-or-matrix->indarray d))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; recurrent layers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rnn-activate-using-stored-state "Similar to rnnTimeStep, this method is used for activations using the state stored in the stateMap as the initialization. input (INDArray or vec) of input values to the layer store-last-for-tbptt? (boolean), save state to be used in tbptt training? (boolean) is the model currently in training or not?" [& {:keys [rnn-layer input training? store-last-for-tbptt? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?)) :training? (:or (_ :guard seq?) (_ :guard boolean?)) :store-last-for-tbptt? (:or (_ :guard seq?) (_ :guard boolean?))}] (obj-or-code? as-code? `(.rnnActivateUsingStoredState rnn-layer (vec-or-matrix->indarray input) training? store-last-for-tbptt?)) :else (let [[rnn i t? store?] (eval-if-code [rnn-layer seq?] [input seq?] [training? seq? boolean?] [store-last-for-tbptt? seq? boolean?])] (.rnnActivateUsingStoredState rnn (vec-or-matrix->indarray i) t? store?)))) (defn rnn-clear-previous-state! "Reset/clear the stateMap for rnn-time-step and tBpttStateMap for rnn-activate-using-stored-state returns the rnn-layer" [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnClearPreviousState))) :else (doto rnn-layer (.rnnClearPreviousState)))) (defn rnn-layer-get-prev-state "Returns a shallow copy of the RNN stateMap (that contains the stored history for use in fns such as rnn-time-step" [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.rnnGetPreviousState ~rnn-layer)) :else (.rnnGetPreviousState rnn-layer))) (defn rnn-get-tbptt-state "Get the RNN truncated backpropagations through time (TBPTT) state for the recurrent layer." [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.rnnGetTBPTTState ~rnn-layer)) :else (.rnnGetTBPTTState rnn-layer))) (defn rnn-set-tbptt-state! "Set the RNN truncated backpropagations through time (TBPTT) state for the recurrent layer. and returns the layer state is a map of {string (indArray or code for creating one)}" [& {:keys [rnn-layer state as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :state (:or (_ :guard map?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnSetTBPTTState ~state))) :else (let [[s] (eval-if-code [state seq? map?])] (doto rnn-layer (.rnnSetTBPTTState s))))) (defn rnn-layer-set-prev-state! "Set the stateMap (stored history) and return the layer. state is a map of {string (indArray or code for creating one)} - where seq is the code for creating an indArray There is no validation for whats in the state map" [& {:keys [rnn-layer state as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :state (:or (_ :guard seq?) (_ :guard map?))}] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnSetPreviousState ~state))) :else (let [[s] (eval-if-code [state seq? map?])] (doto rnn-layer (.rnnSetPreviousState s))))) (defn rnn-layer-time-step "Do one or more time steps using the previous time step state stored in stateMap. Can be used to efficiently do forward pass one or n-steps at a time (instead of doing forward pass always from t=0) If stateMap is empty, default initialization (usually zeros) is used Implementations also update stateMap at the end of this method input should be an INDArray or vector of input values to the layer" [& {:keys [rnn-layer input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.rnnTimeStep ~rnn-layer (vec-or-matrix->indarray ~input))) :else (let [[rnn i] (eval-if-code [rnn-layer seq?] [input seq?])] (.rnnTimeStep rnn (vec-or-matrix->indarray i))))) (defn tbptt-backprop-gradient "Returns the Truncated BPTT gradient epsilon should be an INDArray or vec tbptt-back-length is an integer" [& {:keys [rnn-layer epsilon tbptt-back-length as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :epsilon (:or (_ :guard seq?) (_ :guard vector?)) :tbptt-back-length (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.tbpttBackpropGradient ~rnn-layer (vec-or-matrix->indarray ~epsilon) (int ~tbptt-back-length))) :else (let [[rnn e length] (eval-if-code [rnn-layer seq?] [epsilon seq?] [tbptt-back-length seq? number?])] (.tbpttBackpropGradient rnn (vec-or-matrix->indarray e) length))))
true
(ns ^{:doc "see https://deeplearning4j.org/doc/org/deeplearning4j/nn/conf/layers/Layer.html and https://deeplearning4j.org/doc/org/deeplearning4j/nn/conf/layers/package-frame.html"} dl4clj.nn.api.layer-specific-fns (:import [org.deeplearning4j.nn.conf.layers BaseOutputLayer CenterLossOutputLayer SubsamplingLayer] [org.deeplearning4j.nn.layers BasePretrainNetwork FrozenLayer LossLayer] [org.deeplearning4j.nn.layers.feedforward.autoencoder AutoEncoder] [org.deeplearning4j.nn.layers.feedforward.rbm RBM] [org.deeplearning4j.nn.layers.normalization BatchNormalization] [org.deeplearning4j.nn.layers.variational VariationalAutoencoder] [org.deeplearning4j.nn.api.layers RecurrentLayer] [org.deeplearning4j.nn.api.layers IOutputLayer]) (:require [nd4clj.linalg.factory.nd4j :refer [vec-or-matrix->indarray]] [dl4clj.utils :refer [contains-many? obj-or-code? eval-if-code]] [clojure.core.match :refer [match]] [dl4clj.constants :as enum])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From BaseOutputlayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-loss-fn [output-layer & {:keys [as-code?] :or {as-code? true}}] (match [output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getLossFn ~output-layer)) :else (.getLossFn output-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From CenterLossOutputLayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-alpha [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getAlpha ~center-loss-output-layer)) :else (.getAlpha center-loss-output-layer))) (defn get-gradient-check [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getGradientCheck ~center-loss-output-layer)) :else (.getGradientCheck center-loss-output-layer))) (defn get-lambda [center-loss-output-layer & {:keys [as-code?] :or {as-code? true}}] (match [center-loss-output-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getLambda ~center-loss-output-layer)) :else (.getLambda center-loss-output-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; From SubsamplingLayer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-eps [subsampling-layer & {:keys [as-code?] :or {as-code? true}}] (match [subsampling-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getEps ~subsampling-layer)) :else (.getEps subsampling-layer))) (defn get-pnorm [subsampling-layer & {:keys [as-code?] :or {as-code? true}}] (match [subsampling-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getPnorm ~subsampling-layer)) :else (.getPnorm subsampling-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; output layers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn compute-score "Compute score after labels and input have been set. output-layer is the output layer in question full-network-l1 (double) is the l1 regularization term for the model the layer is apart of full-network-l2 (double) is the l2 regularization term for the model the layer is aprt of -note: it is okay for L1 and L2 to be set to 0.0 if regularization was not used training? (boolean) are we traing the model or testing it?" [& {:keys [output-layer full-network-l1 full-network-l2 training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :full-network-l1 (:or (_ :guard number?) (_ :guard seq?)) :full-network-l2 (:or (_ :guard number?) (_ :guard seq?)) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.computeScore ~output-layer (double ~full-network-l1) (double ~full-network-l2) ~training?)) :else (let [[o-l n-l1 n-l2 t?] (eval-if-code [output-layer seq?] [full-network-l1 seq? number?] [full-network-l2 seq? number?] [training? seq? boolean?])] (.computeScore o-l n-l1 n-l2 t?)))) (defn compute-score-for-examples "Compute the score for each example individually, after labels and input have been set. output-layer is the output layer in question full-network-l1 (double) is the l1 regularization term for the model the layer is apart of full-network-l2 (double) is the l2 regularization term for the model the layer is aprt of -note: it is okay for L1 and L2 to be set to 0.0 if regularization was not used" [& {:keys [output-layer full-network-l1 full-network-l2 as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :full-network-l1 (:or (_ :guard number?) (_ :guard seq?)) :full-network-l2 (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.computeScoreForExamples ~output-layer (double ~full-network-l1) (double ~full-network-l2))) :else (let [[n-l1 n-l2] (eval-if-code [full-network-l1 seq? number?] [full-network-l2 seq? number?])] (.computeScoreForExamples output-layer n-l1 n-l2)))) (defn set-labels! "Set the labels array for this output layer and returns the layer labels is an INDArray or vec of labels" [& {:keys [output-layer labels as-code?] :or {as-code? true} :as opts}] (match [opts] [{:output-layer (_ :guard seq?) :labels (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(doto ~output-layer (.setLabels (vec-or-matrix->indarray ~labels)))) :else (let [[o-layer l] (eval-if-code [output-layer seq?] [labels seq?])] (doto o-layer (.setLabels (vec-or-matrix->indarray l)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; base pretrain layer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-corrupted-input "Corrupts the given input by doing a binomial sampling given the corruption level :features is an INDArray or vector of input features to the network :corruption-level (double) amount of corruption to apply." [& {:keys [base-pretrain-network features corruption-level as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :features (:or (_ :guard seq?) (_ :guard vector?)) :corruption-level (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.getCorruptedInput ~base-pretrain-network (vec-or-matrix->indarray ~features) (double ~corruption-level))) :else (let [[f c-lvl bpn] (eval-if-code [features seq?] [corruption-level seq? number?] [base-pretrain-network seq?])] (.getCorruptedInput bpn (vec-or-matrix->indarray f) c-lvl)))) (defn sample-hidden-given-visible "Sample the hidden distribution given the visible :visible is an INDArray or vector of the visibile distribution" [& {:keys [base-pretrain-network visible as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :visible (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.sampleHiddenGivenVisible ~base-pretrain-network (vec-or-matrix->indarray ~visible))) :else (let [[v bpn] (eval-if-code [visible seq?] [base-pretrain-network seq?])] (.sampleHiddenGivenVisible bpn (vec-or-matrix->indarray v))))) (defn sample-visible-given-hidden "Sample the visible distribution given the hidden :hidden is an INDArray or vector of the hidden distribution" [& {:keys [base-pretrain-network hidden as-code?] :or {as-code? true} :as opts}] (match [opts] [{:base-pretrain-network (_ :guard seq?) :hidden (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.sampleVisibleGivenHidden ~base-pretrain-network (vec-or-matrix->indarray ~hidden))) :else (let [[h bpn] (eval-if-code [hidden seq?] [base-pretrain-network seq?])] (.sampleVisibleGivenHidden bpn (vec-or-matrix->indarray h))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; autoencoders ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn decode "decodes an encoded output of an autoencoder" [& {:keys [autoencoder layer-output as-code?] :or {as-code? true} :as opts}] (match [opts] [{:autoencoder (_ :guard seq?) :layer-output (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.decode ~autoencoder (vec-or-matrix->indarray ~layer-output))) :else (let [[l-o a] (eval-if-code [layer-output seq?] [autoencoder seq?])] (.decode a (vec-or-matrix->indarray l-o))))) (defn encode "encodes an input to be passed to an autoencoder" [& {:keys [autoencoder input training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:autoencoder (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?)) :training (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.encode ~autoencoder (vec-or-matrix->indarray ~input) ~training?)) :else (let [[i t? a] (eval-if-code [input seq?] [training? seq? boolean?] [autoencoder seq?])] (.encode a (vec-or-matrix->indarray i) t?)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rbm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gibbs-sampling-step "Gibbs sampling step: hidden ---> visible ---> hidden returns the expected values and samples of both the visible samples given the hidden and the new hidden input and expected values" [& {:keys [rbm hidden-input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :hidden-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.gibbhVh ~rbm (vec-or-matrix->indarray ~hidden-input))) :else (let [[h-i rbm-model] (eval-if-code [hidden-input seq?] [rbm seq?])] (.gibbhVh rbm-model (vec-or-matrix->indarray h-i))))) (defn prop-up "Calculates the activation of the visible : sigmoid(v * W + hbias)" [& {:keys [rbm visible-input training? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :visible-input (:or (_ :guard seq?) (_ :guard vector?)) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(.propUp ~rbm (vec-or-matrix->indarray ~visible-input) ~training?)) [{:rbm _ :visible-input _ :training? _}] (let [[v-i t? rbm-model] (eval-if-code [visible-input seq?] [training? seq? boolean?] [rbm seq?])] (.propUp rbm-model (vec-or-matrix->indarray v-i) t?)) [{:rbm (_ :guard seq?) :visible-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? (obj-or-code? as-code? `(.propUp ~rbm (vec-or-matrix->indarray ~visible-input)))) :else (let [[v-i rbm-model] (eval-if-code [visible-input seq?] [rbm seq?])] (.propUp rbm-model (vec-or-matrix->indarray v-i))))) (defn prop-up-derivative "derivative of the prop-up activation" [& {:keys [rbm prop-up-vals as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :prop-up-vals (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.propUpDerivative ~rbm (vec-or-matrix->indarray ~prop-up-vals))) :else (let [[p-up rbm-model] (eval-if-code [prop-up-vals seq?] [rbm seq?])] (.propUpDerivative rbm-model (vec-or-matrix->indarray p-up))))) (defn prop-down "Calculates the activation of the hidden: (activation (h * W + vbias))" [& {:keys [rbm hidden-input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rbm (_ :guard seq?) :hidden-input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.propDown ~rbm (vec-or-matrix->indarray ~hidden-input))) :else (let [[h-i rbm-model] (eval-if-code [hidden-input seq?] [rbm seq?])] (.propDown rbm-model (vec-or-matrix->indarray h-i))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; frozen layer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn log-test-mode ":training? (boolean) training or testing? :training-mode (keyword) one of :training or :testing" [& {:keys [frozen-layer training? training-mode as-code?] :or {as-code? true} :as opts}] (match [opts] [{:frozen-layer (_ :guard seq?) :training? (:or (_ :guard boolean?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~frozen-layer (.logTestMode ~training?))) [{:frozen-layer _ :training? _}] (let [[t?] (eval-if-code [training? seq? boolean?])] (doto frozen-layer (.logTestMode t?))) [{:frozen-layer (_ :guard seq?) :training-mode (:or (_ :guard keyword?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~frozen-layer (.logTestMode (enum/value-of {:layer-training-mode ~training-mode})))) [{:frozen-layer _ :training-mode _}] (let [[t-mode] (eval-if-code [training-mode seq? keyword?])] (doto frozen-layer (.logTestMode (enum/value-of {:layer-training-mode t-mode})))))) (defn get-inside-layer [frozen-layer & {:keys [as-code?] :or {as-code? true}}] (match [frozen-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.getInsideLayer ~frozen-layer)) :else (.getInsideLayer frozen-layer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; batch normalization ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-shape "returns an integer array of the shape after passing through the normalization layer" [& {:keys [batch-norm features as-code?] :or {as-code? true} :as opts}] (match [opts] [{:batch-norm (_ :guard seq?) :features (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.getShape ~batch-norm (vec-or-matrix->indarray ~features))) :else (let [[f b-norm] (eval-if-code [features seq?] [batch-norm seq?])] (.getShape b-norm (vec-or-matrix->indarray f))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; vae ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn is-pretrain-param? "checks to see if the supplied param can be pretrained :param (string), name of the paramter" [& {:keys [vae param as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :param (:or (_ :guard string?) (_ :guard seq?))}] (obj-or-code? as-code? `(.isPretrainParam ~vae ~param)) :else (let [[p] (eval-if-code [param seq? string?])] (.isPretrainParam vae p)))) (defn reconstruction-probability "Calculate the reconstruction probability, as described in PI:NAME:<NAME>END_PI & Cho, 2015 - Variational Autoencoder based Anomaly Detection using Reconstruction Probability - (Algorithm 4) The authors describe it as follows: - This is essentially the probability of the data being generated from a given latent variable drawn from the approximate posterior distribution. Specifically, for each example x in the input, calculate p(x). Note however that p(x) is a stochastic (Monte-Carlo) estimate of the true p(x), based on the specified number of samples. More samples will produce a more accurate (lower variance) estimate of the true p(x) for the current model parameters. The returned array is a column vector of reconstruction probabilities, for each example. Thus, reconstruction probabilities can (and should, for efficiency) be calculated in a batched manner. under the hood, this fn calls reconstructionLogProbability in dl4j land. :data (INDArray or vec), the data to calculate the reconstruction probability for :num-samples (int), Number of samples with which to base the reconstruction probability on." [& {:keys [vae data num-samples as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?)) :num-samples (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.reconstructionProbability ~vae (vec-or-matrix->indarray ~data) (int ~num-samples))) :else (let [[d n-samples model] (eval-if-code [data seq?] [num-samples seq? number?] [vae seq?])] (.reconstructionProbability model (vec-or-matrix->indarray d) n-samples)))) (defn reconstruction-log-probability "Return the log reconstruction probability given the specified number of samples. the docs in reconstruction-probability also apply to this fn." [& {:keys [vae data num-samples as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?)) :num-samples (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.reconstructionLogProbability ~vae (vec-or-matrix->indarray ~data) (int ~num-samples))) :else (let [[d n-samples model] (eval-if-code [data seq?] [num-samples seq? number?] [vae seq?])] (.reconstructionLogProbability model (vec-or-matrix->indarray d) n-samples)))) (defn generate-random-given-z "Given a specified values for the latent space as input (latent space being z in p(z|data)), randomly generate output x, where x ~ P(x|z) :latent-space-values (INDArray or vec), Values for the latent space. - size(1) must equal nOut configuration parameter :vae (layer), is the variational autoencoder" [& {:keys [vae latent-space-values as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :latent-space-values (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.generateRandomGivenZ ~vae (vec-or-matrix->indarray ~latent-space-values))) :else (let [[lsv model] (eval-if-code [latent-space-values seq?] [vae seq?])] (.generateRandomGivenZ model (vec-or-matrix->indarray lsv))))) (defn generate-at-mean-given-z "Given a specified values for the latent space as input (latent space being z in p(z|data)), generate output from P(x|z), where x = E[P(x|z)] - i.e., return the mean value for the distribution P(x|z) :latent-space-values (INDArray or vec), Values for the latent space. - size(1) must equal nOut configuration parameter :vae (layer), is the variational autoencoder" [& {:keys [vae latent-space-values as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :latent-space-values (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.generateAtMeanGivenZ ~vae (vec-or-matrix->indarray ~latent-space-values))) :else (let [[lsv model] (eval-if-code [latent-space-values seq?] [vae seq?])] (.generateAtMeanGivenZ model (vec-or-matrix->indarray lsv))))) (defn has-loss-fn? "Does the reconstruction distribution have a loss function (such as mean squared error) or is it a standard probabilistic reconstruction distribution?" [vae & {:keys [as-code?] :or {as-code? true}}] (match [vae] [(_ :guard seq?)] (obj-or-code? as-code? `(.hasLossFunction ~vae)) :else (.hasLossFunction vae))) (defn reconstruction-error "Return the reconstruction error for this variational autoencoder. This method is used ONLY for VAEs that have a standard neural network loss function (i.e., an ILossFunction instance such as mean squared error) instead of using a probabilistic reconstruction distribution P(x|z) for the reconstructions (as presented in the VAE architecture by Kingma and Welling). reconstruction error is a simple deterministic function :vae (layer), is the variational autoencoder :data (INDArray or vec), the data to calc the reconstruction error on" [& {:keys [vae data as-code?] :or {as-code? true} :as opts}] (match [opts] [{:vae (_ :guard seq?) :data (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.reconstructionError ~vae (vec-or-matrix->indarray ~data))) :else (let [[d model] (eval-if-code [data seq?] [vae seq?])] (.reconstructionError model (vec-or-matrix->indarray d))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; recurrent layers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn rnn-activate-using-stored-state "Similar to rnnTimeStep, this method is used for activations using the state stored in the stateMap as the initialization. input (INDArray or vec) of input values to the layer store-last-for-tbptt? (boolean), save state to be used in tbptt training? (boolean) is the model currently in training or not?" [& {:keys [rnn-layer input training? store-last-for-tbptt? as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?)) :training? (:or (_ :guard seq?) (_ :guard boolean?)) :store-last-for-tbptt? (:or (_ :guard seq?) (_ :guard boolean?))}] (obj-or-code? as-code? `(.rnnActivateUsingStoredState rnn-layer (vec-or-matrix->indarray input) training? store-last-for-tbptt?)) :else (let [[rnn i t? store?] (eval-if-code [rnn-layer seq?] [input seq?] [training? seq? boolean?] [store-last-for-tbptt? seq? boolean?])] (.rnnActivateUsingStoredState rnn (vec-or-matrix->indarray i) t? store?)))) (defn rnn-clear-previous-state! "Reset/clear the stateMap for rnn-time-step and tBpttStateMap for rnn-activate-using-stored-state returns the rnn-layer" [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnClearPreviousState))) :else (doto rnn-layer (.rnnClearPreviousState)))) (defn rnn-layer-get-prev-state "Returns a shallow copy of the RNN stateMap (that contains the stored history for use in fns such as rnn-time-step" [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.rnnGetPreviousState ~rnn-layer)) :else (.rnnGetPreviousState rnn-layer))) (defn rnn-get-tbptt-state "Get the RNN truncated backpropagations through time (TBPTT) state for the recurrent layer." [rnn-layer & {:keys [as-code?] :or {as-code? true}}] (match [rnn-layer] [(_ :guard seq?)] (obj-or-code? as-code? `(.rnnGetTBPTTState ~rnn-layer)) :else (.rnnGetTBPTTState rnn-layer))) (defn rnn-set-tbptt-state! "Set the RNN truncated backpropagations through time (TBPTT) state for the recurrent layer. and returns the layer state is a map of {string (indArray or code for creating one)}" [& {:keys [rnn-layer state as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :state (:or (_ :guard map?) (_ :guard seq?))}] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnSetTBPTTState ~state))) :else (let [[s] (eval-if-code [state seq? map?])] (doto rnn-layer (.rnnSetTBPTTState s))))) (defn rnn-layer-set-prev-state! "Set the stateMap (stored history) and return the layer. state is a map of {string (indArray or code for creating one)} - where seq is the code for creating an indArray There is no validation for whats in the state map" [& {:keys [rnn-layer state as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :state (:or (_ :guard seq?) (_ :guard map?))}] (obj-or-code? as-code? `(doto ~rnn-layer (.rnnSetPreviousState ~state))) :else (let [[s] (eval-if-code [state seq? map?])] (doto rnn-layer (.rnnSetPreviousState s))))) (defn rnn-layer-time-step "Do one or more time steps using the previous time step state stored in stateMap. Can be used to efficiently do forward pass one or n-steps at a time (instead of doing forward pass always from t=0) If stateMap is empty, default initialization (usually zeros) is used Implementations also update stateMap at the end of this method input should be an INDArray or vector of input values to the layer" [& {:keys [rnn-layer input as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :input (:or (_ :guard seq?) (_ :guard vector?))}] (obj-or-code? as-code? `(.rnnTimeStep ~rnn-layer (vec-or-matrix->indarray ~input))) :else (let [[rnn i] (eval-if-code [rnn-layer seq?] [input seq?])] (.rnnTimeStep rnn (vec-or-matrix->indarray i))))) (defn tbptt-backprop-gradient "Returns the Truncated BPTT gradient epsilon should be an INDArray or vec tbptt-back-length is an integer" [& {:keys [rnn-layer epsilon tbptt-back-length as-code?] :or {as-code? true} :as opts}] (match [opts] [{:rnn-layer (_ :guard seq?) :epsilon (:or (_ :guard seq?) (_ :guard vector?)) :tbptt-back-length (:or (_ :guard number?) (_ :guard seq?))}] (obj-or-code? as-code? `(.tbpttBackpropGradient ~rnn-layer (vec-or-matrix->indarray ~epsilon) (int ~tbptt-back-length))) :else (let [[rnn e length] (eval-if-code [rnn-layer seq?] [epsilon seq?] [tbptt-back-length seq? number?])] (.tbpttBackpropGradient rnn (vec-or-matrix->indarray e) length))))
[ { "context": "string :value \"ab\"})\n psa2 (dc/psa {:name \"bravo\" :group \"G1\" :data-type :string :value \"bf\"})\n ", "end": 2250, "score": 0.7526576519012451, "start": 2245, "tag": "NAME", "value": "bravo" }, { "context": "string :value \"bf\"})\n psa3 (dc/psa {:name \"charlie\" :group \"G2\" :data-type :string :value \"foo\"})\n ", "end": 2333, "score": 0.8307515382766724, "start": 2326, "tag": "NAME", "value": "charlie" }, { "context": " [coll1 coll2] \"bravo\" {}\n [coll2] \"charlie\" {}\n [coll3] \"case\" {}\n [] \"B", "end": 4940, "score": 0.6500757932662964, "start": 4933, "tag": "NAME", "value": "charlie" }, { "context": "e :float :value 10})\n psa2 (dc/psa {:name \"bravo\" :data-type :float :value -12})\n psa3 (dc/", "end": 11521, "score": 0.7783938646316528, "start": 11516, "tag": "NAME", "value": "bravo" }, { "context": " :float :value -12})\n psa3 (dc/psa {:name \"charlie\" :data-type :float :value 45})\n coll1 (d/i", "end": 11590, "score": 0.7876729965209961, "start": 11583, "tag": "NAME", "value": "charlie" }, { "context": "}]\n [coll1 coll2] [{:type :float :name \"bravo\" :value -12}]\n [coll2] [{:type :float :", "end": 12876, "score": 0.8963009119033813, "start": 12871, "tag": "NAME", "value": "bravo" }, { "context": "ue -12}]\n [coll2] [{:type :float :name \"charlie\" :value 45}]))\n\n (testing \"search by range\"\n ", "end": 12939, "score": 0.8969808220863342, "start": 12932, "tag": "NAME", "value": "charlie" }, { "context": "]}]\n [coll2] [{:type :floatRange :name \"charlie\" :value [44 45.1]}]))\n\n (testing \"search colle", "end": 14855, "score": 0.8088828325271606, "start": 14848, "tag": "NAME", "value": "charlie" }, { "context": "pe :int :value -12})\n psa3 (dc/psa {:name \"charlie\" :data-type :int :value 45})\n coll1 (d/ing", "end": 16593, "score": 0.9980276823043823, "start": 16586, "tag": "NAME", "value": "charlie" }, { "context": " [coll1 coll2] [{:type :intRange :name \"bravo\" :value [-120 nil]}]\n [coll1 coll2] [{:", "end": 19505, "score": 0.9714597463607788, "start": 19500, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] [{:type :intRange :name \"bravo\" :value [nil 12]}]\n [coll2] [{:type :in", "end": 19582, "score": 0.9780275225639343, "start": 19577, "tag": "NAME", "value": "bravo" }, { "context": "12]}]\n [coll2] [{:type :intRange :name \"charlie\" :value [44 46]}]))\n\n (testing \"search collect", "end": 19653, "score": 0.9833301305770874, "start": 19646, "tag": "NAME", "value": "charlie" }, { "context": "nge\n {:type \"int\" :name \"bravo\" :min_value -120}}\n [coll1 coll2] {:add", "end": 20368, "score": 0.8117165565490723, "start": 20363, "tag": "NAME", "value": "bravo" }, { "context": "nge\n {:type \"int\" :name \"bravo\" :max_value 12}}\n [coll2] {:additional_", "end": 20493, "score": 0.863079845905304, "start": 20488, "tag": "NAME", "value": "bravo" }, { "context": "ute_range\n {:type \"int\" :name \"charlie\" :min_value 44 :max_value 46}}\n\n ;; Exa", "end": 20606, "score": 0.8939744234085083, "start": 20599, "tag": "NAME", "value": "charlie" }, { "context": " {:additional_attribute_range {:type \"int\" :name \"bravo\" :min_value -12\n ", "end": 20875, "score": 0.8339734077453613, "start": 20870, "tag": "NAME", "value": "bravo" }, { "context": " {:additional_attribute_range {:type \"int\" :name \"bravo\" :min_value -12\n ", "end": 21055, "score": 0.805044412612915, "start": 21050, "tag": "NAME", "value": "bravo" }, { "context": "ime-psas-search-test\n (let [psa1 (dc/psa {:name \"alpha\" :data-type :datetime :value (d/make-datetime 10 ", "end": 21229, "score": 0.9902043342590332, "start": 21224, "tag": "NAME", "value": "alpha" }, { "context": "datetime 10 false)})\n psa2 (dc/psa {:name \"bravo\" :data-type :datetime :value (d/make-datetime 14 ", "end": 21322, "score": 0.9956055283546448, "start": 21317, "tag": "NAME", "value": "bravo" }, { "context": "datetime 14 false)})\n psa3 (dc/psa {:name \"charlie\" :data-type :datetime :value (d/make-datetime 45 ", "end": 21417, "score": 0.9987766742706299, "start": 21410, "tag": "NAME", "value": "charlie" }, { "context": ")\n\n [coll1, coll2] [{:type :date :name \"bravo\" :value 14}]\n [] [{:type :date :name \"a", "end": 22820, "score": 0.9785601496696472, "start": 22815, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] [{:type :dateRange :name \"bravo\" :value [10 nil]}]\n [coll1 coll2] [{:ty", "end": 25240, "score": 0.6210795640945435, "start": 25235, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] [{:type :dateRange :name \"bravo\" :value [nil 17]}]\n [coll2] [{:type :da", "end": 25316, "score": 0.5940458178520203, "start": 25311, "tag": "NAME", "value": "bravo" }, { "context": "7]}]\n [coll2] [{:type :dateRange :name \"charlie\" :value [44 45]}]))\n\n (testing \"search collect", "end": 25388, "score": 0.9893916845321655, "start": 25381, "tag": "NAME", "value": "charlie" }, { "context": " [coll1 coll2] {:type \"datetime\" :name \"bravo\" :min_value 10}\n [coll1 coll2] {:type \"", "end": 26560, "score": 0.8381428718566895, "start": 26555, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] {:type \"datetime\" :name \"bravo\" :max_value 17}\n [coll2] {:type \"dateti", "end": 26632, "score": 0.9362123012542725, "start": 26627, "tag": "NAME", "value": "bravo" }, { "context": "e 17}\n [coll2] {:type \"datetime\" :name \"charlie\" :min_value 44 :max_value 45}\n\n ;; Test", "end": 26700, "score": 0.9967187643051147, "start": 26693, "tag": "NAME", "value": "charlie" }, { "context": " [coll1 coll2] {:type \"datetime\" :name \"bravo\" :min_value 0 :max_value 14\n ", "end": 26823, "score": 0.9510625600814819, "start": 26818, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] {:type \"datetime\" :name \"bravo\" :min_value 0 :max_value 15\n ", "end": 26958, "score": 0.9548066854476929, "start": 26953, "tag": "NAME", "value": "bravo" }, { "context": "dary true}\n [] {:type \"datetime\" :name \"bravo\" :min_value 0 :max_value 14 :exclude_boundary tru", "end": 27081, "score": 0.9327768087387085, "start": 27076, "tag": "NAME", "value": "bravo" }, { "context": "ime-psas-search-test\n (let [psa1 (dc/psa {:name \"alpha\" :data-type :time :value (d/make-time 10 false)})", "end": 27204, "score": 0.9815473556518555, "start": 27199, "tag": "NAME", "value": "alpha" }, { "context": "ake-time 10 false)})\n psa2 (dc/psa {:name \"bravo\" :data-type :time :value (d/make-time 23 false)})", "end": 27289, "score": 0.9878594875335693, "start": 27284, "tag": "NAME", "value": "bravo" }, { "context": "ake-time 23 false)})\n psa3 (dc/psa {:name \"charlie\" :data-type :time :value (d/make-time 45 false)})", "end": 27376, "score": 0.9970544576644897, "start": 27369, "tag": "NAME", "value": "charlie" }, { "context": "alue 23}]\n [coll2] [{:type :time :name \"charlie\" :value 45}]))\n\n (testing \"search by range\"\n ", "end": 28894, "score": 0.8003814220428467, "start": 28887, "tag": "NAME", "value": "charlie" }, { "context": " [coll1 coll2] [{:type :timeRange :name \"bravo\" :value [20 nil]}]\n [coll1 coll2] [{:ty", "end": 31072, "score": 0.8673334717750549, "start": 31067, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] [{:type :timeRange :name \"bravo\" :value [nil 24]}]\n [coll2] [{:type :ti", "end": 31148, "score": 0.959072470664978, "start": 31143, "tag": "NAME", "value": "bravo" }, { "context": "4]}]\n [coll2] [{:type :timeRange :name \"charlie\" :value [44 45]}]))\n\n (testing \"search collect", "end": 31220, "score": 0.8725181818008423, "start": 31213, "tag": "NAME", "value": "charlie" }, { "context": "10}\n [coll1 coll2] {:type \"time\" :name \"bravo\" :min_value 20}\n [coll1 coll2] {:type \"", "end": 32335, "score": 0.9469557404518127, "start": 32330, "tag": "NAME", "value": "bravo" }, { "context": "20}\n [coll1 coll2] {:type \"time\" :name \"bravo\" :max_value 24}\n [coll2] {:type \"time\" ", "end": 32403, "score": 0.979450523853302, "start": 32398, "tag": "NAME", "value": "bravo" }, { "context": "value 24}\n [coll2] {:type \"time\" :name \"charlie\" :min_value 44 :max_value 45}\n\n ;; Test", "end": 32467, "score": 0.9950413107872009, "start": 32460, "tag": "NAME", "value": "charlie" }, { "context": "ary\n [coll1 coll2] {:type \"time\" :name \"bravo\" :min_value 0 :max_value 23\n ", "end": 32586, "score": 0.9806168079376221, "start": 32581, "tag": "NAME", "value": "bravo" }, { "context": "se}\n [coll1 coll2] {:type \"time\" :name \"bravo\" :min_value 0 :max_value 24\n ", "end": 32717, "score": 0.9826218485832214, "start": 32712, "tag": "NAME", "value": "bravo" }, { "context": "boundary true}\n [] {:type \"time\" :name \"bravo\" :min_value 0 :max_value 23 :exclude_boundary tru", "end": 32836, "score": 0.9834455251693726, "start": 32831, "tag": "NAME", "value": "bravo" }, { "context": "ate-psas-search-test\n (let [psa1 (dc/psa {:name \"alpha\" :data-type :date :value (d/make-date 10 false)})", "end": 32959, "score": 0.9828378558158875, "start": 32954, "tag": "NAME", "value": "alpha" }, { "context": "ake-date 10 false)})\n psa2 (dc/psa {:name \"bravo\" :data-type :date :value (d/make-date 23 false)})", "end": 33044, "score": 0.9883043766021729, "start": 33039, "tag": "NAME", "value": "bravo" }, { "context": "ake-date 23 false)})\n psa3 (dc/psa {:name \"charlie\" :data-type :date :value (d/make-date 45 false)})", "end": 33131, "score": 0.9935909509658813, "start": 33124, "tag": "NAME", "value": "charlie" }, { "context": " [coll1 coll2] [{:type :dateRange :name \"bravo\" :value [20 nil]}]\n [coll1 coll2] [{:ty", "end": 36828, "score": 0.9908431768417358, "start": 36823, "tag": "NAME", "value": "bravo" }, { "context": " [coll1 coll2] [{:type :dateRange :name \"bravo\" :value [nil 24]}]\n [coll2] [{:type :da", "end": 36904, "score": 0.9911956191062927, "start": 36899, "tag": "NAME", "value": "bravo" }, { "context": "4]}]\n [coll2] [{:type :dateRange :name \"charlie\" :value [44 45]}]))\n\n (testing \"search collect", "end": 36976, "score": 0.9980224370956421, "start": 36969, "tag": "NAME", "value": "charlie" }, { "context": "alue\n {:type \"date\" :name \"bravo\" :value (d/make-date 23)}}))\n (are [items se", "end": 37306, "score": 0.9624303579330444, "start": 37301, "tag": "NAME", "value": "bravo" }, { "context": ";; Ranges\n [coll1] {:type \"date\" :name \"alpha\" :min_value 9 :max_value 11}\n [coll1] {", "end": 37859, "score": 0.5743759274482727, "start": 37854, "tag": "NAME", "value": "alpha" }, { "context": "value 11}\n [coll1] {:type \"date\" :name \"alpha\" :min_value 9 :max_value 10}\n [coll1 co", "end": 38010, "score": 0.9334926009178162, "start": 38005, "tag": "NAME", "value": "alpha" }, { "context": "10}\n [coll1 coll2] {:type \"date\" :name \"bravo\" :min_value 20}\n [coll1 coll2] {:type \"", "end": 38091, "score": 0.9862773418426514, "start": 38086, "tag": "NAME", "value": "bravo" }, { "context": "20}\n [coll1 coll2] {:type \"date\" :name \"bravo\" :max_value 24}\n [coll2] {:type \"date\" ", "end": 38159, "score": 0.9886914491653442, "start": 38154, "tag": "NAME", "value": "bravo" }, { "context": "value 24}\n [coll2] {:type \"date\" :name \"charlie\" :min_value 44 :max_value 45}\n\n ;; Test", "end": 38223, "score": 0.9977151155471802, "start": 38216, "tag": "NAME", "value": "charlie" }, { "context": "ary\n [coll1 coll2] {:type \"date\" :name \"bravo\" :min_value 0 :max_value 23\n ", "end": 38342, "score": 0.9808679819107056, "start": 38337, "tag": "NAME", "value": "bravo" }, { "context": "se}\n [coll1 coll2] {:type \"date\" :name \"bravo\" :min_value 0 :max_value 24\n ", "end": 38473, "score": 0.9798547029495239, "start": 38468, "tag": "NAME", "value": "bravo" }, { "context": "boundary true}\n [] {:type \"date\" :name \"bravo\" :min_value 0 :max_value 23 :exclude_boundary tru", "end": 38592, "score": 0.9853270053863525, "start": 38587, "tag": "NAME", "value": "bravo" } ]
system-int-test/test/cmr/system_int_test/search/collection_psa_search_test.clj
sxu123/Common-Metadata-Repository
0
(ns cmr.system-int-test.search.collection-psa-search-test "Tests searching for granules by product specific attributes." (:require [clojure.test :refer :all] [clj-time.core :as t] [clj-time.format :as f] [clojure.string :as s] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.granule :as dg] [cmr.system-int-test.data2.core :as d] [cmr.search.services.messages.attribute-messages :as am] [cmr.common.util :as util] [clj-http.client :as client])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) ;; These are for boolean, datetime_string, time_string, and date_string attribute types which are ;; all indexed and searchable as strings. (deftest indexed-as-string-psas-search-test (let [psa1 (dc/psa {:name "bool" :data-type :boolean :value true}) psa2 (dc/psa {:name "dts" :data-type :datetime-string :value "2012-01-01T01:02:03Z"}) psa3 (dc/psa {:name "ts" :data-type :time-string :value "01:02:03Z"}) psa4 (dc/psa {:name "ds" :data-type :date-string :value "2012-01-01"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1 psa2 psa3]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2 psa3]}) {:format :dif}) coll3 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa3 psa4]}) {:format :dif})] (index/wait-until-indexed) (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "string,bool,true" [coll1] "string,bool,false" [] "string,dts,2012-01-01T01:02:03Z" [coll1 coll2] "string,ts,01:02:03Z" [coll1 coll2 coll3] "string,ds,2012-01-01" [coll3]))) (deftest string-psas-search-test (let [psa1 (dc/psa {:name "alpha" :group "G1" :data-type :string :value "ab"}) psa2 (dc/psa {:name "bravo" :group "G1" :data-type :string :value "bf"}) psa3 (dc/psa {:name "charlie" :group "G2" :data-type :string :value "foo"}) psa4 (dc/psa {:name "case" :group "G3" :data-type :string :value "up"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1 psa2]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2 psa3]}) {:format :dif}) coll3 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa4]}) {:format :dif})] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "string,alpha,ab" [coll1] "string,alpha,AB" [coll1] "string,alpha,c" [] "string,bravo,bf" [coll1 coll2] "string,case,UP" [coll3] "string,case,up" [coll3])) (testing "search by value catalog-rest style" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "string,alpha,ab" [coll1] "string,alpha,c" [] "string,alpha,c" [] "string,bravo,bf" [coll1 coll2])) (testing "search collections by additionalAttributes string value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :string :name "alpha" :value "ab"}] [coll1] [{:type :string :name "'alpha'" :value "'ab'"}] [coll1] [{:type :string :name "alpha" :value "AB"}] [] [{:type :string :name "alpha" :value "c"}] [coll1 coll2] [{:type :string :name "bravo" :value "bf"}] [coll3] [{:type :string :name "case" :value "UP"}] [coll3] [{:type :string :name "case" :value "up"}] [coll1] [{:type :string :name "alpha" :value ["ab" "cd"]}] [coll1] [{:type :string :name "alpha" :value "a%" :pattern true}] [coll1] [{:type :string :name "alpha" :value "a_" :pattern true}])) (testing "search collections by additionalAttributeNames with AQL." (are [items attrib-names options] (let [condition (merge {:additionalAttributeNames attrib-names} options)] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] "alpha" {} [coll1] "'alpha'" {} [coll1 coll2] "bravo" {} [coll2] "charlie" {} [coll3] "case" {} [] "BLAH" {} [coll1 coll3] ["alpha" "case"] {} [coll1 coll3] ["'alpha'" "'case'"] {} [coll1 coll2 coll3] ["alpha" "charlie" "case"] {} [coll2 coll3] "c%" {:pattern true} [coll3] "cas_" {:pattern true})) (testing "searching with multiple attribute conditions" (are [v items operation] (d/refs-match? items (search/find-refs :collection (merge {"attribute[]" v} (when operation {"options[attribute][or]" (= operation :or)})))) ["string,alpha,ab" "string,bravo,,bc"] [coll1] :or ["string,alpha,ab" "string,bravo,,bc"] [] :and ["string,alpha,ab" "string,bravo,bc,"] [coll1] :and ; and is the default ["string,alpha,ab" "string,bravo,,bc"] [] nil)) (testing "searching with multiple attribute conditions catalog-rest style" ;; the query is in the format of ;; attribute[0][name]=alpha&attribute[0][type]=string&attribute[0][value]=ab&attribute[1][name]=bravo&attribute[1][type]=string&attribute[1][maxValue]=bc (are [v items operation] (let [query (->> (map-indexed search/csv->tuples v) (mapcat identity)) query (if operation (merge query ["options[attribute][or]" (= operation :or)]) query)] (d/refs-match? items (search/find-refs :collection query {:snake-kebab? false}))) ["string,alpha,ab" "string,bravo,,bc"] [coll1] :or ["string,alpha,ab" "string,bravo,,bc"] [] :and ["string,alpha,ab" "string,bravo,bc,"] [coll1] :and ; and is the default ["string,alpha,ab" "string,bravo,,bc"] [] nil)) (testing "search collections by additionalAttributes multiple string values with aql" (are [items additional-attribs options] (let [condition (merge {:additionalAttributes additional-attribs} options)] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {:or true} ;; single quotes [coll1] [{:type :string :name "'alpha'" :value "'ab'"} {:type :range :name "'bravo'" :value [nil "'bc'"]}] {:or true} [] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {:and true} [] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {} [coll1] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value ["bc" nil]}] {:and true})) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "string,alpha,aa,ac" [coll1] ;; beginning edge of range "string,alpha,ab,ac" [coll1] ;; ending edge of range "string,alpha,aa,ab" [coll1] ;; only min range provided "string,bravo,bc," [coll1 coll2] ;; only max range provided "string,bravo,,bg" [coll1 coll2])) (testing "search by range catalog-rest style" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "string,alpha,aa,ac" [coll1] ;; beginning edge of range "string,alpha,ab,ac"[coll1] ;; ending edge of range "string,alpha,aa,ab" [coll1] ;; only min range provided "string,bravo,bc," [coll1 coll2] ;; only max range provided "string,bravo,,bg" [coll1 coll2])) (testing "search collections by additionalAttributes string range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :range :name "alpha" :value ["aa" "ac"]}] [coll1] [{:type :range :name "'alpha'" :value ["'aa'" "'ac'"]}] [coll1] [{:type :range :name "alpha" :value ["ab" "ac"]}] [coll1] [{:type :range :name "alpha" :value ["aa" "ab"]}] [coll1 coll2] [{:type :range :name "bravo" :value ["bc" nil]}] [coll1 coll2] [{:type :range :name "bravo" :value [nil "bg"]}])) (testing "search collections by string attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ac"}} [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "ab" :max_value "ac"}} [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab"}} [coll1 coll2] {:additional_attribute_range {:type "string" :name "bravo" :min_value "bc"}} [coll1 coll2] {:additional_attribute_range {:type "string" :name "bravo" :max_value "bg"}} ;; Exact value [coll1] {:additional_attribute_value {:type "string" :name "alpha" :value "ab"}} ;; Test exclude boundary [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab" :exclude_boundary false}} [] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab" :exclude_boundary true}} ;; Test searching by group [coll3] {:additional_attribute_name {:group "G3"}} [coll3] {:additional_attribute_name {:group "*3" :pattern true}} [coll1 coll2 coll3] {:additional_attribute_name {:group "G?" :pattern true}})))) (deftest float-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :float :value 10}) psa2 (dc/psa {:name "bravo" :data-type :float :value -12}) psa3 (dc/psa {:name "charlie" :data-type :float :value 45}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "float,alpha,10" [coll1] "float,alpha,11" [] "float,bravo,-12" [coll1 coll2] "float,charlie,45" [coll2])) (testing "search by value legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "float,alpha,10" [coll1] "float,alpha,11" [] "float,bravo,-12" [coll1 coll2] "float,charlie,45" [coll2])) (testing "search collections by additionalAttributes float value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :float :name "alpha" :value 10}] [] [{:type :float :name "alpha" :value 11}] [coll1 coll2] [{:type :float :name "bravo" :value -12}] [coll2] [{:type :float :name "charlie" :value 45}])) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "float,alpha,9.2,11" [coll1] ;; beginning edge of range "float,alpha,10.0,10.6" [coll1] ;; ending edge of range "float,alpha,9.2,10.0" [coll1] ;; only min range provided "float,bravo,-120," [coll1 coll2] ;; only max range provided "float,bravo,,13.6" [coll1 coll2] "float,charlie,44,45.1" [coll2])) (testing "search by range legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "float,alpha,9.2,11" [coll1] ;; beginning edge of range "float,alpha,10.0,10.6" [coll1] ;; ending edge of range "float,alpha,9.2,10.0" [coll1] ;; only min range provided "float,bravo,-120," [coll1 coll2] ;; only max range provided "float,bravo,,13.6" [coll1 coll2] "float,charlie,44,45.1" [coll2])) (testing "search collections by additionalAttributes float range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :floatRange :name "alpha" :value [9.2 11]}] [coll1] [{:type :floatRange :name "alpha" :value [10.0 10.6]}] [coll1] [{:type :floatRange :name "alpha" :value [9.2 10.0]}] [coll1 coll2] [{:type :floatRange :name "bravo" :value [-120 nil]}] [coll1 coll2] [{:type :floatRange :name "bravo" :value [nil 13.6]}] [coll2] [{:type :floatRange :name "charlie" :value [44 45.1]}])) (testing "search collections by float attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 9.2 :max_value 11}} [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 10.0 :max_value 10.6}} [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 9.2 :max_value 10.0}} [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :min_value -120}} [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :max_value 13.6}} [coll2] {:additional_attribute_range {:type "float" :name "charlie" :min_value 44 :max_value 45.1}} ;; Exact value [coll1 coll2] {:additional_attribute_value {:type "float" :name "bravo" :value -12}} ;; Test exclude boundary [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary false}} [] {:additional_attribute_range {:type "float" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary true}})))) (deftest int-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :int :value 10}) psa2 (dc/psa {:name "bravo" :data-type :int :value -12}) psa3 (dc/psa {:name "charlie" :data-type :int :value 45}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "int,alpha,10" [coll1] "int,alpha,11" [] "int,bravo,-12" [coll1 coll2])) (testing "search by value legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "int,alpha,10" [coll1] "int,alpha,11" [] "int,bravo,-12" [coll1 coll2])) (testing "search collections by additionalAttributes int value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :int :name "alpha" :value 10}] [] [{:type :int :name "alpha" :value 11}] [coll1 coll2] [{:type :int :name "bravo" :value -12}])) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "int,alpha,9,11" [coll1] ;; beginning edge of range "int,alpha,10,11" [coll1] ;; ending edge of range "int,alpha,9,10" [coll1] ;; only min range provided "int,bravo,-120," [coll1 coll2] ;; only max range provided "int,bravo,,12" [coll1 coll2] "int,charlie,44,46" [coll2])) (testing "search by range legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "int,alpha,9,11" [coll1] ;; beginning edge of range "int,alpha,10,11" [coll1] ;; ending edge of range "int,alpha,9,10" [coll1] ;; only min range provided "int,bravo,-120," [coll1 coll2] ;; only max range provided "int,bravo,,12" [coll1 coll2] ;; range inheritance "int,charlie,44,46" [coll2])) (testing "search collections by additionalAttributes int range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :intRange :name "alpha" :value [9 11]}] [coll1] [{:type :intRange :name "alpha" :value [10 11]}] [coll1] [{:type :intRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :intRange :name "bravo" :value [-120 nil]}] [coll1 coll2] [{:type :intRange :name "bravo" :value [nil 12]}] [coll2] [{:type :intRange :name "charlie" :value [44 46]}])) (testing "search collections by int attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 9 :max_value 11}} [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 10 :max_value 11}} [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 9 :max_value 10}} [coll1 coll2] {:additional_attribute_range {:type "int" :name "bravo" :min_value -120}} [coll1 coll2] {:additional_attribute_range {:type "int" :name "bravo" :max_value 12}} [coll2] {:additional_attribute_range {:type "int" :name "charlie" :min_value 44 :max_value 46}} ;; Exact value [coll1 coll2] {:additional_attribute_value {:type "int" :name "bravo" :value -12}} ;; Test exclude boundary [coll1 coll2] {:additional_attribute_range {:type "int" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary false}} [] {:additional_attribute_range {:type "int" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary true}})))) (deftest datetime-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :datetime :value (d/make-datetime 10 false)}) psa2 (dc/psa {:name "bravo" :data-type :datetime :value (d/make-datetime 14 false)}) psa3 (dc/psa {:name "charlie" :data-type :datetime :value (d/make-datetime 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-datetime n))})) "datetime,bravo," 14 [coll1, coll2] "datetime,alpha," 11 [] "datetime,alpha," 10 [coll1] "datetime,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-datetime n))))) "datetime,bravo," 14 [coll1, coll2] "datetime,alpha," 11 [] "datetime,alpha," 10 [coll1] "datetime,charlie," 45 [coll2])) (testing "search collections by additionalAttributes datetime value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-datetime) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1, coll2] [{:type :date :name "bravo" :value 14}] [] [{:type :date :name "alpha" :value 11}] [coll1] [{:type :date :name "alpha" :value 10}] [coll2] [{:type :date :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-datetime min-n) max-v (d/make-datetime max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "datetime,alpha," 9 11 [coll1] ;; beginning edge of range "datetime,alpha," 10 11 [coll1] ;; ending edge of range "datetime,alpha," 9 10 [coll1] ;; only min range provided "datetime,bravo," 10 nil [coll1 coll2] ;; only max range provided "datetime,bravo," nil 17 [coll1 coll2] "datetime,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-datetime min-n) max-v (d/make-datetime max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "datetime,alpha," 9 11 [coll1] ;; beginning edge of range "datetime,alpha," 10 11 [coll1] ;; ending edge of range "datetime,alpha," 9 10 [coll1] ;; only min range provided "datetime,bravo," 10 nil [coll1 coll2] ;; only max range provided "datetime,bravo," nil 17 [coll1 coll2] "datetime,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes date range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-datetime v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :dateRange :name "alpha" :value [9 11]}] [coll1] [{:type :dateRange :name "alpha" :value [10 11]}] [coll1] [{:type :dateRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :dateRange :name "bravo" :value [10 nil]}] [coll1 coll2] [{:type :dateRange :name "bravo" :value [nil 17]}] [coll2] [{:type :dateRange :name "charlie" :value [44 45]}])) (testing "search collections by datetime attribute using JSON Query Language" ;; Exact value (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "datetime" :name "bravo" :value (d/make-datetime 14)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-datetime (:min_value search)) :max_value (d/make-datetime (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "datetime" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "datetime" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "datetime" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "datetime" :name "bravo" :min_value 10} [coll1 coll2] {:type "datetime" :name "bravo" :max_value 17} [coll2] {:type "datetime" :name "charlie" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "datetime" :name "bravo" :min_value 0 :max_value 14 :exclude_boundary false} [coll1 coll2] {:type "datetime" :name "bravo" :min_value 0 :max_value 15 :exclude_boundary true} [] {:type "datetime" :name "bravo" :min_value 0 :max_value 14 :exclude_boundary true})))) (deftest time-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :time :value (d/make-time 10 false)}) psa2 (dc/psa {:name "bravo" :data-type :time :value (d/make-time 23 false)}) psa3 (dc/psa {:name "charlie" :data-type :time :value (d/make-time 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-time n))})) "time,alpha," 10 [coll1] "time,alpha," 11 [] "time,bravo," 23 [coll1 coll2] "time,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-time n))))) "time,alpha," 10 [coll1] "time,alpha," 11 [] "time,bravo," 23 [coll1 coll2] "time,charlie," 45 [coll2])) (testing "search collections by additionalAttributes time value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-time) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :time :name "alpha" :value 10}] [] [{:type :time :name "alpha" :value 11}] [coll1 coll2] [{:type :time :name "bravo" :value 23}] [coll2] [{:type :time :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-time min-n) max-v (d/make-time max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "time,alpha," 9 11 [coll1] ;; beginning edge of range "time,alpha," 10 11 [coll1] ;; ending edge of range "time,alpha," 9 10 [coll1] ;; only min range provided "time,bravo," 20 nil [coll1 coll2] ;; only max range provided "time,bravo," nil 24 [coll1 coll2] "time,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-time min-n) max-v (d/make-time max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "time,alpha," 9 11 [coll1] ;; beginning edge of range "time,alpha," 10 11 [coll1] ;; ending edge of range "time,alpha," 9 10 [coll1] ;; only min range provided "time,bravo," 20 nil [coll1 coll2] ;; only max range provided "time,bravo," nil 24 [coll1 coll2] "time,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes time range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-time v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :timeRange :name "alpha" :value [9 11]}] [coll1] [{:type :timeRange :name "alpha" :value [10 11]}] [coll1] [{:type :timeRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :timeRange :name "bravo" :value [20 nil]}] [coll1 coll2] [{:type :timeRange :name "bravo" :value [nil 24]}] [coll2] [{:type :timeRange :name "charlie" :value [44 45]}])) (testing "search collections by time attribute using JSON Query Language" (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "time" :name "bravo" :value (d/make-time 23)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-time (:min_value search)) :max_value (d/make-time (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "time" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "time" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "time" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "time" :name "bravo" :min_value 20} [coll1 coll2] {:type "time" :name "bravo" :max_value 24} [coll2] {:type "time" :name "charlie" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "time" :name "bravo" :min_value 0 :max_value 23 :exclude_boundary false} [coll1 coll2] {:type "time" :name "bravo" :min_value 0 :max_value 24 :exclude_boundary true} [] {:type "time" :name "bravo" :min_value 0 :max_value 23 :exclude_boundary true})))) (deftest date-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :date :value (d/make-date 10 false)}) psa2 (dc/psa {:name "bravo" :data-type :date :value (d/make-date 23 false)}) psa3 (dc/psa {:name "charlie" :data-type :date :value (d/make-date 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-date n))})) "date,bravo," 23 [coll1 coll2] "date,alpha," 11 [] "date,alpha," 10 [coll1] "date,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-date n))))) "date,bravo," 23 [coll1 coll2] "date,alpha," 11 [] "date,alpha," 10 [coll1] "date,charlie," 45 [coll2])) (testing "search collections by additionalAttributes date value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-date) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1 coll2] [{:type :date :name "bravo" :value 23}] [coll1] [{:type :date :name "alpha" :value 10}] [] [{:type :date :name "alpha" :value 11}] [coll2] [{:type :date :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-date min-n) max-v (d/make-date max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "date,alpha," 9 11 [coll1] ;; beginning edge of range "date,alpha," 10 11 [coll1] ;; ending edge of range "date,alpha," 9 10 [coll1] ;; only min range provided "date,bravo," 20 nil [coll1 coll2] ;; only max range provided "date,bravo," nil 24 [coll1 coll2] "date,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-date min-n) max-v (d/make-date max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "date,alpha," 9 11 [coll1] ;; beginning edge of range "date,alpha," 10 11 [coll1] ;; ending edge of range "date,alpha," 9 10 [coll1] ;; only min range provided "date,bravo," 20 nil [coll1 coll2] ;; only max range provided "date,bravo," nil 24 [coll1 coll2] "date,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes date range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-date v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :dateRange :name "alpha" :value [9 11]}] [coll1] [{:type :dateRange :name "alpha" :value [10 11]}] [coll1] [{:type :dateRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :dateRange :name "bravo" :value [20 nil]}] [coll1 coll2] [{:type :dateRange :name "bravo" :value [nil 24]}] [coll2] [{:type :dateRange :name "charlie" :value [44 45]}])) (testing "search collections by date attribute using JSON Query Language" (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "date" :name "bravo" :value (d/make-date 23)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-date (:min_value search)) :max_value (d/make-date (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "date" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "date" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "date" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "date" :name "bravo" :min_value 20} [coll1 coll2] {:type "date" :name "bravo" :max_value 24} [coll2] {:type "date" :name "charlie" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "date" :name "bravo" :min_value 0 :max_value 23 :exclude_boundary false} [coll1 coll2] {:type "date" :name "bravo" :min_value 0 :max_value 24 :exclude_boundary true} [] {:type "date" :name "bravo" :min_value 0 :max_value 23 :exclude_boundary true})))) (deftest range-validation-test (testing "empty parameter range" (are [attrib-value] (= {:errors [(am/one-of-min-max-msg)] :status 400} (search/get-search-failure-xml-data (search/find-refs :collection {"attribute[]" attrib-value}))) "string,alpha,," "int,alpha,," "float,alpha,," "date,alpha,," "time,alpha,," "datetime,alpha,,")) (testing "invalid parameter range values" (are [v min-n max-n] (= {:errors [(am/max-must-be-greater-than-min-msg min-n max-n)] :status 400} (search/get-search-failure-xml-data (search/find-refs :collection {"attribute[]" (format "%s,%s,%s" v (str min-n) (str max-n))}))) "string,alpha" "y" "m" "int,alpha" 10 6 "float,alpha" 10.0 6.0)) (testing "empty aql range" (are [attrib-value] (= {:errors [(am/one-of-min-max-msg)] :status 400} (search/get-search-failure-xml-data (search/find-refs-with-aql :collection [{:additionalAttributes [attrib-value]}]))) {:type :range :name "alpha" :value [nil nil]} {:type :intRange :name "alpha" :value [nil nil]} {:type :floatRange :name "alpha" :value [nil nil]} {:type :dateRange :name "alpha" :value [nil nil]} {:type :timeRange :name "alpha" :value [nil nil]})) (testing "invalid aql range values" (are [attrib-value] (= {:errors [(apply am/max-must-be-greater-than-min-msg (:value attrib-value))] :status 400} (search/get-search-failure-xml-data (search/find-refs-with-aql :collection [{:additionalAttributes [attrib-value]}]))) {:type :range :name "alpha" :value ["y" "m"]} {:type :intRange :name "alpha" :value [10 6]} {:type :floatRange :name "alpha" :value [10.0 6.0]}))) (deftest search-by-name-and-group-test (let [psa1 (dc/psa {:name "foo" :group "g1" :data-type :boolean :value true}) psa2 (dc/psa {:name "two" :group "g2" :data-type :datetime-string :value "2012-01-01T01:02:03Z"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2]}) {:format :dif})] (index/wait-until-indexed) (are [matches a-name group pattern?] (d/refs-match? matches (search/find-refs-with-json-query :collection {} {:additional_attribute_name (util/remove-nil-keys {:name a-name :group group :pattern pattern?})})) [coll1] "foo" nil false [coll1] "f?o" nil true [] "f?o" nil false [coll1] nil "g1" false [coll1 coll2] nil "g*" true [] nil "g*" false [] "t*o" "*" false [coll2] "t*o" "*" true))) (deftest json-query-validate-types-test (are [type value] (d/refs-match? [] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:name "a" :type type :value value}})) "string" "abc" "string" 1.5 "int" 12 "float" 1.23 "datetime" "2012-01-11T10:00:00.000Z" "date" "2012-01-11" "time" "10:00:00.000Z")) (deftest json-query-validation-errors-test (util/are2 [search errors] (= {:status 400 :errors errors} (search/find-refs-with-json-query :collection {} search)) "Invalid data type" {:additional_attribute_value {:type "bad" :value "c" :name "n"}} ["/condition/additional_attribute_value/type instance value (\"bad\") not found in enum (possible values: [\"string\",\"boolean\",\"time\",\"date\",\"datetime\",\"int\",\"float\"])"] "Invalid int" {:additional_attribute_value {:type "int" :name "B" :value "1"}} ["[\"1\"] is an invalid value for type [int]"] "Invalid float" {:additional_attribute_value {:type "float" :name "B" :value "1.42"}} ["[\"1.42\"] is an invalid value for type [float]"] "Invalid datetime" {:additional_attribute_value {:type "datetime" :name "B" :value "2012-01-11 10:00:00"}} ["[\"2012-01-11 10:00:00\"] is an invalid value for type [datetime]"] "Invalid date" {:additional_attribute_value {:type "date" :name "B" :value "10:00:00Z"}} ["[\"10:00:00Z\"] is an invalid value for type [date]"] "Invalid time" {:additional_attribute_value {:type "time" :name "B" :value "2012-01-11"}} ["[\"2012-01-11\"] is an invalid value for type [time]"] "Invalid use of exclude-boundary" {:additional_attribute_value {:type "string" :name "a" :value "b" :exclude_boundary true}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"exclude_boundary\"]"] "Invalid use of pattern" {:additional_attribute_value {:type "string" :group "g" :name "a*" :value "b" :pattern true}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"pattern\"]"] "Invalid range max < min" {:additional_attribute_range {:type "int" :name "foo" :min_value 25 :max_value 14}} ["The maximum value [14] must be greater than the minimum value [25]"] "Cannot include both range and an exact value - value search" {:additional_attribute_value {:type "int" :name "foo" :min_value 25 :value 37}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"min_value\"]"] "Cannot include both range and an exact value - range search" {:additional_attribute_range {:type "int" :name "foo" :min_value 25 :value 37}} ["/condition/additional_attribute_range object instance has properties which are not allowed by the schema: [\"value\"]"] "Name is required when doing an exact value search" {:additional_attribute_value {:type "int" :value 25 :group "abc"}} ["/condition/additional_attribute_value object has missing required properties ([\"name\"])"] "Name is required when doing a range search" {:additional_attribute_range {:type "int" :min_value 25 :max_value 35 :group "abc"}} ["/condition/additional_attribute_range object has missing required properties ([\"name\"])"] "Type is required when doing an exact value search" {:additional_attribute_value {:value 25 :name "a" :group "abc"}} ["/condition/additional_attribute_value object has missing required properties ([\"type\"])"] "Type is required when doing a range search" {:additional_attribute_range {:min_value 25 :max_value 35 :name "c" :group "abc"}} ["/condition/additional_attribute_range object has missing required properties ([\"type\"])"] "One of group or name is required" {:additional_attribute_name {:pattern true}} ["One of 'group' or 'name' must be provided."] "Multiple errors can be returned" {:additional_attribute_range {:type "float" :name "B" :min_value "1.42" :max_value "foo"}} ["[\"foo\"] is an invalid value for type [float]" "[\"1.42\"] is an invalid value for type [float]"])) (deftest dif-extended-metadata-test (let [dif9-coll (d/ingest-concept-with-metadata-file "data/dif/sample_collection_with_extended_metadata.xml" {:provider-id "PROV1" :concept-type :collection :format-key :dif :native-id "dif9-coll"}) dif10-coll (d/ingest-concept-with-metadata-file "data/dif10/sample_collection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :dif10 :native-id "dif10-coll"})] (index/wait-until-indexed) (testing "search for extended metadata fields" (util/are2 [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) "By group" [dif9-coll dif10-coll] {:additional_attribute_name {:group "gov.nasa.gsfc.gcmd"}} "By group - pattern" [dif9-coll dif10-coll] {:additional_attribute_name {:group "*gcmd" :pattern true}} "By name - link_notification.contact" [dif9-coll] {:additional_attribute_name {:name "link_notification.contact"}} "By name - metadata.extraction_date" [dif9-coll] {:additional_attribute_name {:name "metadata.extraction_date"}} "By name - metadata.keyword_version" [dif9-coll dif10-coll] {:additional_attribute_name {:name "metadata.keyword_version"}} "By name - pattern" [dif9-coll dif10-coll] {:additional_attribute_name {:name "meta??ta*" :pattern true}} "By value - string" [dif9-coll] {:additional_attribute_value {:name "metadata.extraction_date" :type "string" :value "2015-05-21 15:58:46"}} ;; CMR-2413 - This is failing due to 8.100000381469727 being sent to elasticsearch. ; "By value - float" ; [dif9-coll] {:additional_attribute_name {:name "metadata.keyword_version" :value 8.1 :type "float"}} "By range - float" [dif9-coll dif10-coll] {:additional_attribute_range {:name "metadata.keyword_version" :min_value 8.0 :max_value 8.5 :type "float"}}))))
73681
(ns cmr.system-int-test.search.collection-psa-search-test "Tests searching for granules by product specific attributes." (:require [clojure.test :refer :all] [clj-time.core :as t] [clj-time.format :as f] [clojure.string :as s] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.granule :as dg] [cmr.system-int-test.data2.core :as d] [cmr.search.services.messages.attribute-messages :as am] [cmr.common.util :as util] [clj-http.client :as client])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) ;; These are for boolean, datetime_string, time_string, and date_string attribute types which are ;; all indexed and searchable as strings. (deftest indexed-as-string-psas-search-test (let [psa1 (dc/psa {:name "bool" :data-type :boolean :value true}) psa2 (dc/psa {:name "dts" :data-type :datetime-string :value "2012-01-01T01:02:03Z"}) psa3 (dc/psa {:name "ts" :data-type :time-string :value "01:02:03Z"}) psa4 (dc/psa {:name "ds" :data-type :date-string :value "2012-01-01"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1 psa2 psa3]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2 psa3]}) {:format :dif}) coll3 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa3 psa4]}) {:format :dif})] (index/wait-until-indexed) (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "string,bool,true" [coll1] "string,bool,false" [] "string,dts,2012-01-01T01:02:03Z" [coll1 coll2] "string,ts,01:02:03Z" [coll1 coll2 coll3] "string,ds,2012-01-01" [coll3]))) (deftest string-psas-search-test (let [psa1 (dc/psa {:name "alpha" :group "G1" :data-type :string :value "ab"}) psa2 (dc/psa {:name "<NAME>" :group "G1" :data-type :string :value "bf"}) psa3 (dc/psa {:name "<NAME>" :group "G2" :data-type :string :value "foo"}) psa4 (dc/psa {:name "case" :group "G3" :data-type :string :value "up"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1 psa2]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2 psa3]}) {:format :dif}) coll3 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa4]}) {:format :dif})] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "string,alpha,ab" [coll1] "string,alpha,AB" [coll1] "string,alpha,c" [] "string,bravo,bf" [coll1 coll2] "string,case,UP" [coll3] "string,case,up" [coll3])) (testing "search by value catalog-rest style" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "string,alpha,ab" [coll1] "string,alpha,c" [] "string,alpha,c" [] "string,bravo,bf" [coll1 coll2])) (testing "search collections by additionalAttributes string value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :string :name "alpha" :value "ab"}] [coll1] [{:type :string :name "'alpha'" :value "'ab'"}] [coll1] [{:type :string :name "alpha" :value "AB"}] [] [{:type :string :name "alpha" :value "c"}] [coll1 coll2] [{:type :string :name "bravo" :value "bf"}] [coll3] [{:type :string :name "case" :value "UP"}] [coll3] [{:type :string :name "case" :value "up"}] [coll1] [{:type :string :name "alpha" :value ["ab" "cd"]}] [coll1] [{:type :string :name "alpha" :value "a%" :pattern true}] [coll1] [{:type :string :name "alpha" :value "a_" :pattern true}])) (testing "search collections by additionalAttributeNames with AQL." (are [items attrib-names options] (let [condition (merge {:additionalAttributeNames attrib-names} options)] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] "alpha" {} [coll1] "'alpha'" {} [coll1 coll2] "bravo" {} [coll2] "<NAME>" {} [coll3] "case" {} [] "BLAH" {} [coll1 coll3] ["alpha" "case"] {} [coll1 coll3] ["'alpha'" "'case'"] {} [coll1 coll2 coll3] ["alpha" "charlie" "case"] {} [coll2 coll3] "c%" {:pattern true} [coll3] "cas_" {:pattern true})) (testing "searching with multiple attribute conditions" (are [v items operation] (d/refs-match? items (search/find-refs :collection (merge {"attribute[]" v} (when operation {"options[attribute][or]" (= operation :or)})))) ["string,alpha,ab" "string,bravo,,bc"] [coll1] :or ["string,alpha,ab" "string,bravo,,bc"] [] :and ["string,alpha,ab" "string,bravo,bc,"] [coll1] :and ; and is the default ["string,alpha,ab" "string,bravo,,bc"] [] nil)) (testing "searching with multiple attribute conditions catalog-rest style" ;; the query is in the format of ;; attribute[0][name]=alpha&attribute[0][type]=string&attribute[0][value]=ab&attribute[1][name]=bravo&attribute[1][type]=string&attribute[1][maxValue]=bc (are [v items operation] (let [query (->> (map-indexed search/csv->tuples v) (mapcat identity)) query (if operation (merge query ["options[attribute][or]" (= operation :or)]) query)] (d/refs-match? items (search/find-refs :collection query {:snake-kebab? false}))) ["string,alpha,ab" "string,bravo,,bc"] [coll1] :or ["string,alpha,ab" "string,bravo,,bc"] [] :and ["string,alpha,ab" "string,bravo,bc,"] [coll1] :and ; and is the default ["string,alpha,ab" "string,bravo,,bc"] [] nil)) (testing "search collections by additionalAttributes multiple string values with aql" (are [items additional-attribs options] (let [condition (merge {:additionalAttributes additional-attribs} options)] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {:or true} ;; single quotes [coll1] [{:type :string :name "'alpha'" :value "'ab'"} {:type :range :name "'bravo'" :value [nil "'bc'"]}] {:or true} [] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {:and true} [] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {} [coll1] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value ["bc" nil]}] {:and true})) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "string,alpha,aa,ac" [coll1] ;; beginning edge of range "string,alpha,ab,ac" [coll1] ;; ending edge of range "string,alpha,aa,ab" [coll1] ;; only min range provided "string,bravo,bc," [coll1 coll2] ;; only max range provided "string,bravo,,bg" [coll1 coll2])) (testing "search by range catalog-rest style" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "string,alpha,aa,ac" [coll1] ;; beginning edge of range "string,alpha,ab,ac"[coll1] ;; ending edge of range "string,alpha,aa,ab" [coll1] ;; only min range provided "string,bravo,bc," [coll1 coll2] ;; only max range provided "string,bravo,,bg" [coll1 coll2])) (testing "search collections by additionalAttributes string range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :range :name "alpha" :value ["aa" "ac"]}] [coll1] [{:type :range :name "'alpha'" :value ["'aa'" "'ac'"]}] [coll1] [{:type :range :name "alpha" :value ["ab" "ac"]}] [coll1] [{:type :range :name "alpha" :value ["aa" "ab"]}] [coll1 coll2] [{:type :range :name "bravo" :value ["bc" nil]}] [coll1 coll2] [{:type :range :name "bravo" :value [nil "bg"]}])) (testing "search collections by string attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ac"}} [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "ab" :max_value "ac"}} [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab"}} [coll1 coll2] {:additional_attribute_range {:type "string" :name "bravo" :min_value "bc"}} [coll1 coll2] {:additional_attribute_range {:type "string" :name "bravo" :max_value "bg"}} ;; Exact value [coll1] {:additional_attribute_value {:type "string" :name "alpha" :value "ab"}} ;; Test exclude boundary [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab" :exclude_boundary false}} [] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab" :exclude_boundary true}} ;; Test searching by group [coll3] {:additional_attribute_name {:group "G3"}} [coll3] {:additional_attribute_name {:group "*3" :pattern true}} [coll1 coll2 coll3] {:additional_attribute_name {:group "G?" :pattern true}})))) (deftest float-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :float :value 10}) psa2 (dc/psa {:name "<NAME>" :data-type :float :value -12}) psa3 (dc/psa {:name "<NAME>" :data-type :float :value 45}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "float,alpha,10" [coll1] "float,alpha,11" [] "float,bravo,-12" [coll1 coll2] "float,charlie,45" [coll2])) (testing "search by value legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "float,alpha,10" [coll1] "float,alpha,11" [] "float,bravo,-12" [coll1 coll2] "float,charlie,45" [coll2])) (testing "search collections by additionalAttributes float value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :float :name "alpha" :value 10}] [] [{:type :float :name "alpha" :value 11}] [coll1 coll2] [{:type :float :name "<NAME>" :value -12}] [coll2] [{:type :float :name "<NAME>" :value 45}])) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "float,alpha,9.2,11" [coll1] ;; beginning edge of range "float,alpha,10.0,10.6" [coll1] ;; ending edge of range "float,alpha,9.2,10.0" [coll1] ;; only min range provided "float,bravo,-120," [coll1 coll2] ;; only max range provided "float,bravo,,13.6" [coll1 coll2] "float,charlie,44,45.1" [coll2])) (testing "search by range legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "float,alpha,9.2,11" [coll1] ;; beginning edge of range "float,alpha,10.0,10.6" [coll1] ;; ending edge of range "float,alpha,9.2,10.0" [coll1] ;; only min range provided "float,bravo,-120," [coll1 coll2] ;; only max range provided "float,bravo,,13.6" [coll1 coll2] "float,charlie,44,45.1" [coll2])) (testing "search collections by additionalAttributes float range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :floatRange :name "alpha" :value [9.2 11]}] [coll1] [{:type :floatRange :name "alpha" :value [10.0 10.6]}] [coll1] [{:type :floatRange :name "alpha" :value [9.2 10.0]}] [coll1 coll2] [{:type :floatRange :name "bravo" :value [-120 nil]}] [coll1 coll2] [{:type :floatRange :name "bravo" :value [nil 13.6]}] [coll2] [{:type :floatRange :name "<NAME>" :value [44 45.1]}])) (testing "search collections by float attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 9.2 :max_value 11}} [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 10.0 :max_value 10.6}} [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 9.2 :max_value 10.0}} [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :min_value -120}} [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :max_value 13.6}} [coll2] {:additional_attribute_range {:type "float" :name "charlie" :min_value 44 :max_value 45.1}} ;; Exact value [coll1 coll2] {:additional_attribute_value {:type "float" :name "bravo" :value -12}} ;; Test exclude boundary [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary false}} [] {:additional_attribute_range {:type "float" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary true}})))) (deftest int-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :int :value 10}) psa2 (dc/psa {:name "bravo" :data-type :int :value -12}) psa3 (dc/psa {:name "<NAME>" :data-type :int :value 45}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "int,alpha,10" [coll1] "int,alpha,11" [] "int,bravo,-12" [coll1 coll2])) (testing "search by value legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "int,alpha,10" [coll1] "int,alpha,11" [] "int,bravo,-12" [coll1 coll2])) (testing "search collections by additionalAttributes int value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :int :name "alpha" :value 10}] [] [{:type :int :name "alpha" :value 11}] [coll1 coll2] [{:type :int :name "bravo" :value -12}])) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "int,alpha,9,11" [coll1] ;; beginning edge of range "int,alpha,10,11" [coll1] ;; ending edge of range "int,alpha,9,10" [coll1] ;; only min range provided "int,bravo,-120," [coll1 coll2] ;; only max range provided "int,bravo,,12" [coll1 coll2] "int,charlie,44,46" [coll2])) (testing "search by range legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "int,alpha,9,11" [coll1] ;; beginning edge of range "int,alpha,10,11" [coll1] ;; ending edge of range "int,alpha,9,10" [coll1] ;; only min range provided "int,bravo,-120," [coll1 coll2] ;; only max range provided "int,bravo,,12" [coll1 coll2] ;; range inheritance "int,charlie,44,46" [coll2])) (testing "search collections by additionalAttributes int range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :intRange :name "alpha" :value [9 11]}] [coll1] [{:type :intRange :name "alpha" :value [10 11]}] [coll1] [{:type :intRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :intRange :name "<NAME>" :value [-120 nil]}] [coll1 coll2] [{:type :intRange :name "<NAME>" :value [nil 12]}] [coll2] [{:type :intRange :name "<NAME>" :value [44 46]}])) (testing "search collections by int attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 9 :max_value 11}} [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 10 :max_value 11}} [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 9 :max_value 10}} [coll1 coll2] {:additional_attribute_range {:type "int" :name "<NAME>" :min_value -120}} [coll1 coll2] {:additional_attribute_range {:type "int" :name "<NAME>" :max_value 12}} [coll2] {:additional_attribute_range {:type "int" :name "<NAME>" :min_value 44 :max_value 46}} ;; Exact value [coll1 coll2] {:additional_attribute_value {:type "int" :name "bravo" :value -12}} ;; Test exclude boundary [coll1 coll2] {:additional_attribute_range {:type "int" :name "<NAME>" :min_value -12 :max_value -5 :exclude_boundary false}} [] {:additional_attribute_range {:type "int" :name "<NAME>" :min_value -12 :max_value -5 :exclude_boundary true}})))) (deftest datetime-psas-search-test (let [psa1 (dc/psa {:name "<NAME>" :data-type :datetime :value (d/make-datetime 10 false)}) psa2 (dc/psa {:name "<NAME>" :data-type :datetime :value (d/make-datetime 14 false)}) psa3 (dc/psa {:name "<NAME>" :data-type :datetime :value (d/make-datetime 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-datetime n))})) "datetime,bravo," 14 [coll1, coll2] "datetime,alpha," 11 [] "datetime,alpha," 10 [coll1] "datetime,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-datetime n))))) "datetime,bravo," 14 [coll1, coll2] "datetime,alpha," 11 [] "datetime,alpha," 10 [coll1] "datetime,charlie," 45 [coll2])) (testing "search collections by additionalAttributes datetime value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-datetime) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1, coll2] [{:type :date :name "<NAME>" :value 14}] [] [{:type :date :name "alpha" :value 11}] [coll1] [{:type :date :name "alpha" :value 10}] [coll2] [{:type :date :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-datetime min-n) max-v (d/make-datetime max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "datetime,alpha," 9 11 [coll1] ;; beginning edge of range "datetime,alpha," 10 11 [coll1] ;; ending edge of range "datetime,alpha," 9 10 [coll1] ;; only min range provided "datetime,bravo," 10 nil [coll1 coll2] ;; only max range provided "datetime,bravo," nil 17 [coll1 coll2] "datetime,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-datetime min-n) max-v (d/make-datetime max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "datetime,alpha," 9 11 [coll1] ;; beginning edge of range "datetime,alpha," 10 11 [coll1] ;; ending edge of range "datetime,alpha," 9 10 [coll1] ;; only min range provided "datetime,bravo," 10 nil [coll1 coll2] ;; only max range provided "datetime,bravo," nil 17 [coll1 coll2] "datetime,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes date range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-datetime v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :dateRange :name "alpha" :value [9 11]}] [coll1] [{:type :dateRange :name "alpha" :value [10 11]}] [coll1] [{:type :dateRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :dateRange :name "<NAME>" :value [10 nil]}] [coll1 coll2] [{:type :dateRange :name "<NAME>" :value [nil 17]}] [coll2] [{:type :dateRange :name "<NAME>" :value [44 45]}])) (testing "search collections by datetime attribute using JSON Query Language" ;; Exact value (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "datetime" :name "bravo" :value (d/make-datetime 14)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-datetime (:min_value search)) :max_value (d/make-datetime (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "datetime" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "datetime" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "datetime" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "datetime" :name "<NAME>" :min_value 10} [coll1 coll2] {:type "datetime" :name "<NAME>" :max_value 17} [coll2] {:type "datetime" :name "<NAME>" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "datetime" :name "<NAME>" :min_value 0 :max_value 14 :exclude_boundary false} [coll1 coll2] {:type "datetime" :name "<NAME>" :min_value 0 :max_value 15 :exclude_boundary true} [] {:type "datetime" :name "<NAME>" :min_value 0 :max_value 14 :exclude_boundary true})))) (deftest time-psas-search-test (let [psa1 (dc/psa {:name "<NAME>" :data-type :time :value (d/make-time 10 false)}) psa2 (dc/psa {:name "<NAME>" :data-type :time :value (d/make-time 23 false)}) psa3 (dc/psa {:name "<NAME>" :data-type :time :value (d/make-time 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-time n))})) "time,alpha," 10 [coll1] "time,alpha," 11 [] "time,bravo," 23 [coll1 coll2] "time,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-time n))))) "time,alpha," 10 [coll1] "time,alpha," 11 [] "time,bravo," 23 [coll1 coll2] "time,charlie," 45 [coll2])) (testing "search collections by additionalAttributes time value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-time) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :time :name "alpha" :value 10}] [] [{:type :time :name "alpha" :value 11}] [coll1 coll2] [{:type :time :name "bravo" :value 23}] [coll2] [{:type :time :name "<NAME>" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-time min-n) max-v (d/make-time max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "time,alpha," 9 11 [coll1] ;; beginning edge of range "time,alpha," 10 11 [coll1] ;; ending edge of range "time,alpha," 9 10 [coll1] ;; only min range provided "time,bravo," 20 nil [coll1 coll2] ;; only max range provided "time,bravo," nil 24 [coll1 coll2] "time,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-time min-n) max-v (d/make-time max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "time,alpha," 9 11 [coll1] ;; beginning edge of range "time,alpha," 10 11 [coll1] ;; ending edge of range "time,alpha," 9 10 [coll1] ;; only min range provided "time,bravo," 20 nil [coll1 coll2] ;; only max range provided "time,bravo," nil 24 [coll1 coll2] "time,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes time range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-time v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :timeRange :name "alpha" :value [9 11]}] [coll1] [{:type :timeRange :name "alpha" :value [10 11]}] [coll1] [{:type :timeRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :timeRange :name "<NAME>" :value [20 nil]}] [coll1 coll2] [{:type :timeRange :name "<NAME>" :value [nil 24]}] [coll2] [{:type :timeRange :name "<NAME>" :value [44 45]}])) (testing "search collections by time attribute using JSON Query Language" (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "time" :name "bravo" :value (d/make-time 23)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-time (:min_value search)) :max_value (d/make-time (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "time" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "time" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "time" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "time" :name "<NAME>" :min_value 20} [coll1 coll2] {:type "time" :name "<NAME>" :max_value 24} [coll2] {:type "time" :name "<NAME>" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "time" :name "<NAME>" :min_value 0 :max_value 23 :exclude_boundary false} [coll1 coll2] {:type "time" :name "<NAME>" :min_value 0 :max_value 24 :exclude_boundary true} [] {:type "time" :name "<NAME>" :min_value 0 :max_value 23 :exclude_boundary true})))) (deftest date-psas-search-test (let [psa1 (dc/psa {:name "<NAME>" :data-type :date :value (d/make-date 10 false)}) psa2 (dc/psa {:name "<NAME>" :data-type :date :value (d/make-date 23 false)}) psa3 (dc/psa {:name "<NAME>" :data-type :date :value (d/make-date 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-date n))})) "date,bravo," 23 [coll1 coll2] "date,alpha," 11 [] "date,alpha," 10 [coll1] "date,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-date n))))) "date,bravo," 23 [coll1 coll2] "date,alpha," 11 [] "date,alpha," 10 [coll1] "date,charlie," 45 [coll2])) (testing "search collections by additionalAttributes date value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-date) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1 coll2] [{:type :date :name "bravo" :value 23}] [coll1] [{:type :date :name "alpha" :value 10}] [] [{:type :date :name "alpha" :value 11}] [coll2] [{:type :date :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-date min-n) max-v (d/make-date max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "date,alpha," 9 11 [coll1] ;; beginning edge of range "date,alpha," 10 11 [coll1] ;; ending edge of range "date,alpha," 9 10 [coll1] ;; only min range provided "date,bravo," 20 nil [coll1 coll2] ;; only max range provided "date,bravo," nil 24 [coll1 coll2] "date,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-date min-n) max-v (d/make-date max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "date,alpha," 9 11 [coll1] ;; beginning edge of range "date,alpha," 10 11 [coll1] ;; ending edge of range "date,alpha," 9 10 [coll1] ;; only min range provided "date,bravo," 20 nil [coll1 coll2] ;; only max range provided "date,bravo," nil 24 [coll1 coll2] "date,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes date range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-date v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :dateRange :name "alpha" :value [9 11]}] [coll1] [{:type :dateRange :name "alpha" :value [10 11]}] [coll1] [{:type :dateRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :dateRange :name "<NAME>" :value [20 nil]}] [coll1 coll2] [{:type :dateRange :name "<NAME>" :value [nil 24]}] [coll2] [{:type :dateRange :name "<NAME>" :value [44 45]}])) (testing "search collections by date attribute using JSON Query Language" (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "date" :name "<NAME>" :value (d/make-date 23)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-date (:min_value search)) :max_value (d/make-date (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "date" :name "<NAME>" :min_value 9 :max_value 11} [coll1] {:type "date" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "date" :name "<NAME>" :min_value 9 :max_value 10} [coll1 coll2] {:type "date" :name "<NAME>" :min_value 20} [coll1 coll2] {:type "date" :name "<NAME>" :max_value 24} [coll2] {:type "date" :name "<NAME>" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "date" :name "<NAME>" :min_value 0 :max_value 23 :exclude_boundary false} [coll1 coll2] {:type "date" :name "<NAME>" :min_value 0 :max_value 24 :exclude_boundary true} [] {:type "date" :name "<NAME>" :min_value 0 :max_value 23 :exclude_boundary true})))) (deftest range-validation-test (testing "empty parameter range" (are [attrib-value] (= {:errors [(am/one-of-min-max-msg)] :status 400} (search/get-search-failure-xml-data (search/find-refs :collection {"attribute[]" attrib-value}))) "string,alpha,," "int,alpha,," "float,alpha,," "date,alpha,," "time,alpha,," "datetime,alpha,,")) (testing "invalid parameter range values" (are [v min-n max-n] (= {:errors [(am/max-must-be-greater-than-min-msg min-n max-n)] :status 400} (search/get-search-failure-xml-data (search/find-refs :collection {"attribute[]" (format "%s,%s,%s" v (str min-n) (str max-n))}))) "string,alpha" "y" "m" "int,alpha" 10 6 "float,alpha" 10.0 6.0)) (testing "empty aql range" (are [attrib-value] (= {:errors [(am/one-of-min-max-msg)] :status 400} (search/get-search-failure-xml-data (search/find-refs-with-aql :collection [{:additionalAttributes [attrib-value]}]))) {:type :range :name "alpha" :value [nil nil]} {:type :intRange :name "alpha" :value [nil nil]} {:type :floatRange :name "alpha" :value [nil nil]} {:type :dateRange :name "alpha" :value [nil nil]} {:type :timeRange :name "alpha" :value [nil nil]})) (testing "invalid aql range values" (are [attrib-value] (= {:errors [(apply am/max-must-be-greater-than-min-msg (:value attrib-value))] :status 400} (search/get-search-failure-xml-data (search/find-refs-with-aql :collection [{:additionalAttributes [attrib-value]}]))) {:type :range :name "alpha" :value ["y" "m"]} {:type :intRange :name "alpha" :value [10 6]} {:type :floatRange :name "alpha" :value [10.0 6.0]}))) (deftest search-by-name-and-group-test (let [psa1 (dc/psa {:name "foo" :group "g1" :data-type :boolean :value true}) psa2 (dc/psa {:name "two" :group "g2" :data-type :datetime-string :value "2012-01-01T01:02:03Z"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2]}) {:format :dif})] (index/wait-until-indexed) (are [matches a-name group pattern?] (d/refs-match? matches (search/find-refs-with-json-query :collection {} {:additional_attribute_name (util/remove-nil-keys {:name a-name :group group :pattern pattern?})})) [coll1] "foo" nil false [coll1] "f?o" nil true [] "f?o" nil false [coll1] nil "g1" false [coll1 coll2] nil "g*" true [] nil "g*" false [] "t*o" "*" false [coll2] "t*o" "*" true))) (deftest json-query-validate-types-test (are [type value] (d/refs-match? [] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:name "a" :type type :value value}})) "string" "abc" "string" 1.5 "int" 12 "float" 1.23 "datetime" "2012-01-11T10:00:00.000Z" "date" "2012-01-11" "time" "10:00:00.000Z")) (deftest json-query-validation-errors-test (util/are2 [search errors] (= {:status 400 :errors errors} (search/find-refs-with-json-query :collection {} search)) "Invalid data type" {:additional_attribute_value {:type "bad" :value "c" :name "n"}} ["/condition/additional_attribute_value/type instance value (\"bad\") not found in enum (possible values: [\"string\",\"boolean\",\"time\",\"date\",\"datetime\",\"int\",\"float\"])"] "Invalid int" {:additional_attribute_value {:type "int" :name "B" :value "1"}} ["[\"1\"] is an invalid value for type [int]"] "Invalid float" {:additional_attribute_value {:type "float" :name "B" :value "1.42"}} ["[\"1.42\"] is an invalid value for type [float]"] "Invalid datetime" {:additional_attribute_value {:type "datetime" :name "B" :value "2012-01-11 10:00:00"}} ["[\"2012-01-11 10:00:00\"] is an invalid value for type [datetime]"] "Invalid date" {:additional_attribute_value {:type "date" :name "B" :value "10:00:00Z"}} ["[\"10:00:00Z\"] is an invalid value for type [date]"] "Invalid time" {:additional_attribute_value {:type "time" :name "B" :value "2012-01-11"}} ["[\"2012-01-11\"] is an invalid value for type [time]"] "Invalid use of exclude-boundary" {:additional_attribute_value {:type "string" :name "a" :value "b" :exclude_boundary true}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"exclude_boundary\"]"] "Invalid use of pattern" {:additional_attribute_value {:type "string" :group "g" :name "a*" :value "b" :pattern true}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"pattern\"]"] "Invalid range max < min" {:additional_attribute_range {:type "int" :name "foo" :min_value 25 :max_value 14}} ["The maximum value [14] must be greater than the minimum value [25]"] "Cannot include both range and an exact value - value search" {:additional_attribute_value {:type "int" :name "foo" :min_value 25 :value 37}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"min_value\"]"] "Cannot include both range and an exact value - range search" {:additional_attribute_range {:type "int" :name "foo" :min_value 25 :value 37}} ["/condition/additional_attribute_range object instance has properties which are not allowed by the schema: [\"value\"]"] "Name is required when doing an exact value search" {:additional_attribute_value {:type "int" :value 25 :group "abc"}} ["/condition/additional_attribute_value object has missing required properties ([\"name\"])"] "Name is required when doing a range search" {:additional_attribute_range {:type "int" :min_value 25 :max_value 35 :group "abc"}} ["/condition/additional_attribute_range object has missing required properties ([\"name\"])"] "Type is required when doing an exact value search" {:additional_attribute_value {:value 25 :name "a" :group "abc"}} ["/condition/additional_attribute_value object has missing required properties ([\"type\"])"] "Type is required when doing a range search" {:additional_attribute_range {:min_value 25 :max_value 35 :name "c" :group "abc"}} ["/condition/additional_attribute_range object has missing required properties ([\"type\"])"] "One of group or name is required" {:additional_attribute_name {:pattern true}} ["One of 'group' or 'name' must be provided."] "Multiple errors can be returned" {:additional_attribute_range {:type "float" :name "B" :min_value "1.42" :max_value "foo"}} ["[\"foo\"] is an invalid value for type [float]" "[\"1.42\"] is an invalid value for type [float]"])) (deftest dif-extended-metadata-test (let [dif9-coll (d/ingest-concept-with-metadata-file "data/dif/sample_collection_with_extended_metadata.xml" {:provider-id "PROV1" :concept-type :collection :format-key :dif :native-id "dif9-coll"}) dif10-coll (d/ingest-concept-with-metadata-file "data/dif10/sample_collection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :dif10 :native-id "dif10-coll"})] (index/wait-until-indexed) (testing "search for extended metadata fields" (util/are2 [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) "By group" [dif9-coll dif10-coll] {:additional_attribute_name {:group "gov.nasa.gsfc.gcmd"}} "By group - pattern" [dif9-coll dif10-coll] {:additional_attribute_name {:group "*gcmd" :pattern true}} "By name - link_notification.contact" [dif9-coll] {:additional_attribute_name {:name "link_notification.contact"}} "By name - metadata.extraction_date" [dif9-coll] {:additional_attribute_name {:name "metadata.extraction_date"}} "By name - metadata.keyword_version" [dif9-coll dif10-coll] {:additional_attribute_name {:name "metadata.keyword_version"}} "By name - pattern" [dif9-coll dif10-coll] {:additional_attribute_name {:name "meta??ta*" :pattern true}} "By value - string" [dif9-coll] {:additional_attribute_value {:name "metadata.extraction_date" :type "string" :value "2015-05-21 15:58:46"}} ;; CMR-2413 - This is failing due to 8.100000381469727 being sent to elasticsearch. ; "By value - float" ; [dif9-coll] {:additional_attribute_name {:name "metadata.keyword_version" :value 8.1 :type "float"}} "By range - float" [dif9-coll dif10-coll] {:additional_attribute_range {:name "metadata.keyword_version" :min_value 8.0 :max_value 8.5 :type "float"}}))))
true
(ns cmr.system-int-test.search.collection-psa-search-test "Tests searching for granules by product specific attributes." (:require [clojure.test :refer :all] [clj-time.core :as t] [clj-time.format :as f] [clojure.string :as s] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.granule :as dg] [cmr.system-int-test.data2.core :as d] [cmr.search.services.messages.attribute-messages :as am] [cmr.common.util :as util] [clj-http.client :as client])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) ;; These are for boolean, datetime_string, time_string, and date_string attribute types which are ;; all indexed and searchable as strings. (deftest indexed-as-string-psas-search-test (let [psa1 (dc/psa {:name "bool" :data-type :boolean :value true}) psa2 (dc/psa {:name "dts" :data-type :datetime-string :value "2012-01-01T01:02:03Z"}) psa3 (dc/psa {:name "ts" :data-type :time-string :value "01:02:03Z"}) psa4 (dc/psa {:name "ds" :data-type :date-string :value "2012-01-01"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1 psa2 psa3]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2 psa3]}) {:format :dif}) coll3 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa3 psa4]}) {:format :dif})] (index/wait-until-indexed) (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "string,bool,true" [coll1] "string,bool,false" [] "string,dts,2012-01-01T01:02:03Z" [coll1 coll2] "string,ts,01:02:03Z" [coll1 coll2 coll3] "string,ds,2012-01-01" [coll3]))) (deftest string-psas-search-test (let [psa1 (dc/psa {:name "alpha" :group "G1" :data-type :string :value "ab"}) psa2 (dc/psa {:name "PI:NAME:<NAME>END_PI" :group "G1" :data-type :string :value "bf"}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :group "G2" :data-type :string :value "foo"}) psa4 (dc/psa {:name "case" :group "G3" :data-type :string :value "up"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1 psa2]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2 psa3]}) {:format :dif}) coll3 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa4]}) {:format :dif})] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "string,alpha,ab" [coll1] "string,alpha,AB" [coll1] "string,alpha,c" [] "string,bravo,bf" [coll1 coll2] "string,case,UP" [coll3] "string,case,up" [coll3])) (testing "search by value catalog-rest style" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "string,alpha,ab" [coll1] "string,alpha,c" [] "string,alpha,c" [] "string,bravo,bf" [coll1 coll2])) (testing "search collections by additionalAttributes string value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :string :name "alpha" :value "ab"}] [coll1] [{:type :string :name "'alpha'" :value "'ab'"}] [coll1] [{:type :string :name "alpha" :value "AB"}] [] [{:type :string :name "alpha" :value "c"}] [coll1 coll2] [{:type :string :name "bravo" :value "bf"}] [coll3] [{:type :string :name "case" :value "UP"}] [coll3] [{:type :string :name "case" :value "up"}] [coll1] [{:type :string :name "alpha" :value ["ab" "cd"]}] [coll1] [{:type :string :name "alpha" :value "a%" :pattern true}] [coll1] [{:type :string :name "alpha" :value "a_" :pattern true}])) (testing "search collections by additionalAttributeNames with AQL." (are [items attrib-names options] (let [condition (merge {:additionalAttributeNames attrib-names} options)] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] "alpha" {} [coll1] "'alpha'" {} [coll1 coll2] "bravo" {} [coll2] "PI:NAME:<NAME>END_PI" {} [coll3] "case" {} [] "BLAH" {} [coll1 coll3] ["alpha" "case"] {} [coll1 coll3] ["'alpha'" "'case'"] {} [coll1 coll2 coll3] ["alpha" "charlie" "case"] {} [coll2 coll3] "c%" {:pattern true} [coll3] "cas_" {:pattern true})) (testing "searching with multiple attribute conditions" (are [v items operation] (d/refs-match? items (search/find-refs :collection (merge {"attribute[]" v} (when operation {"options[attribute][or]" (= operation :or)})))) ["string,alpha,ab" "string,bravo,,bc"] [coll1] :or ["string,alpha,ab" "string,bravo,,bc"] [] :and ["string,alpha,ab" "string,bravo,bc,"] [coll1] :and ; and is the default ["string,alpha,ab" "string,bravo,,bc"] [] nil)) (testing "searching with multiple attribute conditions catalog-rest style" ;; the query is in the format of ;; attribute[0][name]=alpha&attribute[0][type]=string&attribute[0][value]=ab&attribute[1][name]=bravo&attribute[1][type]=string&attribute[1][maxValue]=bc (are [v items operation] (let [query (->> (map-indexed search/csv->tuples v) (mapcat identity)) query (if operation (merge query ["options[attribute][or]" (= operation :or)]) query)] (d/refs-match? items (search/find-refs :collection query {:snake-kebab? false}))) ["string,alpha,ab" "string,bravo,,bc"] [coll1] :or ["string,alpha,ab" "string,bravo,,bc"] [] :and ["string,alpha,ab" "string,bravo,bc,"] [coll1] :and ; and is the default ["string,alpha,ab" "string,bravo,,bc"] [] nil)) (testing "search collections by additionalAttributes multiple string values with aql" (are [items additional-attribs options] (let [condition (merge {:additionalAttributes additional-attribs} options)] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {:or true} ;; single quotes [coll1] [{:type :string :name "'alpha'" :value "'ab'"} {:type :range :name "'bravo'" :value [nil "'bc'"]}] {:or true} [] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {:and true} [] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value [nil "bc"]}] {} [coll1] [{:type :string :name "alpha" :value "ab"} {:type :range :name "bravo" :value ["bc" nil]}] {:and true})) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "string,alpha,aa,ac" [coll1] ;; beginning edge of range "string,alpha,ab,ac" [coll1] ;; ending edge of range "string,alpha,aa,ab" [coll1] ;; only min range provided "string,bravo,bc," [coll1 coll2] ;; only max range provided "string,bravo,,bg" [coll1 coll2])) (testing "search by range catalog-rest style" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "string,alpha,aa,ac" [coll1] ;; beginning edge of range "string,alpha,ab,ac"[coll1] ;; ending edge of range "string,alpha,aa,ab" [coll1] ;; only min range provided "string,bravo,bc," [coll1 coll2] ;; only max range provided "string,bravo,,bg" [coll1 coll2])) (testing "search collections by additionalAttributes string range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :range :name "alpha" :value ["aa" "ac"]}] [coll1] [{:type :range :name "'alpha'" :value ["'aa'" "'ac'"]}] [coll1] [{:type :range :name "alpha" :value ["ab" "ac"]}] [coll1] [{:type :range :name "alpha" :value ["aa" "ab"]}] [coll1 coll2] [{:type :range :name "bravo" :value ["bc" nil]}] [coll1 coll2] [{:type :range :name "bravo" :value [nil "bg"]}])) (testing "search collections by string attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ac"}} [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "ab" :max_value "ac"}} [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab"}} [coll1 coll2] {:additional_attribute_range {:type "string" :name "bravo" :min_value "bc"}} [coll1 coll2] {:additional_attribute_range {:type "string" :name "bravo" :max_value "bg"}} ;; Exact value [coll1] {:additional_attribute_value {:type "string" :name "alpha" :value "ab"}} ;; Test exclude boundary [coll1] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab" :exclude_boundary false}} [] {:additional_attribute_range {:type "string" :name "alpha" :min_value "aa" :max_value "ab" :exclude_boundary true}} ;; Test searching by group [coll3] {:additional_attribute_name {:group "G3"}} [coll3] {:additional_attribute_name {:group "*3" :pattern true}} [coll1 coll2 coll3] {:additional_attribute_name {:group "G?" :pattern true}})))) (deftest float-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :float :value 10}) psa2 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :float :value -12}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :float :value 45}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "float,alpha,10" [coll1] "float,alpha,11" [] "float,bravo,-12" [coll1 coll2] "float,charlie,45" [coll2])) (testing "search by value legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "float,alpha,10" [coll1] "float,alpha,11" [] "float,bravo,-12" [coll1 coll2] "float,charlie,45" [coll2])) (testing "search collections by additionalAttributes float value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :float :name "alpha" :value 10}] [] [{:type :float :name "alpha" :value 11}] [coll1 coll2] [{:type :float :name "PI:NAME:<NAME>END_PI" :value -12}] [coll2] [{:type :float :name "PI:NAME:<NAME>END_PI" :value 45}])) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "float,alpha,9.2,11" [coll1] ;; beginning edge of range "float,alpha,10.0,10.6" [coll1] ;; ending edge of range "float,alpha,9.2,10.0" [coll1] ;; only min range provided "float,bravo,-120," [coll1 coll2] ;; only max range provided "float,bravo,,13.6" [coll1 coll2] "float,charlie,44,45.1" [coll2])) (testing "search by range legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "float,alpha,9.2,11" [coll1] ;; beginning edge of range "float,alpha,10.0,10.6" [coll1] ;; ending edge of range "float,alpha,9.2,10.0" [coll1] ;; only min range provided "float,bravo,-120," [coll1 coll2] ;; only max range provided "float,bravo,,13.6" [coll1 coll2] "float,charlie,44,45.1" [coll2])) (testing "search collections by additionalAttributes float range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :floatRange :name "alpha" :value [9.2 11]}] [coll1] [{:type :floatRange :name "alpha" :value [10.0 10.6]}] [coll1] [{:type :floatRange :name "alpha" :value [9.2 10.0]}] [coll1 coll2] [{:type :floatRange :name "bravo" :value [-120 nil]}] [coll1 coll2] [{:type :floatRange :name "bravo" :value [nil 13.6]}] [coll2] [{:type :floatRange :name "PI:NAME:<NAME>END_PI" :value [44 45.1]}])) (testing "search collections by float attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 9.2 :max_value 11}} [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 10.0 :max_value 10.6}} [coll1] {:additional_attribute_range {:type "float" :name "alpha" :min_value 9.2 :max_value 10.0}} [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :min_value -120}} [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :max_value 13.6}} [coll2] {:additional_attribute_range {:type "float" :name "charlie" :min_value 44 :max_value 45.1}} ;; Exact value [coll1 coll2] {:additional_attribute_value {:type "float" :name "bravo" :value -12}} ;; Test exclude boundary [coll1 coll2] {:additional_attribute_range {:type "float" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary false}} [] {:additional_attribute_range {:type "float" :name "bravo" :min_value -12 :max_value -5 :exclude_boundary true}})))) (deftest int-psas-search-test (let [psa1 (dc/psa {:name "alpha" :data-type :int :value 10}) psa2 (dc/psa {:name "bravo" :data-type :int :value -12}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :int :value 45}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) "int,alpha,10" [coll1] "int,alpha,11" [] "int,bravo,-12" [coll1 coll2])) (testing "search by value legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v))) "int,alpha,10" [coll1] "int,alpha,11" [] "int,bravo,-12" [coll1 coll2])) (testing "search collections by additionalAttributes int value with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :int :name "alpha" :value 10}] [] [{:type :int :name "alpha" :value 11}] [coll1 coll2] [{:type :int :name "bravo" :value -12}])) (testing "search by range" (are [v items] (d/refs-match? items (search/find-refs :collection {"attribute[]" v})) ;; inside range "int,alpha,9,11" [coll1] ;; beginning edge of range "int,alpha,10,11" [coll1] ;; ending edge of range "int,alpha,9,10" [coll1] ;; only min range provided "int,bravo,-120," [coll1 coll2] ;; only max range provided "int,bravo,,12" [coll1 coll2] "int,charlie,44,46" [coll2])) (testing "search by range legacy parameters" (are [v items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples v) {:snake-kebab? false})) ;; inside range "int,alpha,9,11" [coll1] ;; beginning edge of range "int,alpha,10,11" [coll1] ;; ending edge of range "int,alpha,9,10" [coll1] ;; only min range provided "int,bravo,-120," [coll1 coll2] ;; only max range provided "int,bravo,,12" [coll1 coll2] ;; range inheritance "int,charlie,44,46" [coll2])) (testing "search collections by additionalAttributes int range with aql" (are [items additional-attribs] (let [condition {:additionalAttributes additional-attribs}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :intRange :name "alpha" :value [9 11]}] [coll1] [{:type :intRange :name "alpha" :value [10 11]}] [coll1] [{:type :intRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :intRange :name "PI:NAME:<NAME>END_PI" :value [-120 nil]}] [coll1 coll2] [{:type :intRange :name "PI:NAME:<NAME>END_PI" :value [nil 12]}] [coll2] [{:type :intRange :name "PI:NAME:<NAME>END_PI" :value [44 46]}])) (testing "search collections by int attribute using JSON Query Language" (are [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) ;; Ranges [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 9 :max_value 11}} [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 10 :max_value 11}} [coll1] {:additional_attribute_range {:type "int" :name "alpha" :min_value 9 :max_value 10}} [coll1 coll2] {:additional_attribute_range {:type "int" :name "PI:NAME:<NAME>END_PI" :min_value -120}} [coll1 coll2] {:additional_attribute_range {:type "int" :name "PI:NAME:<NAME>END_PI" :max_value 12}} [coll2] {:additional_attribute_range {:type "int" :name "PI:NAME:<NAME>END_PI" :min_value 44 :max_value 46}} ;; Exact value [coll1 coll2] {:additional_attribute_value {:type "int" :name "bravo" :value -12}} ;; Test exclude boundary [coll1 coll2] {:additional_attribute_range {:type "int" :name "PI:NAME:<NAME>END_PI" :min_value -12 :max_value -5 :exclude_boundary false}} [] {:additional_attribute_range {:type "int" :name "PI:NAME:<NAME>END_PI" :min_value -12 :max_value -5 :exclude_boundary true}})))) (deftest datetime-psas-search-test (let [psa1 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :datetime :value (d/make-datetime 10 false)}) psa2 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :datetime :value (d/make-datetime 14 false)}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :datetime :value (d/make-datetime 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-datetime n))})) "datetime,bravo," 14 [coll1, coll2] "datetime,alpha," 11 [] "datetime,alpha," 10 [coll1] "datetime,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-datetime n))))) "datetime,bravo," 14 [coll1, coll2] "datetime,alpha," 11 [] "datetime,alpha," 10 [coll1] "datetime,charlie," 45 [coll2])) (testing "search collections by additionalAttributes datetime value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-datetime) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1, coll2] [{:type :date :name "PI:NAME:<NAME>END_PI" :value 14}] [] [{:type :date :name "alpha" :value 11}] [coll1] [{:type :date :name "alpha" :value 10}] [coll2] [{:type :date :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-datetime min-n) max-v (d/make-datetime max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "datetime,alpha," 9 11 [coll1] ;; beginning edge of range "datetime,alpha," 10 11 [coll1] ;; ending edge of range "datetime,alpha," 9 10 [coll1] ;; only min range provided "datetime,bravo," 10 nil [coll1 coll2] ;; only max range provided "datetime,bravo," nil 17 [coll1 coll2] "datetime,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-datetime min-n) max-v (d/make-datetime max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "datetime,alpha," 9 11 [coll1] ;; beginning edge of range "datetime,alpha," 10 11 [coll1] ;; ending edge of range "datetime,alpha," 9 10 [coll1] ;; only min range provided "datetime,bravo," 10 nil [coll1 coll2] ;; only max range provided "datetime,bravo," nil 17 [coll1 coll2] "datetime,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes date range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-datetime v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :dateRange :name "alpha" :value [9 11]}] [coll1] [{:type :dateRange :name "alpha" :value [10 11]}] [coll1] [{:type :dateRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :dateRange :name "PI:NAME:<NAME>END_PI" :value [10 nil]}] [coll1 coll2] [{:type :dateRange :name "PI:NAME:<NAME>END_PI" :value [nil 17]}] [coll2] [{:type :dateRange :name "PI:NAME:<NAME>END_PI" :value [44 45]}])) (testing "search collections by datetime attribute using JSON Query Language" ;; Exact value (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "datetime" :name "bravo" :value (d/make-datetime 14)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-datetime (:min_value search)) :max_value (d/make-datetime (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "datetime" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "datetime" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "datetime" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "datetime" :name "PI:NAME:<NAME>END_PI" :min_value 10} [coll1 coll2] {:type "datetime" :name "PI:NAME:<NAME>END_PI" :max_value 17} [coll2] {:type "datetime" :name "PI:NAME:<NAME>END_PI" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "datetime" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 14 :exclude_boundary false} [coll1 coll2] {:type "datetime" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 15 :exclude_boundary true} [] {:type "datetime" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 14 :exclude_boundary true})))) (deftest time-psas-search-test (let [psa1 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :time :value (d/make-time 10 false)}) psa2 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :time :value (d/make-time 23 false)}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :time :value (d/make-time 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-time n))})) "time,alpha," 10 [coll1] "time,alpha," 11 [] "time,bravo," 23 [coll1 coll2] "time,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-time n))))) "time,alpha," 10 [coll1] "time,alpha," 11 [] "time,bravo," 23 [coll1 coll2] "time,charlie," 45 [coll2])) (testing "search collections by additionalAttributes time value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-time) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :time :name "alpha" :value 10}] [] [{:type :time :name "alpha" :value 11}] [coll1 coll2] [{:type :time :name "bravo" :value 23}] [coll2] [{:type :time :name "PI:NAME:<NAME>END_PI" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-time min-n) max-v (d/make-time max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "time,alpha," 9 11 [coll1] ;; beginning edge of range "time,alpha," 10 11 [coll1] ;; ending edge of range "time,alpha," 9 10 [coll1] ;; only min range provided "time,bravo," 20 nil [coll1 coll2] ;; only max range provided "time,bravo," nil 24 [coll1 coll2] "time,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-time min-n) max-v (d/make-time max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "time,alpha," 9 11 [coll1] ;; beginning edge of range "time,alpha," 10 11 [coll1] ;; ending edge of range "time,alpha," 9 10 [coll1] ;; only min range provided "time,bravo," 20 nil [coll1 coll2] ;; only max range provided "time,bravo," nil 24 [coll1 coll2] "time,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes time range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-time v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :timeRange :name "alpha" :value [9 11]}] [coll1] [{:type :timeRange :name "alpha" :value [10 11]}] [coll1] [{:type :timeRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :timeRange :name "PI:NAME:<NAME>END_PI" :value [20 nil]}] [coll1 coll2] [{:type :timeRange :name "PI:NAME:<NAME>END_PI" :value [nil 24]}] [coll2] [{:type :timeRange :name "PI:NAME:<NAME>END_PI" :value [44 45]}])) (testing "search collections by time attribute using JSON Query Language" (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "time" :name "bravo" :value (d/make-time 23)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-time (:min_value search)) :max_value (d/make-time (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "time" :name "alpha" :min_value 9 :max_value 11} [coll1] {:type "time" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "time" :name "alpha" :min_value 9 :max_value 10} [coll1 coll2] {:type "time" :name "PI:NAME:<NAME>END_PI" :min_value 20} [coll1 coll2] {:type "time" :name "PI:NAME:<NAME>END_PI" :max_value 24} [coll2] {:type "time" :name "PI:NAME:<NAME>END_PI" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "time" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 23 :exclude_boundary false} [coll1 coll2] {:type "time" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 24 :exclude_boundary true} [] {:type "time" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 23 :exclude_boundary true})))) (deftest date-psas-search-test (let [psa1 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :date :value (d/make-date 10 false)}) psa2 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :date :value (d/make-date 23 false)}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :date :value (d/make-date 45 false)}) coll1 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa1 psa2]})) coll2 (d/ingest "PROV1" (dc/collection {:product-specific-attributes [psa2 psa3]}))] (index/wait-until-indexed) (testing "search by value" (are [v n items] (d/refs-match? items (search/find-refs :collection {"attribute[]" (str v (d/make-date n))})) "date,bravo," 23 [coll1 coll2] "date,alpha," 11 [] "date,alpha," 10 [coll1] "date,charlie," 45 [coll2])) (testing "search by value legacy parameters" (are [v n items] (d/refs-match? items (search/find-refs :collection (search/csv->tuples (str v (d/make-date n))))) "date,bravo," 23 [coll1 coll2] "date,alpha," 11 [] "date,alpha," 10 [coll1] "date,charlie," 45 [coll2])) (testing "search collections by additionalAttributes date value with aql" (are [items additional-attribs] (let [value (map #(update-in % [:value] d/make-date) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1 coll2] [{:type :date :name "bravo" :value 23}] [coll1] [{:type :date :name "alpha" :value 10}] [] [{:type :date :name "alpha" :value 11}] [coll2] [{:type :date :name "charlie" :value 45}])) (testing "search by range" (are [v min-n max-n items] (let [min-v (d/make-date min-n) max-v (d/make-date max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection {"attribute[]" full-value}))) ;; inside range "date,alpha," 9 11 [coll1] ;; beginning edge of range "date,alpha," 10 11 [coll1] ;; ending edge of range "date,alpha," 9 10 [coll1] ;; only min range provided "date,bravo," 20 nil [coll1 coll2] ;; only max range provided "date,bravo," nil 24 [coll1 coll2] "date,charlie," 44 45 [coll2])) (testing "search by range legacy parameters" (are [v min-n max-n items] (let [min-v (d/make-date min-n) max-v (d/make-date max-n) full-value (str v min-v "," max-v)] (d/refs-match? items (search/find-refs :collection (search/csv->tuples full-value) {:snake-kebab? false}))) ;; inside range "date,alpha," 9 11 [coll1] ;; beginning edge of range "date,alpha," 10 11 [coll1] ;; ending edge of range "date,alpha," 9 10 [coll1] ;; only min range provided "date,bravo," 20 nil [coll1 coll2] ;; only max range provided "date,bravo," nil 24 [coll1 coll2] "date,charlie," 44 45 [coll2])) (testing "search collections by additionalAttributes date range with aql" (are [items additional-attribs] (let [value-fn (fn [v] (map d/make-date v)) value (map #(update-in % [:value] value-fn) additional-attribs) condition {:additionalAttributes value}] (d/refs-match? items (search/find-refs-with-aql :collection [condition]))) [coll1] [{:type :dateRange :name "alpha" :value [9 11]}] [coll1] [{:type :dateRange :name "alpha" :value [10 11]}] [coll1] [{:type :dateRange :name "alpha" :value [9 10]}] [coll1 coll2] [{:type :dateRange :name "PI:NAME:<NAME>END_PI" :value [20 nil]}] [coll1 coll2] [{:type :dateRange :name "PI:NAME:<NAME>END_PI" :value [nil 24]}] [coll2] [{:type :dateRange :name "PI:NAME:<NAME>END_PI" :value [44 45]}])) (testing "search collections by date attribute using JSON Query Language" (d/refs-match? [coll1 coll2] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:type "date" :name "PI:NAME:<NAME>END_PI" :value (d/make-date 23)}})) (are [items search] (let [date-search (util/remove-nil-keys (assoc search :min_value (d/make-date (:min_value search)) :max_value (d/make-date (:max_value search)))) condition {:additional_attribute_range date-search}] (d/refs-match? items (search/find-refs-with-json-query :collection {} condition))) ;; Ranges [coll1] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 9 :max_value 11} [coll1] {:type "date" :name "alpha" :min_value 10 :max_value 11} [coll1] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 9 :max_value 10} [coll1 coll2] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 20} [coll1 coll2] {:type "date" :name "PI:NAME:<NAME>END_PI" :max_value 24} [coll2] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 44 :max_value 45} ;; Test exclude boundary [coll1 coll2] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 23 :exclude_boundary false} [coll1 coll2] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 24 :exclude_boundary true} [] {:type "date" :name "PI:NAME:<NAME>END_PI" :min_value 0 :max_value 23 :exclude_boundary true})))) (deftest range-validation-test (testing "empty parameter range" (are [attrib-value] (= {:errors [(am/one-of-min-max-msg)] :status 400} (search/get-search-failure-xml-data (search/find-refs :collection {"attribute[]" attrib-value}))) "string,alpha,," "int,alpha,," "float,alpha,," "date,alpha,," "time,alpha,," "datetime,alpha,,")) (testing "invalid parameter range values" (are [v min-n max-n] (= {:errors [(am/max-must-be-greater-than-min-msg min-n max-n)] :status 400} (search/get-search-failure-xml-data (search/find-refs :collection {"attribute[]" (format "%s,%s,%s" v (str min-n) (str max-n))}))) "string,alpha" "y" "m" "int,alpha" 10 6 "float,alpha" 10.0 6.0)) (testing "empty aql range" (are [attrib-value] (= {:errors [(am/one-of-min-max-msg)] :status 400} (search/get-search-failure-xml-data (search/find-refs-with-aql :collection [{:additionalAttributes [attrib-value]}]))) {:type :range :name "alpha" :value [nil nil]} {:type :intRange :name "alpha" :value [nil nil]} {:type :floatRange :name "alpha" :value [nil nil]} {:type :dateRange :name "alpha" :value [nil nil]} {:type :timeRange :name "alpha" :value [nil nil]})) (testing "invalid aql range values" (are [attrib-value] (= {:errors [(apply am/max-must-be-greater-than-min-msg (:value attrib-value))] :status 400} (search/get-search-failure-xml-data (search/find-refs-with-aql :collection [{:additionalAttributes [attrib-value]}]))) {:type :range :name "alpha" :value ["y" "m"]} {:type :intRange :name "alpha" :value [10 6]} {:type :floatRange :name "alpha" :value [10.0 6.0]}))) (deftest search-by-name-and-group-test (let [psa1 (dc/psa {:name "foo" :group "g1" :data-type :boolean :value true}) psa2 (dc/psa {:name "two" :group "g2" :data-type :datetime-string :value "2012-01-01T01:02:03Z"}) coll1 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa1]}) {:format :dif}) coll2 (d/ingest "PROV1" (dc/collection-dif {:product-specific-attributes [psa2]}) {:format :dif})] (index/wait-until-indexed) (are [matches a-name group pattern?] (d/refs-match? matches (search/find-refs-with-json-query :collection {} {:additional_attribute_name (util/remove-nil-keys {:name a-name :group group :pattern pattern?})})) [coll1] "foo" nil false [coll1] "f?o" nil true [] "f?o" nil false [coll1] nil "g1" false [coll1 coll2] nil "g*" true [] nil "g*" false [] "t*o" "*" false [coll2] "t*o" "*" true))) (deftest json-query-validate-types-test (are [type value] (d/refs-match? [] (search/find-refs-with-json-query :collection {} {:additional_attribute_value {:name "a" :type type :value value}})) "string" "abc" "string" 1.5 "int" 12 "float" 1.23 "datetime" "2012-01-11T10:00:00.000Z" "date" "2012-01-11" "time" "10:00:00.000Z")) (deftest json-query-validation-errors-test (util/are2 [search errors] (= {:status 400 :errors errors} (search/find-refs-with-json-query :collection {} search)) "Invalid data type" {:additional_attribute_value {:type "bad" :value "c" :name "n"}} ["/condition/additional_attribute_value/type instance value (\"bad\") not found in enum (possible values: [\"string\",\"boolean\",\"time\",\"date\",\"datetime\",\"int\",\"float\"])"] "Invalid int" {:additional_attribute_value {:type "int" :name "B" :value "1"}} ["[\"1\"] is an invalid value for type [int]"] "Invalid float" {:additional_attribute_value {:type "float" :name "B" :value "1.42"}} ["[\"1.42\"] is an invalid value for type [float]"] "Invalid datetime" {:additional_attribute_value {:type "datetime" :name "B" :value "2012-01-11 10:00:00"}} ["[\"2012-01-11 10:00:00\"] is an invalid value for type [datetime]"] "Invalid date" {:additional_attribute_value {:type "date" :name "B" :value "10:00:00Z"}} ["[\"10:00:00Z\"] is an invalid value for type [date]"] "Invalid time" {:additional_attribute_value {:type "time" :name "B" :value "2012-01-11"}} ["[\"2012-01-11\"] is an invalid value for type [time]"] "Invalid use of exclude-boundary" {:additional_attribute_value {:type "string" :name "a" :value "b" :exclude_boundary true}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"exclude_boundary\"]"] "Invalid use of pattern" {:additional_attribute_value {:type "string" :group "g" :name "a*" :value "b" :pattern true}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"pattern\"]"] "Invalid range max < min" {:additional_attribute_range {:type "int" :name "foo" :min_value 25 :max_value 14}} ["The maximum value [14] must be greater than the minimum value [25]"] "Cannot include both range and an exact value - value search" {:additional_attribute_value {:type "int" :name "foo" :min_value 25 :value 37}} ["/condition/additional_attribute_value object instance has properties which are not allowed by the schema: [\"min_value\"]"] "Cannot include both range and an exact value - range search" {:additional_attribute_range {:type "int" :name "foo" :min_value 25 :value 37}} ["/condition/additional_attribute_range object instance has properties which are not allowed by the schema: [\"value\"]"] "Name is required when doing an exact value search" {:additional_attribute_value {:type "int" :value 25 :group "abc"}} ["/condition/additional_attribute_value object has missing required properties ([\"name\"])"] "Name is required when doing a range search" {:additional_attribute_range {:type "int" :min_value 25 :max_value 35 :group "abc"}} ["/condition/additional_attribute_range object has missing required properties ([\"name\"])"] "Type is required when doing an exact value search" {:additional_attribute_value {:value 25 :name "a" :group "abc"}} ["/condition/additional_attribute_value object has missing required properties ([\"type\"])"] "Type is required when doing a range search" {:additional_attribute_range {:min_value 25 :max_value 35 :name "c" :group "abc"}} ["/condition/additional_attribute_range object has missing required properties ([\"type\"])"] "One of group or name is required" {:additional_attribute_name {:pattern true}} ["One of 'group' or 'name' must be provided."] "Multiple errors can be returned" {:additional_attribute_range {:type "float" :name "B" :min_value "1.42" :max_value "foo"}} ["[\"foo\"] is an invalid value for type [float]" "[\"1.42\"] is an invalid value for type [float]"])) (deftest dif-extended-metadata-test (let [dif9-coll (d/ingest-concept-with-metadata-file "data/dif/sample_collection_with_extended_metadata.xml" {:provider-id "PROV1" :concept-type :collection :format-key :dif :native-id "dif9-coll"}) dif10-coll (d/ingest-concept-with-metadata-file "data/dif10/sample_collection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :dif10 :native-id "dif10-coll"})] (index/wait-until-indexed) (testing "search for extended metadata fields" (util/are2 [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) "By group" [dif9-coll dif10-coll] {:additional_attribute_name {:group "gov.nasa.gsfc.gcmd"}} "By group - pattern" [dif9-coll dif10-coll] {:additional_attribute_name {:group "*gcmd" :pattern true}} "By name - link_notification.contact" [dif9-coll] {:additional_attribute_name {:name "link_notification.contact"}} "By name - metadata.extraction_date" [dif9-coll] {:additional_attribute_name {:name "metadata.extraction_date"}} "By name - metadata.keyword_version" [dif9-coll dif10-coll] {:additional_attribute_name {:name "metadata.keyword_version"}} "By name - pattern" [dif9-coll dif10-coll] {:additional_attribute_name {:name "meta??ta*" :pattern true}} "By value - string" [dif9-coll] {:additional_attribute_value {:name "metadata.extraction_date" :type "string" :value "2015-05-21 15:58:46"}} ;; CMR-2413 - This is failing due to 8.100000381469727 being sent to elasticsearch. ; "By value - float" ; [dif9-coll] {:additional_attribute_name {:name "metadata.keyword_version" :value 8.1 :type "float"}} "By range - float" [dif9-coll dif10-coll] {:additional_attribute_range {:name "metadata.keyword_version" :min_value 8.0 :max_value 8.5 :type "float"}}))))
[ { "context": "ge (.getProxy @(._peer stage)))\n (should= \"Bill\" (.getName @(._peer stage)))\n (should= :th", "end": 725, "score": 0.7218877673149109, "start": 721, "tag": "NAME", "value": "Bill" }, { "context": "(new-stage :theater \"George\" (hash-map :title \"Dr. Mario\"))]\n (should= \"George\" (.getName @(._peer ", "end": 939, "score": 0.9057388305664062, "start": 934, "tag": "NAME", "value": "Mario" }, { "context": "(hash-map :title \"Dr. Mario\"))]\n (should= \"George\" (.getName @(._peer stage)))\n (should=", "end": 964, "score": 0.6283563375473022, "start": 962, "tag": "NAME", "value": "Ge" }, { "context": " (.getName @(._peer stage)))\n (should= \"Dr. Mario\" (.getTitle @(._peer stage)))))\n )\n )\n", "end": 1025, "score": 0.935765266418457, "start": 1020, "tag": "NAME", "value": "Mario" } ]
clojure/spec/limelight/clojure/stage_spec.clj
slagyr/limelight
10
;- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. ;- Limelight and all included source files are distributed under terms of the MIT License. (ns limelight.clojure.stage-spec (:use [speclj.core] [limelight.clojure.spec-helper] [limelight.clojure.stage] [limelight.clojure.core :only (theater)])) (describe "Stage" (it "has limelight lineage" (should (isa? limelight.clojure.stage.Stage limelight.model.api.StageProxy))) (unless-headless (it "can be created with all the right values" (let [stage (new-stage :theater "Bill" {})] (should= limelight.ui.model.FramedStage (type @(._peer stage))) (should= stage (.getProxy @(._peer stage))) (should= "Bill" (.getName @(._peer stage))) (should= :theater (._theater stage)))) (it "uses the options map passed in constructor function" (let [stage (new-stage :theater "George" (hash-map :title "Dr. Mario"))] (should= "George" (.getName @(._peer stage))) (should= "Dr. Mario" (.getTitle @(._peer stage))))) ) )
114885
;- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. ;- Limelight and all included source files are distributed under terms of the MIT License. (ns limelight.clojure.stage-spec (:use [speclj.core] [limelight.clojure.spec-helper] [limelight.clojure.stage] [limelight.clojure.core :only (theater)])) (describe "Stage" (it "has limelight lineage" (should (isa? limelight.clojure.stage.Stage limelight.model.api.StageProxy))) (unless-headless (it "can be created with all the right values" (let [stage (new-stage :theater "Bill" {})] (should= limelight.ui.model.FramedStage (type @(._peer stage))) (should= stage (.getProxy @(._peer stage))) (should= "<NAME>" (.getName @(._peer stage))) (should= :theater (._theater stage)))) (it "uses the options map passed in constructor function" (let [stage (new-stage :theater "George" (hash-map :title "Dr. <NAME>"))] (should= "<NAME>orge" (.getName @(._peer stage))) (should= "Dr. <NAME>" (.getTitle @(._peer stage))))) ) )
true
;- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. ;- Limelight and all included source files are distributed under terms of the MIT License. (ns limelight.clojure.stage-spec (:use [speclj.core] [limelight.clojure.spec-helper] [limelight.clojure.stage] [limelight.clojure.core :only (theater)])) (describe "Stage" (it "has limelight lineage" (should (isa? limelight.clojure.stage.Stage limelight.model.api.StageProxy))) (unless-headless (it "can be created with all the right values" (let [stage (new-stage :theater "Bill" {})] (should= limelight.ui.model.FramedStage (type @(._peer stage))) (should= stage (.getProxy @(._peer stage))) (should= "PI:NAME:<NAME>END_PI" (.getName @(._peer stage))) (should= :theater (._theater stage)))) (it "uses the options map passed in constructor function" (let [stage (new-stage :theater "George" (hash-map :title "Dr. PI:NAME:<NAME>END_PI"))] (should= "PI:NAME:<NAME>END_PIorge" (.getName @(._peer stage))) (should= "Dr. PI:NAME:<NAME>END_PI" (.getTitle @(._peer stage))))) ) )
[ { "context": ";\n;\n; Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>\n;\n; ============================================", "end": 71, "score": 0.9999290704727173, "start": 48, "tag": "EMAIL", "value": "info@cloudconscious.com" }, { "context": "d runs tests in context. From users mailing\nlist, Alan Dipert and MeikelBrandmeyer.\"\n `(let ~(reduce #(conj %1", "end": 1087, "score": 0.9998906850814819, "start": 1076, "tag": "NAME", "value": "Alan Dipert" }, { "context": "context. From users mailing\nlist, Alan Dipert and MeikelBrandmeyer.\"\n `(let ~(reduce #(conj %1 %2 `@(ns-resolve '~n", "end": 1108, "score": 0.9998904466629028, "start": 1092, "tag": "NAME", "value": "MeikelBrandmeyer" } ]
compute/src/test/clojure/org/jclouds/compute_test.clj
bosschaert/jclouds
1
; ; ; Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com> ; ; ==================================================================== ; 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 org.jclouds.compute-test (:use [org.jclouds.compute] :reload-all) (:use clojure.test) (:import org.jclouds.compute.domain.OsFamily clojure.contrib.condition.Condition)) (defmacro with-private-vars [[ns fns] & tests] "Refers private fns from ns and runs tests in context. From users mailing list, Alan Dipert and MeikelBrandmeyer." `(let ~(reduce #(conj %1 %2 `@(ns-resolve '~ns '~%2)) [] fns) ~@tests)) (deftest os-families-test (is (some #{"centos"} (map str (os-families))))) (defn clean-stub-fixture "This should allow basic tests to easily be run with another service." [service account key & options] (fn [f] (with-compute-service [(apply compute-service service account key options)] (doseq [node (nodes)] (destroy-node (.getId node))) (f)))) (use-fixtures :each (clean-stub-fixture "stub" "" "")) (deftest compute-service?-test (is (compute-service? *compute*))) (deftest as-compute-service-test (is (compute-service? (compute-service "stub" "user" "password"))) (is (compute-service? (as-compute-service *compute*))) (is (compute-service? (as-compute-service (compute-context *compute*))))) (deftest build-template-test (let [service (compute-service "stub" "user" "password")] (testing "nullary" (is (>= (-> (build-template service {:fastest true}) bean :hardware bean :processors first bean :cores) 8.0))) (testing "one arg" (is (> (-> (build-template service {:min-ram 512}) bean :hardware bean :ram) 512))) (testing "enumerated" (is (= OsFamily/CENTOS (-> (build-template service {:os-family :centos}) bean :image bean :operatingSystem bean :family)))) (testing "varags" (is (java.util.Arrays/equals (int-array [22 8080]) (-> (build-template service {:inbound-ports [22 8080]}) bean :options bean :inboundPorts)))) (testing "invalid" (is (thrown? Condition (build-template service {:xx :yy}))))))
102546
; ; ; Copyright (C) 2010 Cloud Conscious, LLC. <<EMAIL>> ; ; ==================================================================== ; 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 org.jclouds.compute-test (:use [org.jclouds.compute] :reload-all) (:use clojure.test) (:import org.jclouds.compute.domain.OsFamily clojure.contrib.condition.Condition)) (defmacro with-private-vars [[ns fns] & tests] "Refers private fns from ns and runs tests in context. From users mailing list, <NAME> and <NAME>." `(let ~(reduce #(conj %1 %2 `@(ns-resolve '~ns '~%2)) [] fns) ~@tests)) (deftest os-families-test (is (some #{"centos"} (map str (os-families))))) (defn clean-stub-fixture "This should allow basic tests to easily be run with another service." [service account key & options] (fn [f] (with-compute-service [(apply compute-service service account key options)] (doseq [node (nodes)] (destroy-node (.getId node))) (f)))) (use-fixtures :each (clean-stub-fixture "stub" "" "")) (deftest compute-service?-test (is (compute-service? *compute*))) (deftest as-compute-service-test (is (compute-service? (compute-service "stub" "user" "password"))) (is (compute-service? (as-compute-service *compute*))) (is (compute-service? (as-compute-service (compute-context *compute*))))) (deftest build-template-test (let [service (compute-service "stub" "user" "password")] (testing "nullary" (is (>= (-> (build-template service {:fastest true}) bean :hardware bean :processors first bean :cores) 8.0))) (testing "one arg" (is (> (-> (build-template service {:min-ram 512}) bean :hardware bean :ram) 512))) (testing "enumerated" (is (= OsFamily/CENTOS (-> (build-template service {:os-family :centos}) bean :image bean :operatingSystem bean :family)))) (testing "varags" (is (java.util.Arrays/equals (int-array [22 8080]) (-> (build-template service {:inbound-ports [22 8080]}) bean :options bean :inboundPorts)))) (testing "invalid" (is (thrown? Condition (build-template service {:xx :yy}))))))
true
; ; ; Copyright (C) 2010 Cloud Conscious, LLC. <PI:EMAIL:<EMAIL>END_PI> ; ; ==================================================================== ; 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 org.jclouds.compute-test (:use [org.jclouds.compute] :reload-all) (:use clojure.test) (:import org.jclouds.compute.domain.OsFamily clojure.contrib.condition.Condition)) (defmacro with-private-vars [[ns fns] & tests] "Refers private fns from ns and runs tests in context. From users mailing list, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI." `(let ~(reduce #(conj %1 %2 `@(ns-resolve '~ns '~%2)) [] fns) ~@tests)) (deftest os-families-test (is (some #{"centos"} (map str (os-families))))) (defn clean-stub-fixture "This should allow basic tests to easily be run with another service." [service account key & options] (fn [f] (with-compute-service [(apply compute-service service account key options)] (doseq [node (nodes)] (destroy-node (.getId node))) (f)))) (use-fixtures :each (clean-stub-fixture "stub" "" "")) (deftest compute-service?-test (is (compute-service? *compute*))) (deftest as-compute-service-test (is (compute-service? (compute-service "stub" "user" "password"))) (is (compute-service? (as-compute-service *compute*))) (is (compute-service? (as-compute-service (compute-context *compute*))))) (deftest build-template-test (let [service (compute-service "stub" "user" "password")] (testing "nullary" (is (>= (-> (build-template service {:fastest true}) bean :hardware bean :processors first bean :cores) 8.0))) (testing "one arg" (is (> (-> (build-template service {:min-ram 512}) bean :hardware bean :ram) 512))) (testing "enumerated" (is (= OsFamily/CENTOS (-> (build-template service {:os-family :centos}) bean :image bean :operatingSystem bean :family)))) (testing "varags" (is (java.util.Arrays/equals (int-array [22 8080]) (-> (build-template service {:inbound-ports [22 8080]}) bean :options bean :inboundPorts)))) (testing "invalid" (is (thrown? Condition (build-template service {:xx :yy}))))))
[ { "context": "provider \"user-password\"\n :data { :user \"tmpuser\" :password \"tmppassword\" :date_of_birth \"2011-01-", "end": 996, "score": 0.9981077313423157, "start": 989, "tag": "USERNAME", "value": "tmpuser" }, { "context": "ord\"\n :data { :user \"tmpuser\" :password \"tmppassword\" :date_of_birth \"2011-01-01\"}\n }\n\n ", "end": 1020, "score": 0.9994671940803528, "start": 1009, "tag": "PASSWORD", "value": "tmppassword" } ]
workspace/real-clojure/src/real_clojure/protocol_demo/register.clj
muthuishere/clojure-workshop-template
0
(ns real-clojure.protocol-demo.register) (defmulti register (fn [{:keys [provider]}] (keyword provider) )) (defmethod register :google [_] (do (println "Setting up Google API") (println "Redirect to Google Register Page") (println "Register in Google") (println "Complete Registration via Google") ) ) (defmethod register :github [_] (do (println "Setting up Github API") (println "Redirect to Github Register Page") (println "Register in Github") (println "Complete Registration via Github") ) ) (defmethod register :user-password [{:keys [data]}] (do (println "Get Registration info from user") (println "Registering with" data ) (println "Complete Registration via User password" ) ) ) (comment ;Implement Multi method for (register {:provider "google" }) (register {:provider "github" }) (register { :provider "user-password" :data { :user "tmpuser" :password "tmppassword" :date_of_birth "2011-01-01"} } ) )
47599
(ns real-clojure.protocol-demo.register) (defmulti register (fn [{:keys [provider]}] (keyword provider) )) (defmethod register :google [_] (do (println "Setting up Google API") (println "Redirect to Google Register Page") (println "Register in Google") (println "Complete Registration via Google") ) ) (defmethod register :github [_] (do (println "Setting up Github API") (println "Redirect to Github Register Page") (println "Register in Github") (println "Complete Registration via Github") ) ) (defmethod register :user-password [{:keys [data]}] (do (println "Get Registration info from user") (println "Registering with" data ) (println "Complete Registration via User password" ) ) ) (comment ;Implement Multi method for (register {:provider "google" }) (register {:provider "github" }) (register { :provider "user-password" :data { :user "tmpuser" :password "<PASSWORD>" :date_of_birth "2011-01-01"} } ) )
true
(ns real-clojure.protocol-demo.register) (defmulti register (fn [{:keys [provider]}] (keyword provider) )) (defmethod register :google [_] (do (println "Setting up Google API") (println "Redirect to Google Register Page") (println "Register in Google") (println "Complete Registration via Google") ) ) (defmethod register :github [_] (do (println "Setting up Github API") (println "Redirect to Github Register Page") (println "Register in Github") (println "Complete Registration via Github") ) ) (defmethod register :user-password [{:keys [data]}] (do (println "Get Registration info from user") (println "Registering with" data ) (println "Complete Registration via User password" ) ) ) (comment ;Implement Multi method for (register {:provider "google" }) (register {:provider "github" }) (register { :provider "user-password" :data { :user "tmpuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :date_of_birth "2011-01-01"} } ) )
[ { "context": "; Copyright 2009, 2010, 2011 Howard M. Lewis Ship\n;\n; Licensed under the Apache License, Version 2.", "end": 49, "score": 0.9998643398284912, "start": 29, "tag": "NAME", "value": "Howard M. Lewis Ship" } ]
test/cascade/test_utils.clj
hlship/cascade
8
; Copyright 2009, 2010, 2011 Howard M. Lewis Ship ; ; 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 cascade.test-utils (:use clojure.test clojure.tools.macro [cascade utils])) (deftest test-lcond (let [f #(lcond (nil? %) "nil" :let [x2 (* 2 %)] true x2)] (is (= (f nil) "nil")) (is (= (f 5) 10)))) (deftest empty-lcond-is-nil (is (nil? (lcond)))) ; Broken by upgrade to Clojure 1.3 ; (deftest lcond-requires-even-clauses ; (is (thrown-with-msg? RuntimeException #".* lcond requires an even number of forms" ; (mexpand-all `(lcond (= 1 2) :b :c)))))
47415
; Copyright 2009, 2010, 2011 <NAME> ; ; 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 cascade.test-utils (:use clojure.test clojure.tools.macro [cascade utils])) (deftest test-lcond (let [f #(lcond (nil? %) "nil" :let [x2 (* 2 %)] true x2)] (is (= (f nil) "nil")) (is (= (f 5) 10)))) (deftest empty-lcond-is-nil (is (nil? (lcond)))) ; Broken by upgrade to Clojure 1.3 ; (deftest lcond-requires-even-clauses ; (is (thrown-with-msg? RuntimeException #".* lcond requires an even number of forms" ; (mexpand-all `(lcond (= 1 2) :b :c)))))
true
; Copyright 2009, 2010, 2011 PI:NAME:<NAME>END_PI ; ; 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 cascade.test-utils (:use clojure.test clojure.tools.macro [cascade utils])) (deftest test-lcond (let [f #(lcond (nil? %) "nil" :let [x2 (* 2 %)] true x2)] (is (= (f nil) "nil")) (is (= (f 5) 10)))) (deftest empty-lcond-is-nil (is (nil? (lcond)))) ; Broken by upgrade to Clojure 1.3 ; (deftest lcond-requires-even-clauses ; (is (thrown-with-msg? RuntimeException #".* lcond requires an even number of forms" ; (mexpand-all `(lcond (= 1 2) :b :c)))))
[ { "context": "an})\n\n(defn- make-pan-key [key] (keyword (str \"pan-\" (name key))))\n\n(defn- make-triggers-pans\n [trigg", "end": 3500, "score": 0.5305845737457275, "start": 3500, "tag": "KEY", "value": "" } ]
src/overtime/microsounds.clj
shj333/overtime
0
(ns overtime.microsounds (:require [overtone.core :as ot] [overtime.busses :as bus] [overtime.buffers :as buf] [overtime.instruments :as instr] [overtime.probability :as prob] [overtime.shapes :as shp] [overtime.utils :as u] [clojure.tools.logging :as log])) (defonce ^:private random-density-range (atom [2 20])) (defonce ^:private triggers (atom {})) (defonce ^:private pans (atom {})) ; ; Grain envelopes ; (defn- make-env-bufs [env-signals] (into {} (for [[k signals] env-signals] [k (buf/signals->buffer signals)]))) (defonce env-data {:guass (ot/env-sine) :quasi-guass (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :sin) :linear (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :lin) :welch (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :welch) :expodec (ot/envelope [1, 0.001] [1] :exp) :rexpodec (ot/envelope [0.001, 1] [1] :exp) :perc1 (ot/env-perc 0.05 0.95) :perc2 (ot/env-perc 0.1 0.9)}) (defonce env-signals (merge (shp/make-sincs 10 400) (into {} (for [[k env] env-data] [k (shp/env->signals (shp/zero-last env) 400)])))) ; ; Triggers ; (ot/defsynth sync-trigger [out 0 density 1] (ot/out:kr out (ot/impulse:kr density))) (ot/defsynth async-trigger [out 0 density 1] (ot/out:kr out (ot/dust:kr density))) (ot/defsynth coin-trigger [out 0 density 1 prob 0.5] (ot/out:kr out (ot/coin-gate:kr prob (ot/impulse:kr density)))) ; ; Pans ; (ot/defsynth rand-pan [out 0 density 1] (ot/out:kr out (ot/lf-noise0:kr density))) (ot/defsynth const-pan [out 0 pan 0] (ot/out:kr out pan)) ; ; Sets density of given instruments to random values over time ; (defn- random-density [prev-density-time] (let [[low high] @random-density-range density (prob/exp-rand low high) wait-time (Math/round (/ 1000.0 density)) [_ prev-time] prev-density-time] [density (+ prev-time wait-time)])) (defn- random-density-loop [instrs] (let [num-densities 50 start-time (+ (ot/now) 500) densities-times (rest (take num-densities (iterate #(random-density %) [0 start-time]))) next-time (last (last densities-times))] (doseq [[density time] densities-times] (ot/at time (doseq [instr instrs] (ot/ctl instr :density density)))) (ot/apply-by next-time #'random-density-loop [instrs]))) (defn- set-random-density-range [low high] (log/info "Setting random density range to" low "->" high) (reset! random-density-range [low high])) ; ; Creates busses and instruments for triggers and pans that drive grain synths ; (defn- make-busses-instrs [synth-defs bus-category] (bus/add-busses bus-category (keys synth-defs) :control 1) (into {} (for [[key synth-def] synth-defs] [key (synth-def :out (bus/bus bus-category key))]))) (defonce core-trigger-defs {:sync sync-trigger :rand-sync sync-trigger :async async-trigger :coin coin-trigger}) (defonce core-pan-defs {:pan-left const-pan :pan-center-left const-pan :pan-center const-pan :pan-center-right const-pan :pan-right const-pan}) (defn- make-pan-key [key] (keyword (str "pan-" (name key)))) (defn- make-triggers-pans [trigger-defs] (let [all-trigger-defs (merge core-trigger-defs trigger-defs) new-triggers (make-busses-instrs all-trigger-defs :trigger) pan-defs (into {} (for [k (map make-pan-key (keys all-trigger-defs))] [k rand-pan])) all-pan-defs (merge core-pan-defs pan-defs) new-pans (make-busses-instrs all-pan-defs :pan)] (log/debug "Created triggers" (keys new-triggers)) (log/debug "Created pans" (keys new-pans)) (ot/ctl (:pan-left new-pans) :pan -1) (ot/ctl (:pan-center-left new-pans) :pan -0.5) (ot/ctl (:pan-center new-pans) :pan 0) (ot/ctl (:pan-center-right new-pans) :pan 0.5) (ot/ctl (:pan-right new-pans) :pan 1) (random-density-loop [(:rand-sync new-triggers) (:pan-rand-sync new-pans)]) (swap! triggers merge new-triggers) (swap! pans merge new-pans) (instr/add-instrs new-triggers) (instr/add-instrs new-pans) true)) ; ; Public API ; ; Accessors to triggers, pans (defn trigger [key] (u/check-nil (key @triggers) "Trigger" key)) (defn trigger-keys [] (keys @triggers)) (defn pan [key] (u/check-nil (key @pans) "Pan" key)) (defn pan-keys [] (keys @pans)) ; ; Initialize data structions (envelope buffers, triggers and pans) for this namespace ; (defn init ([] (init {})) ([{:keys [triggers density-range]}] (buf/add-buffers :env (make-env-bufs env-signals)) (make-triggers-pans triggers) (when density-range (apply set-random-density-range density-range)) (log/info "Finished microsounds init, env bufs:" (buf/buffer-keys :env) ", triggers:" (trigger-keys) ", pans:" (pan-keys)) true)) (comment (micro/init {:coin2 micro/coin-trigger}))
111741
(ns overtime.microsounds (:require [overtone.core :as ot] [overtime.busses :as bus] [overtime.buffers :as buf] [overtime.instruments :as instr] [overtime.probability :as prob] [overtime.shapes :as shp] [overtime.utils :as u] [clojure.tools.logging :as log])) (defonce ^:private random-density-range (atom [2 20])) (defonce ^:private triggers (atom {})) (defonce ^:private pans (atom {})) ; ; Grain envelopes ; (defn- make-env-bufs [env-signals] (into {} (for [[k signals] env-signals] [k (buf/signals->buffer signals)]))) (defonce env-data {:guass (ot/env-sine) :quasi-guass (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :sin) :linear (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :lin) :welch (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :welch) :expodec (ot/envelope [1, 0.001] [1] :exp) :rexpodec (ot/envelope [0.001, 1] [1] :exp) :perc1 (ot/env-perc 0.05 0.95) :perc2 (ot/env-perc 0.1 0.9)}) (defonce env-signals (merge (shp/make-sincs 10 400) (into {} (for [[k env] env-data] [k (shp/env->signals (shp/zero-last env) 400)])))) ; ; Triggers ; (ot/defsynth sync-trigger [out 0 density 1] (ot/out:kr out (ot/impulse:kr density))) (ot/defsynth async-trigger [out 0 density 1] (ot/out:kr out (ot/dust:kr density))) (ot/defsynth coin-trigger [out 0 density 1 prob 0.5] (ot/out:kr out (ot/coin-gate:kr prob (ot/impulse:kr density)))) ; ; Pans ; (ot/defsynth rand-pan [out 0 density 1] (ot/out:kr out (ot/lf-noise0:kr density))) (ot/defsynth const-pan [out 0 pan 0] (ot/out:kr out pan)) ; ; Sets density of given instruments to random values over time ; (defn- random-density [prev-density-time] (let [[low high] @random-density-range density (prob/exp-rand low high) wait-time (Math/round (/ 1000.0 density)) [_ prev-time] prev-density-time] [density (+ prev-time wait-time)])) (defn- random-density-loop [instrs] (let [num-densities 50 start-time (+ (ot/now) 500) densities-times (rest (take num-densities (iterate #(random-density %) [0 start-time]))) next-time (last (last densities-times))] (doseq [[density time] densities-times] (ot/at time (doseq [instr instrs] (ot/ctl instr :density density)))) (ot/apply-by next-time #'random-density-loop [instrs]))) (defn- set-random-density-range [low high] (log/info "Setting random density range to" low "->" high) (reset! random-density-range [low high])) ; ; Creates busses and instruments for triggers and pans that drive grain synths ; (defn- make-busses-instrs [synth-defs bus-category] (bus/add-busses bus-category (keys synth-defs) :control 1) (into {} (for [[key synth-def] synth-defs] [key (synth-def :out (bus/bus bus-category key))]))) (defonce core-trigger-defs {:sync sync-trigger :rand-sync sync-trigger :async async-trigger :coin coin-trigger}) (defonce core-pan-defs {:pan-left const-pan :pan-center-left const-pan :pan-center const-pan :pan-center-right const-pan :pan-right const-pan}) (defn- make-pan-key [key] (keyword (str "pan<KEY>-" (name key)))) (defn- make-triggers-pans [trigger-defs] (let [all-trigger-defs (merge core-trigger-defs trigger-defs) new-triggers (make-busses-instrs all-trigger-defs :trigger) pan-defs (into {} (for [k (map make-pan-key (keys all-trigger-defs))] [k rand-pan])) all-pan-defs (merge core-pan-defs pan-defs) new-pans (make-busses-instrs all-pan-defs :pan)] (log/debug "Created triggers" (keys new-triggers)) (log/debug "Created pans" (keys new-pans)) (ot/ctl (:pan-left new-pans) :pan -1) (ot/ctl (:pan-center-left new-pans) :pan -0.5) (ot/ctl (:pan-center new-pans) :pan 0) (ot/ctl (:pan-center-right new-pans) :pan 0.5) (ot/ctl (:pan-right new-pans) :pan 1) (random-density-loop [(:rand-sync new-triggers) (:pan-rand-sync new-pans)]) (swap! triggers merge new-triggers) (swap! pans merge new-pans) (instr/add-instrs new-triggers) (instr/add-instrs new-pans) true)) ; ; Public API ; ; Accessors to triggers, pans (defn trigger [key] (u/check-nil (key @triggers) "Trigger" key)) (defn trigger-keys [] (keys @triggers)) (defn pan [key] (u/check-nil (key @pans) "Pan" key)) (defn pan-keys [] (keys @pans)) ; ; Initialize data structions (envelope buffers, triggers and pans) for this namespace ; (defn init ([] (init {})) ([{:keys [triggers density-range]}] (buf/add-buffers :env (make-env-bufs env-signals)) (make-triggers-pans triggers) (when density-range (apply set-random-density-range density-range)) (log/info "Finished microsounds init, env bufs:" (buf/buffer-keys :env) ", triggers:" (trigger-keys) ", pans:" (pan-keys)) true)) (comment (micro/init {:coin2 micro/coin-trigger}))
true
(ns overtime.microsounds (:require [overtone.core :as ot] [overtime.busses :as bus] [overtime.buffers :as buf] [overtime.instruments :as instr] [overtime.probability :as prob] [overtime.shapes :as shp] [overtime.utils :as u] [clojure.tools.logging :as log])) (defonce ^:private random-density-range (atom [2 20])) (defonce ^:private triggers (atom {})) (defonce ^:private pans (atom {})) ; ; Grain envelopes ; (defn- make-env-bufs [env-signals] (into {} (for [[k signals] env-signals] [k (buf/signals->buffer signals)]))) (defonce env-data {:guass (ot/env-sine) :quasi-guass (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :sin) :linear (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :lin) :welch (ot/envelope [0, 1, 1, 0] [0.33, 0.34, 0.33] :welch) :expodec (ot/envelope [1, 0.001] [1] :exp) :rexpodec (ot/envelope [0.001, 1] [1] :exp) :perc1 (ot/env-perc 0.05 0.95) :perc2 (ot/env-perc 0.1 0.9)}) (defonce env-signals (merge (shp/make-sincs 10 400) (into {} (for [[k env] env-data] [k (shp/env->signals (shp/zero-last env) 400)])))) ; ; Triggers ; (ot/defsynth sync-trigger [out 0 density 1] (ot/out:kr out (ot/impulse:kr density))) (ot/defsynth async-trigger [out 0 density 1] (ot/out:kr out (ot/dust:kr density))) (ot/defsynth coin-trigger [out 0 density 1 prob 0.5] (ot/out:kr out (ot/coin-gate:kr prob (ot/impulse:kr density)))) ; ; Pans ; (ot/defsynth rand-pan [out 0 density 1] (ot/out:kr out (ot/lf-noise0:kr density))) (ot/defsynth const-pan [out 0 pan 0] (ot/out:kr out pan)) ; ; Sets density of given instruments to random values over time ; (defn- random-density [prev-density-time] (let [[low high] @random-density-range density (prob/exp-rand low high) wait-time (Math/round (/ 1000.0 density)) [_ prev-time] prev-density-time] [density (+ prev-time wait-time)])) (defn- random-density-loop [instrs] (let [num-densities 50 start-time (+ (ot/now) 500) densities-times (rest (take num-densities (iterate #(random-density %) [0 start-time]))) next-time (last (last densities-times))] (doseq [[density time] densities-times] (ot/at time (doseq [instr instrs] (ot/ctl instr :density density)))) (ot/apply-by next-time #'random-density-loop [instrs]))) (defn- set-random-density-range [low high] (log/info "Setting random density range to" low "->" high) (reset! random-density-range [low high])) ; ; Creates busses and instruments for triggers and pans that drive grain synths ; (defn- make-busses-instrs [synth-defs bus-category] (bus/add-busses bus-category (keys synth-defs) :control 1) (into {} (for [[key synth-def] synth-defs] [key (synth-def :out (bus/bus bus-category key))]))) (defonce core-trigger-defs {:sync sync-trigger :rand-sync sync-trigger :async async-trigger :coin coin-trigger}) (defonce core-pan-defs {:pan-left const-pan :pan-center-left const-pan :pan-center const-pan :pan-center-right const-pan :pan-right const-pan}) (defn- make-pan-key [key] (keyword (str "panPI:KEY:<KEY>END_PI-" (name key)))) (defn- make-triggers-pans [trigger-defs] (let [all-trigger-defs (merge core-trigger-defs trigger-defs) new-triggers (make-busses-instrs all-trigger-defs :trigger) pan-defs (into {} (for [k (map make-pan-key (keys all-trigger-defs))] [k rand-pan])) all-pan-defs (merge core-pan-defs pan-defs) new-pans (make-busses-instrs all-pan-defs :pan)] (log/debug "Created triggers" (keys new-triggers)) (log/debug "Created pans" (keys new-pans)) (ot/ctl (:pan-left new-pans) :pan -1) (ot/ctl (:pan-center-left new-pans) :pan -0.5) (ot/ctl (:pan-center new-pans) :pan 0) (ot/ctl (:pan-center-right new-pans) :pan 0.5) (ot/ctl (:pan-right new-pans) :pan 1) (random-density-loop [(:rand-sync new-triggers) (:pan-rand-sync new-pans)]) (swap! triggers merge new-triggers) (swap! pans merge new-pans) (instr/add-instrs new-triggers) (instr/add-instrs new-pans) true)) ; ; Public API ; ; Accessors to triggers, pans (defn trigger [key] (u/check-nil (key @triggers) "Trigger" key)) (defn trigger-keys [] (keys @triggers)) (defn pan [key] (u/check-nil (key @pans) "Pan" key)) (defn pan-keys [] (keys @pans)) ; ; Initialize data structions (envelope buffers, triggers and pans) for this namespace ; (defn init ([] (init {})) ([{:keys [triggers density-range]}] (buf/add-buffers :env (make-env-bufs env-signals)) (make-triggers-pans triggers) (when density-range (apply set-random-density-range density-range)) (log/info "Finished microsounds init, env bufs:" (buf/buffer-keys :env) ", triggers:" (trigger-keys) ", pans:" (pan-keys)) true)) (comment (micro/init {:coin2 micro/coin-trigger}))
[ { "context": " :full_name \"Charlottesville, Virginia, USA\"\n ", "end": 1458, "score": 0.57948237657547, "start": 1452, "tag": "NAME", "value": "lottes" }, { "context": " :full_name \"Charlottesville, Virginia, USA\"\n ", "end": 2674, "score": 0.9294977188110352, "start": 2659, "tag": "NAME", "value": "Charlottesville" }, { "context": " :full_name \"Charlottesville, Virginia, USA\"\n :", "end": 2684, "score": 0.8939545750617981, "start": 2677, "tag": "NAME", "value": "irginia" }, { "context": "\n :name \"Charlottesville\"\n :place", "end": 2886, "score": 0.9918164610862732, "start": 2871, "tag": "NAME", "value": "Charlottesville" } ]
test/t_fun/unit/cloudsearch_load.clj
justjohn2001/t-fun
0
(ns t-fun.unit.cloudsearch-load (:require [t-fun.cloudsearch-load :refer :all :as cs-load] [t-fun.lib.datomic :as t-d] [midje.sweet :as t :refer [=> contains anything just]] [datomic.ion :as ion])) (t/fact "datomic-config" (t-d/datomic-config :test) => map?) (t/fact "make-resource-name" (make-resource-name "test") => "app-group-infrastructure-test" (provided (ion/get-app-info) => {:app-name "app" :deployment-group "group"})) (def datomic-result {:place/id "abc123" :iata/airport-code "CHO" :place/display-name "Charlottesville, Virginia, USA" :location/hotel-count 23 :geo/latitude -78.3 :geo/longitude 38.2 :place/name "Charlottesville" :place/type "city" :place/region {:region/code "VA" :region/name "Virginia"} :place/country {:country/code "USA" :country/name "USA"}}) (t/facts (t/fact "datomic->aws" (datomic->aws datomic-result) => (contains {:type "add" :id "abc123" :fields (contains {:id "abc123" :full_name "Charlottesville, Virginia, USA" :hotel_count 23 :latlng "-78.300000,38.200000" :name "Charlottesville" :place_type "city" :airport_code "CHO" :country_code "USA" :country_name "USA" :region_code "VA" :region "Virginia"})})) (t/fact "datomic->aws minimal" (datomic->aws (dissoc datomic-result :iata/airport-code :place/region :place/country)) => (contains {:type "add" :id "abc123" :fields (contains {:id "abc123" :full_name "Charlottesville, Virginia, USA" :hotel_count 23 :latlng "-78.300000,38.200000" :name "Charlottesville" :place_type "city"})})) (t/fact "datomic->aws with no hotel count results in delete" (datomic->aws (dissoc datomic-result :location/hotel-count)) => {:type "delete" :id "abc123"} (datomic->aws (assoc datomic-result :location/hotel-count 0)) => {:type "delete" :id "abc123"})) (t/fact "datomic-transactions is lazy" (take 1 (datomic-transactions ..conn.. 0)) => (t/one-of [1]) (provided (datomic.client.api/tx-range ..conn.. anything) => [1]) (take 5 (datomic-transactions ..conn.. 0)) => (t/five-of [1]) (provided (datomic.client.api/tx-range ..conn.. anything) => [1] :times 5)) (t/fact "take-while* includes the first false element" (sequence (take-while* even?) [2 4 5 6 7]) => [2 4 5] (take-while* even? [2 4 5 6 7]) => [2 4 5]) (t/facts "expand-counties-and-regions" (t/fact "type :place not expanded" (expand-countries-and-regions ..conn.. [{:type :place :e 123 :tx 1 :t-id 1} {:type :place :e 124 :tx 1 :t-id 2}]) => [[123 1] [124 2]]) (t/fact "type :country expands" (expand-countries-and-regions ..conn.. [{:type :country :e 123 :t-id 1 :tx 1}]) => [[456 1] [457 1]] (provided (datomic.client.api/db ..conn..) => ..db.. (datomic.client.api/as-of ..db.. anything) => ..asof.. (datomic.client.api/q anything anything anything) => [[456 1] [457 1]])) (t/fact "type :region expands" (expand-countries-and-regions ..conn.. [{:type :region :e 123 :t-id 1 :tx 1}]) => [[456 1] [457 1]] (provided (datomic.client.api/db ..conn..) => ..db.. (datomic.client.api/as-of ..db.. anything) => ..asof.. (datomic.client.api/q anything anything anything) => [[456 1] [457 1]]))) (t/facts "entity-reducer" (t/fact "0 arity returns default map" ((entity-reducer ..conn.. ..sqsclient.. "url" 1)) => map?) (t/fact "2 arity accumulates pending" ((entity-reducer ..conn.. ..sqsclient.. "url" 1) {:pending {} :max-t 1} [123 6]) => {:pending {123 6} :max-t 6}) (t/fact "2 arity accumulates t-values for entities" ((entity-reducer ..conn.. ..sqsclient.. "url" 1) {:pending {123 3} :max-t 3} [123 6]) => {:pending {123 6} :max-t 6}) ; TODO - test 1 arity version. But it has many side effects. ) (defn fake-reducer ([] {:pending {} :max-t 0}) ([result] result) ([result [e t-val]] (cond-> result e (update-in [:pending e] (fnil max 0) t-val) t-val (update :max-t (fnil max 0) t-val)))) (t/facts "walk-transaction" (t/fact "runs" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true}]}]])) (t/fact "accumulates mmultiple" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10 1235 10}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true} {:e 1235 :a 2 :v "val2" :tx 9999 :added true}]}]])) (t/fact "ignores undesired attributes" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10 1235 10}} (provided (entity-reducer ..conn.. ..sqs-client.. ..url.. anything) => fake-reducer (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true} {:e 1235 :a 2 :v "val2" :tx 9999 :added true} {:e 1236 :a 3 :v "Attribute not desired" :tx 9999 :added true}]}]])) (t/fact "aggregates over multiple transactions" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 11 :pending {1234 10 1235 11}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true}]} {:t 11 :data [{:e 1235 :a 2 :v "val2" :tx 1000 :added true}]}]])) (t/against-background (get-queue-url ..sqs-client.. anything) => ..url.. (get-attribute-ids ..conn..) => [{:db/id 1 :db/ident :place/id} {:db/id 2 :db/identy :place/name}] (entity-reducer ..conn.. ..sqs-client.. ..url.. anything) => fake-reducer)) (t/facts "queue-updates" (t/fact "runs" (queue-updates {:input "{}"}) => #"Read through transaction" (provided (datomic.ion.cast/event anything) => nil)) (t/fact "input overrides defaults and get-tx-param" (queue-updates {:input "{:start-tx 100 :timeout 10}"}) => #"transaction 100" (provided (walk-transactions ..conn.. anything 100 10) => {:max-t 100 :sent 1 :deleted 0} (datomic.ion.cast/event anything) => nil)) (t/fact "exception is propagated out" (queue-updates {:input "{}"}) => (t/throws Exception) (provided (walk-transactions ..conn.. anything anything anything) t/=throws=> (Exception.) (datomic.ion.cast/alert anything) => nil)) (t/against-background (t-fun.core/stage) => :test (datomic.client.api/client anything) => ..client.. (datomic.client.api/connect ..client.. anything) => ..conn.. (get-tx-param ..conn..) => {:param/int-value 10} (walk-transactions ..conn.. anything 11 anything) => {:max-t 11 :sent 1 :deleted 0} (set-tx-param ..conn.. anything) => nil)) (t/facts "upload-docs" (t/fact "runs and logs the count" (upload-docs ..client.. [1 2 3 4]) => {:test "1"}) (t/against-background (cognitect.aws.client.api/invoke ..client.. anything) => {"test" "1"} (datomic.ion.cast/event (contains {::cs-load/count anything})) => nil)) (t/facts "load-locations-to-cloudsearch" (t/fact "processes deletes" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :delete :ids [1, 2]}\"}]}"}) => "({:status \"success\"})") (t/fact "processes updates" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :update :ids [1, 2]}\"}]}"}) => "({:status \"success\"})" (provided (datomic.client.api/db ..client..) => ..db.. (location-details ..db.. anything) => [{:place/id "1234"} {:place/id "2345"}])) (t/fact "unknown ops are thrown" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :unknown :ids [1, 2]}\"}]}"}) => (t/throws Exception) (provided (datomic.ion.cast/alert anything) => nil)) (t/against-background (t-fun.core/stage) => :test (datomic.client.api/client anything) => ..client.. (datomic.client.api/connect anything anything) => ..client.. (datomic.ion.cast/event anything) => (t/two-of nil) (upload-docs anything anything) => {:status "success"}))
103538
(ns t-fun.unit.cloudsearch-load (:require [t-fun.cloudsearch-load :refer :all :as cs-load] [t-fun.lib.datomic :as t-d] [midje.sweet :as t :refer [=> contains anything just]] [datomic.ion :as ion])) (t/fact "datomic-config" (t-d/datomic-config :test) => map?) (t/fact "make-resource-name" (make-resource-name "test") => "app-group-infrastructure-test" (provided (ion/get-app-info) => {:app-name "app" :deployment-group "group"})) (def datomic-result {:place/id "abc123" :iata/airport-code "CHO" :place/display-name "Charlottesville, Virginia, USA" :location/hotel-count 23 :geo/latitude -78.3 :geo/longitude 38.2 :place/name "Charlottesville" :place/type "city" :place/region {:region/code "VA" :region/name "Virginia"} :place/country {:country/code "USA" :country/name "USA"}}) (t/facts (t/fact "datomic->aws" (datomic->aws datomic-result) => (contains {:type "add" :id "abc123" :fields (contains {:id "abc123" :full_name "Char<NAME>ville, Virginia, USA" :hotel_count 23 :latlng "-78.300000,38.200000" :name "Charlottesville" :place_type "city" :airport_code "CHO" :country_code "USA" :country_name "USA" :region_code "VA" :region "Virginia"})})) (t/fact "datomic->aws minimal" (datomic->aws (dissoc datomic-result :iata/airport-code :place/region :place/country)) => (contains {:type "add" :id "abc123" :fields (contains {:id "abc123" :full_name "<NAME>, V<NAME>, USA" :hotel_count 23 :latlng "-78.300000,38.200000" :name "<NAME>" :place_type "city"})})) (t/fact "datomic->aws with no hotel count results in delete" (datomic->aws (dissoc datomic-result :location/hotel-count)) => {:type "delete" :id "abc123"} (datomic->aws (assoc datomic-result :location/hotel-count 0)) => {:type "delete" :id "abc123"})) (t/fact "datomic-transactions is lazy" (take 1 (datomic-transactions ..conn.. 0)) => (t/one-of [1]) (provided (datomic.client.api/tx-range ..conn.. anything) => [1]) (take 5 (datomic-transactions ..conn.. 0)) => (t/five-of [1]) (provided (datomic.client.api/tx-range ..conn.. anything) => [1] :times 5)) (t/fact "take-while* includes the first false element" (sequence (take-while* even?) [2 4 5 6 7]) => [2 4 5] (take-while* even? [2 4 5 6 7]) => [2 4 5]) (t/facts "expand-counties-and-regions" (t/fact "type :place not expanded" (expand-countries-and-regions ..conn.. [{:type :place :e 123 :tx 1 :t-id 1} {:type :place :e 124 :tx 1 :t-id 2}]) => [[123 1] [124 2]]) (t/fact "type :country expands" (expand-countries-and-regions ..conn.. [{:type :country :e 123 :t-id 1 :tx 1}]) => [[456 1] [457 1]] (provided (datomic.client.api/db ..conn..) => ..db.. (datomic.client.api/as-of ..db.. anything) => ..asof.. (datomic.client.api/q anything anything anything) => [[456 1] [457 1]])) (t/fact "type :region expands" (expand-countries-and-regions ..conn.. [{:type :region :e 123 :t-id 1 :tx 1}]) => [[456 1] [457 1]] (provided (datomic.client.api/db ..conn..) => ..db.. (datomic.client.api/as-of ..db.. anything) => ..asof.. (datomic.client.api/q anything anything anything) => [[456 1] [457 1]]))) (t/facts "entity-reducer" (t/fact "0 arity returns default map" ((entity-reducer ..conn.. ..sqsclient.. "url" 1)) => map?) (t/fact "2 arity accumulates pending" ((entity-reducer ..conn.. ..sqsclient.. "url" 1) {:pending {} :max-t 1} [123 6]) => {:pending {123 6} :max-t 6}) (t/fact "2 arity accumulates t-values for entities" ((entity-reducer ..conn.. ..sqsclient.. "url" 1) {:pending {123 3} :max-t 3} [123 6]) => {:pending {123 6} :max-t 6}) ; TODO - test 1 arity version. But it has many side effects. ) (defn fake-reducer ([] {:pending {} :max-t 0}) ([result] result) ([result [e t-val]] (cond-> result e (update-in [:pending e] (fnil max 0) t-val) t-val (update :max-t (fnil max 0) t-val)))) (t/facts "walk-transaction" (t/fact "runs" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true}]}]])) (t/fact "accumulates mmultiple" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10 1235 10}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true} {:e 1235 :a 2 :v "val2" :tx 9999 :added true}]}]])) (t/fact "ignores undesired attributes" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10 1235 10}} (provided (entity-reducer ..conn.. ..sqs-client.. ..url.. anything) => fake-reducer (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true} {:e 1235 :a 2 :v "val2" :tx 9999 :added true} {:e 1236 :a 3 :v "Attribute not desired" :tx 9999 :added true}]}]])) (t/fact "aggregates over multiple transactions" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 11 :pending {1234 10 1235 11}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true}]} {:t 11 :data [{:e 1235 :a 2 :v "val2" :tx 1000 :added true}]}]])) (t/against-background (get-queue-url ..sqs-client.. anything) => ..url.. (get-attribute-ids ..conn..) => [{:db/id 1 :db/ident :place/id} {:db/id 2 :db/identy :place/name}] (entity-reducer ..conn.. ..sqs-client.. ..url.. anything) => fake-reducer)) (t/facts "queue-updates" (t/fact "runs" (queue-updates {:input "{}"}) => #"Read through transaction" (provided (datomic.ion.cast/event anything) => nil)) (t/fact "input overrides defaults and get-tx-param" (queue-updates {:input "{:start-tx 100 :timeout 10}"}) => #"transaction 100" (provided (walk-transactions ..conn.. anything 100 10) => {:max-t 100 :sent 1 :deleted 0} (datomic.ion.cast/event anything) => nil)) (t/fact "exception is propagated out" (queue-updates {:input "{}"}) => (t/throws Exception) (provided (walk-transactions ..conn.. anything anything anything) t/=throws=> (Exception.) (datomic.ion.cast/alert anything) => nil)) (t/against-background (t-fun.core/stage) => :test (datomic.client.api/client anything) => ..client.. (datomic.client.api/connect ..client.. anything) => ..conn.. (get-tx-param ..conn..) => {:param/int-value 10} (walk-transactions ..conn.. anything 11 anything) => {:max-t 11 :sent 1 :deleted 0} (set-tx-param ..conn.. anything) => nil)) (t/facts "upload-docs" (t/fact "runs and logs the count" (upload-docs ..client.. [1 2 3 4]) => {:test "1"}) (t/against-background (cognitect.aws.client.api/invoke ..client.. anything) => {"test" "1"} (datomic.ion.cast/event (contains {::cs-load/count anything})) => nil)) (t/facts "load-locations-to-cloudsearch" (t/fact "processes deletes" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :delete :ids [1, 2]}\"}]}"}) => "({:status \"success\"})") (t/fact "processes updates" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :update :ids [1, 2]}\"}]}"}) => "({:status \"success\"})" (provided (datomic.client.api/db ..client..) => ..db.. (location-details ..db.. anything) => [{:place/id "1234"} {:place/id "2345"}])) (t/fact "unknown ops are thrown" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :unknown :ids [1, 2]}\"}]}"}) => (t/throws Exception) (provided (datomic.ion.cast/alert anything) => nil)) (t/against-background (t-fun.core/stage) => :test (datomic.client.api/client anything) => ..client.. (datomic.client.api/connect anything anything) => ..client.. (datomic.ion.cast/event anything) => (t/two-of nil) (upload-docs anything anything) => {:status "success"}))
true
(ns t-fun.unit.cloudsearch-load (:require [t-fun.cloudsearch-load :refer :all :as cs-load] [t-fun.lib.datomic :as t-d] [midje.sweet :as t :refer [=> contains anything just]] [datomic.ion :as ion])) (t/fact "datomic-config" (t-d/datomic-config :test) => map?) (t/fact "make-resource-name" (make-resource-name "test") => "app-group-infrastructure-test" (provided (ion/get-app-info) => {:app-name "app" :deployment-group "group"})) (def datomic-result {:place/id "abc123" :iata/airport-code "CHO" :place/display-name "Charlottesville, Virginia, USA" :location/hotel-count 23 :geo/latitude -78.3 :geo/longitude 38.2 :place/name "Charlottesville" :place/type "city" :place/region {:region/code "VA" :region/name "Virginia"} :place/country {:country/code "USA" :country/name "USA"}}) (t/facts (t/fact "datomic->aws" (datomic->aws datomic-result) => (contains {:type "add" :id "abc123" :fields (contains {:id "abc123" :full_name "CharPI:NAME:<NAME>END_PIville, Virginia, USA" :hotel_count 23 :latlng "-78.300000,38.200000" :name "Charlottesville" :place_type "city" :airport_code "CHO" :country_code "USA" :country_name "USA" :region_code "VA" :region "Virginia"})})) (t/fact "datomic->aws minimal" (datomic->aws (dissoc datomic-result :iata/airport-code :place/region :place/country)) => (contains {:type "add" :id "abc123" :fields (contains {:id "abc123" :full_name "PI:NAME:<NAME>END_PI, VPI:NAME:<NAME>END_PI, USA" :hotel_count 23 :latlng "-78.300000,38.200000" :name "PI:NAME:<NAME>END_PI" :place_type "city"})})) (t/fact "datomic->aws with no hotel count results in delete" (datomic->aws (dissoc datomic-result :location/hotel-count)) => {:type "delete" :id "abc123"} (datomic->aws (assoc datomic-result :location/hotel-count 0)) => {:type "delete" :id "abc123"})) (t/fact "datomic-transactions is lazy" (take 1 (datomic-transactions ..conn.. 0)) => (t/one-of [1]) (provided (datomic.client.api/tx-range ..conn.. anything) => [1]) (take 5 (datomic-transactions ..conn.. 0)) => (t/five-of [1]) (provided (datomic.client.api/tx-range ..conn.. anything) => [1] :times 5)) (t/fact "take-while* includes the first false element" (sequence (take-while* even?) [2 4 5 6 7]) => [2 4 5] (take-while* even? [2 4 5 6 7]) => [2 4 5]) (t/facts "expand-counties-and-regions" (t/fact "type :place not expanded" (expand-countries-and-regions ..conn.. [{:type :place :e 123 :tx 1 :t-id 1} {:type :place :e 124 :tx 1 :t-id 2}]) => [[123 1] [124 2]]) (t/fact "type :country expands" (expand-countries-and-regions ..conn.. [{:type :country :e 123 :t-id 1 :tx 1}]) => [[456 1] [457 1]] (provided (datomic.client.api/db ..conn..) => ..db.. (datomic.client.api/as-of ..db.. anything) => ..asof.. (datomic.client.api/q anything anything anything) => [[456 1] [457 1]])) (t/fact "type :region expands" (expand-countries-and-regions ..conn.. [{:type :region :e 123 :t-id 1 :tx 1}]) => [[456 1] [457 1]] (provided (datomic.client.api/db ..conn..) => ..db.. (datomic.client.api/as-of ..db.. anything) => ..asof.. (datomic.client.api/q anything anything anything) => [[456 1] [457 1]]))) (t/facts "entity-reducer" (t/fact "0 arity returns default map" ((entity-reducer ..conn.. ..sqsclient.. "url" 1)) => map?) (t/fact "2 arity accumulates pending" ((entity-reducer ..conn.. ..sqsclient.. "url" 1) {:pending {} :max-t 1} [123 6]) => {:pending {123 6} :max-t 6}) (t/fact "2 arity accumulates t-values for entities" ((entity-reducer ..conn.. ..sqsclient.. "url" 1) {:pending {123 3} :max-t 3} [123 6]) => {:pending {123 6} :max-t 6}) ; TODO - test 1 arity version. But it has many side effects. ) (defn fake-reducer ([] {:pending {} :max-t 0}) ([result] result) ([result [e t-val]] (cond-> result e (update-in [:pending e] (fnil max 0) t-val) t-val (update :max-t (fnil max 0) t-val)))) (t/facts "walk-transaction" (t/fact "runs" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true}]}]])) (t/fact "accumulates mmultiple" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10 1235 10}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true} {:e 1235 :a 2 :v "val2" :tx 9999 :added true}]}]])) (t/fact "ignores undesired attributes" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 10 :pending {1234 10 1235 10}} (provided (entity-reducer ..conn.. ..sqs-client.. ..url.. anything) => fake-reducer (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true} {:e 1235 :a 2 :v "val2" :tx 9999 :added true} {:e 1236 :a 3 :v "Attribute not desired" :tx 9999 :added true}]}]])) (t/fact "aggregates over multiple transactions" (walk-transactions ..conn.. ..sqs-client.. 10 0) => {:max-t 11 :pending {1234 10 1235 11}} (provided (datomic-transactions ..conn.. anything) => [[{:t 10 :data [{:e 1234 :a 1 :v "val1" :tx 9999 :added true}]} {:t 11 :data [{:e 1235 :a 2 :v "val2" :tx 1000 :added true}]}]])) (t/against-background (get-queue-url ..sqs-client.. anything) => ..url.. (get-attribute-ids ..conn..) => [{:db/id 1 :db/ident :place/id} {:db/id 2 :db/identy :place/name}] (entity-reducer ..conn.. ..sqs-client.. ..url.. anything) => fake-reducer)) (t/facts "queue-updates" (t/fact "runs" (queue-updates {:input "{}"}) => #"Read through transaction" (provided (datomic.ion.cast/event anything) => nil)) (t/fact "input overrides defaults and get-tx-param" (queue-updates {:input "{:start-tx 100 :timeout 10}"}) => #"transaction 100" (provided (walk-transactions ..conn.. anything 100 10) => {:max-t 100 :sent 1 :deleted 0} (datomic.ion.cast/event anything) => nil)) (t/fact "exception is propagated out" (queue-updates {:input "{}"}) => (t/throws Exception) (provided (walk-transactions ..conn.. anything anything anything) t/=throws=> (Exception.) (datomic.ion.cast/alert anything) => nil)) (t/against-background (t-fun.core/stage) => :test (datomic.client.api/client anything) => ..client.. (datomic.client.api/connect ..client.. anything) => ..conn.. (get-tx-param ..conn..) => {:param/int-value 10} (walk-transactions ..conn.. anything 11 anything) => {:max-t 11 :sent 1 :deleted 0} (set-tx-param ..conn.. anything) => nil)) (t/facts "upload-docs" (t/fact "runs and logs the count" (upload-docs ..client.. [1 2 3 4]) => {:test "1"}) (t/against-background (cognitect.aws.client.api/invoke ..client.. anything) => {"test" "1"} (datomic.ion.cast/event (contains {::cs-load/count anything})) => nil)) (t/facts "load-locations-to-cloudsearch" (t/fact "processes deletes" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :delete :ids [1, 2]}\"}]}"}) => "({:status \"success\"})") (t/fact "processes updates" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :update :ids [1, 2]}\"}]}"}) => "({:status \"success\"})" (provided (datomic.client.api/db ..client..) => ..db.. (location-details ..db.. anything) => [{:place/id "1234"} {:place/id "2345"}])) (t/fact "unknown ops are thrown" (load-locations-to-cloudsearch {:input "{\"Records\":[{\"body\": \"{:op :unknown :ids [1, 2]}\"}]}"}) => (t/throws Exception) (provided (datomic.ion.cast/alert anything) => nil)) (t/against-background (t-fun.core/stage) => :test (datomic.client.api/client anything) => ..client.. (datomic.client.api/connect anything anything) => ..client.. (datomic.ion.cast/event anything) => (t/two-of nil) (upload-docs anything anything) => {:status "success"}))
[ { "context": "))\n ;; => [{:name \\\"Tiger\\\"}\n ;; {:name \\\"Dolphin\\\", :intelligence 80}\n ;; {:name \\\"Zebra\\\", ", "end": 3251, "score": 0.7258128523826599, "start": 3244, "tag": "NAME", "value": "Dolphin" }, { "context": "af})])\n (engine/run!!))\n ;; => [{:name \\\"Tiger\\\"}\n ;; {:name \\\"Dolphin\\\", :intelligence 80", "end": 4103, "score": 0.9300040006637573, "start": 4098, "tag": "NAME", "value": "Tiger" }, { "context": "))\n ;; => [{:name \\\"Tiger\\\"}\n ;; {:name \\\"Dolphin\\\", :intelligence 80}\n ;; {:name \\\"Zebra\\\", ", "end": 4133, "score": 0.9858496785163879, "start": 4126, "tag": "NAME", "value": "Dolphin" }, { "context": "\\\"Dolphin\\\", :intelligence 80}\n ;; {:name \\\"Zebra\\\", :number-of-stripes 20}]\n ```\n\n By specifiy", "end": 4179, "score": 0.768876314163208, "start": 4174, "tag": "NAME", "value": "Zebra" } ]
src/claro/projection/case.cljc
xsc/claro
147
(ns claro.projection.case (:refer-clojure :exclude [case]) (:require [claro.projection.protocols :as pr] [claro.data.ops.then :refer [then]] [claro.data.error :refer [with-error?]] [claro.data.protocols :as p])) ;; Helpers (defn- throw-case-mismatch! [value class->template] (throw (IllegalArgumentException. (format (str "no match in 'case'/'case-resolvable' projection.%n" "value: %s%n" "cases: %s") (pr-str value) (pr-str (vec (keys class->template))))))) (defn- assert-resolvable! [value class->template] (when-not (p/resolvable? value) (throw (IllegalArgumentException. (format (str "'case-resolvable' projection can only be applied to resolvable.%n" "value: %s%n" "cases: %s") (pr-str value) (pr-str (vec (keys class->template)))))))) ;; ## Records (deftype CaseResolvableProjection [class->template] pr/Projection (project [_ value] (with-error? value (assert-resolvable! value class->template) (let [template (get class->template (class value) (:else class->template ::none))] (if (not= template ::none) (pr/project template value) (throw-case-mismatch! value class->template)))))) (defmethod print-method CaseResolvableProjection [^CaseResolvableProjection value ^java.io.Writer w] (.write w "#<claro/case-resolvable ") (print-method (.-class->template value) w) (.write w ">")) (deftype CaseProjection [class->template] pr/Projection (project [_ value] (with-error? value (->> (fn [value] (let [template (get class->template (class value) (:else class->template ::none))] (if (not= template ::none) (pr/project template value) (throw-case-mismatch! value class->template)))) (then value))))) (defmethod print-method CaseProjection [^CaseProjection value ^java.io.Writer w] (.write w "#<claro/case ") (print-method (.-class->template value) w) (.write w ">")) ;; ## Constructor (defn- collect-cases [pairs] (->> (for [[classes template] pairs class (if (sequential? classes) classes [classes])] [class template]) (reduce (fn [result [^Class class template]] (when (contains? result class) (throw (IllegalArgumentException. (str "duplicate in 'case' projection: " (.getName class))))) (assoc result class template)) {}))) (defn ^{:added "0.2.1"} case-resolvable "Dispatch on the class of a `Resolvable`, applying the corresponding template. ```clojure (-> (->Animals) (projection/apply [(projection/case-resolvable Dolphin {:name projection/leaf, :intelligence projection/leaf} Zebra {:name projection/leaf, :number-of-stripes projection/leaf} :else {:name projection/leaf})]) (engine/run!!)) ;; => [{:name \"Tiger\"} ;; {:name \"Dolphin\", :intelligence 80} ;; {:name \"Zebra\", :number-of-stripes 20}] ``` By specifiying a vector of classes, e.g. `[Tiger Zebra]` you can apply the same projection to multiple kinds of resolvables." [class template & more] {:pre [(even? (count more))]} (->> (partition 2 more) (cons [class template]) (collect-cases) (->CaseResolvableProjection))) (defn ^{:added "0.2.1"} case "Dispatch on the class of a value (after resolution), applying the corresponding template. ```clojure (-> (->Animals) (projection/apply [(projection/case Dolphin {:name projection/leaf, :intelligence projection/leaf} Zebra {:name projection/leaf, :number-of-stripes projection/leaf} :else {:name projection/leaf})]) (engine/run!!)) ;; => [{:name \"Tiger\"} ;; {:name \"Dolphin\", :intelligence 80} ;; {:name \"Zebra\", :number-of-stripes 20}] ``` By specifiying a vector of classes, e.g. `[Tiger Zebra]` you can apply the same projection to multiple kinds of resolvables." [class template & more] {:pre [(even? (count more))]} (->> (partition 2 more) (cons [class template]) (collect-cases) (->CaseProjection)))
97040
(ns claro.projection.case (:refer-clojure :exclude [case]) (:require [claro.projection.protocols :as pr] [claro.data.ops.then :refer [then]] [claro.data.error :refer [with-error?]] [claro.data.protocols :as p])) ;; Helpers (defn- throw-case-mismatch! [value class->template] (throw (IllegalArgumentException. (format (str "no match in 'case'/'case-resolvable' projection.%n" "value: %s%n" "cases: %s") (pr-str value) (pr-str (vec (keys class->template))))))) (defn- assert-resolvable! [value class->template] (when-not (p/resolvable? value) (throw (IllegalArgumentException. (format (str "'case-resolvable' projection can only be applied to resolvable.%n" "value: %s%n" "cases: %s") (pr-str value) (pr-str (vec (keys class->template)))))))) ;; ## Records (deftype CaseResolvableProjection [class->template] pr/Projection (project [_ value] (with-error? value (assert-resolvable! value class->template) (let [template (get class->template (class value) (:else class->template ::none))] (if (not= template ::none) (pr/project template value) (throw-case-mismatch! value class->template)))))) (defmethod print-method CaseResolvableProjection [^CaseResolvableProjection value ^java.io.Writer w] (.write w "#<claro/case-resolvable ") (print-method (.-class->template value) w) (.write w ">")) (deftype CaseProjection [class->template] pr/Projection (project [_ value] (with-error? value (->> (fn [value] (let [template (get class->template (class value) (:else class->template ::none))] (if (not= template ::none) (pr/project template value) (throw-case-mismatch! value class->template)))) (then value))))) (defmethod print-method CaseProjection [^CaseProjection value ^java.io.Writer w] (.write w "#<claro/case ") (print-method (.-class->template value) w) (.write w ">")) ;; ## Constructor (defn- collect-cases [pairs] (->> (for [[classes template] pairs class (if (sequential? classes) classes [classes])] [class template]) (reduce (fn [result [^Class class template]] (when (contains? result class) (throw (IllegalArgumentException. (str "duplicate in 'case' projection: " (.getName class))))) (assoc result class template)) {}))) (defn ^{:added "0.2.1"} case-resolvable "Dispatch on the class of a `Resolvable`, applying the corresponding template. ```clojure (-> (->Animals) (projection/apply [(projection/case-resolvable Dolphin {:name projection/leaf, :intelligence projection/leaf} Zebra {:name projection/leaf, :number-of-stripes projection/leaf} :else {:name projection/leaf})]) (engine/run!!)) ;; => [{:name \"Tiger\"} ;; {:name \"<NAME>\", :intelligence 80} ;; {:name \"Zebra\", :number-of-stripes 20}] ``` By specifiying a vector of classes, e.g. `[Tiger Zebra]` you can apply the same projection to multiple kinds of resolvables." [class template & more] {:pre [(even? (count more))]} (->> (partition 2 more) (cons [class template]) (collect-cases) (->CaseResolvableProjection))) (defn ^{:added "0.2.1"} case "Dispatch on the class of a value (after resolution), applying the corresponding template. ```clojure (-> (->Animals) (projection/apply [(projection/case Dolphin {:name projection/leaf, :intelligence projection/leaf} Zebra {:name projection/leaf, :number-of-stripes projection/leaf} :else {:name projection/leaf})]) (engine/run!!)) ;; => [{:name \"<NAME>\"} ;; {:name \"<NAME>\", :intelligence 80} ;; {:name \"<NAME>\", :number-of-stripes 20}] ``` By specifiying a vector of classes, e.g. `[Tiger Zebra]` you can apply the same projection to multiple kinds of resolvables." [class template & more] {:pre [(even? (count more))]} (->> (partition 2 more) (cons [class template]) (collect-cases) (->CaseProjection)))
true
(ns claro.projection.case (:refer-clojure :exclude [case]) (:require [claro.projection.protocols :as pr] [claro.data.ops.then :refer [then]] [claro.data.error :refer [with-error?]] [claro.data.protocols :as p])) ;; Helpers (defn- throw-case-mismatch! [value class->template] (throw (IllegalArgumentException. (format (str "no match in 'case'/'case-resolvable' projection.%n" "value: %s%n" "cases: %s") (pr-str value) (pr-str (vec (keys class->template))))))) (defn- assert-resolvable! [value class->template] (when-not (p/resolvable? value) (throw (IllegalArgumentException. (format (str "'case-resolvable' projection can only be applied to resolvable.%n" "value: %s%n" "cases: %s") (pr-str value) (pr-str (vec (keys class->template)))))))) ;; ## Records (deftype CaseResolvableProjection [class->template] pr/Projection (project [_ value] (with-error? value (assert-resolvable! value class->template) (let [template (get class->template (class value) (:else class->template ::none))] (if (not= template ::none) (pr/project template value) (throw-case-mismatch! value class->template)))))) (defmethod print-method CaseResolvableProjection [^CaseResolvableProjection value ^java.io.Writer w] (.write w "#<claro/case-resolvable ") (print-method (.-class->template value) w) (.write w ">")) (deftype CaseProjection [class->template] pr/Projection (project [_ value] (with-error? value (->> (fn [value] (let [template (get class->template (class value) (:else class->template ::none))] (if (not= template ::none) (pr/project template value) (throw-case-mismatch! value class->template)))) (then value))))) (defmethod print-method CaseProjection [^CaseProjection value ^java.io.Writer w] (.write w "#<claro/case ") (print-method (.-class->template value) w) (.write w ">")) ;; ## Constructor (defn- collect-cases [pairs] (->> (for [[classes template] pairs class (if (sequential? classes) classes [classes])] [class template]) (reduce (fn [result [^Class class template]] (when (contains? result class) (throw (IllegalArgumentException. (str "duplicate in 'case' projection: " (.getName class))))) (assoc result class template)) {}))) (defn ^{:added "0.2.1"} case-resolvable "Dispatch on the class of a `Resolvable`, applying the corresponding template. ```clojure (-> (->Animals) (projection/apply [(projection/case-resolvable Dolphin {:name projection/leaf, :intelligence projection/leaf} Zebra {:name projection/leaf, :number-of-stripes projection/leaf} :else {:name projection/leaf})]) (engine/run!!)) ;; => [{:name \"Tiger\"} ;; {:name \"PI:NAME:<NAME>END_PI\", :intelligence 80} ;; {:name \"Zebra\", :number-of-stripes 20}] ``` By specifiying a vector of classes, e.g. `[Tiger Zebra]` you can apply the same projection to multiple kinds of resolvables." [class template & more] {:pre [(even? (count more))]} (->> (partition 2 more) (cons [class template]) (collect-cases) (->CaseResolvableProjection))) (defn ^{:added "0.2.1"} case "Dispatch on the class of a value (after resolution), applying the corresponding template. ```clojure (-> (->Animals) (projection/apply [(projection/case Dolphin {:name projection/leaf, :intelligence projection/leaf} Zebra {:name projection/leaf, :number-of-stripes projection/leaf} :else {:name projection/leaf})]) (engine/run!!)) ;; => [{:name \"PI:NAME:<NAME>END_PI\"} ;; {:name \"PI:NAME:<NAME>END_PI\", :intelligence 80} ;; {:name \"PI:NAME:<NAME>END_PI\", :number-of-stripes 20}] ``` By specifiying a vector of classes, e.g. `[Tiger Zebra]` you can apply the same projection to multiple kinds of resolvables." [class template & more] {:pre [(even? (count more))]} (->> (partition 2 more) (cons [class template]) (collect-cases) (->CaseProjection)))
[ { "context": "4.0.0/css/bootstrap.min.css\" \n :integrity \"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" \n :crossorigin \"anonymous\"}]\n [:script", "end": 1106, "score": 0.9992602467536926, "start": 1035, "tag": "KEY", "value": "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" }, { "context": "om/jquery-3.2.1.slim.min.js\" \n :integrity \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n :crossorigin \"anonymous\"}]\n [:script", "end": 1314, "score": 0.9993685483932495, "start": 1243, "tag": "KEY", "value": "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" }, { "context": "js/1.12.9/umd/popper.min.js\" \n :integrity \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n :crossorigin \"anonymous\"\n :defer", "end": 1546, "score": 0.9994310140609741, "start": 1475, "tag": "KEY", "value": "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" }, { "context": "p/4.0.0/js/bootstrap.min.js\" \n :integrity \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n :crossorigin \"anonymous\"\n :defer", "end": 1792, "score": 0.9993010759353638, "start": 1721, "tag": "KEY", "value": "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" } ]
src/ccheck/web/html.clj
maxp/coincheckhack-monitor
1
(ns ccheck.web.html (:require [hiccup.page :refer [html5]] [ccheck.build :refer [build]])) ; (defn head-meta [req _] (list [:title "NEM Info"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}] ; [:meta {:name "description" :content ds}] ; [:meta {:property "og:site_name" :content "NEM Info"}] ; [:meta {:property "og:type" :content "article"}] ; [:meta {:property "og:locale" :content "ru_RU"}] ; [:meta {:property "og:image" :content og-img}] ; [:meta {:property "og:title" :content og-tit}] ; [:meta {:property "og:url" :content og-url}] ; [:meta {:property "og:description" :content ds}] [:link {:rel "shortcut icon" :href "//nem.io/favicon.ico"}])) ; (defn head-bootstrap [] (list [:link { :rel "stylesheet" :href "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" :integrity "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" :crossorigin "anonymous"}] [:script { :src "https://code.jquery.com/jquery-3.2.1.slim.min.js" :integrity "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" :crossorigin "anonymous"}] [:script { :src "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" :integrity "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" :crossorigin "anonymous" :defer true}] [:script { :src "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" :integrity "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" :crossorigin "anonymous" :defer true}])) ; (defn head [req {:keys [css js] :as params}] [:head (head-meta req params) (head-bootstrap) [:link {:rel "stylesheet" :href "/css/style.css"}]]) ; (map #(css-link (inc-pfx %)) ; (concat ["css/main.css"] css)) ; (map #(script (inc-pfx %)) ; (concat ["js/mlib.js" "js/site.js"] js))]) ; (defn render [req params & content] (html5 (head req params) "\n" [:body [:div.container content [:div [:small "" (:name build) " v" (:version build) " - " (:commit build)]]]])) ; (defn html5-resp [content] {:status 200 :headers {"Content-Type" "text/html;charset=utf-8"} :body (html5 content)}) ; ;;.
72031
(ns ccheck.web.html (:require [hiccup.page :refer [html5]] [ccheck.build :refer [build]])) ; (defn head-meta [req _] (list [:title "NEM Info"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}] ; [:meta {:name "description" :content ds}] ; [:meta {:property "og:site_name" :content "NEM Info"}] ; [:meta {:property "og:type" :content "article"}] ; [:meta {:property "og:locale" :content "ru_RU"}] ; [:meta {:property "og:image" :content og-img}] ; [:meta {:property "og:title" :content og-tit}] ; [:meta {:property "og:url" :content og-url}] ; [:meta {:property "og:description" :content ds}] [:link {:rel "shortcut icon" :href "//nem.io/favicon.ico"}])) ; (defn head-bootstrap [] (list [:link { :rel "stylesheet" :href "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" :integrity "<KEY>" :crossorigin "anonymous"}] [:script { :src "https://code.jquery.com/jquery-3.2.1.slim.min.js" :integrity "<KEY>" :crossorigin "anonymous"}] [:script { :src "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" :integrity "<KEY>" :crossorigin "anonymous" :defer true}] [:script { :src "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" :integrity "<KEY>" :crossorigin "anonymous" :defer true}])) ; (defn head [req {:keys [css js] :as params}] [:head (head-meta req params) (head-bootstrap) [:link {:rel "stylesheet" :href "/css/style.css"}]]) ; (map #(css-link (inc-pfx %)) ; (concat ["css/main.css"] css)) ; (map #(script (inc-pfx %)) ; (concat ["js/mlib.js" "js/site.js"] js))]) ; (defn render [req params & content] (html5 (head req params) "\n" [:body [:div.container content [:div [:small "" (:name build) " v" (:version build) " - " (:commit build)]]]])) ; (defn html5-resp [content] {:status 200 :headers {"Content-Type" "text/html;charset=utf-8"} :body (html5 content)}) ; ;;.
true
(ns ccheck.web.html (:require [hiccup.page :refer [html5]] [ccheck.build :refer [build]])) ; (defn head-meta [req _] (list [:title "NEM Info"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}] ; [:meta {:name "description" :content ds}] ; [:meta {:property "og:site_name" :content "NEM Info"}] ; [:meta {:property "og:type" :content "article"}] ; [:meta {:property "og:locale" :content "ru_RU"}] ; [:meta {:property "og:image" :content og-img}] ; [:meta {:property "og:title" :content og-tit}] ; [:meta {:property "og:url" :content og-url}] ; [:meta {:property "og:description" :content ds}] [:link {:rel "shortcut icon" :href "//nem.io/favicon.ico"}])) ; (defn head-bootstrap [] (list [:link { :rel "stylesheet" :href "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" :integrity "PI:KEY:<KEY>END_PI" :crossorigin "anonymous"}] [:script { :src "https://code.jquery.com/jquery-3.2.1.slim.min.js" :integrity "PI:KEY:<KEY>END_PI" :crossorigin "anonymous"}] [:script { :src "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" :integrity "PI:KEY:<KEY>END_PI" :crossorigin "anonymous" :defer true}] [:script { :src "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" :integrity "PI:KEY:<KEY>END_PI" :crossorigin "anonymous" :defer true}])) ; (defn head [req {:keys [css js] :as params}] [:head (head-meta req params) (head-bootstrap) [:link {:rel "stylesheet" :href "/css/style.css"}]]) ; (map #(css-link (inc-pfx %)) ; (concat ["css/main.css"] css)) ; (map #(script (inc-pfx %)) ; (concat ["js/mlib.js" "js/site.js"] js))]) ; (defn render [req params & content] (html5 (head req params) "\n" [:body [:div.container content [:div [:small "" (:name build) " v" (:version build) " - " (:commit build)]]]])) ; (defn html5-resp [content] {:status 200 :headers {"Content-Type" "text/html;charset=utf-8"} :body (html5 content)}) ; ;;.
[ { "context": "\"\n :username \"solita\"\n :password \"", "end": 276, "score": 0.9996309280395508, "start": 270, "tag": "USERNAME", "value": "solita" }, { "context": "\"\n :password \"Solita321\"}\n \"releases\" {:url \"http", "end": 335, "score": 0.9992559552192688, "start": 326, "tag": "PASSWORD", "value": "Solita321" }, { "context": "\"\n :username \"solita\"\n :password \"", "end": 483, "score": 0.9996418952941895, "start": 477, "tag": "USERNAME", "value": "solita" }, { "context": "\"\n :password \"Solita321\"\n :sign-relea", "end": 542, "score": 0.9992440938949585, "start": 533, "tag": "PASSWORD", "value": "Solita321" } ]
applications/lupapiste/build/package/project.clj
okauppinen/oskari
0
(defproject fi.sito/oskari "0.9.2" :description "Oskari map stuff for Lupapiste" :dependencies [[org.clojure/clojure "1.4.0"]] :deploy-repositories {"snapshots" {:url "http://mvn.solita.fi/archiva/repository/solita" :username "solita" :password "Solita321"} "releases" {:url "http://mvn.solita.fi/archiva/repository/solita" :username "solita" :password "Solita321" :sign-releases false}})
47506
(defproject fi.sito/oskari "0.9.2" :description "Oskari map stuff for Lupapiste" :dependencies [[org.clojure/clojure "1.4.0"]] :deploy-repositories {"snapshots" {:url "http://mvn.solita.fi/archiva/repository/solita" :username "solita" :password "<PASSWORD>"} "releases" {:url "http://mvn.solita.fi/archiva/repository/solita" :username "solita" :password "<PASSWORD>" :sign-releases false}})
true
(defproject fi.sito/oskari "0.9.2" :description "Oskari map stuff for Lupapiste" :dependencies [[org.clojure/clojure "1.4.0"]] :deploy-repositories {"snapshots" {:url "http://mvn.solita.fi/archiva/repository/solita" :username "solita" :password "PI:PASSWORD:<PASSWORD>END_PI"} "releases" {:url "http://mvn.solita.fi/archiva/repository/solita" :username "solita" :password "PI:PASSWORD:<PASSWORD>END_PI" :sign-releases false}})
[ { "context": " (assoc-in [:flash :email-address] \"user@email.com\")\n invite-user)]\n ", "end": 2782, "score": 0.9990833401679993, "start": 2768, "tag": "EMAIL", "value": "user@email.com" } ]
test/stonecutter/test/view/invite_user.clj
d-cent/stonecutter
39
(ns stonecutter.test.view.invite-user (:require [midje.sweet :refer :all] [net.cgrand.enlive-html :as html] [stonecutter.test.view.test-helpers :as th] [stonecutter.routes :as r] [stonecutter.view.invite-user :refer [invite-user]] [stonecutter.translation :as t] [stonecutter.config :as config] [stonecutter.view.invite-user :as invite-user])) (fact "invite user should return some html" (let [page (-> (th/create-request) invite-user)] (html/select page [:body]) =not=> empty?)) (fact "work in progress should be removed from page" (let [page (-> (th/create-request) invite-user)] page => th/work-in-progress-removed)) (fact "sign out link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out)))) (fact "profile link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile)))) (fact "user list link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list)))) (fact "apps list link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list)))) (fact "invite link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--invite__link] :href (r/path :show-invite)))) (fact "there are no missing translations" (let [translator (t/translations-fn t/translation-map) request (th/create-request translator)] (th/test-translations "invite-user" invite-user request))) (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) invite-user)] (-> page (html/select [:.clj--flash-message-text])) => empty?)) (fact "form posts to correct endpoint" (let [page (-> (th/create-request nil nil {}) invite-user/invite-user)] page => (th/has-form-action? (r/path :send-invite)) page => (th/has-form-method? "post"))) (facts "about flash messages" (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) invite-user)] (-> page (html/select [:.func--flash-message-container])) => empty?)) (fact "success flash message is displayed on page when a flash key is included in the request" (let [page (-> (th/create-request) (assoc-in [:flash :email-address] "user@email.com") invite-user)] (-> page (html/select [:.clj--flash-message-container])) =not=> empty?)))
63993
(ns stonecutter.test.view.invite-user (:require [midje.sweet :refer :all] [net.cgrand.enlive-html :as html] [stonecutter.test.view.test-helpers :as th] [stonecutter.routes :as r] [stonecutter.view.invite-user :refer [invite-user]] [stonecutter.translation :as t] [stonecutter.config :as config] [stonecutter.view.invite-user :as invite-user])) (fact "invite user should return some html" (let [page (-> (th/create-request) invite-user)] (html/select page [:body]) =not=> empty?)) (fact "work in progress should be removed from page" (let [page (-> (th/create-request) invite-user)] page => th/work-in-progress-removed)) (fact "sign out link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out)))) (fact "profile link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile)))) (fact "user list link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list)))) (fact "apps list link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list)))) (fact "invite link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--invite__link] :href (r/path :show-invite)))) (fact "there are no missing translations" (let [translator (t/translations-fn t/translation-map) request (th/create-request translator)] (th/test-translations "invite-user" invite-user request))) (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) invite-user)] (-> page (html/select [:.clj--flash-message-text])) => empty?)) (fact "form posts to correct endpoint" (let [page (-> (th/create-request nil nil {}) invite-user/invite-user)] page => (th/has-form-action? (r/path :send-invite)) page => (th/has-form-method? "post"))) (facts "about flash messages" (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) invite-user)] (-> page (html/select [:.func--flash-message-container])) => empty?)) (fact "success flash message is displayed on page when a flash key is included in the request" (let [page (-> (th/create-request) (assoc-in [:flash :email-address] "<EMAIL>") invite-user)] (-> page (html/select [:.clj--flash-message-container])) =not=> empty?)))
true
(ns stonecutter.test.view.invite-user (:require [midje.sweet :refer :all] [net.cgrand.enlive-html :as html] [stonecutter.test.view.test-helpers :as th] [stonecutter.routes :as r] [stonecutter.view.invite-user :refer [invite-user]] [stonecutter.translation :as t] [stonecutter.config :as config] [stonecutter.view.invite-user :as invite-user])) (fact "invite user should return some html" (let [page (-> (th/create-request) invite-user)] (html/select page [:body]) =not=> empty?)) (fact "work in progress should be removed from page" (let [page (-> (th/create-request) invite-user)] page => th/work-in-progress-removed)) (fact "sign out link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out)))) (fact "profile link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile)))) (fact "user list link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list)))) (fact "apps list link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list)))) (fact "invite link should go to correct endpoint" (let [page (-> (th/create-request) invite-user)] page => (th/has-attr? [:.clj--invite__link] :href (r/path :show-invite)))) (fact "there are no missing translations" (let [translator (t/translations-fn t/translation-map) request (th/create-request translator)] (th/test-translations "invite-user" invite-user request))) (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) invite-user)] (-> page (html/select [:.clj--flash-message-text])) => empty?)) (fact "form posts to correct endpoint" (let [page (-> (th/create-request nil nil {}) invite-user/invite-user)] page => (th/has-form-action? (r/path :send-invite)) page => (th/has-form-method? "post"))) (facts "about flash messages" (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) invite-user)] (-> page (html/select [:.func--flash-message-container])) => empty?)) (fact "success flash message is displayed on page when a flash key is included in the request" (let [page (-> (th/create-request) (assoc-in [:flash :email-address] "PI:EMAIL:<EMAIL>END_PI") invite-user)] (-> page (html/select [:.clj--flash-message-container])) =not=> empty?)))
[ { "context": "hering Heights\"\n :author \"Emily Bronte\"})})\n :headers {\"Content-Type\"\n ", "end": 2791, "score": 0.9998885989189148, "start": 2779, "tag": "NAME", "value": "Emily Bronte" } ]
src/cljs-node/rx/log_ingress.cljs
zk/rx-lib
0
(ns rx.log-ingress (:require [rx.kitchen-sink :as ks] [rx.http :as http] [clojure.string :as str] [cljs-http.client :as hc] [cljs.core.async :as async :refer [<! put! timeout] :refer-macros [go go-loop]])) (def HTTP (js/require "http")) (def NET (js/require "net")) (defonce !server (atom nil)) (defonce !listeners (atom #{})) (defn listen! [f] (swap! !listeners conj f)) (defn unlisten! [f] (swap! !listeners disj f)) (defn fire [le] (doseq [f @!listeners] (f le)) {:handler-count (count @!listeners)}) (defn body->log-event [body] (ks/from-transit body)) (defn restart [& [{:keys [port] :or {port 7330}}]] (when @!server (.close @!server)) (reset! !server (let [server (.createServer HTTP (fn [req resp] (let [stream req !body (atom nil)] (.on stream "readable" (fn [] (swap! !body str (.read stream)))) (.on stream "end" (fn [] (let [body @!body] (pr-str (fire (body->log-event body))) (.writeHead resp 200 (clj->js {"Content-Type" "text/plain"})) (.end resp "ok") ))))))] (.listen server port (fn [err] (if err (ks/prn "Error starting server: " err) (ks/prn "Server started")))) server))) (defonce !!run-test-logging? (atom (atom nil))) (defn stop-test-logging [] (reset! (deref !!run-test-logging?) false)) (defn <paras [] (->> (:body (<! (hc/get "https://www.gutenberg.org/files/768/768-h/768-h.htm"))) (re-seq #"<p>([^<]*)</p>") (map second) (map (fn [s] (let [el (.createElement js/document "textarea")] (set! (.-innerHTML el) s) (.-value el)))) (map #(str/replace % #"\n" " ")) vec)) (defn start-test-logging [] (let [!old-run? (deref !!run-test-logging?) !run? (atom true)] (reset! !old-run? false) (reset! !!run-test-logging? !run?) (go (let [paras (<! (<paras))] (loop [iters 0] (hc/post "http://localhost:7330" {:body (ks/to-transit {:rx.log/event-name (str "foo.bar." iters) :rx.log/body-edn (pr-str {:paras [(nth paras (rand (count paras)))] :title "Whurthering Heights" :author "Emily Bronte"})}) :headers {"Content-Type" "application/json+transit"}}) (<! (timeout 1000)) (when @!run? (recur (inc iters)))))))) (comment (stop-test-logging) (start-test-logging) (reset! !listeners #{}) (restart) (hc/post "http://localhost:7330" {:body (ks/to-transit {:foo/bar "baz"}) :headers {"Content-Type" "application/json+transit"}}) (def !r? (atom true)) )
90341
(ns rx.log-ingress (:require [rx.kitchen-sink :as ks] [rx.http :as http] [clojure.string :as str] [cljs-http.client :as hc] [cljs.core.async :as async :refer [<! put! timeout] :refer-macros [go go-loop]])) (def HTTP (js/require "http")) (def NET (js/require "net")) (defonce !server (atom nil)) (defonce !listeners (atom #{})) (defn listen! [f] (swap! !listeners conj f)) (defn unlisten! [f] (swap! !listeners disj f)) (defn fire [le] (doseq [f @!listeners] (f le)) {:handler-count (count @!listeners)}) (defn body->log-event [body] (ks/from-transit body)) (defn restart [& [{:keys [port] :or {port 7330}}]] (when @!server (.close @!server)) (reset! !server (let [server (.createServer HTTP (fn [req resp] (let [stream req !body (atom nil)] (.on stream "readable" (fn [] (swap! !body str (.read stream)))) (.on stream "end" (fn [] (let [body @!body] (pr-str (fire (body->log-event body))) (.writeHead resp 200 (clj->js {"Content-Type" "text/plain"})) (.end resp "ok") ))))))] (.listen server port (fn [err] (if err (ks/prn "Error starting server: " err) (ks/prn "Server started")))) server))) (defonce !!run-test-logging? (atom (atom nil))) (defn stop-test-logging [] (reset! (deref !!run-test-logging?) false)) (defn <paras [] (->> (:body (<! (hc/get "https://www.gutenberg.org/files/768/768-h/768-h.htm"))) (re-seq #"<p>([^<]*)</p>") (map second) (map (fn [s] (let [el (.createElement js/document "textarea")] (set! (.-innerHTML el) s) (.-value el)))) (map #(str/replace % #"\n" " ")) vec)) (defn start-test-logging [] (let [!old-run? (deref !!run-test-logging?) !run? (atom true)] (reset! !old-run? false) (reset! !!run-test-logging? !run?) (go (let [paras (<! (<paras))] (loop [iters 0] (hc/post "http://localhost:7330" {:body (ks/to-transit {:rx.log/event-name (str "foo.bar." iters) :rx.log/body-edn (pr-str {:paras [(nth paras (rand (count paras)))] :title "Whurthering Heights" :author "<NAME>"})}) :headers {"Content-Type" "application/json+transit"}}) (<! (timeout 1000)) (when @!run? (recur (inc iters)))))))) (comment (stop-test-logging) (start-test-logging) (reset! !listeners #{}) (restart) (hc/post "http://localhost:7330" {:body (ks/to-transit {:foo/bar "baz"}) :headers {"Content-Type" "application/json+transit"}}) (def !r? (atom true)) )
true
(ns rx.log-ingress (:require [rx.kitchen-sink :as ks] [rx.http :as http] [clojure.string :as str] [cljs-http.client :as hc] [cljs.core.async :as async :refer [<! put! timeout] :refer-macros [go go-loop]])) (def HTTP (js/require "http")) (def NET (js/require "net")) (defonce !server (atom nil)) (defonce !listeners (atom #{})) (defn listen! [f] (swap! !listeners conj f)) (defn unlisten! [f] (swap! !listeners disj f)) (defn fire [le] (doseq [f @!listeners] (f le)) {:handler-count (count @!listeners)}) (defn body->log-event [body] (ks/from-transit body)) (defn restart [& [{:keys [port] :or {port 7330}}]] (when @!server (.close @!server)) (reset! !server (let [server (.createServer HTTP (fn [req resp] (let [stream req !body (atom nil)] (.on stream "readable" (fn [] (swap! !body str (.read stream)))) (.on stream "end" (fn [] (let [body @!body] (pr-str (fire (body->log-event body))) (.writeHead resp 200 (clj->js {"Content-Type" "text/plain"})) (.end resp "ok") ))))))] (.listen server port (fn [err] (if err (ks/prn "Error starting server: " err) (ks/prn "Server started")))) server))) (defonce !!run-test-logging? (atom (atom nil))) (defn stop-test-logging [] (reset! (deref !!run-test-logging?) false)) (defn <paras [] (->> (:body (<! (hc/get "https://www.gutenberg.org/files/768/768-h/768-h.htm"))) (re-seq #"<p>([^<]*)</p>") (map second) (map (fn [s] (let [el (.createElement js/document "textarea")] (set! (.-innerHTML el) s) (.-value el)))) (map #(str/replace % #"\n" " ")) vec)) (defn start-test-logging [] (let [!old-run? (deref !!run-test-logging?) !run? (atom true)] (reset! !old-run? false) (reset! !!run-test-logging? !run?) (go (let [paras (<! (<paras))] (loop [iters 0] (hc/post "http://localhost:7330" {:body (ks/to-transit {:rx.log/event-name (str "foo.bar." iters) :rx.log/body-edn (pr-str {:paras [(nth paras (rand (count paras)))] :title "Whurthering Heights" :author "PI:NAME:<NAME>END_PI"})}) :headers {"Content-Type" "application/json+transit"}}) (<! (timeout 1000)) (when @!run? (recur (inc iters)))))))) (comment (stop-test-logging) (start-test-logging) (reset! !listeners #{}) (restart) (hc/post "http://localhost:7330" {:body (ks/to-transit {:foo/bar "baz"}) :headers {"Content-Type" "application/json+transit"}}) (def !r? (atom true)) )
[ { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,", "end": 48, "score": 0.9998860359191895, "start": 36, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version 2.", "end": 61, "score": 0.8598191738128662, "start": 51, "tag": "EMAIL", "value": "arkisr.com" } ]
src/openstack/model.clj
celestial-ops/core
1
(comment re-core, Copyright 2012 Ronen Narkis, narkisr.com 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 openstack.model "Openstack model" (:use [flatland.useful.map :only (dissoc-in*)] [re-core.model :only (clone)])) (def identifiers {:machine #{:ip :hostname :domain} :openstack #{:instance-id :floating-ip}}) (defmethod clone :openstack [spec clone-spec] "Clones the model replace unique identifiers in the process" (-> spec (dissoc-in* [:machine :ip]) (dissoc-in* [:openstack :instance-id])))
107579
(comment re-core, Copyright 2012 <NAME>, n<EMAIL> 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 openstack.model "Openstack model" (:use [flatland.useful.map :only (dissoc-in*)] [re-core.model :only (clone)])) (def identifiers {:machine #{:ip :hostname :domain} :openstack #{:instance-id :floating-ip}}) (defmethod clone :openstack [spec clone-spec] "Clones the model replace unique identifiers in the process" (-> spec (dissoc-in* [:machine :ip]) (dissoc-in* [:openstack :instance-id])))
true
(comment re-core, Copyright 2012 PI:NAME:<NAME>END_PI, nPI:EMAIL:<EMAIL>END_PI 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 openstack.model "Openstack model" (:use [flatland.useful.map :only (dissoc-in*)] [re-core.model :only (clone)])) (def identifiers {:machine #{:ip :hostname :domain} :openstack #{:instance-id :floating-ip}}) (defmethod clone :openstack [spec clone-spec] "Clones the model replace unique identifiers in the process" (-> spec (dissoc-in* [:machine :ip]) (dissoc-in* [:openstack :instance-id])))
[ { "context": "e \"Email can't be empty\")\n\n (empty? (:username @s))\n (swap! s assoc :flash-message \"Username ca", "end": 3380, "score": 0.9486656188964844, "start": 3378, "tag": "USERNAME", "value": "@s" }, { "context": ")\n\n (not= (:password @s) (:confirm-password @s))\n (swap! s assoc :flash-message \"Passwords m", "end": 3862, "score": 0.6007328629493713, "start": 3861, "tag": "PASSWORD", "value": "s" }, { "context": "t {:type \"text\"\n :placeholder \"Username\"\n :name \"username\"\n ", "end": 4847, "score": 0.9899041056632996, "start": 4839, "tag": "USERNAME", "value": "Username" }, { "context": "placeholder \"Username\"\n :name \"username\"\n :ref \"username\"\n ", "end": 4884, "score": 0.9921013712882996, "start": 4876, "tag": "USERNAME", "value": "username" }, { "context": " :name \"username\"\n :ref \"username\"\n :value (:username @s)\n ", "end": 4920, "score": 0.8963930010795593, "start": 4912, "tag": "USERNAME", "value": "username" }, { "context": "f \"username\"\n :value (:username @s)\n :on-change #(swap! s assoc :", "end": 4962, "score": 0.6915770769119263, "start": 4960, "tag": "USERNAME", "value": "@s" }, { "context": ")}\n [:p [:input {:type \"text\" :placeholder \"Username\" :name \"username\"}]]\n [:p [:input {:type \"p", "end": 7563, "score": 0.9990962743759155, "start": 7555, "tag": "USERNAME", "value": "Username" }, { "context": "nput {:type \"text\" :placeholder \"Username\" :name \"username\"}]]\n [:p [:input {:type \"password\" :placeho", "end": 7580, "score": 0.9994914531707764, "start": 7572, "tag": "USERNAME", "value": "username" }, { "context": " [:p [:input {:type \"password\" :placeholder \"Password\" :name \"password\"}]]\n [:p [:button \"Log in\"", "end": 7644, "score": 0.9864704012870789, "start": 7636, "tag": "PASSWORD", "value": "Password" } ]
src/cljs/nr/auth.cljs
NBKelly/netrunner
0
(ns nr.auth (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [<!]] [clojure.string :refer [lower-case]] [nr.ajax :refer [GET POST]] [nr.appstate :refer [app-state]] [nr.avatar :refer [avatar]] [nr.translations :refer [tr]] [reagent.core :as r])) (defn authenticated [f] (if-let [user (:user @app-state)] (f user) (do (.modal (js/$ "#login-form") "show") nil))) (defn handle-post [event url s] (.preventDefault event) (swap! s dissoc :flash-message) (let [params (-> event .-target js/$ .serialize) _ (.-serialize (js/$ (.-target event)))] ;; params is nil when built in :advanced mode. This fixes the issue. (go (let [response (<! (POST url params))] (if (and (= (:status response) 200) (= url "/forgot")) (swap! s assoc :flash-message "Reset password sent") (case (:status response) 401 (swap! s assoc :flash-message "Invalid login or password") 421 (swap! s assoc :flash-message "No account with that email address exists") 422 (swap! s assoc :flash-message "Username taken") 423 (swap! s assoc :flash-message "Username too long") 424 (swap! s assoc :flash-message "Email already used") (-> js/document .-location (.reload true)))))))) (defn handle-logout [event] (.preventDefault event) (go (<! (POST "/logout" nil)) (-> js/document .-location (.reload true)))) (defn logged-menu [user] [:ul [:li.dropdown.usermenu [:a.dropdown-toggle {:href "" :data-toggle "dropdown"} [avatar user {:opts {:size 22}}] (:username user) [:b.caret]] [:div.dropdown-menu.blue-shade.float-right (when (:isadmin user) [:a.block-link {:href "/admin"} (str "[" (tr [:menu/admin "Admin"]) "]")]) (when (:ismoderator user) [:a.block-link (str "[" (tr [:menu/moderator "Moderator"]) "]")]) [:a.block-link {:href "/account"} (tr [:menu/settings "Settings"])] [:a.block-link {:on-click #(handle-logout %)} (tr [:menu/logout "Jack out"])]]]]) (defn unlogged-menu [] [:ul [:li [:a {:href "" :data-target "#register-form" :data-toggle "modal" :on-click (fn [] (.focus (js/$ "input[name='email']")))} "Sign up"]] [:li [:a {:href "" :data-target "#login-form" :data-toggle "modal"} "Login"]]]) (defn check-username [value s] (go (let [response (<! (GET (str "/check-username/" value)))] (case (:status response) 422 (swap! s assoc :flash-message "Username taken") 423 (swap! s assoc :flash-message "Username too short/too long") (swap! s assoc :flash-message ""))))) (defn check-email [value s] (go (let [response (<! (GET (str "/check-email/" value)))] (case (:status response) 422 (swap! s assoc :flash-message "Email taken") (swap! s assoc :flash-message ""))))) (defn valid-email? [email] (let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"] (and (string? email) (re-matches pattern (lower-case email))))) (defn register [event s] (.preventDefault event) (cond (empty? (:email @s)) (swap! s assoc :flash-message "Email can't be empty") (empty? (:username @s)) (swap! s assoc :flash-message "Username can't be empty") (not (-> @s :email valid-email?)) (swap! s assoc :flash-message "Please enter a valid email address") (< 20 (-> @s :username count)) (swap! s assoc :flash-message "Username must be 20 characters or shorter") (or (empty? (:password @s)) (empty? (:confirm-password @s))) (swap! s assoc :flash-message "Password can't be empty") (not= (:password @s) (:confirm-password @s)) (swap! s assoc :flash-message "Passwords must match") :else (handle-post event "/register" s))) (defn register-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#register-form.modal.fade {:ref "register-form"} [:div.modal-dialog [:h3 "Create an account"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(register % s)} [:p [:input {:type "text" :placeholder "Email" :name "email" :ref "email" :value (:email @s) :on-change #(swap! s assoc :email (-> % .-target .-value)) :on-blur #(do (check-email (-> % .-target .-value) s) (when-not (valid-email? (.. % -target -value)) (swap! s assoc :flash-message "Please enter a valid email address")))}]] [:p [:input {:type "text" :placeholder "Username" :name "username" :ref "username" :value (:username @s) :on-change #(swap! s assoc :username (-> % .-target .-value)) :on-blur #(check-username (-> % .-target .-value) s) :maxLength "16"}]] [:p [:input {:type "password" :placeholder "Password" :name "password" :ref "password" :value (:password @s) :on-change #(swap! s assoc :password (-> % .-target .-value))}]] [:p [:input {:type "password" :placeholder "Confirm password" :name "confirm-password" :ref "confirm-password" :value (:confirm-password @s) :on-change #(swap! s assoc :confirm-password (-> % .-target .-value)) :on-blur #(let [value (-> % .-target .-value)] (when-not (subs value 0 (count (:password @s))) (swap! s assoc :flash-message "Please enter matching passwords")))}]] [:p [:button "Sign up"] [:button {:data-dismiss "modal"} "Cancel"]]] [:p "Already have an account? " \ [:span.fake-link {:on-click #(.modal (js/$ "#login-form") "show") :data-dismiss "modal"} "Log in"]] [:p "Need to reset your password? " [:span.fake-link {:on-click #(.modal (js/$ "#forgot-form") "show") :data-dismiss "modal"} "Reset"]]]])) (defn forgot-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#forgot-form.modal.fade {:ref "forgot-form"} [:div.modal-dialog [:h3 "Reset your Password"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(handle-post % "/forgot" s)} [:p [:input {:type "text" :placeholder "Email" :name "email" :on-blur #(when-not (valid-email? (.. % -target -value)) (swap! s assoc :flash-message "Please enter a valid email address"))}]] [:p [:button "Submit"] [:button {:data-dismiss "modal"} "Cancel"]] [:p "No account? " [:span.fake-link {:on-click #(.modal (js/$ "#register-form") "show") :data-dismiss "modal"} "Sign up!"]]]]])) (defn login-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#login-form.modal.fade [:div.modal-dialog [:h3 "Log in"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(handle-post % "/login" s)} [:p [:input {:type "text" :placeholder "Username" :name "username"}]] [:p [:input {:type "password" :placeholder "Password" :name "password"}]] [:p [:button "Log in"] [:button {:data-dismiss "modal"} "Cancel"]] [:p "No account? " [:span.fake-link {:on-click #(.modal (js/$ "#register-form") "show") :data-dismiss "modal"} "Sign up!"]] [:p "Forgot your password? " [:span.fake-link {:on-click #(.modal (js/$ "#forgot-form") "show") :data-dismiss "modal"} "Reset"]]]]])) (defn auth-menu [] (if-let [user (:user @app-state)] [logged-menu user] [unlogged-menu])) (defn auth-forms [] (when-not (:user @app-state) [:div [register-form] [login-form] [forgot-form]]))
76730
(ns nr.auth (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [<!]] [clojure.string :refer [lower-case]] [nr.ajax :refer [GET POST]] [nr.appstate :refer [app-state]] [nr.avatar :refer [avatar]] [nr.translations :refer [tr]] [reagent.core :as r])) (defn authenticated [f] (if-let [user (:user @app-state)] (f user) (do (.modal (js/$ "#login-form") "show") nil))) (defn handle-post [event url s] (.preventDefault event) (swap! s dissoc :flash-message) (let [params (-> event .-target js/$ .serialize) _ (.-serialize (js/$ (.-target event)))] ;; params is nil when built in :advanced mode. This fixes the issue. (go (let [response (<! (POST url params))] (if (and (= (:status response) 200) (= url "/forgot")) (swap! s assoc :flash-message "Reset password sent") (case (:status response) 401 (swap! s assoc :flash-message "Invalid login or password") 421 (swap! s assoc :flash-message "No account with that email address exists") 422 (swap! s assoc :flash-message "Username taken") 423 (swap! s assoc :flash-message "Username too long") 424 (swap! s assoc :flash-message "Email already used") (-> js/document .-location (.reload true)))))))) (defn handle-logout [event] (.preventDefault event) (go (<! (POST "/logout" nil)) (-> js/document .-location (.reload true)))) (defn logged-menu [user] [:ul [:li.dropdown.usermenu [:a.dropdown-toggle {:href "" :data-toggle "dropdown"} [avatar user {:opts {:size 22}}] (:username user) [:b.caret]] [:div.dropdown-menu.blue-shade.float-right (when (:isadmin user) [:a.block-link {:href "/admin"} (str "[" (tr [:menu/admin "Admin"]) "]")]) (when (:ismoderator user) [:a.block-link (str "[" (tr [:menu/moderator "Moderator"]) "]")]) [:a.block-link {:href "/account"} (tr [:menu/settings "Settings"])] [:a.block-link {:on-click #(handle-logout %)} (tr [:menu/logout "Jack out"])]]]]) (defn unlogged-menu [] [:ul [:li [:a {:href "" :data-target "#register-form" :data-toggle "modal" :on-click (fn [] (.focus (js/$ "input[name='email']")))} "Sign up"]] [:li [:a {:href "" :data-target "#login-form" :data-toggle "modal"} "Login"]]]) (defn check-username [value s] (go (let [response (<! (GET (str "/check-username/" value)))] (case (:status response) 422 (swap! s assoc :flash-message "Username taken") 423 (swap! s assoc :flash-message "Username too short/too long") (swap! s assoc :flash-message ""))))) (defn check-email [value s] (go (let [response (<! (GET (str "/check-email/" value)))] (case (:status response) 422 (swap! s assoc :flash-message "Email taken") (swap! s assoc :flash-message ""))))) (defn valid-email? [email] (let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"] (and (string? email) (re-matches pattern (lower-case email))))) (defn register [event s] (.preventDefault event) (cond (empty? (:email @s)) (swap! s assoc :flash-message "Email can't be empty") (empty? (:username @s)) (swap! s assoc :flash-message "Username can't be empty") (not (-> @s :email valid-email?)) (swap! s assoc :flash-message "Please enter a valid email address") (< 20 (-> @s :username count)) (swap! s assoc :flash-message "Username must be 20 characters or shorter") (or (empty? (:password @s)) (empty? (:confirm-password @s))) (swap! s assoc :flash-message "Password can't be empty") (not= (:password @s) (:confirm-password @<PASSWORD>)) (swap! s assoc :flash-message "Passwords must match") :else (handle-post event "/register" s))) (defn register-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#register-form.modal.fade {:ref "register-form"} [:div.modal-dialog [:h3 "Create an account"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(register % s)} [:p [:input {:type "text" :placeholder "Email" :name "email" :ref "email" :value (:email @s) :on-change #(swap! s assoc :email (-> % .-target .-value)) :on-blur #(do (check-email (-> % .-target .-value) s) (when-not (valid-email? (.. % -target -value)) (swap! s assoc :flash-message "Please enter a valid email address")))}]] [:p [:input {:type "text" :placeholder "Username" :name "username" :ref "username" :value (:username @s) :on-change #(swap! s assoc :username (-> % .-target .-value)) :on-blur #(check-username (-> % .-target .-value) s) :maxLength "16"}]] [:p [:input {:type "password" :placeholder "Password" :name "password" :ref "password" :value (:password @s) :on-change #(swap! s assoc :password (-> % .-target .-value))}]] [:p [:input {:type "password" :placeholder "Confirm password" :name "confirm-password" :ref "confirm-password" :value (:confirm-password @s) :on-change #(swap! s assoc :confirm-password (-> % .-target .-value)) :on-blur #(let [value (-> % .-target .-value)] (when-not (subs value 0 (count (:password @s))) (swap! s assoc :flash-message "Please enter matching passwords")))}]] [:p [:button "Sign up"] [:button {:data-dismiss "modal"} "Cancel"]]] [:p "Already have an account? " \ [:span.fake-link {:on-click #(.modal (js/$ "#login-form") "show") :data-dismiss "modal"} "Log in"]] [:p "Need to reset your password? " [:span.fake-link {:on-click #(.modal (js/$ "#forgot-form") "show") :data-dismiss "modal"} "Reset"]]]])) (defn forgot-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#forgot-form.modal.fade {:ref "forgot-form"} [:div.modal-dialog [:h3 "Reset your Password"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(handle-post % "/forgot" s)} [:p [:input {:type "text" :placeholder "Email" :name "email" :on-blur #(when-not (valid-email? (.. % -target -value)) (swap! s assoc :flash-message "Please enter a valid email address"))}]] [:p [:button "Submit"] [:button {:data-dismiss "modal"} "Cancel"]] [:p "No account? " [:span.fake-link {:on-click #(.modal (js/$ "#register-form") "show") :data-dismiss "modal"} "Sign up!"]]]]])) (defn login-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#login-form.modal.fade [:div.modal-dialog [:h3 "Log in"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(handle-post % "/login" s)} [:p [:input {:type "text" :placeholder "Username" :name "username"}]] [:p [:input {:type "password" :placeholder "<PASSWORD>" :name "password"}]] [:p [:button "Log in"] [:button {:data-dismiss "modal"} "Cancel"]] [:p "No account? " [:span.fake-link {:on-click #(.modal (js/$ "#register-form") "show") :data-dismiss "modal"} "Sign up!"]] [:p "Forgot your password? " [:span.fake-link {:on-click #(.modal (js/$ "#forgot-form") "show") :data-dismiss "modal"} "Reset"]]]]])) (defn auth-menu [] (if-let [user (:user @app-state)] [logged-menu user] [unlogged-menu])) (defn auth-forms [] (when-not (:user @app-state) [:div [register-form] [login-form] [forgot-form]]))
true
(ns nr.auth (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [<!]] [clojure.string :refer [lower-case]] [nr.ajax :refer [GET POST]] [nr.appstate :refer [app-state]] [nr.avatar :refer [avatar]] [nr.translations :refer [tr]] [reagent.core :as r])) (defn authenticated [f] (if-let [user (:user @app-state)] (f user) (do (.modal (js/$ "#login-form") "show") nil))) (defn handle-post [event url s] (.preventDefault event) (swap! s dissoc :flash-message) (let [params (-> event .-target js/$ .serialize) _ (.-serialize (js/$ (.-target event)))] ;; params is nil when built in :advanced mode. This fixes the issue. (go (let [response (<! (POST url params))] (if (and (= (:status response) 200) (= url "/forgot")) (swap! s assoc :flash-message "Reset password sent") (case (:status response) 401 (swap! s assoc :flash-message "Invalid login or password") 421 (swap! s assoc :flash-message "No account with that email address exists") 422 (swap! s assoc :flash-message "Username taken") 423 (swap! s assoc :flash-message "Username too long") 424 (swap! s assoc :flash-message "Email already used") (-> js/document .-location (.reload true)))))))) (defn handle-logout [event] (.preventDefault event) (go (<! (POST "/logout" nil)) (-> js/document .-location (.reload true)))) (defn logged-menu [user] [:ul [:li.dropdown.usermenu [:a.dropdown-toggle {:href "" :data-toggle "dropdown"} [avatar user {:opts {:size 22}}] (:username user) [:b.caret]] [:div.dropdown-menu.blue-shade.float-right (when (:isadmin user) [:a.block-link {:href "/admin"} (str "[" (tr [:menu/admin "Admin"]) "]")]) (when (:ismoderator user) [:a.block-link (str "[" (tr [:menu/moderator "Moderator"]) "]")]) [:a.block-link {:href "/account"} (tr [:menu/settings "Settings"])] [:a.block-link {:on-click #(handle-logout %)} (tr [:menu/logout "Jack out"])]]]]) (defn unlogged-menu [] [:ul [:li [:a {:href "" :data-target "#register-form" :data-toggle "modal" :on-click (fn [] (.focus (js/$ "input[name='email']")))} "Sign up"]] [:li [:a {:href "" :data-target "#login-form" :data-toggle "modal"} "Login"]]]) (defn check-username [value s] (go (let [response (<! (GET (str "/check-username/" value)))] (case (:status response) 422 (swap! s assoc :flash-message "Username taken") 423 (swap! s assoc :flash-message "Username too short/too long") (swap! s assoc :flash-message ""))))) (defn check-email [value s] (go (let [response (<! (GET (str "/check-email/" value)))] (case (:status response) 422 (swap! s assoc :flash-message "Email taken") (swap! s assoc :flash-message ""))))) (defn valid-email? [email] (let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"] (and (string? email) (re-matches pattern (lower-case email))))) (defn register [event s] (.preventDefault event) (cond (empty? (:email @s)) (swap! s assoc :flash-message "Email can't be empty") (empty? (:username @s)) (swap! s assoc :flash-message "Username can't be empty") (not (-> @s :email valid-email?)) (swap! s assoc :flash-message "Please enter a valid email address") (< 20 (-> @s :username count)) (swap! s assoc :flash-message "Username must be 20 characters or shorter") (or (empty? (:password @s)) (empty? (:confirm-password @s))) (swap! s assoc :flash-message "Password can't be empty") (not= (:password @s) (:confirm-password @PI:PASSWORD:<PASSWORD>END_PI)) (swap! s assoc :flash-message "Passwords must match") :else (handle-post event "/register" s))) (defn register-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#register-form.modal.fade {:ref "register-form"} [:div.modal-dialog [:h3 "Create an account"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(register % s)} [:p [:input {:type "text" :placeholder "Email" :name "email" :ref "email" :value (:email @s) :on-change #(swap! s assoc :email (-> % .-target .-value)) :on-blur #(do (check-email (-> % .-target .-value) s) (when-not (valid-email? (.. % -target -value)) (swap! s assoc :flash-message "Please enter a valid email address")))}]] [:p [:input {:type "text" :placeholder "Username" :name "username" :ref "username" :value (:username @s) :on-change #(swap! s assoc :username (-> % .-target .-value)) :on-blur #(check-username (-> % .-target .-value) s) :maxLength "16"}]] [:p [:input {:type "password" :placeholder "Password" :name "password" :ref "password" :value (:password @s) :on-change #(swap! s assoc :password (-> % .-target .-value))}]] [:p [:input {:type "password" :placeholder "Confirm password" :name "confirm-password" :ref "confirm-password" :value (:confirm-password @s) :on-change #(swap! s assoc :confirm-password (-> % .-target .-value)) :on-blur #(let [value (-> % .-target .-value)] (when-not (subs value 0 (count (:password @s))) (swap! s assoc :flash-message "Please enter matching passwords")))}]] [:p [:button "Sign up"] [:button {:data-dismiss "modal"} "Cancel"]]] [:p "Already have an account? " \ [:span.fake-link {:on-click #(.modal (js/$ "#login-form") "show") :data-dismiss "modal"} "Log in"]] [:p "Need to reset your password? " [:span.fake-link {:on-click #(.modal (js/$ "#forgot-form") "show") :data-dismiss "modal"} "Reset"]]]])) (defn forgot-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#forgot-form.modal.fade {:ref "forgot-form"} [:div.modal-dialog [:h3 "Reset your Password"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(handle-post % "/forgot" s)} [:p [:input {:type "text" :placeholder "Email" :name "email" :on-blur #(when-not (valid-email? (.. % -target -value)) (swap! s assoc :flash-message "Please enter a valid email address"))}]] [:p [:button "Submit"] [:button {:data-dismiss "modal"} "Cancel"]] [:p "No account? " [:span.fake-link {:on-click #(.modal (js/$ "#register-form") "show") :data-dismiss "modal"} "Sign up!"]]]]])) (defn login-form [] (r/with-let [s (r/atom {:flash-message ""})] [:div#login-form.modal.fade [:div.modal-dialog [:h3 "Log in"] [:p.flash-message (:flash-message @s)] [:form {:on-submit #(handle-post % "/login" s)} [:p [:input {:type "text" :placeholder "Username" :name "username"}]] [:p [:input {:type "password" :placeholder "PI:PASSWORD:<PASSWORD>END_PI" :name "password"}]] [:p [:button "Log in"] [:button {:data-dismiss "modal"} "Cancel"]] [:p "No account? " [:span.fake-link {:on-click #(.modal (js/$ "#register-form") "show") :data-dismiss "modal"} "Sign up!"]] [:p "Forgot your password? " [:span.fake-link {:on-click #(.modal (js/$ "#forgot-form") "show") :data-dismiss "modal"} "Reset"]]]]])) (defn auth-menu [] (if-let [user (:user @app-state)] [logged-menu user] [unlogged-menu])) (defn auth-forms [] (when-not (:user @app-state) [:div [register-form] [login-form] [forgot-form]]))
[ { "context": " (comp/set-state! this {:input-key (str (rand-int 1000000))})))})))\n ui-factory (comp/compu", "end": 11678, "score": 0.9227049350738525, "start": 11657, "tag": "KEY", "value": "str (rand-int 1000000" } ]
src/main/com/fulcrologic/rad/rendering/semantic_ui/form.cljc
gpellis/fulcro-rad-semantic-ui
0
(ns com.fulcrologic.rad.rendering.semantic-ui.form (:require [com.fulcrologic.rad.attributes :as attr] [com.fulcrologic.rad.options-util :refer [?! narrow-keyword]] [com.fulcrologic.rad.ui-validation :as validation] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.control :as control] [com.fulcrologic.rad.blob :as blob] [com.fulcrologic.fulcro.dom.events :as evt] [com.fulcrologic.fulcro-i18n.i18n :refer [tr]] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.application :as app] #?(:cljs [com.fulcrologic.fulcro.dom :as dom :refer [div h3 button i span]] :clj [com.fulcrologic.fulcro.dom-server :as dom :refer [div h3 button i span]]) [com.fulcrologic.fulcro.dom.html-entities :as ent] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro.algorithms.tempid :as tempid] [com.fulcrologic.fulcro.algorithms.merge :as merge] [taoensso.encore :as enc] [taoensso.timbre :as log])) (defn render-to-many [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{:semantic-ui/keys [add-position] ::form/keys [ui title can-delete? can-add? added-via-upload?]} (get subforms k) form-instance-props (comp/props form-instance) read-only? (form/read-only? form-instance attr) add? (if read-only? false (?! can-add? form-instance attr)) delete? (fn [item] (and (not read-only?) (?! can-delete? form-instance item))) items (get form-instance-props k) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-instance-props) invalid? (validation/invalid-attribute-value? env attr) validation-message (validation/validation-error-message env attr) add (when (or (nil? add?) add?) (let [order (if (keyword? add?) add? :append)] (if (?! added-via-upload? env) (dom/input {:type "file" :onChange (fn [evt] (log/info "UPLOAD FILE!!!") (let [new-id (tempid/tempid) js-file (-> evt blob/evt->js-files first) attributes (comp/component-options ui ::form/attributes) id-attr (comp/component-options ui ::form/id) id-key (::attr/qualified-key id-attr) {::attr/keys [qualified-key] :as sha-attr} (first (filter ::blob/store attributes)) target (conj (comp/get-ident form-instance) k) new-entity (fs/add-form-config ui {id-key new-id qualified-key ""})] (merge/merge-component! form-instance ui new-entity order target) (blob/upload-file! form-instance sha-attr js-file {:file-ident [id-key new-id]})))}) (button :.ui.tiny.icon.button {:onClick (fn [_] (form/add-child! (assoc env ::form/order order ::form/parent-relation k ::form/parent form-instance ::form/child-class ui)))} (i :.plus.icon))))) ui-factory (comp/computed-factory ui {:keyfn (fn [item] (-> ui (comp/get-ident item) second str))})] (div :.ui.container {:key (str k)} (h3 title (span ent/nbsp ent/nbsp) (when (or (nil? add-position) (= :top add-position)) add)) (when invalid? (div :.ui.error.message validation-message)) (if (seq items) (div :.ui.segments (mapv (fn [props] (ui-factory props (merge env {::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if delete? (delete? props) false)}))) items)) (div :.ui.message "None.")) (when (= :bottom add-position) add)))) (defn render-to-one [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{::form/keys [ui can-delete? title]} (get subforms k) form-props (comp/props form-instance) props (get form-props k) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-props) ui-factory (comp/computed-factory ui) invalid? (validation/invalid-attribute-value? env attr) validation-message (validation/validation-error-message env attr) std-props {::form/nested? true ::form/parent form-instance ::form/parent-relation k ::form/can-delete? (or (?! can-delete? form-instance form-props) false)}] (cond props (div {:key (str k)} (h3 :.ui.header title) (when invalid? (div :.ui.error.message validation-message)) (ui-factory props (merge env std-props))) :else (div {:key (str k)} (h3 :.ui.header title) (button {:onClick (fn [] (form/add-child! (assoc env ::form/parent-relation k ::form/parent form-instance ::form/child-class ui)))} "Create"))))) (defn standard-ref-container [env {::attr/keys [cardinality] :as attr} options] (if (= :many cardinality) (render-to-many env attr options) (render-to-one env attr options))) (defn render-single-file [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{::form/keys [ui can-delete?]} (get subforms k) parent (comp/props form-instance) form-props (comp/props form-instance) props (get form-props k) ui-factory (comp/computed-factory ui) label (form/field-label env attr) std-props {::form/nested? true ::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if can-delete? (can-delete? parent props) false)}] (if props (div :.field {:key (str k)} (dom/label label) (ui-factory props (merge env std-props))) (div {:key (str k)} (div "Upload??? (TODO)"))))) (defsc ManyFiles [this {{::form/keys [form-instance master-form] :as env} :env {k ::attr/qualified-key :as attr} :attribute {::form/keys [subforms] :as options} :options}] {:initLocalState (fn [this] {:input-key (str (rand-int 1000000))})} (let [{:semantic-ui/keys [add-position] ::form/keys [ui title can-delete? can-add? sort-children]} (get subforms k) form-instance-props (comp/props form-instance) read-only? (or (form/read-only? master-form attr) (form/read-only? form-instance attr)) add? (if read-only? false (?! can-add? form-instance attr)) delete? (if read-only? false (fn [item] (?! can-delete? form-instance item))) items (-> form-instance comp/props k (cond-> sort-children sort-children)) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-instance-props) upload-id (str k "-file-upload") add (when (or (nil? add?) add?) (dom/div (dom/label :.ui.green.button {:htmlFor upload-id} (dom/i :.ui.plus.icon) "Add File") (dom/input {:type "file" ;; trick: changing the key on change clears the input, so a failed upload can be retried :key (comp/get-state this :input-key) :id upload-id :style {:zIndex -1 :width "1px" :height "1px" :opacity 0} :onChange (fn [evt] (let [new-id (tempid/tempid) js-file (-> evt blob/evt->js-files first) attributes (comp/component-options ui ::form/attributes) id-attr (comp/component-options ui ::form/id) id-key (::attr/qualified-key id-attr) {::attr/keys [qualified-key] :as sha-attr} (first (filter ::blob/store attributes)) target (conj (comp/get-ident form-instance) k) new-entity (fs/add-form-config ui {id-key new-id qualified-key ""})] (merge/merge-component! form-instance ui new-entity :append target) (blob/upload-file! form-instance sha-attr js-file {:file-ident [id-key new-id]}) (comp/set-state! this {:input-key (str (rand-int 1000000))})))}))) ui-factory (comp/computed-factory ui {:keyfn (fn [item] (-> ui (comp/get-ident item) second str))})] (div :.ui.basic.segment {:key (str k)} (dom/h2 :.ui.header title) (when (or (nil? add-position) (= :top add-position)) add) (if (seq items) (div :.ui.very.relaxed.items (mapv (fn [props] (ui-factory props (merge env {::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if delete? (?! delete? props) false)}))) items)) (div :.ui.message "None")) (when (= :bottom add-position) add)))) (def ui-many-files (comp/factory ManyFiles {:keyfn (fn [{:keys [attribute]}] (::attr/qualified-key attribute))})) (defn file-ref-container [env {::attr/keys [cardinality] :as attr} options] (if (= :many cardinality) (ui-many-files {:env env :attribute attr :options options}) (render-single-file env attr options))) (defn render-attribute [env attr {::form/keys [subforms] :as options}] (let [{k ::attr/qualified-key} attr] (if (contains? subforms k) (let [render-ref (or (form/ref-container-renderer env attr) standard-ref-container)] (render-ref env attr options)) (form/render-field env attr)))) (def n-fields-string {1 "one field" 2 "two fields" 3 "three fields" 4 "four fields" 5 "five fields" 6 "six fields" 7 "seven fields"}) (def attribute-map (memoize (fn [attributes] (reduce (fn [m {::attr/keys [qualified-key] :as attr}] (assoc m qualified-key attr)) {} attributes)))) (defn- render-layout* [env options k->attribute layout] (when #?(:clj true :cljs goog.DEBUG) (when-not (and (vector? layout) (every? vector? layout)) (log/error "::form/layout must be a vector of vectors!"))) (try (into [] (map-indexed (fn [idx row] (div {:key idx :className (n-fields-string (count row))} (mapv (fn [col] (enc/if-let [_ k->attribute attr (k->attribute col)] (render-attribute env attr options) (if (some-> options ::control/controls (get col)) (control/render-control (::form/form-instance env) col) (log/error "Missing attribute (or lookup) for" col)))) row))) layout)) (catch #?(:clj Exception :cljs :default) _))) (defn render-layout [env {::form/keys [attributes layout] :as options}] (let [k->attribute (attribute-map attributes)] (render-layout* env options k->attribute layout))) (defsc TabbedLayout [this env {::form/keys [attributes tabbed-layout] :as options}] {:initLocalState (fn [this] (try {:current-tab 0 :tab-details (memoize (fn [attributes tabbed-layout] (let [k->attr (attribute-map attributes) tab-labels (filterv string? tabbed-layout) tab-label->layout (into {} (map vec) (partition 2 (mapv first (partition-by string? tabbed-layout))))] {:k->attr k->attr :tab-labels tab-labels :tab-label->layout tab-label->layout})))} (catch #?(:clj Exception :cljs :default) _ (log/error "Cannot build tabs for tabbed layout. Check your tabbed-layout options for" (comp/component-name this)))))} (let [{:keys [tab-details current-tab]} (comp/get-state this) {:keys [k->attr tab-labels tab-label->layout]} (tab-details attributes tabbed-layout) active-layout (some->> current-tab (get tab-labels) (get tab-label->layout))] (div {:key (str current-tab)} (div :.ui.pointing.menu {} (map-indexed (fn [idx title] (dom/a :.item {:key (str idx) :onClick #(comp/set-state! this {:current-tab idx}) :classes [(when (= current-tab idx) "active")]} title)) tab-labels)) (div :.ui.segment (render-layout* env options k->attr active-layout))))) (def ui-tabbed-layout (comp/computed-factory TabbedLayout)) (declare standard-form-layout-renderer) (defsc StandardFormContainer [this {::form/keys [props computed-props form-instance master-form] :as env}] {:shouldComponentUpdate (fn [_ _ _] true)} (let [{::form/keys [can-delete?]} computed-props nested? (not= master-form form-instance) read-only-form? (or (?! (comp/component-options form-instance ::form/read-only?) form-instance) (?! (comp/component-options master-form ::form/read-only?) master-form)) invalid? (if read-only-form? false (form/invalid? env)) render-fields (or (form/form-layout-renderer env) standard-form-layout-renderer)] (when #?(:cljs goog.DEBUG :clj true) (let [valid? (if read-only-form? true (form/valid? env)) dirty? (if read-only-form? false (or (:ui/new? props) (fs/dirty? props)))] (log/debug "Form " (comp/component-name form-instance) " valid? " valid?) (log/debug "Form " (comp/component-name form-instance) " dirty? " dirty?))) (if nested? (div :.ui.segment (div :.ui.form {:classes [(when invalid? "error")] :key (str (comp/get-ident form-instance))} (when can-delete? (button :.ui.icon.primary.right.floated.button {:disabled (not can-delete?) :onClick (fn [] (form/delete-child! env))} (i :.times.icon))) (render-fields env))) (let [{::form/keys [title action-buttons controls]} (comp/component-options form-instance) title (?! title form-instance props) action-buttons (if action-buttons action-buttons form/standard-action-buttons)] (div :.ui.container {:key (str (comp/get-ident form-instance))} (div :.ui.top.attached.segment (dom/h3 :.ui.header title (div :.ui.right.floated.buttons (keep #(control/render-control master-form %) action-buttons)))) (div :.ui.attached.form {:classes [(when invalid? "error")]} (div :.ui.error.message (tr "The form has errors and cannot be saved.")) (div :.ui.attached.segment (render-fields env)))))))) (def standard-form-container (comp/factory StandardFormContainer)) (defn standard-form-layout-renderer [{::form/keys [form-instance] :as env}] (let [{::form/keys [attributes layout tabbed-layout] :as options} (comp/component-options form-instance)] (cond (vector? layout) (render-layout env options) (vector? tabbed-layout) (ui-tabbed-layout env options) :else (mapv (fn [attr] (render-attribute env attr options)) attributes)))) (defn- file-icon-renderer* [{::form/keys [form-instance] :as env}] (let [{::form/keys [attributes] :as options} (comp/component-options form-instance) attribute (first (filter ::blob/store attributes)) sha-key (::attr/qualified-key attribute) file-key (blob/filename-key sha-key) url-key (blob/url-key sha-key) props (comp/props form-instance) filename (get props file-key "File") dirty? (fs/dirty? props sha-key) failed? (blob/failed-upload? props sha-key) invalid? (validation/invalid-attribute-value? env attribute) pct (blob/upload-percentage props sha-key) sha (get props sha-key) url (get props url-key)] (if (blob/uploading? props sha-key) (dom/span :.item {:key (str sha)} (dom/div :.ui.tiny.image (dom/i :.huge.file.icon) (dom/div :.ui.active.red.loader {:style {:marginLeft "-10px"}}) (dom/div :.ui.bottom.attached.blue.progress {:data-percent pct} (div :.bar {:style {:transitionDuration "300ms" :width pct}} (div :.progress "")))) (div :.middle.aligned.content filename) (dom/button :.ui.red.icon.button {:onClick (fn [] (app/abort! form-instance sha) (form/delete-child! env))} (dom/i :.times.icon))) ((if dirty? dom/span dom/a) :.item {:target "_blank" :key (str sha) :href (str url "?filename=" filename) :onClick (fn [evt] #?(:cljs (when-not (or (not (blob/blob-downloadable? props sha-key)) (js/confirm "View/download?")) (evt/stop-propagation! evt) (evt/prevent-default! evt))))} (dom/div :.ui.tiny.image (if failed? (dom/i :.huge.skull.crossbones.icon) (dom/i :.huge.file.icon))) (div :.middle.aligned.content (str filename (cond failed? " (Upload failed. Delete and try again.)" dirty? " (unsaved)"))) (dom/button :.ui.red.icon.button {:onClick (fn [evt] (evt/stop-propagation! evt) (evt/prevent-default! evt) (when #?(:clj true :cljs (js/confirm "Permanently Delete File?")) (form/delete-child! env)))} (dom/i :.times.icon)))))) (defn file-icon-renderer [env] (file-icon-renderer* env))
115812
(ns com.fulcrologic.rad.rendering.semantic-ui.form (:require [com.fulcrologic.rad.attributes :as attr] [com.fulcrologic.rad.options-util :refer [?! narrow-keyword]] [com.fulcrologic.rad.ui-validation :as validation] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.control :as control] [com.fulcrologic.rad.blob :as blob] [com.fulcrologic.fulcro.dom.events :as evt] [com.fulcrologic.fulcro-i18n.i18n :refer [tr]] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.application :as app] #?(:cljs [com.fulcrologic.fulcro.dom :as dom :refer [div h3 button i span]] :clj [com.fulcrologic.fulcro.dom-server :as dom :refer [div h3 button i span]]) [com.fulcrologic.fulcro.dom.html-entities :as ent] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro.algorithms.tempid :as tempid] [com.fulcrologic.fulcro.algorithms.merge :as merge] [taoensso.encore :as enc] [taoensso.timbre :as log])) (defn render-to-many [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{:semantic-ui/keys [add-position] ::form/keys [ui title can-delete? can-add? added-via-upload?]} (get subforms k) form-instance-props (comp/props form-instance) read-only? (form/read-only? form-instance attr) add? (if read-only? false (?! can-add? form-instance attr)) delete? (fn [item] (and (not read-only?) (?! can-delete? form-instance item))) items (get form-instance-props k) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-instance-props) invalid? (validation/invalid-attribute-value? env attr) validation-message (validation/validation-error-message env attr) add (when (or (nil? add?) add?) (let [order (if (keyword? add?) add? :append)] (if (?! added-via-upload? env) (dom/input {:type "file" :onChange (fn [evt] (log/info "UPLOAD FILE!!!") (let [new-id (tempid/tempid) js-file (-> evt blob/evt->js-files first) attributes (comp/component-options ui ::form/attributes) id-attr (comp/component-options ui ::form/id) id-key (::attr/qualified-key id-attr) {::attr/keys [qualified-key] :as sha-attr} (first (filter ::blob/store attributes)) target (conj (comp/get-ident form-instance) k) new-entity (fs/add-form-config ui {id-key new-id qualified-key ""})] (merge/merge-component! form-instance ui new-entity order target) (blob/upload-file! form-instance sha-attr js-file {:file-ident [id-key new-id]})))}) (button :.ui.tiny.icon.button {:onClick (fn [_] (form/add-child! (assoc env ::form/order order ::form/parent-relation k ::form/parent form-instance ::form/child-class ui)))} (i :.plus.icon))))) ui-factory (comp/computed-factory ui {:keyfn (fn [item] (-> ui (comp/get-ident item) second str))})] (div :.ui.container {:key (str k)} (h3 title (span ent/nbsp ent/nbsp) (when (or (nil? add-position) (= :top add-position)) add)) (when invalid? (div :.ui.error.message validation-message)) (if (seq items) (div :.ui.segments (mapv (fn [props] (ui-factory props (merge env {::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if delete? (delete? props) false)}))) items)) (div :.ui.message "None.")) (when (= :bottom add-position) add)))) (defn render-to-one [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{::form/keys [ui can-delete? title]} (get subforms k) form-props (comp/props form-instance) props (get form-props k) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-props) ui-factory (comp/computed-factory ui) invalid? (validation/invalid-attribute-value? env attr) validation-message (validation/validation-error-message env attr) std-props {::form/nested? true ::form/parent form-instance ::form/parent-relation k ::form/can-delete? (or (?! can-delete? form-instance form-props) false)}] (cond props (div {:key (str k)} (h3 :.ui.header title) (when invalid? (div :.ui.error.message validation-message)) (ui-factory props (merge env std-props))) :else (div {:key (str k)} (h3 :.ui.header title) (button {:onClick (fn [] (form/add-child! (assoc env ::form/parent-relation k ::form/parent form-instance ::form/child-class ui)))} "Create"))))) (defn standard-ref-container [env {::attr/keys [cardinality] :as attr} options] (if (= :many cardinality) (render-to-many env attr options) (render-to-one env attr options))) (defn render-single-file [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{::form/keys [ui can-delete?]} (get subforms k) parent (comp/props form-instance) form-props (comp/props form-instance) props (get form-props k) ui-factory (comp/computed-factory ui) label (form/field-label env attr) std-props {::form/nested? true ::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if can-delete? (can-delete? parent props) false)}] (if props (div :.field {:key (str k)} (dom/label label) (ui-factory props (merge env std-props))) (div {:key (str k)} (div "Upload??? (TODO)"))))) (defsc ManyFiles [this {{::form/keys [form-instance master-form] :as env} :env {k ::attr/qualified-key :as attr} :attribute {::form/keys [subforms] :as options} :options}] {:initLocalState (fn [this] {:input-key (str (rand-int 1000000))})} (let [{:semantic-ui/keys [add-position] ::form/keys [ui title can-delete? can-add? sort-children]} (get subforms k) form-instance-props (comp/props form-instance) read-only? (or (form/read-only? master-form attr) (form/read-only? form-instance attr)) add? (if read-only? false (?! can-add? form-instance attr)) delete? (if read-only? false (fn [item] (?! can-delete? form-instance item))) items (-> form-instance comp/props k (cond-> sort-children sort-children)) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-instance-props) upload-id (str k "-file-upload") add (when (or (nil? add?) add?) (dom/div (dom/label :.ui.green.button {:htmlFor upload-id} (dom/i :.ui.plus.icon) "Add File") (dom/input {:type "file" ;; trick: changing the key on change clears the input, so a failed upload can be retried :key (comp/get-state this :input-key) :id upload-id :style {:zIndex -1 :width "1px" :height "1px" :opacity 0} :onChange (fn [evt] (let [new-id (tempid/tempid) js-file (-> evt blob/evt->js-files first) attributes (comp/component-options ui ::form/attributes) id-attr (comp/component-options ui ::form/id) id-key (::attr/qualified-key id-attr) {::attr/keys [qualified-key] :as sha-attr} (first (filter ::blob/store attributes)) target (conj (comp/get-ident form-instance) k) new-entity (fs/add-form-config ui {id-key new-id qualified-key ""})] (merge/merge-component! form-instance ui new-entity :append target) (blob/upload-file! form-instance sha-attr js-file {:file-ident [id-key new-id]}) (comp/set-state! this {:input-key (<KEY>))})))}))) ui-factory (comp/computed-factory ui {:keyfn (fn [item] (-> ui (comp/get-ident item) second str))})] (div :.ui.basic.segment {:key (str k)} (dom/h2 :.ui.header title) (when (or (nil? add-position) (= :top add-position)) add) (if (seq items) (div :.ui.very.relaxed.items (mapv (fn [props] (ui-factory props (merge env {::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if delete? (?! delete? props) false)}))) items)) (div :.ui.message "None")) (when (= :bottom add-position) add)))) (def ui-many-files (comp/factory ManyFiles {:keyfn (fn [{:keys [attribute]}] (::attr/qualified-key attribute))})) (defn file-ref-container [env {::attr/keys [cardinality] :as attr} options] (if (= :many cardinality) (ui-many-files {:env env :attribute attr :options options}) (render-single-file env attr options))) (defn render-attribute [env attr {::form/keys [subforms] :as options}] (let [{k ::attr/qualified-key} attr] (if (contains? subforms k) (let [render-ref (or (form/ref-container-renderer env attr) standard-ref-container)] (render-ref env attr options)) (form/render-field env attr)))) (def n-fields-string {1 "one field" 2 "two fields" 3 "three fields" 4 "four fields" 5 "five fields" 6 "six fields" 7 "seven fields"}) (def attribute-map (memoize (fn [attributes] (reduce (fn [m {::attr/keys [qualified-key] :as attr}] (assoc m qualified-key attr)) {} attributes)))) (defn- render-layout* [env options k->attribute layout] (when #?(:clj true :cljs goog.DEBUG) (when-not (and (vector? layout) (every? vector? layout)) (log/error "::form/layout must be a vector of vectors!"))) (try (into [] (map-indexed (fn [idx row] (div {:key idx :className (n-fields-string (count row))} (mapv (fn [col] (enc/if-let [_ k->attribute attr (k->attribute col)] (render-attribute env attr options) (if (some-> options ::control/controls (get col)) (control/render-control (::form/form-instance env) col) (log/error "Missing attribute (or lookup) for" col)))) row))) layout)) (catch #?(:clj Exception :cljs :default) _))) (defn render-layout [env {::form/keys [attributes layout] :as options}] (let [k->attribute (attribute-map attributes)] (render-layout* env options k->attribute layout))) (defsc TabbedLayout [this env {::form/keys [attributes tabbed-layout] :as options}] {:initLocalState (fn [this] (try {:current-tab 0 :tab-details (memoize (fn [attributes tabbed-layout] (let [k->attr (attribute-map attributes) tab-labels (filterv string? tabbed-layout) tab-label->layout (into {} (map vec) (partition 2 (mapv first (partition-by string? tabbed-layout))))] {:k->attr k->attr :tab-labels tab-labels :tab-label->layout tab-label->layout})))} (catch #?(:clj Exception :cljs :default) _ (log/error "Cannot build tabs for tabbed layout. Check your tabbed-layout options for" (comp/component-name this)))))} (let [{:keys [tab-details current-tab]} (comp/get-state this) {:keys [k->attr tab-labels tab-label->layout]} (tab-details attributes tabbed-layout) active-layout (some->> current-tab (get tab-labels) (get tab-label->layout))] (div {:key (str current-tab)} (div :.ui.pointing.menu {} (map-indexed (fn [idx title] (dom/a :.item {:key (str idx) :onClick #(comp/set-state! this {:current-tab idx}) :classes [(when (= current-tab idx) "active")]} title)) tab-labels)) (div :.ui.segment (render-layout* env options k->attr active-layout))))) (def ui-tabbed-layout (comp/computed-factory TabbedLayout)) (declare standard-form-layout-renderer) (defsc StandardFormContainer [this {::form/keys [props computed-props form-instance master-form] :as env}] {:shouldComponentUpdate (fn [_ _ _] true)} (let [{::form/keys [can-delete?]} computed-props nested? (not= master-form form-instance) read-only-form? (or (?! (comp/component-options form-instance ::form/read-only?) form-instance) (?! (comp/component-options master-form ::form/read-only?) master-form)) invalid? (if read-only-form? false (form/invalid? env)) render-fields (or (form/form-layout-renderer env) standard-form-layout-renderer)] (when #?(:cljs goog.DEBUG :clj true) (let [valid? (if read-only-form? true (form/valid? env)) dirty? (if read-only-form? false (or (:ui/new? props) (fs/dirty? props)))] (log/debug "Form " (comp/component-name form-instance) " valid? " valid?) (log/debug "Form " (comp/component-name form-instance) " dirty? " dirty?))) (if nested? (div :.ui.segment (div :.ui.form {:classes [(when invalid? "error")] :key (str (comp/get-ident form-instance))} (when can-delete? (button :.ui.icon.primary.right.floated.button {:disabled (not can-delete?) :onClick (fn [] (form/delete-child! env))} (i :.times.icon))) (render-fields env))) (let [{::form/keys [title action-buttons controls]} (comp/component-options form-instance) title (?! title form-instance props) action-buttons (if action-buttons action-buttons form/standard-action-buttons)] (div :.ui.container {:key (str (comp/get-ident form-instance))} (div :.ui.top.attached.segment (dom/h3 :.ui.header title (div :.ui.right.floated.buttons (keep #(control/render-control master-form %) action-buttons)))) (div :.ui.attached.form {:classes [(when invalid? "error")]} (div :.ui.error.message (tr "The form has errors and cannot be saved.")) (div :.ui.attached.segment (render-fields env)))))))) (def standard-form-container (comp/factory StandardFormContainer)) (defn standard-form-layout-renderer [{::form/keys [form-instance] :as env}] (let [{::form/keys [attributes layout tabbed-layout] :as options} (comp/component-options form-instance)] (cond (vector? layout) (render-layout env options) (vector? tabbed-layout) (ui-tabbed-layout env options) :else (mapv (fn [attr] (render-attribute env attr options)) attributes)))) (defn- file-icon-renderer* [{::form/keys [form-instance] :as env}] (let [{::form/keys [attributes] :as options} (comp/component-options form-instance) attribute (first (filter ::blob/store attributes)) sha-key (::attr/qualified-key attribute) file-key (blob/filename-key sha-key) url-key (blob/url-key sha-key) props (comp/props form-instance) filename (get props file-key "File") dirty? (fs/dirty? props sha-key) failed? (blob/failed-upload? props sha-key) invalid? (validation/invalid-attribute-value? env attribute) pct (blob/upload-percentage props sha-key) sha (get props sha-key) url (get props url-key)] (if (blob/uploading? props sha-key) (dom/span :.item {:key (str sha)} (dom/div :.ui.tiny.image (dom/i :.huge.file.icon) (dom/div :.ui.active.red.loader {:style {:marginLeft "-10px"}}) (dom/div :.ui.bottom.attached.blue.progress {:data-percent pct} (div :.bar {:style {:transitionDuration "300ms" :width pct}} (div :.progress "")))) (div :.middle.aligned.content filename) (dom/button :.ui.red.icon.button {:onClick (fn [] (app/abort! form-instance sha) (form/delete-child! env))} (dom/i :.times.icon))) ((if dirty? dom/span dom/a) :.item {:target "_blank" :key (str sha) :href (str url "?filename=" filename) :onClick (fn [evt] #?(:cljs (when-not (or (not (blob/blob-downloadable? props sha-key)) (js/confirm "View/download?")) (evt/stop-propagation! evt) (evt/prevent-default! evt))))} (dom/div :.ui.tiny.image (if failed? (dom/i :.huge.skull.crossbones.icon) (dom/i :.huge.file.icon))) (div :.middle.aligned.content (str filename (cond failed? " (Upload failed. Delete and try again.)" dirty? " (unsaved)"))) (dom/button :.ui.red.icon.button {:onClick (fn [evt] (evt/stop-propagation! evt) (evt/prevent-default! evt) (when #?(:clj true :cljs (js/confirm "Permanently Delete File?")) (form/delete-child! env)))} (dom/i :.times.icon)))))) (defn file-icon-renderer [env] (file-icon-renderer* env))
true
(ns com.fulcrologic.rad.rendering.semantic-ui.form (:require [com.fulcrologic.rad.attributes :as attr] [com.fulcrologic.rad.options-util :refer [?! narrow-keyword]] [com.fulcrologic.rad.ui-validation :as validation] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.control :as control] [com.fulcrologic.rad.blob :as blob] [com.fulcrologic.fulcro.dom.events :as evt] [com.fulcrologic.fulcro-i18n.i18n :refer [tr]] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.application :as app] #?(:cljs [com.fulcrologic.fulcro.dom :as dom :refer [div h3 button i span]] :clj [com.fulcrologic.fulcro.dom-server :as dom :refer [div h3 button i span]]) [com.fulcrologic.fulcro.dom.html-entities :as ent] [com.fulcrologic.fulcro.algorithms.form-state :as fs] [com.fulcrologic.fulcro.algorithms.tempid :as tempid] [com.fulcrologic.fulcro.algorithms.merge :as merge] [taoensso.encore :as enc] [taoensso.timbre :as log])) (defn render-to-many [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{:semantic-ui/keys [add-position] ::form/keys [ui title can-delete? can-add? added-via-upload?]} (get subforms k) form-instance-props (comp/props form-instance) read-only? (form/read-only? form-instance attr) add? (if read-only? false (?! can-add? form-instance attr)) delete? (fn [item] (and (not read-only?) (?! can-delete? form-instance item))) items (get form-instance-props k) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-instance-props) invalid? (validation/invalid-attribute-value? env attr) validation-message (validation/validation-error-message env attr) add (when (or (nil? add?) add?) (let [order (if (keyword? add?) add? :append)] (if (?! added-via-upload? env) (dom/input {:type "file" :onChange (fn [evt] (log/info "UPLOAD FILE!!!") (let [new-id (tempid/tempid) js-file (-> evt blob/evt->js-files first) attributes (comp/component-options ui ::form/attributes) id-attr (comp/component-options ui ::form/id) id-key (::attr/qualified-key id-attr) {::attr/keys [qualified-key] :as sha-attr} (first (filter ::blob/store attributes)) target (conj (comp/get-ident form-instance) k) new-entity (fs/add-form-config ui {id-key new-id qualified-key ""})] (merge/merge-component! form-instance ui new-entity order target) (blob/upload-file! form-instance sha-attr js-file {:file-ident [id-key new-id]})))}) (button :.ui.tiny.icon.button {:onClick (fn [_] (form/add-child! (assoc env ::form/order order ::form/parent-relation k ::form/parent form-instance ::form/child-class ui)))} (i :.plus.icon))))) ui-factory (comp/computed-factory ui {:keyfn (fn [item] (-> ui (comp/get-ident item) second str))})] (div :.ui.container {:key (str k)} (h3 title (span ent/nbsp ent/nbsp) (when (or (nil? add-position) (= :top add-position)) add)) (when invalid? (div :.ui.error.message validation-message)) (if (seq items) (div :.ui.segments (mapv (fn [props] (ui-factory props (merge env {::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if delete? (delete? props) false)}))) items)) (div :.ui.message "None.")) (when (= :bottom add-position) add)))) (defn render-to-one [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{::form/keys [ui can-delete? title]} (get subforms k) form-props (comp/props form-instance) props (get form-props k) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-props) ui-factory (comp/computed-factory ui) invalid? (validation/invalid-attribute-value? env attr) validation-message (validation/validation-error-message env attr) std-props {::form/nested? true ::form/parent form-instance ::form/parent-relation k ::form/can-delete? (or (?! can-delete? form-instance form-props) false)}] (cond props (div {:key (str k)} (h3 :.ui.header title) (when invalid? (div :.ui.error.message validation-message)) (ui-factory props (merge env std-props))) :else (div {:key (str k)} (h3 :.ui.header title) (button {:onClick (fn [] (form/add-child! (assoc env ::form/parent-relation k ::form/parent form-instance ::form/child-class ui)))} "Create"))))) (defn standard-ref-container [env {::attr/keys [cardinality] :as attr} options] (if (= :many cardinality) (render-to-many env attr options) (render-to-one env attr options))) (defn render-single-file [{::form/keys [form-instance] :as env} {k ::attr/qualified-key :as attr} {::form/keys [subforms] :as options}] (let [{::form/keys [ui can-delete?]} (get subforms k) parent (comp/props form-instance) form-props (comp/props form-instance) props (get form-props k) ui-factory (comp/computed-factory ui) label (form/field-label env attr) std-props {::form/nested? true ::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if can-delete? (can-delete? parent props) false)}] (if props (div :.field {:key (str k)} (dom/label label) (ui-factory props (merge env std-props))) (div {:key (str k)} (div "Upload??? (TODO)"))))) (defsc ManyFiles [this {{::form/keys [form-instance master-form] :as env} :env {k ::attr/qualified-key :as attr} :attribute {::form/keys [subforms] :as options} :options}] {:initLocalState (fn [this] {:input-key (str (rand-int 1000000))})} (let [{:semantic-ui/keys [add-position] ::form/keys [ui title can-delete? can-add? sort-children]} (get subforms k) form-instance-props (comp/props form-instance) read-only? (or (form/read-only? master-form attr) (form/read-only? form-instance attr)) add? (if read-only? false (?! can-add? form-instance attr)) delete? (if read-only? false (fn [item] (?! can-delete? form-instance item))) items (-> form-instance comp/props k (cond-> sort-children sort-children)) title (?! (or title (some-> ui (comp/component-options ::form/title)) "") form-instance form-instance-props) upload-id (str k "-file-upload") add (when (or (nil? add?) add?) (dom/div (dom/label :.ui.green.button {:htmlFor upload-id} (dom/i :.ui.plus.icon) "Add File") (dom/input {:type "file" ;; trick: changing the key on change clears the input, so a failed upload can be retried :key (comp/get-state this :input-key) :id upload-id :style {:zIndex -1 :width "1px" :height "1px" :opacity 0} :onChange (fn [evt] (let [new-id (tempid/tempid) js-file (-> evt blob/evt->js-files first) attributes (comp/component-options ui ::form/attributes) id-attr (comp/component-options ui ::form/id) id-key (::attr/qualified-key id-attr) {::attr/keys [qualified-key] :as sha-attr} (first (filter ::blob/store attributes)) target (conj (comp/get-ident form-instance) k) new-entity (fs/add-form-config ui {id-key new-id qualified-key ""})] (merge/merge-component! form-instance ui new-entity :append target) (blob/upload-file! form-instance sha-attr js-file {:file-ident [id-key new-id]}) (comp/set-state! this {:input-key (PI:KEY:<KEY>END_PI))})))}))) ui-factory (comp/computed-factory ui {:keyfn (fn [item] (-> ui (comp/get-ident item) second str))})] (div :.ui.basic.segment {:key (str k)} (dom/h2 :.ui.header title) (when (or (nil? add-position) (= :top add-position)) add) (if (seq items) (div :.ui.very.relaxed.items (mapv (fn [props] (ui-factory props (merge env {::form/parent form-instance ::form/parent-relation k ::form/can-delete? (if delete? (?! delete? props) false)}))) items)) (div :.ui.message "None")) (when (= :bottom add-position) add)))) (def ui-many-files (comp/factory ManyFiles {:keyfn (fn [{:keys [attribute]}] (::attr/qualified-key attribute))})) (defn file-ref-container [env {::attr/keys [cardinality] :as attr} options] (if (= :many cardinality) (ui-many-files {:env env :attribute attr :options options}) (render-single-file env attr options))) (defn render-attribute [env attr {::form/keys [subforms] :as options}] (let [{k ::attr/qualified-key} attr] (if (contains? subforms k) (let [render-ref (or (form/ref-container-renderer env attr) standard-ref-container)] (render-ref env attr options)) (form/render-field env attr)))) (def n-fields-string {1 "one field" 2 "two fields" 3 "three fields" 4 "four fields" 5 "five fields" 6 "six fields" 7 "seven fields"}) (def attribute-map (memoize (fn [attributes] (reduce (fn [m {::attr/keys [qualified-key] :as attr}] (assoc m qualified-key attr)) {} attributes)))) (defn- render-layout* [env options k->attribute layout] (when #?(:clj true :cljs goog.DEBUG) (when-not (and (vector? layout) (every? vector? layout)) (log/error "::form/layout must be a vector of vectors!"))) (try (into [] (map-indexed (fn [idx row] (div {:key idx :className (n-fields-string (count row))} (mapv (fn [col] (enc/if-let [_ k->attribute attr (k->attribute col)] (render-attribute env attr options) (if (some-> options ::control/controls (get col)) (control/render-control (::form/form-instance env) col) (log/error "Missing attribute (or lookup) for" col)))) row))) layout)) (catch #?(:clj Exception :cljs :default) _))) (defn render-layout [env {::form/keys [attributes layout] :as options}] (let [k->attribute (attribute-map attributes)] (render-layout* env options k->attribute layout))) (defsc TabbedLayout [this env {::form/keys [attributes tabbed-layout] :as options}] {:initLocalState (fn [this] (try {:current-tab 0 :tab-details (memoize (fn [attributes tabbed-layout] (let [k->attr (attribute-map attributes) tab-labels (filterv string? tabbed-layout) tab-label->layout (into {} (map vec) (partition 2 (mapv first (partition-by string? tabbed-layout))))] {:k->attr k->attr :tab-labels tab-labels :tab-label->layout tab-label->layout})))} (catch #?(:clj Exception :cljs :default) _ (log/error "Cannot build tabs for tabbed layout. Check your tabbed-layout options for" (comp/component-name this)))))} (let [{:keys [tab-details current-tab]} (comp/get-state this) {:keys [k->attr tab-labels tab-label->layout]} (tab-details attributes tabbed-layout) active-layout (some->> current-tab (get tab-labels) (get tab-label->layout))] (div {:key (str current-tab)} (div :.ui.pointing.menu {} (map-indexed (fn [idx title] (dom/a :.item {:key (str idx) :onClick #(comp/set-state! this {:current-tab idx}) :classes [(when (= current-tab idx) "active")]} title)) tab-labels)) (div :.ui.segment (render-layout* env options k->attr active-layout))))) (def ui-tabbed-layout (comp/computed-factory TabbedLayout)) (declare standard-form-layout-renderer) (defsc StandardFormContainer [this {::form/keys [props computed-props form-instance master-form] :as env}] {:shouldComponentUpdate (fn [_ _ _] true)} (let [{::form/keys [can-delete?]} computed-props nested? (not= master-form form-instance) read-only-form? (or (?! (comp/component-options form-instance ::form/read-only?) form-instance) (?! (comp/component-options master-form ::form/read-only?) master-form)) invalid? (if read-only-form? false (form/invalid? env)) render-fields (or (form/form-layout-renderer env) standard-form-layout-renderer)] (when #?(:cljs goog.DEBUG :clj true) (let [valid? (if read-only-form? true (form/valid? env)) dirty? (if read-only-form? false (or (:ui/new? props) (fs/dirty? props)))] (log/debug "Form " (comp/component-name form-instance) " valid? " valid?) (log/debug "Form " (comp/component-name form-instance) " dirty? " dirty?))) (if nested? (div :.ui.segment (div :.ui.form {:classes [(when invalid? "error")] :key (str (comp/get-ident form-instance))} (when can-delete? (button :.ui.icon.primary.right.floated.button {:disabled (not can-delete?) :onClick (fn [] (form/delete-child! env))} (i :.times.icon))) (render-fields env))) (let [{::form/keys [title action-buttons controls]} (comp/component-options form-instance) title (?! title form-instance props) action-buttons (if action-buttons action-buttons form/standard-action-buttons)] (div :.ui.container {:key (str (comp/get-ident form-instance))} (div :.ui.top.attached.segment (dom/h3 :.ui.header title (div :.ui.right.floated.buttons (keep #(control/render-control master-form %) action-buttons)))) (div :.ui.attached.form {:classes [(when invalid? "error")]} (div :.ui.error.message (tr "The form has errors and cannot be saved.")) (div :.ui.attached.segment (render-fields env)))))))) (def standard-form-container (comp/factory StandardFormContainer)) (defn standard-form-layout-renderer [{::form/keys [form-instance] :as env}] (let [{::form/keys [attributes layout tabbed-layout] :as options} (comp/component-options form-instance)] (cond (vector? layout) (render-layout env options) (vector? tabbed-layout) (ui-tabbed-layout env options) :else (mapv (fn [attr] (render-attribute env attr options)) attributes)))) (defn- file-icon-renderer* [{::form/keys [form-instance] :as env}] (let [{::form/keys [attributes] :as options} (comp/component-options form-instance) attribute (first (filter ::blob/store attributes)) sha-key (::attr/qualified-key attribute) file-key (blob/filename-key sha-key) url-key (blob/url-key sha-key) props (comp/props form-instance) filename (get props file-key "File") dirty? (fs/dirty? props sha-key) failed? (blob/failed-upload? props sha-key) invalid? (validation/invalid-attribute-value? env attribute) pct (blob/upload-percentage props sha-key) sha (get props sha-key) url (get props url-key)] (if (blob/uploading? props sha-key) (dom/span :.item {:key (str sha)} (dom/div :.ui.tiny.image (dom/i :.huge.file.icon) (dom/div :.ui.active.red.loader {:style {:marginLeft "-10px"}}) (dom/div :.ui.bottom.attached.blue.progress {:data-percent pct} (div :.bar {:style {:transitionDuration "300ms" :width pct}} (div :.progress "")))) (div :.middle.aligned.content filename) (dom/button :.ui.red.icon.button {:onClick (fn [] (app/abort! form-instance sha) (form/delete-child! env))} (dom/i :.times.icon))) ((if dirty? dom/span dom/a) :.item {:target "_blank" :key (str sha) :href (str url "?filename=" filename) :onClick (fn [evt] #?(:cljs (when-not (or (not (blob/blob-downloadable? props sha-key)) (js/confirm "View/download?")) (evt/stop-propagation! evt) (evt/prevent-default! evt))))} (dom/div :.ui.tiny.image (if failed? (dom/i :.huge.skull.crossbones.icon) (dom/i :.huge.file.icon))) (div :.middle.aligned.content (str filename (cond failed? " (Upload failed. Delete and try again.)" dirty? " (unsaved)"))) (dom/button :.ui.red.icon.button {:onClick (fn [evt] (evt/stop-propagation! evt) (evt/prevent-default! evt) (when #?(:clj true :cljs (js/confirm "Permanently Delete File?")) (form/delete-child! env)))} (dom/i :.times.icon)))))) (defn file-icon-renderer [env] (file-icon-renderer* env))
[ { "context": "e is a cellular automaton devised by mathematician John Conway. \n;;\n;; The 'board' consists of both live (#) and", "end": 98, "score": 0.9996263384819031, "start": 87, "tag": "NAME", "value": "John Conway" } ]
task094 - Game of Life.clj
pavolvarga/4clojure
0
;; Game of Life ;; The game of life is a cellular automaton devised by mathematician John Conway. ;; ;; The 'board' consists of both live (#) and dead ( ) cells. ;; Each cell interacts with its eight neighbours (horizontal, vertical, diagonal), ;; and its next state is dependent on the following rules: ;; ;; 1) Any live cell with fewer than two live neighbours dies, as if caused by under-population. ;; 2) Any live cell with two or three live neighbours lives on to the next generation. ;; 3) Any live cell with more than three live neighbours dies, as if by overcrowding. ;; 4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. ;; ;; Write a function that accepts a board, and returns a board representing the next generation of cells. (defn next-gen-gof [board] (let [live-cell \# dead-cell \space convert-to-vectors (fn [board] "Converts vector of strings into vector of vectors of characters" (loop [b1 board, result []] (if (empty? b1) result (recur (rest b1) (conj result (vec (first b1))))))) gen-indexes (fn [rows columns] "Generate map of indexes" (for [i (range 0 rows), j (range 0 columns)] {:row i, :col j})) gen-idxs-of-neighbours (fn [idx rows columns] "Return indexes of 8 neighbours, filter out indexes outside of the board" (let [{r :row, c :col} idx dr (dec r) dc (dec c) ir (inc r) ic (inc c) r1 [{:row dr, :col dc}, {:row dr, :col c}, {:row dr, :col ic}, {:row r, :col dc}, , {:row r , :col ic}, {:row ir, :col dc}, {:row ir, :col c}, {:row ir, :col ic}] pred (fn [{r :row, c :col}] (cond (neg? r) false (neg? c) false (> r (dec rows)) false (> c (dec columns)) false :default true))] (filter pred r1))) is-live? (fn [c] (if (= live-cell c) true false)) get-vals (fn [board, indexes] "Get values from the board at indexes" (loop [idx1 indexes, result []] (if (empty? idx1) result (let [{r :row, c :col} (first idx1) v ((board r) c)] (recur (rest idx1) (conj result v)))))) how-many-is-alive (fn [neighbours] "Return count of live cells from input" (count (filter is-live? neighbours))) evolve-for-live (fn [neighbours] "Depending on number of live neighbours evolve actual live-cell according to rules" (let [alive (how-many-is-alive neighbours)] (cond (< alive 2) dead-cell (or (= alive 2) (= alive 3)) live-cell (> alive 3) dead-cell))) evolve-for-dead (fn [neighbours] "Depending on number of dead neighbours evolve actual dead-cell according to rules" (let [alive (how-many-is-alive neighbours)] (if (= alive 3) live-cell dead-cell))) evolve-cell (fn [cell neighbours] "Evolve the cell depening on type and number of neighbours according to rules" (if (is-live? cell) (evolve-for-live neighbours) (evolve-for-dead neighbours))) evolve-board (fn [board] (let [vectorized-board (convert-to-vectors board) rows (count vectorized-board) columns (count (first vectorized-board)) indexes (gen-indexes rows columns)] (loop [idxs1 indexes, result []] (if (empty? idxs1) result (let [idx (first idxs1) r (idx :row) c (idx :col) cell ((vectorized-board r) c) idxs-of-neighs (gen-idxs-of-neighbours idx rows columns) neighbours (get-vals vectorized-board idxs-of-neighs) next-cell (evolve-cell cell neighbours)] (recur (rest idxs1) (conj result next-cell))))))) next-board (evolve-board board) partitioned-board (partition (-> board first count) next-board)] (map #(apply str %) partitioned-board))) ;; Tests (println (= (next-gen-gof [ " " " ## " " ## " " ## " " ## " " "]) [" " " ## " " # " " # " " ## " " "])) (println (= (next-gen-gof [ " " " " " ### " " " " "]) [" " " # " " # " " # " " "])) (println (= (next-gen-gof [ " " " " " ### " " ### " " " " "]) [" " " # " " # # " " # # " " # " " "]))
115971
;; Game of Life ;; The game of life is a cellular automaton devised by mathematician <NAME>. ;; ;; The 'board' consists of both live (#) and dead ( ) cells. ;; Each cell interacts with its eight neighbours (horizontal, vertical, diagonal), ;; and its next state is dependent on the following rules: ;; ;; 1) Any live cell with fewer than two live neighbours dies, as if caused by under-population. ;; 2) Any live cell with two or three live neighbours lives on to the next generation. ;; 3) Any live cell with more than three live neighbours dies, as if by overcrowding. ;; 4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. ;; ;; Write a function that accepts a board, and returns a board representing the next generation of cells. (defn next-gen-gof [board] (let [live-cell \# dead-cell \space convert-to-vectors (fn [board] "Converts vector of strings into vector of vectors of characters" (loop [b1 board, result []] (if (empty? b1) result (recur (rest b1) (conj result (vec (first b1))))))) gen-indexes (fn [rows columns] "Generate map of indexes" (for [i (range 0 rows), j (range 0 columns)] {:row i, :col j})) gen-idxs-of-neighbours (fn [idx rows columns] "Return indexes of 8 neighbours, filter out indexes outside of the board" (let [{r :row, c :col} idx dr (dec r) dc (dec c) ir (inc r) ic (inc c) r1 [{:row dr, :col dc}, {:row dr, :col c}, {:row dr, :col ic}, {:row r, :col dc}, , {:row r , :col ic}, {:row ir, :col dc}, {:row ir, :col c}, {:row ir, :col ic}] pred (fn [{r :row, c :col}] (cond (neg? r) false (neg? c) false (> r (dec rows)) false (> c (dec columns)) false :default true))] (filter pred r1))) is-live? (fn [c] (if (= live-cell c) true false)) get-vals (fn [board, indexes] "Get values from the board at indexes" (loop [idx1 indexes, result []] (if (empty? idx1) result (let [{r :row, c :col} (first idx1) v ((board r) c)] (recur (rest idx1) (conj result v)))))) how-many-is-alive (fn [neighbours] "Return count of live cells from input" (count (filter is-live? neighbours))) evolve-for-live (fn [neighbours] "Depending on number of live neighbours evolve actual live-cell according to rules" (let [alive (how-many-is-alive neighbours)] (cond (< alive 2) dead-cell (or (= alive 2) (= alive 3)) live-cell (> alive 3) dead-cell))) evolve-for-dead (fn [neighbours] "Depending on number of dead neighbours evolve actual dead-cell according to rules" (let [alive (how-many-is-alive neighbours)] (if (= alive 3) live-cell dead-cell))) evolve-cell (fn [cell neighbours] "Evolve the cell depening on type and number of neighbours according to rules" (if (is-live? cell) (evolve-for-live neighbours) (evolve-for-dead neighbours))) evolve-board (fn [board] (let [vectorized-board (convert-to-vectors board) rows (count vectorized-board) columns (count (first vectorized-board)) indexes (gen-indexes rows columns)] (loop [idxs1 indexes, result []] (if (empty? idxs1) result (let [idx (first idxs1) r (idx :row) c (idx :col) cell ((vectorized-board r) c) idxs-of-neighs (gen-idxs-of-neighbours idx rows columns) neighbours (get-vals vectorized-board idxs-of-neighs) next-cell (evolve-cell cell neighbours)] (recur (rest idxs1) (conj result next-cell))))))) next-board (evolve-board board) partitioned-board (partition (-> board first count) next-board)] (map #(apply str %) partitioned-board))) ;; Tests (println (= (next-gen-gof [ " " " ## " " ## " " ## " " ## " " "]) [" " " ## " " # " " # " " ## " " "])) (println (= (next-gen-gof [ " " " " " ### " " " " "]) [" " " # " " # " " # " " "])) (println (= (next-gen-gof [ " " " " " ### " " ### " " " " "]) [" " " # " " # # " " # # " " # " " "]))
true
;; Game of Life ;; The game of life is a cellular automaton devised by mathematician PI:NAME:<NAME>END_PI. ;; ;; The 'board' consists of both live (#) and dead ( ) cells. ;; Each cell interacts with its eight neighbours (horizontal, vertical, diagonal), ;; and its next state is dependent on the following rules: ;; ;; 1) Any live cell with fewer than two live neighbours dies, as if caused by under-population. ;; 2) Any live cell with two or three live neighbours lives on to the next generation. ;; 3) Any live cell with more than three live neighbours dies, as if by overcrowding. ;; 4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. ;; ;; Write a function that accepts a board, and returns a board representing the next generation of cells. (defn next-gen-gof [board] (let [live-cell \# dead-cell \space convert-to-vectors (fn [board] "Converts vector of strings into vector of vectors of characters" (loop [b1 board, result []] (if (empty? b1) result (recur (rest b1) (conj result (vec (first b1))))))) gen-indexes (fn [rows columns] "Generate map of indexes" (for [i (range 0 rows), j (range 0 columns)] {:row i, :col j})) gen-idxs-of-neighbours (fn [idx rows columns] "Return indexes of 8 neighbours, filter out indexes outside of the board" (let [{r :row, c :col} idx dr (dec r) dc (dec c) ir (inc r) ic (inc c) r1 [{:row dr, :col dc}, {:row dr, :col c}, {:row dr, :col ic}, {:row r, :col dc}, , {:row r , :col ic}, {:row ir, :col dc}, {:row ir, :col c}, {:row ir, :col ic}] pred (fn [{r :row, c :col}] (cond (neg? r) false (neg? c) false (> r (dec rows)) false (> c (dec columns)) false :default true))] (filter pred r1))) is-live? (fn [c] (if (= live-cell c) true false)) get-vals (fn [board, indexes] "Get values from the board at indexes" (loop [idx1 indexes, result []] (if (empty? idx1) result (let [{r :row, c :col} (first idx1) v ((board r) c)] (recur (rest idx1) (conj result v)))))) how-many-is-alive (fn [neighbours] "Return count of live cells from input" (count (filter is-live? neighbours))) evolve-for-live (fn [neighbours] "Depending on number of live neighbours evolve actual live-cell according to rules" (let [alive (how-many-is-alive neighbours)] (cond (< alive 2) dead-cell (or (= alive 2) (= alive 3)) live-cell (> alive 3) dead-cell))) evolve-for-dead (fn [neighbours] "Depending on number of dead neighbours evolve actual dead-cell according to rules" (let [alive (how-many-is-alive neighbours)] (if (= alive 3) live-cell dead-cell))) evolve-cell (fn [cell neighbours] "Evolve the cell depening on type and number of neighbours according to rules" (if (is-live? cell) (evolve-for-live neighbours) (evolve-for-dead neighbours))) evolve-board (fn [board] (let [vectorized-board (convert-to-vectors board) rows (count vectorized-board) columns (count (first vectorized-board)) indexes (gen-indexes rows columns)] (loop [idxs1 indexes, result []] (if (empty? idxs1) result (let [idx (first idxs1) r (idx :row) c (idx :col) cell ((vectorized-board r) c) idxs-of-neighs (gen-idxs-of-neighbours idx rows columns) neighbours (get-vals vectorized-board idxs-of-neighs) next-cell (evolve-cell cell neighbours)] (recur (rest idxs1) (conj result next-cell))))))) next-board (evolve-board board) partitioned-board (partition (-> board first count) next-board)] (map #(apply str %) partitioned-board))) ;; Tests (println (= (next-gen-gof [ " " " ## " " ## " " ## " " ## " " "]) [" " " ## " " # " " # " " ## " " "])) (println (= (next-gen-gof [ " " " " " ### " " " " "]) [" " " # " " # " " # " " "])) (println (= (next-gen-gof [ " " " " " ### " " ### " " " " "]) [" " " # " " # # " " # # " " # " " "]))
[ { "context": "\n parent :parent\n key :keymap\n name :name\n id :id\n kind :pred\n :else :bug)))\n", "end": 1126, "score": 0.949219286441803, "start": 1122, "tag": "NAME", "value": "name" } ]
datastore/src/org/mobileink/migae/datastore/key.clj
mobileink/migae
0
(ns org.mobileink.migae.datastore.key (:refer-clojure :exclude [name hash]) (:import [com.google.appengine.api.datastore KeyFactory Key])) (defn kind [^Key key] (.getKind key)) (defn name [^Key key] (.getName key)) (defn id [^Key key] (.getId key)) (defn name-space [^Key key] (.getNamespace key)) (defn parent [^Key key] (.getParent key)) (defn compareTo [^Key key] (.compareTo key)) (defn equals [^Object obj] (.equals obj)) (defn appId [^Key key] (.getAppId key)) (defn hash [^Key key] (.hashCode key)) ;; ################ (defmulti child (fn [key {kind :_kind name :_name id :_id}] (cond name :name id :id))) (defmethod child :name [key {kind :_kind name :_name}] (.getChild key (clojure.core/name kind) name)) (defmethod child :id [key {kind :_kind id :_id}] (.getChild key kind id)) ;; ################ (defmulti make (fn [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] (cond (= (type args) com.google.appengine.api.datastore.Key) :key parent :parent key :keymap name :name id :id kind :pred :else :bug))) ;; (cond ;; ;; (type (first args)) com.google.appengine.api.datastore.Key) :parent ;; (= (type (first args)) java.lang.String) :child ;; (= (type (first args)) java.lang.String) :name ;; (= (type (first args))java.lang.Long) :id))) ;; (defmethod make :parent ;; [{parent :_parent kind :_kind name :_name}] ;; (KeyFactory/createKey parent (clojure.core/name kind) name)) (defmethod make :parent [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] (let [pkind (:_kind parent) pname (:_name parent) pKey (KeyFactory/createKey (clojure.core/name pkind) pname)] (KeyFactory/createKey pKey (clojure.core/name kind) name))) (defmethod make :name [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] ; [kind name] (KeyFactory/createKey (clojure.core/name kind) name)) (defmethod make :id [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] ; [kind id] (KeyFactory/createKey (clojure.core/name kind) id)) ;; Key k = new KeyFactory.Builder("Person", "GreatGrandpa") ;; .addChild("Person", "Grandpa") ;; .addChild("Person", "Dad") ;; .addChild("Person", "Me") ;; .getKey(); ;; (defmethod make :path ;; [{path :_path}] ;; (-> KeyFactory$Builder (clojure.core/name kind) id) ;; ) ;; ################ (defn to-string [^Key key] (.keyToString key)) (defn string-to-key [^String s] (.stringToKey s)) ;; ################ ;; KeyFactory$Builder
68099
(ns org.mobileink.migae.datastore.key (:refer-clojure :exclude [name hash]) (:import [com.google.appengine.api.datastore KeyFactory Key])) (defn kind [^Key key] (.getKind key)) (defn name [^Key key] (.getName key)) (defn id [^Key key] (.getId key)) (defn name-space [^Key key] (.getNamespace key)) (defn parent [^Key key] (.getParent key)) (defn compareTo [^Key key] (.compareTo key)) (defn equals [^Object obj] (.equals obj)) (defn appId [^Key key] (.getAppId key)) (defn hash [^Key key] (.hashCode key)) ;; ################ (defmulti child (fn [key {kind :_kind name :_name id :_id}] (cond name :name id :id))) (defmethod child :name [key {kind :_kind name :_name}] (.getChild key (clojure.core/name kind) name)) (defmethod child :id [key {kind :_kind id :_id}] (.getChild key kind id)) ;; ################ (defmulti make (fn [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] (cond (= (type args) com.google.appengine.api.datastore.Key) :key parent :parent key :keymap name :<NAME> id :id kind :pred :else :bug))) ;; (cond ;; ;; (type (first args)) com.google.appengine.api.datastore.Key) :parent ;; (= (type (first args)) java.lang.String) :child ;; (= (type (first args)) java.lang.String) :name ;; (= (type (first args))java.lang.Long) :id))) ;; (defmethod make :parent ;; [{parent :_parent kind :_kind name :_name}] ;; (KeyFactory/createKey parent (clojure.core/name kind) name)) (defmethod make :parent [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] (let [pkind (:_kind parent) pname (:_name parent) pKey (KeyFactory/createKey (clojure.core/name pkind) pname)] (KeyFactory/createKey pKey (clojure.core/name kind) name))) (defmethod make :name [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] ; [kind name] (KeyFactory/createKey (clojure.core/name kind) name)) (defmethod make :id [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] ; [kind id] (KeyFactory/createKey (clojure.core/name kind) id)) ;; Key k = new KeyFactory.Builder("Person", "GreatGrandpa") ;; .addChild("Person", "Grandpa") ;; .addChild("Person", "Dad") ;; .addChild("Person", "Me") ;; .getKey(); ;; (defmethod make :path ;; [{path :_path}] ;; (-> KeyFactory$Builder (clojure.core/name kind) id) ;; ) ;; ################ (defn to-string [^Key key] (.keyToString key)) (defn string-to-key [^String s] (.stringToKey s)) ;; ################ ;; KeyFactory$Builder
true
(ns org.mobileink.migae.datastore.key (:refer-clojure :exclude [name hash]) (:import [com.google.appengine.api.datastore KeyFactory Key])) (defn kind [^Key key] (.getKind key)) (defn name [^Key key] (.getName key)) (defn id [^Key key] (.getId key)) (defn name-space [^Key key] (.getNamespace key)) (defn parent [^Key key] (.getParent key)) (defn compareTo [^Key key] (.compareTo key)) (defn equals [^Object obj] (.equals obj)) (defn appId [^Key key] (.getAppId key)) (defn hash [^Key key] (.hashCode key)) ;; ################ (defmulti child (fn [key {kind :_kind name :_name id :_id}] (cond name :name id :id))) (defmethod child :name [key {kind :_kind name :_name}] (.getChild key (clojure.core/name kind) name)) (defmethod child :id [key {kind :_kind id :_id}] (.getChild key kind id)) ;; ################ (defmulti make (fn [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] (cond (= (type args) com.google.appengine.api.datastore.Key) :key parent :parent key :keymap name :PI:NAME:<NAME>END_PI id :id kind :pred :else :bug))) ;; (cond ;; ;; (type (first args)) com.google.appengine.api.datastore.Key) :parent ;; (= (type (first args)) java.lang.String) :child ;; (= (type (first args)) java.lang.String) :name ;; (= (type (first args))java.lang.Long) :id))) ;; (defmethod make :parent ;; [{parent :_parent kind :_kind name :_name}] ;; (KeyFactory/createKey parent (clojure.core/name kind) name)) (defmethod make :parent [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] (let [pkind (:_kind parent) pname (:_name parent) pKey (KeyFactory/createKey (clojure.core/name pkind) pname)] (KeyFactory/createKey pKey (clojure.core/name kind) name))) (defmethod make :name [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] ; [kind name] (KeyFactory/createKey (clojure.core/name kind) name)) (defmethod make :id [{key :_key kind :_kind name :_name id :_id parent :_parent :as args}] ; [kind id] (KeyFactory/createKey (clojure.core/name kind) id)) ;; Key k = new KeyFactory.Builder("Person", "GreatGrandpa") ;; .addChild("Person", "Grandpa") ;; .addChild("Person", "Dad") ;; .addChild("Person", "Me") ;; .getKey(); ;; (defmethod make :path ;; [{path :_path}] ;; (-> KeyFactory$Builder (clojure.core/name kind) id) ;; ) ;; ################ (defn to-string [^Key key] (.keyToString key)) (defn string-to-key [^String s] (.stringToKey s)) ;; ################ ;; KeyFactory$Builder
[ { "context": "rnative multimethod implementations.\"\n {:author \"palisades dot lakes at gmail dot com\"\n :since \"2017-05-29\"\n :version \"2017-09-05\"}", "end": 297, "score": 0.9561319947242737, "start": 261, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/multix/intersects/bench.clj
palisades-lakes/multimethod-experiments
5
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.intersects.bench "Use criterium for alternative multimethod implementations." {:author "palisades dot lakes at gmail dot com" :since "2017-05-29" :version "2017-09-05"} (:require [palisades.lakes.bench.prng :as prng] [palisades.lakes.bench.generators :as g] [palisades.lakes.bench.core :as bench] [palisades.lakes.multix.intersects.defs :as defs])) ;;---------------------------------------------------------------- (def options {} #_{:n 1024 :samples 4}) ;; baselines: both args always IntegerInterval (bench/bench [g/IntegerIntervals defs/ii g/IntegerIntervals defs/ii] [defs/invokestatic defs/invokevirtual defs/invokeinterface defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;; 50% probability of repeat same method, ;; 1st arg always IntegerInterval ;; 2nd randomly IntegerInterval or DoubleInterval (bench/bench [g/Sets defs/r2 g/Sets defs/ii] [defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;; 1/9 probability of same method ;; 1st and 2nd args randomly from IntegerInterval, ;; DoubleInterval and SingletonSet (bench/bench [prng/objects defs/r3 prng/objects defs/r3] [defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;;---------------------------------------------------------------- #_(shutdown-agents) #_(System/exit 0)
107643
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.intersects.bench "Use criterium for alternative multimethod implementations." {:author "<EMAIL>" :since "2017-05-29" :version "2017-09-05"} (:require [palisades.lakes.bench.prng :as prng] [palisades.lakes.bench.generators :as g] [palisades.lakes.bench.core :as bench] [palisades.lakes.multix.intersects.defs :as defs])) ;;---------------------------------------------------------------- (def options {} #_{:n 1024 :samples 4}) ;; baselines: both args always IntegerInterval (bench/bench [g/IntegerIntervals defs/ii g/IntegerIntervals defs/ii] [defs/invokestatic defs/invokevirtual defs/invokeinterface defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;; 50% probability of repeat same method, ;; 1st arg always IntegerInterval ;; 2nd randomly IntegerInterval or DoubleInterval (bench/bench [g/Sets defs/r2 g/Sets defs/ii] [defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;; 1/9 probability of same method ;; 1st and 2nd args randomly from IntegerInterval, ;; DoubleInterval and SingletonSet (bench/bench [prng/objects defs/r3 prng/objects defs/r3] [defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;;---------------------------------------------------------------- #_(shutdown-agents) #_(System/exit 0)
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.intersects.bench "Use criterium for alternative multimethod implementations." {:author "PI:EMAIL:<EMAIL>END_PI" :since "2017-05-29" :version "2017-09-05"} (:require [palisades.lakes.bench.prng :as prng] [palisades.lakes.bench.generators :as g] [palisades.lakes.bench.core :as bench] [palisades.lakes.multix.intersects.defs :as defs])) ;;---------------------------------------------------------------- (def options {} #_{:n 1024 :samples 4}) ;; baselines: both args always IntegerInterval (bench/bench [g/IntegerIntervals defs/ii g/IntegerIntervals defs/ii] [defs/invokestatic defs/invokevirtual defs/invokeinterface defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;; 50% probability of repeat same method, ;; 1st arg always IntegerInterval ;; 2nd randomly IntegerInterval or DoubleInterval (bench/bench [g/Sets defs/r2 g/Sets defs/ii] [defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;; 1/9 probability of same method ;; 1st and 2nd args randomly from IntegerInterval, ;; DoubleInterval and SingletonSet (bench/bench [prng/objects defs/r3 prng/objects defs/r3] [defs/protocols defs/instanceof defs/instancefn defs/defmulti defs/hashmaps defs/signatures defs/nohierarchy defs/dynafun defs/dynamap] options) ;;---------------------------------------------------------------- #_(shutdown-agents) #_(System/exit 0)
[ { "context": " and we extend types to support this protocol.\n;\n; Eli Bendersky [http://eli.thegreenplace.net]\n; This code is in ", "end": 143, "score": 0.993743896484375, "start": 130, "tag": "NAME", "value": "Eli Bendersky" } ]
2016/expression-problem/clojure/expression/src/expression/protocols.clj
mikiec84/code-for-blog
1,199
; Solving the expression problem with protocols. Each operation is a protocol ; and we extend types to support this protocol. ; ; Eli Bendersky [http://eli.thegreenplace.net] ; This code is in the public domain. (ns expression.protocols) (defrecord Constant [value]) (defrecord BinaryPlus [lhs rhs]) (defprotocol Evaluatable (evaluate [this])) (defprotocol Stringable (stringify [this])) (extend-type Constant Evaluatable (evaluate [this] (:value this)) Stringable (stringify [this] (str (:value this)))) (extend-type BinaryPlus Evaluatable (evaluate [this] (+ (evaluate (:lhs this)) (evaluate (:rhs this)))) Stringable (stringify [this] (clojure.string/join " + " [(stringify (:lhs this)) (stringify (:rhs this))]))) ; Also have an alternative to use extend-protocol here... ; the core is 'extend' - a true matrix of type/op (def c1 (Constant. 1.1)) (def c2 (Constant. 2.2)) (def p1 (BinaryPlus. c1 c2)) (def p2 (BinaryPlus. p1 c2)) (evaluate p2) (stringify p2) ; "Adding" a new data type - the built-in double type and showing how to extend ; all protocols for it. (extend-type java.lang.Double Evaluatable (evaluate [this] this) Stringable (stringify [this] (str this))) (def f1 11.5) (def p3 (BinaryPlus. c1 f1)) (evaluate p3) (stringify p3) ; Adding a new protocol and implementing it for the existing data types. (defprotocol Serializable (serialize [this])) (extend-protocol Serializable Constant (serialize [this] [(type this) (:value this)]) BinaryPlus (serialize [this] [(type this) (serialize (:lhs this)) (serialize (:rhs this))])) (serialize p2)
43109
; Solving the expression problem with protocols. Each operation is a protocol ; and we extend types to support this protocol. ; ; <NAME> [http://eli.thegreenplace.net] ; This code is in the public domain. (ns expression.protocols) (defrecord Constant [value]) (defrecord BinaryPlus [lhs rhs]) (defprotocol Evaluatable (evaluate [this])) (defprotocol Stringable (stringify [this])) (extend-type Constant Evaluatable (evaluate [this] (:value this)) Stringable (stringify [this] (str (:value this)))) (extend-type BinaryPlus Evaluatable (evaluate [this] (+ (evaluate (:lhs this)) (evaluate (:rhs this)))) Stringable (stringify [this] (clojure.string/join " + " [(stringify (:lhs this)) (stringify (:rhs this))]))) ; Also have an alternative to use extend-protocol here... ; the core is 'extend' - a true matrix of type/op (def c1 (Constant. 1.1)) (def c2 (Constant. 2.2)) (def p1 (BinaryPlus. c1 c2)) (def p2 (BinaryPlus. p1 c2)) (evaluate p2) (stringify p2) ; "Adding" a new data type - the built-in double type and showing how to extend ; all protocols for it. (extend-type java.lang.Double Evaluatable (evaluate [this] this) Stringable (stringify [this] (str this))) (def f1 11.5) (def p3 (BinaryPlus. c1 f1)) (evaluate p3) (stringify p3) ; Adding a new protocol and implementing it for the existing data types. (defprotocol Serializable (serialize [this])) (extend-protocol Serializable Constant (serialize [this] [(type this) (:value this)]) BinaryPlus (serialize [this] [(type this) (serialize (:lhs this)) (serialize (:rhs this))])) (serialize p2)
true
; Solving the expression problem with protocols. Each operation is a protocol ; and we extend types to support this protocol. ; ; PI:NAME:<NAME>END_PI [http://eli.thegreenplace.net] ; This code is in the public domain. (ns expression.protocols) (defrecord Constant [value]) (defrecord BinaryPlus [lhs rhs]) (defprotocol Evaluatable (evaluate [this])) (defprotocol Stringable (stringify [this])) (extend-type Constant Evaluatable (evaluate [this] (:value this)) Stringable (stringify [this] (str (:value this)))) (extend-type BinaryPlus Evaluatable (evaluate [this] (+ (evaluate (:lhs this)) (evaluate (:rhs this)))) Stringable (stringify [this] (clojure.string/join " + " [(stringify (:lhs this)) (stringify (:rhs this))]))) ; Also have an alternative to use extend-protocol here... ; the core is 'extend' - a true matrix of type/op (def c1 (Constant. 1.1)) (def c2 (Constant. 2.2)) (def p1 (BinaryPlus. c1 c2)) (def p2 (BinaryPlus. p1 c2)) (evaluate p2) (stringify p2) ; "Adding" a new data type - the built-in double type and showing how to extend ; all protocols for it. (extend-type java.lang.Double Evaluatable (evaluate [this] this) Stringable (stringify [this] (str this))) (def f1 11.5) (def p3 (BinaryPlus. c1 f1)) (evaluate p3) (stringify p3) ; Adding a new protocol and implementing it for the existing data types. (defprotocol Serializable (serialize [this])) (extend-protocol Serializable Constant (serialize [this] [(type this) (:value this)]) BinaryPlus (serialize [this] [(type this) (serialize (:lhs this)) (serialize (:rhs this))])) (serialize p2)
[ { "context": "(temp-file \"hosts\") machine {:domain \"local\" :ip \"1.2.3.4\" :hostname \"iobar\" }]\n (with-redefs [hosts (agen", "end": 717, "score": 0.998879075050354, "start": 710, "tag": "IP_ADDRESS", "value": "1.2.3.4" }, { "context": "\n :domain \"local\" :dnsmasq \"192.168.1.1\" :user \"foo\" }) => truthy\n (await-for 10", "end": 1057, "score": 0.9997299313545227, "start": 1046, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "or hosts) => nil\n (slurp hosts-file) => \"1.2.3.4 iobar iobar.local\\n\")\n\n (fact \"removing a host", "end": 1202, "score": 0.9917948842048645, "start": 1195, "tag": "IP_ADDRESS", "value": "1.2.3.4" }, { "context": "\n :domain \"local\" :dnsmasq \"192.168.1.1\" :user \"foo\" :machine machine}) => truthy\n ", "end": 1422, "score": 0.9997203946113586, "start": 1411, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "\n :domain \"local\" :dnsmasq \"192.168.1.1\" :user \"foo\" }) => truthy\n (await-for 80", "end": 1818, "score": 0.9997182488441467, "start": 1807, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": " :domain \"local\" :dnsmasq \"192.168.1.1\" :user \"foo\" }) => truthy\n (await-for 8000 hosts) =>", "end": 1830, "score": 0.7466447949409485, "start": 1827, "tag": "USERNAME", "value": "foo" }, { "context": "\n :domain \"local\" :dnsmasq \"192.168.1.1\" :user \"foo\" }) => truthy\n (await-for 80", "end": 2163, "score": 0.9997131824493408, "start": 2152, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": " :domain \"local\" :dnsmasq \"192.168.1.1\" :user \"foo\" }) => truthy\n (await-for 8000 hosts) =>", "end": 2175, "score": 0.5137506723403931, "start": 2172, "tag": "USERNAME", "value": "foo" } ]
test/re_core/test/hooks.clj
celestial-ops/core
1
(ns re-core.test.hooks "Testing misc hooks like dns and hubot" (:require [clojure.java.shell :refer (sh)] [me.raynes.fs :refer (temp-file)] [hooks.dnsmasq :refer (update-dns hosts sudo)] [re-core.common :refer (import-logging)] [re-core.persistency.systems :as s] [supernal.sshj :refer (execute)] ) (:use midje.sweet)) (import-logging) (defn stubed-execute [s r] (let [run (temp-file "run")] (when-not (.contains s "dnsmasq") (spit run s) (assert (:exit (sh "bash" (str run))) 0)))) (defn fail "failing on purpouse" [s & r] (throw (RuntimeException. "somthing bad")) ) (let [hosts-file (temp-file "hosts") machine {:domain "local" :ip "1.2.3.4" :hostname "iobar" }] (with-redefs [hosts (agent hosts-file) execute stubed-execute s/get-system (fn [_] {:machine machine}) sudo ""] (fact "adding a host on create" :integration :agent (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 1000 hosts) => true (agent-error hosts) => nil (slurp hosts-file) => "1.2.3.4 iobar iobar.local\n") (fact "removing a host on stop" :integration :agent (update-dns {:event :success :workflow :stop :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" :machine machine}) => truthy (await-for 1000 hosts) => true (agent-error hosts) => nil (slurp hosts-file) => "") (fact "failing execution not in action" :integration :agent (send-off hosts fail) (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 8000 hosts) => true (agent-error hosts) => nil) (with-redefs [execute fail] (fact "failing execution in action" :integration :agent (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 8000 hosts) => true (agent-error hosts) => nil))))
112009
(ns re-core.test.hooks "Testing misc hooks like dns and hubot" (:require [clojure.java.shell :refer (sh)] [me.raynes.fs :refer (temp-file)] [hooks.dnsmasq :refer (update-dns hosts sudo)] [re-core.common :refer (import-logging)] [re-core.persistency.systems :as s] [supernal.sshj :refer (execute)] ) (:use midje.sweet)) (import-logging) (defn stubed-execute [s r] (let [run (temp-file "run")] (when-not (.contains s "dnsmasq") (spit run s) (assert (:exit (sh "bash" (str run))) 0)))) (defn fail "failing on purpouse" [s & r] (throw (RuntimeException. "somthing bad")) ) (let [hosts-file (temp-file "hosts") machine {:domain "local" :ip "172.16.58.3" :hostname "iobar" }] (with-redefs [hosts (agent hosts-file) execute stubed-execute s/get-system (fn [_] {:machine machine}) sudo ""] (fact "adding a host on create" :integration :agent (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 1000 hosts) => true (agent-error hosts) => nil (slurp hosts-file) => "172.16.58.3 iobar iobar.local\n") (fact "removing a host on stop" :integration :agent (update-dns {:event :success :workflow :stop :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" :machine machine}) => truthy (await-for 1000 hosts) => true (agent-error hosts) => nil (slurp hosts-file) => "") (fact "failing execution not in action" :integration :agent (send-off hosts fail) (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 8000 hosts) => true (agent-error hosts) => nil) (with-redefs [execute fail] (fact "failing execution in action" :integration :agent (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 8000 hosts) => true (agent-error hosts) => nil))))
true
(ns re-core.test.hooks "Testing misc hooks like dns and hubot" (:require [clojure.java.shell :refer (sh)] [me.raynes.fs :refer (temp-file)] [hooks.dnsmasq :refer (update-dns hosts sudo)] [re-core.common :refer (import-logging)] [re-core.persistency.systems :as s] [supernal.sshj :refer (execute)] ) (:use midje.sweet)) (import-logging) (defn stubed-execute [s r] (let [run (temp-file "run")] (when-not (.contains s "dnsmasq") (spit run s) (assert (:exit (sh "bash" (str run))) 0)))) (defn fail "failing on purpouse" [s & r] (throw (RuntimeException. "somthing bad")) ) (let [hosts-file (temp-file "hosts") machine {:domain "local" :ip "PI:IP_ADDRESS:172.16.58.3END_PI" :hostname "iobar" }] (with-redefs [hosts (agent hosts-file) execute stubed-execute s/get-system (fn [_] {:machine machine}) sudo ""] (fact "adding a host on create" :integration :agent (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 1000 hosts) => true (agent-error hosts) => nil (slurp hosts-file) => "PI:IP_ADDRESS:172.16.58.3END_PI iobar iobar.local\n") (fact "removing a host on stop" :integration :agent (update-dns {:event :success :workflow :stop :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" :machine machine}) => truthy (await-for 1000 hosts) => true (agent-error hosts) => nil (slurp hosts-file) => "") (fact "failing execution not in action" :integration :agent (send-off hosts fail) (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 8000 hosts) => true (agent-error hosts) => nil) (with-redefs [execute fail] (fact "failing execution in action" :integration :agent (update-dns {:event :success :workflow :create :system-id 1 :domain "local" :dnsmasq "192.168.1.1" :user "foo" }) => truthy (await-for 8000 hosts) => true (agent-error hosts) => nil))))
[ { "context": "sions bknd-store dsname))\n key (rand-str \"key\")]\n (b/update-status (:meta-store bkn", "end": 4081, "score": 0.7508437037467957, "start": 4073, "tag": "KEY", "value": "rand-str" } ]
service/test/optimus/service/core_test.clj
trainline/optimus
13
;; Copyright (c) Trainline Limited, 2017. All rights reserved. ;; See LICENSE.txt in the project root for license information (ns optimus.service.core-test (:require [midje.sweet :refer :all] [optimus.service [backend :as b] [core :as sut] [test-util :refer [backend-fixture rand-str throws-validation-ex]]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; ---==| U T I L I T I E S |==---- ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn val-or-exception "Evaluates the function f in a try catch block and returns the value if call to f succeeds or the exception" [f] (try (f) (catch Exception e e))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; ---==| T E S T S |==---- ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fact "create-entries: fails when version does not exist" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (rand-str "version") dsname [{:table "t1" :key "k" :val "val"}]) => (throws-validation-ex :error :version-not-found))) (fact "create-entries: fails when version does not match dataset" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (:id version) (rand-str "ds") [{:table "t1" :key "k" :val "value"}]) => (throws-validation-ex :error :invalid-version-for-dataset))) (fact "create-entries: fails when version is in an invalid state" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (:id version) dsname [{:table "t1" :key "k" :val "val"}]) => (throws-validation-ex :error :invalid-version-state))) (fact "create-entries: fails when version is in an invalid state" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname)) invalid-table (rand-str "table")] (b/update-status (:meta-store bknd-store) (:id version) :awaiting-entries nil) (sut/create-entries bknd-store (:id version) dsname [{:table invalid-table :key "k" :val "val"}]) => (throws-validation-ex :error :tables-not-found) (->> (val-or-exception #(sut/create-entries bknd-store (:id version) dsname [{:table invalid-table :key "k" :val "value"}])) ex-data :missing-tables (map #(select-keys % [:table]))) => (contains {:table invalid-table}))) (fact "create-entries: succeeds when valid data is passed" (let [dsname (rand-str "ds") table (rand-str "table") bknd-store (backend-fixture dsname #{table}) version (first (sut/get-versions bknd-store dsname)) key (rand-str "key")] (b/update-status (:meta-store bknd-store) (:id version) :awaiting-entries nil) (sut/create-entries bknd-store (:id version) dsname [{:table table :key key :value "valueable"}]) (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "valueable" (sut/create-entries bknd-store (:id version) dsname table [{:key key :value "more_valueable"}]) (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "more_valueable" (sut/create-entries bknd-store (:id version) dsname table key "forever_valueable") (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "forever_valueable")) (fact "save-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/save-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "save-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/save-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "save-version: changes state to :saving and publishes :save event when successful" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update to :awaiting-entries (b/update-status meta-store id :awaiting-entries {}) (sut/save-version bknd-store id) (-> (b/list-messages! queue {:topic (get-in config [:async-task :operations-topic]) :status :new}) first :message (assoc :status (:status (sut/get-version bknd-store id)))) => (contains {:status :saving :action :save :version-id id}))) (fact "publish-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "publish-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "publish-version: changes state to :publishing and publishes :publish event when successful" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :awaiting entries (b/update-status meta-store id :awaiting-entries {}) ;; save the version (sut/save-version bknd-store id) ;;acknowledge the :save message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :saved (b/update-status meta-store id :saved {}) (sut/publish-version bknd-store id) (-> (b/list-messages! queue {:topic (get-in config [:async-task :operations-topic]) :status :new}) first :message (assoc :status (:status (sut/get-version bknd-store id)))) => (contains {:status :publishing :action :publish :version-id id}))) (fact "discard-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "discard-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "discard-version: changes state to :discarded." (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :awaiting entries (b/update-status meta-store id :awaiting-entries {}) ;; save the version (sut/save-version bknd-store id) ;;acknowledge the :save message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :saved (b/update-status meta-store id :saved {}) (sut/discard-version bknd-store id nil) (:status (sut/get-version bknd-store id)) => :discarded))
96338
;; Copyright (c) Trainline Limited, 2017. All rights reserved. ;; See LICENSE.txt in the project root for license information (ns optimus.service.core-test (:require [midje.sweet :refer :all] [optimus.service [backend :as b] [core :as sut] [test-util :refer [backend-fixture rand-str throws-validation-ex]]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; ---==| U T I L I T I E S |==---- ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn val-or-exception "Evaluates the function f in a try catch block and returns the value if call to f succeeds or the exception" [f] (try (f) (catch Exception e e))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; ---==| T E S T S |==---- ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fact "create-entries: fails when version does not exist" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (rand-str "version") dsname [{:table "t1" :key "k" :val "val"}]) => (throws-validation-ex :error :version-not-found))) (fact "create-entries: fails when version does not match dataset" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (:id version) (rand-str "ds") [{:table "t1" :key "k" :val "value"}]) => (throws-validation-ex :error :invalid-version-for-dataset))) (fact "create-entries: fails when version is in an invalid state" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (:id version) dsname [{:table "t1" :key "k" :val "val"}]) => (throws-validation-ex :error :invalid-version-state))) (fact "create-entries: fails when version is in an invalid state" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname)) invalid-table (rand-str "table")] (b/update-status (:meta-store bknd-store) (:id version) :awaiting-entries nil) (sut/create-entries bknd-store (:id version) dsname [{:table invalid-table :key "k" :val "val"}]) => (throws-validation-ex :error :tables-not-found) (->> (val-or-exception #(sut/create-entries bknd-store (:id version) dsname [{:table invalid-table :key "k" :val "value"}])) ex-data :missing-tables (map #(select-keys % [:table]))) => (contains {:table invalid-table}))) (fact "create-entries: succeeds when valid data is passed" (let [dsname (rand-str "ds") table (rand-str "table") bknd-store (backend-fixture dsname #{table}) version (first (sut/get-versions bknd-store dsname)) key (<KEY> "key")] (b/update-status (:meta-store bknd-store) (:id version) :awaiting-entries nil) (sut/create-entries bknd-store (:id version) dsname [{:table table :key key :value "valueable"}]) (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "valueable" (sut/create-entries bknd-store (:id version) dsname table [{:key key :value "more_valueable"}]) (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "more_valueable" (sut/create-entries bknd-store (:id version) dsname table key "forever_valueable") (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "forever_valueable")) (fact "save-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/save-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "save-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/save-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "save-version: changes state to :saving and publishes :save event when successful" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update to :awaiting-entries (b/update-status meta-store id :awaiting-entries {}) (sut/save-version bknd-store id) (-> (b/list-messages! queue {:topic (get-in config [:async-task :operations-topic]) :status :new}) first :message (assoc :status (:status (sut/get-version bknd-store id)))) => (contains {:status :saving :action :save :version-id id}))) (fact "publish-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "publish-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "publish-version: changes state to :publishing and publishes :publish event when successful" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :awaiting entries (b/update-status meta-store id :awaiting-entries {}) ;; save the version (sut/save-version bknd-store id) ;;acknowledge the :save message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :saved (b/update-status meta-store id :saved {}) (sut/publish-version bknd-store id) (-> (b/list-messages! queue {:topic (get-in config [:async-task :operations-topic]) :status :new}) first :message (assoc :status (:status (sut/get-version bknd-store id)))) => (contains {:status :publishing :action :publish :version-id id}))) (fact "discard-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "discard-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "discard-version: changes state to :discarded." (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :awaiting entries (b/update-status meta-store id :awaiting-entries {}) ;; save the version (sut/save-version bknd-store id) ;;acknowledge the :save message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :saved (b/update-status meta-store id :saved {}) (sut/discard-version bknd-store id nil) (:status (sut/get-version bknd-store id)) => :discarded))
true
;; Copyright (c) Trainline Limited, 2017. All rights reserved. ;; See LICENSE.txt in the project root for license information (ns optimus.service.core-test (:require [midje.sweet :refer :all] [optimus.service [backend :as b] [core :as sut] [test-util :refer [backend-fixture rand-str throws-validation-ex]]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; ---==| U T I L I T I E S |==---- ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn val-or-exception "Evaluates the function f in a try catch block and returns the value if call to f succeeds or the exception" [f] (try (f) (catch Exception e e))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; ---==| T E S T S |==---- ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fact "create-entries: fails when version does not exist" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (rand-str "version") dsname [{:table "t1" :key "k" :val "val"}]) => (throws-validation-ex :error :version-not-found))) (fact "create-entries: fails when version does not match dataset" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (:id version) (rand-str "ds") [{:table "t1" :key "k" :val "value"}]) => (throws-validation-ex :error :invalid-version-for-dataset))) (fact "create-entries: fails when version is in an invalid state" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/create-entries bknd-store (:id version) dsname [{:table "t1" :key "k" :val "val"}]) => (throws-validation-ex :error :invalid-version-state))) (fact "create-entries: fails when version is in an invalid state" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname)) invalid-table (rand-str "table")] (b/update-status (:meta-store bknd-store) (:id version) :awaiting-entries nil) (sut/create-entries bknd-store (:id version) dsname [{:table invalid-table :key "k" :val "val"}]) => (throws-validation-ex :error :tables-not-found) (->> (val-or-exception #(sut/create-entries bknd-store (:id version) dsname [{:table invalid-table :key "k" :val "value"}])) ex-data :missing-tables (map #(select-keys % [:table]))) => (contains {:table invalid-table}))) (fact "create-entries: succeeds when valid data is passed" (let [dsname (rand-str "ds") table (rand-str "table") bknd-store (backend-fixture dsname #{table}) version (first (sut/get-versions bknd-store dsname)) key (PI:KEY:<KEY>END_PI "key")] (b/update-status (:meta-store bknd-store) (:id version) :awaiting-entries nil) (sut/create-entries bknd-store (:id version) dsname [{:table table :key key :value "valueable"}]) (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "valueable" (sut/create-entries bknd-store (:id version) dsname table [{:key key :value "more_valueable"}]) (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "more_valueable" (sut/create-entries bknd-store (:id version) dsname table key "forever_valueable") (b/get-one (:kv-store bknd-store) {:dataset dsname :version (:id version) :table table :key key}) => "forever_valueable")) (fact "save-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/save-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "save-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/save-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "save-version: changes state to :saving and publishes :save event when successful" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update to :awaiting-entries (b/update-status meta-store id :awaiting-entries {}) (sut/save-version bknd-store id) (-> (b/list-messages! queue {:topic (get-in config [:async-task :operations-topic]) :status :new}) first :message (assoc :status (:status (sut/get-version bknd-store id)))) => (contains {:status :saving :action :save :version-id id}))) (fact "publish-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "publish-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "publish-version: changes state to :publishing and publishes :publish event when successful" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :awaiting entries (b/update-status meta-store id :awaiting-entries {}) ;; save the version (sut/save-version bknd-store id) ;;acknowledge the :save message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :saved (b/update-status meta-store id :saved {}) (sut/publish-version bknd-store id) (-> (b/list-messages! queue {:topic (get-in config [:async-task :operations-topic]) :status :new}) first :message (assoc :status (:status (sut/get-version bknd-store id)))) => (contains {:status :publishing :action :publish :version-id id}))) (fact "discard-version: fails with :version-not-found when version is not found" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (rand-str "version")) => (throws-validation-ex :error :version-not-found))) (fact "discard-version: fails with :invalid-version-state when version is invalid" (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} bknd-store (backend-fixture dsname tables) version (first (sut/get-versions bknd-store dsname))] (sut/publish-version bknd-store (:id version)) => (throws-validation-ex :error :invalid-version-state))) (fact "discard-version: changes state to :discarded." (let [dsname (rand-str "ds") tables #{(rand-str "tb") (rand-str "ta")} {:keys [pid queue meta-store config] :as bknd-store} (backend-fixture dsname tables) {:keys [id]} (first (sut/get-versions bknd-store dsname))] ;;acknowledge the :prepare message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :awaiting entries (b/update-status meta-store id :awaiting-entries {}) ;; save the version (sut/save-version bknd-store id) ;;acknowledge the :save message (-> (b/reserve-next-message! (:queue bknd-store) (get-in config [:async-task :operations-topic]) pid) :id (#(b/acknowledge-message! queue % pid))) ;; update status to :saved (b/update-status meta-store id :saved {}) (sut/discard-version bknd-store id nil) (:status (sut/get-version bknd-store id)) => :discarded))
[ { "context": ";; Copyright (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rig", "end": 36, "score": 0.9998773336410522, "start": 23, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "ght (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rights reserved.\n;;\n;; Redistribution and ", "end": 75, "score": 0.9998630881309509, "start": 60, "tag": "NAME", "value": "Alejandro Gómez" } ]
src/cljx/cats/monad/writer.cljx
pbaille/cats
0
;; Copyright (c) 2014, Andrey Antukh ;; Copyright (c) 2014, Alejandro Gómez ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.writer "The Writer Monad." #+clj (:require [cats.core :refer [with-monad]]) #+cljs (:require-macros [cats.core :refer (with-monad)]) (:require [cats.protocols :as proto] [cats.core :as m] [cats.data :as d])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def writer-monad (reify proto/Monad (mreturn [_ v] (d/pair v [])) (mbind [_ mv f] (let [[v log] mv [v' log'] (f v)] (d/pair v' (into log log')))) proto/MonadWriter (tell [_ v] (d/pair nil [v])) (listen [_ mv] (d/pair mv (second mv))) (pass [_ mv] (let [[v f] (first mv)] (d/pair v (f (second mv))))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad transformer definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn writer-transformer [inner-monad] (reify proto/Monad (mreturn [_ v] (proto/mreturn inner-monad (d/pair v []))) (mbind [_ mv f] (proto/mbind inner-monad mv (fn [[v log]] (proto/mbind inner-monad (f v) (fn [[v' log']] (proto/mreturn inner-monad (d/pair v' (into log log')))))))) proto/MonadWriter (tell [_ v] (proto/mreturn inner-monad (d/pair nil [v]))) (listen [_ mv] (proto/mbind inner-monad mv (fn [mv] (proto/mreturn inner-monad (d/pair mv (second mv)))))) (pass [_ mv] (proto/mbind inner-monad mv (fn [w] (let [[v f] (first w) log (second w)] (proto/mreturn inner-monad (d/pair v (f log))))))) proto/MonadTrans (base [_] writer-monad) (inner [_] inner-monad) (lift [_ mv] (proto/mbind inner-monad mv (fn [v] (proto/mreturn inner-monad (d/pair v []))))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Writer monad functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tell [v] (proto/tell (m/get-current-context-or writer-monad) v)) (defn listen [mv] (proto/listen (m/get-current-context-or writer-monad) mv)) (defn pass [mv] (proto/pass (m/get-current-context-or writer-monad) mv)) (def value first) (def log second)
121241
;; Copyright (c) 2014, <NAME> ;; Copyright (c) 2014, <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: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.writer "The Writer Monad." #+clj (:require [cats.core :refer [with-monad]]) #+cljs (:require-macros [cats.core :refer (with-monad)]) (:require [cats.protocols :as proto] [cats.core :as m] [cats.data :as d])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def writer-monad (reify proto/Monad (mreturn [_ v] (d/pair v [])) (mbind [_ mv f] (let [[v log] mv [v' log'] (f v)] (d/pair v' (into log log')))) proto/MonadWriter (tell [_ v] (d/pair nil [v])) (listen [_ mv] (d/pair mv (second mv))) (pass [_ mv] (let [[v f] (first mv)] (d/pair v (f (second mv))))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad transformer definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn writer-transformer [inner-monad] (reify proto/Monad (mreturn [_ v] (proto/mreturn inner-monad (d/pair v []))) (mbind [_ mv f] (proto/mbind inner-monad mv (fn [[v log]] (proto/mbind inner-monad (f v) (fn [[v' log']] (proto/mreturn inner-monad (d/pair v' (into log log')))))))) proto/MonadWriter (tell [_ v] (proto/mreturn inner-monad (d/pair nil [v]))) (listen [_ mv] (proto/mbind inner-monad mv (fn [mv] (proto/mreturn inner-monad (d/pair mv (second mv)))))) (pass [_ mv] (proto/mbind inner-monad mv (fn [w] (let [[v f] (first w) log (second w)] (proto/mreturn inner-monad (d/pair v (f log))))))) proto/MonadTrans (base [_] writer-monad) (inner [_] inner-monad) (lift [_ mv] (proto/mbind inner-monad mv (fn [v] (proto/mreturn inner-monad (d/pair v []))))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Writer monad functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tell [v] (proto/tell (m/get-current-context-or writer-monad) v)) (defn listen [mv] (proto/listen (m/get-current-context-or writer-monad) mv)) (defn pass [mv] (proto/pass (m/get-current-context-or writer-monad) mv)) (def value first) (def log second)
true
;; Copyright (c) 2014, PI:NAME:<NAME>END_PI ;; Copyright (c) 2014, 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: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. 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 AUTHOR ``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 AUTHOR 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 cats.monad.writer "The Writer Monad." #+clj (:require [cats.core :refer [with-monad]]) #+cljs (:require-macros [cats.core :refer (with-monad)]) (:require [cats.protocols :as proto] [cats.core :as m] [cats.data :as d])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def writer-monad (reify proto/Monad (mreturn [_ v] (d/pair v [])) (mbind [_ mv f] (let [[v log] mv [v' log'] (f v)] (d/pair v' (into log log')))) proto/MonadWriter (tell [_ v] (d/pair nil [v])) (listen [_ mv] (d/pair mv (second mv))) (pass [_ mv] (let [[v f] (first mv)] (d/pair v (f (second mv))))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad transformer definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn writer-transformer [inner-monad] (reify proto/Monad (mreturn [_ v] (proto/mreturn inner-monad (d/pair v []))) (mbind [_ mv f] (proto/mbind inner-monad mv (fn [[v log]] (proto/mbind inner-monad (f v) (fn [[v' log']] (proto/mreturn inner-monad (d/pair v' (into log log')))))))) proto/MonadWriter (tell [_ v] (proto/mreturn inner-monad (d/pair nil [v]))) (listen [_ mv] (proto/mbind inner-monad mv (fn [mv] (proto/mreturn inner-monad (d/pair mv (second mv)))))) (pass [_ mv] (proto/mbind inner-monad mv (fn [w] (let [[v f] (first w) log (second w)] (proto/mreturn inner-monad (d/pair v (f log))))))) proto/MonadTrans (base [_] writer-monad) (inner [_] inner-monad) (lift [_ mv] (proto/mbind inner-monad mv (fn [v] (proto/mreturn inner-monad (d/pair v []))))) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Writer monad functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tell [v] (proto/tell (m/get-current-context-or writer-monad) v)) (defn listen [mv] (proto/listen (m/get-current-context-or writer-monad) mv)) (defn pass [mv] (proto/pass (m/get-current-context-or writer-monad) mv)) (def value first) (def log second)
[ { "context": "))))\n\n (t/is (not (s/valid? ::swedish-person-nr \"Hejsan\")))\n (t/is (s/valid? ::swedish-person-nr \"890907", "end": 823, "score": 0.9983410239219666, "start": 817, "tag": "NAME", "value": "Hejsan" } ]
test/se/jherrlin/luhn_test.cljc
jherrlin/luhn-cljc
0
(ns se.jherrlin.luhn-test (:require [clojure.spec.alpha :as s] [clojure.test :as t] [clojure.test.check.generators :as gen] [se.jherrlin.luhn :as luhn])) (t/deftest luhns (t/is (s/valid? ::luhn/luhn "0112046438")) (t/is (s/valid? ::luhn/luhn "967425547947112914710")) (t/is (not (s/valid? ::luhn/luhn "1234567890"))) (t/is (= (luhn/validate "0112046438") "0112046438")) (t/is (= (luhn/validate "967425547947112914710") "967425547947112914710")) (t/is (nil? (luhn/validate "1234567890"))) (t/is (= 10 (count (gen/generate (luhn/generator 10))))) (t/is (= 15 (count (gen/generate (luhn/generator 15))))) (s/def ::swedish-person-nr (s/with-gen (s/and string? #(= 10 (count %)) luhn/validate) (fn [] (luhn/generator 10)))) (t/is (not (s/valid? ::swedish-person-nr "Hejsan"))) (t/is (s/valid? ::swedish-person-nr "8909073374")) (t/is (= 10 (count (gen/generate (s/gen ::swedish-person-nr))))) )
42546
(ns se.jherrlin.luhn-test (:require [clojure.spec.alpha :as s] [clojure.test :as t] [clojure.test.check.generators :as gen] [se.jherrlin.luhn :as luhn])) (t/deftest luhns (t/is (s/valid? ::luhn/luhn "0112046438")) (t/is (s/valid? ::luhn/luhn "967425547947112914710")) (t/is (not (s/valid? ::luhn/luhn "1234567890"))) (t/is (= (luhn/validate "0112046438") "0112046438")) (t/is (= (luhn/validate "967425547947112914710") "967425547947112914710")) (t/is (nil? (luhn/validate "1234567890"))) (t/is (= 10 (count (gen/generate (luhn/generator 10))))) (t/is (= 15 (count (gen/generate (luhn/generator 15))))) (s/def ::swedish-person-nr (s/with-gen (s/and string? #(= 10 (count %)) luhn/validate) (fn [] (luhn/generator 10)))) (t/is (not (s/valid? ::swedish-person-nr "<NAME>"))) (t/is (s/valid? ::swedish-person-nr "8909073374")) (t/is (= 10 (count (gen/generate (s/gen ::swedish-person-nr))))) )
true
(ns se.jherrlin.luhn-test (:require [clojure.spec.alpha :as s] [clojure.test :as t] [clojure.test.check.generators :as gen] [se.jherrlin.luhn :as luhn])) (t/deftest luhns (t/is (s/valid? ::luhn/luhn "0112046438")) (t/is (s/valid? ::luhn/luhn "967425547947112914710")) (t/is (not (s/valid? ::luhn/luhn "1234567890"))) (t/is (= (luhn/validate "0112046438") "0112046438")) (t/is (= (luhn/validate "967425547947112914710") "967425547947112914710")) (t/is (nil? (luhn/validate "1234567890"))) (t/is (= 10 (count (gen/generate (luhn/generator 10))))) (t/is (= 15 (count (gen/generate (luhn/generator 15))))) (s/def ::swedish-person-nr (s/with-gen (s/and string? #(= 10 (count %)) luhn/validate) (fn [] (luhn/generator 10)))) (t/is (not (s/valid? ::swedish-person-nr "PI:NAME:<NAME>END_PI"))) (t/is (s/valid? ::swedish-person-nr "8909073374")) (t/is (= 10 (count (gen/generate (s/gen ::swedish-person-nr))))) )
[ { "context": ";; feature testing macro, based on suggestion from Chas Emerick:\n(defmacro when-available\n [sym & body]\n (try\n ", "end": 1891, "score": 0.9967457056045532, "start": 1879, "tag": "NAME", "value": "Chas Emerick" }, { "context": "specs)))\n\n; based on this code https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/cloj", "end": 3605, "score": 0.9994886517524719, "start": 3595, "tag": "USERNAME", "value": "richhickey" } ]
src/main/resources/ogu/core.clj
NinjasCL-archive/Ogu
9
(ns ogu.core) (def ^:dynamic **args** []) (defn banner! [msg] (interpreter.Runtime/banner msg)) (def println! println) (def readln! read-line) (def nothing (fn [] )) (def typeof type) (def classof class) (def curry partial) (def reader clojure.java.io/reader) (def file clojure.java.io/file) (defn split-words [s] (let [w (clojure.string/trim s)] (if (empty? w) [] (clojure.string/split w #"\s+")))) (defn isa-type? [t obj] (cond (instance? clojure.lang.PersistentArrayMap t) (satisfies? t obj) :else (instance? t obj))) (defn prompt! [& args] (binding [*print-readably* nil] (apply pr args)) (flush) (read-line)) ; try-parse (defn to-int [s d] (try (Integer/parseInt s) (catch java.lang.NumberFormatException e d))) (defn sum [args] (reduce + (seq args))) (require 'clojure.set) (defn union [a b] (clojure.set/union (set a) (set b))) (defn -range-to-inf ([start] (iterate inc' start)) ([start, step] (iterate #(+' % step) start))) (defn not-empty? [coll] (seq coll)) (def tail rest) (def to-set set) (def head first) (def fst first) (def snd second) (defn zip [a b] (map vector a b)) (def uniq distinct) (defn is-digit? [d] (Character/isDigit d)) (defn elem [v s] (contains? (set s) v)) (defn not-elem [v s] (not (elem v s))) (defn member? [v s] (contains? (set s) v)) (defn not-member? [v s] (not (member? v s))) (defn to-digit ([d] (Character/digit d 10)) ([d b] (Character/digit d b))) (def boolean-array! boolean-array) (def aset! aset) (def length count) (def trim clojure.string/trim) (def upper clojure.string/upper-case) (def lower clojure.string/lower-case) (def join clojure.string/join) ;; from here are fragments of numeric-tower (def ^{:private true} minus (first [-' -])) (def ^{:private true} mult (first [*' *])) ;; feature testing macro, based on suggestion from Chas Emerick: (defmacro when-available [sym & body] (try (when (resolve sym) (list* 'do body)) (catch ClassNotFoundException _#))) (defn- expt-int [base pow] (loop [n pow, y (num 1), z base] (let [t (even? n), n (quot n 2)] (cond t (recur n y (mult z z)) (zero? n) (mult z y) :else (recur n (mult z y) (mult z z)))))) (defn pow "(pow base power) is base to the power. Returns an exact number if the base is an exact number and the power is an integer, otherwise returns a double." [base power] (if (and (not (float? base)) (integer? power)) (cond (pos? power) (expt-int base power) (zero? power) (cond (= (type base) BigDecimal) 1M (= (type base) java.math.BigInteger) (java.math.BigInteger. "1") (when-available clojure.lang.BigInt (= (type base) clojure.lang.BigInt)) (when-available clojure.lang.BigInt (bigint 1)) :else 1) :else (/ 1 (expt-int base (minus power)))) (Math/pow base power))) (def pi Math/PI) (defn md5 [s] (let [algorithm (java.security.MessageDigest/getInstance "MD5") raw (.digest algorithm (.getBytes s))] (format "%032x" (BigInteger. 1 raw)))) (defn uuid [] (str (java.util.UUID/randomUUID))) (defmacro -def-ogu-var- [name value] (let [meta-name (with-meta name {:dynamic true}) ] `(def ~meta-name ~value))) (defmacro -def-ogu-type- [name fields & opts+specs] (let [filter-fields (vec (map #(if (vector? %) (with-meta (second %) {:volatile-mutable true}) %) fields)) ] `(deftype ~name ~filter-fields ~@opts+specs))) ; based on this code https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/clojure/contrib/import_static.clj (defmacro import-static "Imports the named static fields and/or static methods of the class as (private) symbols in the current namespace. Example: user=> (import-static java.lang.Math PI sqrt) nil user=> PI 3.141592653589793 user=> (sqrt 16) 4.0 Note: The class name must be fully qualified, even if it has already been imported. Static methods are defined as MACROS, not first-class fns." [class & fields-and-methods] (let [only (set (map str fields-and-methods)) the-class (Class/forName (str class)) static? (fn [x] (java.lang.reflect.Modifier/isStatic (.getModifiers x))) statics (fn [array] (set (map (memfn getName) (filter static? array)))) all-fields (statics (.getFields the-class)) all-methods (statics (.getMethods the-class)) fields-to-do (clojure.set/intersection all-fields only) methods-to-do (clojure.set/intersection all-methods only) make-sym (fn [string] (with-meta (symbol string) {:private true})) import-field (fn [name] (list 'def (make-sym name) (list '. class (symbol name)))) import-method (fn [name] (list 'defmacro (make-sym name) '[& args] (list 'list ''. (list 'quote class) (list 'apply 'list (list 'quote (symbol name)) 'args))))] `(do ~@(map import-field fields-to-do) ~@(map import-method methods-to-do)))) ; based on << macro ; defined here: https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/strint.clj (defn- silent-read "Attempts to clojure.core/read a single form from the provided String, returning a vector containing the read form and a String containing the unread remainder of the provided String. Returns nil if no valid form can be read from the head of the String." [s] (try (let [r (-> s java.io.StringReader. java.io.PushbackReader.)] [(read r) (slurp r)]) (catch Exception e))) ; this indicates an invalid form -- the head of s is just string data (defn- interpolate "Yields a seq of Strings and read forms." ([s atom?] (lazy-seq (if-let [[form rest] (silent-read (subs s (if atom? 2 1)))] (cons form (interpolate (if atom? (subs rest 1) rest))) (cons (subs s 0 2) (interpolate (subs s 2)))))) ([^String s] (if-let [start (->> ["${"] (map #(.indexOf s %)) (remove #(== -1 %)) sort first)] (lazy-seq (cons (subs s 0 start) (interpolate (subs s start) (= \{ (.charAt s (inc start)))))) [s]))) (defmacro fmt "Limited string interpolation, just ${var}" [& strings] `(str ~@(interpolate (apply str strings)))) (defn func-fmt [s] (println "func-fmt " s) (interpolate s))
97848
(ns ogu.core) (def ^:dynamic **args** []) (defn banner! [msg] (interpreter.Runtime/banner msg)) (def println! println) (def readln! read-line) (def nothing (fn [] )) (def typeof type) (def classof class) (def curry partial) (def reader clojure.java.io/reader) (def file clojure.java.io/file) (defn split-words [s] (let [w (clojure.string/trim s)] (if (empty? w) [] (clojure.string/split w #"\s+")))) (defn isa-type? [t obj] (cond (instance? clojure.lang.PersistentArrayMap t) (satisfies? t obj) :else (instance? t obj))) (defn prompt! [& args] (binding [*print-readably* nil] (apply pr args)) (flush) (read-line)) ; try-parse (defn to-int [s d] (try (Integer/parseInt s) (catch java.lang.NumberFormatException e d))) (defn sum [args] (reduce + (seq args))) (require 'clojure.set) (defn union [a b] (clojure.set/union (set a) (set b))) (defn -range-to-inf ([start] (iterate inc' start)) ([start, step] (iterate #(+' % step) start))) (defn not-empty? [coll] (seq coll)) (def tail rest) (def to-set set) (def head first) (def fst first) (def snd second) (defn zip [a b] (map vector a b)) (def uniq distinct) (defn is-digit? [d] (Character/isDigit d)) (defn elem [v s] (contains? (set s) v)) (defn not-elem [v s] (not (elem v s))) (defn member? [v s] (contains? (set s) v)) (defn not-member? [v s] (not (member? v s))) (defn to-digit ([d] (Character/digit d 10)) ([d b] (Character/digit d b))) (def boolean-array! boolean-array) (def aset! aset) (def length count) (def trim clojure.string/trim) (def upper clojure.string/upper-case) (def lower clojure.string/lower-case) (def join clojure.string/join) ;; from here are fragments of numeric-tower (def ^{:private true} minus (first [-' -])) (def ^{:private true} mult (first [*' *])) ;; feature testing macro, based on suggestion from <NAME>: (defmacro when-available [sym & body] (try (when (resolve sym) (list* 'do body)) (catch ClassNotFoundException _#))) (defn- expt-int [base pow] (loop [n pow, y (num 1), z base] (let [t (even? n), n (quot n 2)] (cond t (recur n y (mult z z)) (zero? n) (mult z y) :else (recur n (mult z y) (mult z z)))))) (defn pow "(pow base power) is base to the power. Returns an exact number if the base is an exact number and the power is an integer, otherwise returns a double." [base power] (if (and (not (float? base)) (integer? power)) (cond (pos? power) (expt-int base power) (zero? power) (cond (= (type base) BigDecimal) 1M (= (type base) java.math.BigInteger) (java.math.BigInteger. "1") (when-available clojure.lang.BigInt (= (type base) clojure.lang.BigInt)) (when-available clojure.lang.BigInt (bigint 1)) :else 1) :else (/ 1 (expt-int base (minus power)))) (Math/pow base power))) (def pi Math/PI) (defn md5 [s] (let [algorithm (java.security.MessageDigest/getInstance "MD5") raw (.digest algorithm (.getBytes s))] (format "%032x" (BigInteger. 1 raw)))) (defn uuid [] (str (java.util.UUID/randomUUID))) (defmacro -def-ogu-var- [name value] (let [meta-name (with-meta name {:dynamic true}) ] `(def ~meta-name ~value))) (defmacro -def-ogu-type- [name fields & opts+specs] (let [filter-fields (vec (map #(if (vector? %) (with-meta (second %) {:volatile-mutable true}) %) fields)) ] `(deftype ~name ~filter-fields ~@opts+specs))) ; based on this code https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/clojure/contrib/import_static.clj (defmacro import-static "Imports the named static fields and/or static methods of the class as (private) symbols in the current namespace. Example: user=> (import-static java.lang.Math PI sqrt) nil user=> PI 3.141592653589793 user=> (sqrt 16) 4.0 Note: The class name must be fully qualified, even if it has already been imported. Static methods are defined as MACROS, not first-class fns." [class & fields-and-methods] (let [only (set (map str fields-and-methods)) the-class (Class/forName (str class)) static? (fn [x] (java.lang.reflect.Modifier/isStatic (.getModifiers x))) statics (fn [array] (set (map (memfn getName) (filter static? array)))) all-fields (statics (.getFields the-class)) all-methods (statics (.getMethods the-class)) fields-to-do (clojure.set/intersection all-fields only) methods-to-do (clojure.set/intersection all-methods only) make-sym (fn [string] (with-meta (symbol string) {:private true})) import-field (fn [name] (list 'def (make-sym name) (list '. class (symbol name)))) import-method (fn [name] (list 'defmacro (make-sym name) '[& args] (list 'list ''. (list 'quote class) (list 'apply 'list (list 'quote (symbol name)) 'args))))] `(do ~@(map import-field fields-to-do) ~@(map import-method methods-to-do)))) ; based on << macro ; defined here: https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/strint.clj (defn- silent-read "Attempts to clojure.core/read a single form from the provided String, returning a vector containing the read form and a String containing the unread remainder of the provided String. Returns nil if no valid form can be read from the head of the String." [s] (try (let [r (-> s java.io.StringReader. java.io.PushbackReader.)] [(read r) (slurp r)]) (catch Exception e))) ; this indicates an invalid form -- the head of s is just string data (defn- interpolate "Yields a seq of Strings and read forms." ([s atom?] (lazy-seq (if-let [[form rest] (silent-read (subs s (if atom? 2 1)))] (cons form (interpolate (if atom? (subs rest 1) rest))) (cons (subs s 0 2) (interpolate (subs s 2)))))) ([^String s] (if-let [start (->> ["${"] (map #(.indexOf s %)) (remove #(== -1 %)) sort first)] (lazy-seq (cons (subs s 0 start) (interpolate (subs s start) (= \{ (.charAt s (inc start)))))) [s]))) (defmacro fmt "Limited string interpolation, just ${var}" [& strings] `(str ~@(interpolate (apply str strings)))) (defn func-fmt [s] (println "func-fmt " s) (interpolate s))
true
(ns ogu.core) (def ^:dynamic **args** []) (defn banner! [msg] (interpreter.Runtime/banner msg)) (def println! println) (def readln! read-line) (def nothing (fn [] )) (def typeof type) (def classof class) (def curry partial) (def reader clojure.java.io/reader) (def file clojure.java.io/file) (defn split-words [s] (let [w (clojure.string/trim s)] (if (empty? w) [] (clojure.string/split w #"\s+")))) (defn isa-type? [t obj] (cond (instance? clojure.lang.PersistentArrayMap t) (satisfies? t obj) :else (instance? t obj))) (defn prompt! [& args] (binding [*print-readably* nil] (apply pr args)) (flush) (read-line)) ; try-parse (defn to-int [s d] (try (Integer/parseInt s) (catch java.lang.NumberFormatException e d))) (defn sum [args] (reduce + (seq args))) (require 'clojure.set) (defn union [a b] (clojure.set/union (set a) (set b))) (defn -range-to-inf ([start] (iterate inc' start)) ([start, step] (iterate #(+' % step) start))) (defn not-empty? [coll] (seq coll)) (def tail rest) (def to-set set) (def head first) (def fst first) (def snd second) (defn zip [a b] (map vector a b)) (def uniq distinct) (defn is-digit? [d] (Character/isDigit d)) (defn elem [v s] (contains? (set s) v)) (defn not-elem [v s] (not (elem v s))) (defn member? [v s] (contains? (set s) v)) (defn not-member? [v s] (not (member? v s))) (defn to-digit ([d] (Character/digit d 10)) ([d b] (Character/digit d b))) (def boolean-array! boolean-array) (def aset! aset) (def length count) (def trim clojure.string/trim) (def upper clojure.string/upper-case) (def lower clojure.string/lower-case) (def join clojure.string/join) ;; from here are fragments of numeric-tower (def ^{:private true} minus (first [-' -])) (def ^{:private true} mult (first [*' *])) ;; feature testing macro, based on suggestion from PI:NAME:<NAME>END_PI: (defmacro when-available [sym & body] (try (when (resolve sym) (list* 'do body)) (catch ClassNotFoundException _#))) (defn- expt-int [base pow] (loop [n pow, y (num 1), z base] (let [t (even? n), n (quot n 2)] (cond t (recur n y (mult z z)) (zero? n) (mult z y) :else (recur n (mult z y) (mult z z)))))) (defn pow "(pow base power) is base to the power. Returns an exact number if the base is an exact number and the power is an integer, otherwise returns a double." [base power] (if (and (not (float? base)) (integer? power)) (cond (pos? power) (expt-int base power) (zero? power) (cond (= (type base) BigDecimal) 1M (= (type base) java.math.BigInteger) (java.math.BigInteger. "1") (when-available clojure.lang.BigInt (= (type base) clojure.lang.BigInt)) (when-available clojure.lang.BigInt (bigint 1)) :else 1) :else (/ 1 (expt-int base (minus power)))) (Math/pow base power))) (def pi Math/PI) (defn md5 [s] (let [algorithm (java.security.MessageDigest/getInstance "MD5") raw (.digest algorithm (.getBytes s))] (format "%032x" (BigInteger. 1 raw)))) (defn uuid [] (str (java.util.UUID/randomUUID))) (defmacro -def-ogu-var- [name value] (let [meta-name (with-meta name {:dynamic true}) ] `(def ~meta-name ~value))) (defmacro -def-ogu-type- [name fields & opts+specs] (let [filter-fields (vec (map #(if (vector? %) (with-meta (second %) {:volatile-mutable true}) %) fields)) ] `(deftype ~name ~filter-fields ~@opts+specs))) ; based on this code https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/clojure/contrib/import_static.clj (defmacro import-static "Imports the named static fields and/or static methods of the class as (private) symbols in the current namespace. Example: user=> (import-static java.lang.Math PI sqrt) nil user=> PI 3.141592653589793 user=> (sqrt 16) 4.0 Note: The class name must be fully qualified, even if it has already been imported. Static methods are defined as MACROS, not first-class fns." [class & fields-and-methods] (let [only (set (map str fields-and-methods)) the-class (Class/forName (str class)) static? (fn [x] (java.lang.reflect.Modifier/isStatic (.getModifiers x))) statics (fn [array] (set (map (memfn getName) (filter static? array)))) all-fields (statics (.getFields the-class)) all-methods (statics (.getMethods the-class)) fields-to-do (clojure.set/intersection all-fields only) methods-to-do (clojure.set/intersection all-methods only) make-sym (fn [string] (with-meta (symbol string) {:private true})) import-field (fn [name] (list 'def (make-sym name) (list '. class (symbol name)))) import-method (fn [name] (list 'defmacro (make-sym name) '[& args] (list 'list ''. (list 'quote class) (list 'apply 'list (list 'quote (symbol name)) 'args))))] `(do ~@(map import-field fields-to-do) ~@(map import-method methods-to-do)))) ; based on << macro ; defined here: https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/strint.clj (defn- silent-read "Attempts to clojure.core/read a single form from the provided String, returning a vector containing the read form and a String containing the unread remainder of the provided String. Returns nil if no valid form can be read from the head of the String." [s] (try (let [r (-> s java.io.StringReader. java.io.PushbackReader.)] [(read r) (slurp r)]) (catch Exception e))) ; this indicates an invalid form -- the head of s is just string data (defn- interpolate "Yields a seq of Strings and read forms." ([s atom?] (lazy-seq (if-let [[form rest] (silent-read (subs s (if atom? 2 1)))] (cons form (interpolate (if atom? (subs rest 1) rest))) (cons (subs s 0 2) (interpolate (subs s 2)))))) ([^String s] (if-let [start (->> ["${"] (map #(.indexOf s %)) (remove #(== -1 %)) sort first)] (lazy-seq (cons (subs s 0 start) (interpolate (subs s start) (= \{ (.charAt s (inc start)))))) [s]))) (defmacro fmt "Limited string interpolation, just ${var}" [& strings] `(str ~@(interpolate (apply str strings)))) (defn func-fmt [s] (println "func-fmt " s) (interpolate s))
[ { "context": "tr/capitalize \"katy\")))\n (is (= \"John\" (str/capital \"john\")))\n (is (= ", "end": 585, "score": 0.8990502953529358, "start": 581, "tag": "NAME", "value": "John" }, { "context": ")))\n (is (= \"John\" (str/capital \"john\")))\n (is (= \"Mike\" (str/capitali", "end": 605, "score": 0.7742623090744019, "start": 601, "tag": "NAME", "value": "john" }, { "context": " (str/capital \"john\")))\n (is (= \"Mike\" (str/capitalize \"mike\")))))\n\n(deftest capitalize", "end": 640, "score": 0.9472980499267578, "start": 636, "tag": "NAME", "value": "Mike" }, { "context": "\n (is (= \"Mike\" (str/capitalize \"mike\")))))\n\n(deftest capitalize-test-are\n (tes", "end": 663, "score": 0.8283308744430542, "start": 659, "tag": "NAME", "value": "mike" }, { "context": "zed (str/capitalize name))\n \"Amanda\" \"amanda\"\n \"Rob\" \"rob\"\n ", "end": 880, "score": 0.9940085411071777, "start": 874, "tag": "NAME", "value": "Amanda" }, { "context": "capitalize name))\n \"Amanda\" \"amanda\"\n \"Rob\" \"rob\"\n ", "end": 889, "score": 0.9577552080154419, "start": 883, "tag": "NAME", "value": "amanda" }, { "context": " \"Amanda\" \"amanda\"\n \"Rob\" \"rob\"\n \"Dan\" \"dan\")))\n\n(def", "end": 917, "score": 0.999358594417572, "start": 914, "tag": "NAME", "value": "Rob" }, { "context": " \"Amanda\" \"amanda\"\n \"Rob\" \"rob\"\n \"Dan\" \"dan\")))\n\n(deftest p", "end": 923, "score": 0.9991886615753174, "start": 920, "tag": "NAME", "value": "rob" }, { "context": " \"Rob\" \"rob\"\n \"Dan\" \"dan\")))\n\n(deftest profanity-filter-test\n ", "end": 951, "score": 0.9981111288070679, "start": 948, "tag": "NAME", "value": "Dan" }, { "context": " \"Rob\" \"rob\"\n \"Dan\" \"dan\")))\n\n(deftest profanity-filter-test\n (tes", "end": 957, "score": 0.9954348802566528, "start": 954, "tag": "NAME", "value": "dan" } ]
Chapter10/Exercise10.06/hello-test/test/hello_test/core_test.cljs
transducer/The-Clojure-Workshop
55
(ns hello-test.core-test (:require [cljs.test :refer-macros [are async deftest is testing]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :refer-macros [for-all]] [clojure.test.check.clojure-test :refer-macros [defspec]] [cuerdas.core :as str] [hello-test.core :refer [profanity-filter http-get prefix-digit-remover]])) (deftest capitalize-test-is (testing "Test capitalize? function using is macro" (is (= "Katy" (str/capitalize "katy"))) (is (= "John" (str/capital "john"))) (is (= "Mike" (str/capitalize "mike"))))) (deftest capitalize-test-are (testing "Test capitalize? function using are macro" (are [name-capitalized name] (= name-capitalized (str/capitalize name)) "Amanda" "amanda" "Rob" "rob" "Dan" "dan"))) (deftest profanity-filter-test (testing "Filter replaced bad word" (is (= "Clojure is great" (profanity-filter "Clojure is bad")))) (testing "Filter does not replace good words" (are [string result] (= result (profanity-filter string)) "Clojure is great" "Clojure is great" "Clojure is brilliant" "Clojure is brilliant"))) (deftest error-thrown-test (testing "Catching errors in ClojureScript" (is (thrown? js/Error (assoc ["dog" "cat" "parrot"] 4 "apple"))))) (deftest http-get-test (async done (http-get "https://api.github.com/users" {:with-credentials? false :query-params {"since" 135}} (fn [response] (is (= 200 (:status response))) (done))))) (defspec simple-test-check 1000 (for-all [some-string gen/string-ascii] (= (str/replace some-string "bad" "great") (profanity-filter some-string)))) (defspec prefix-digit-remover-test 1000 (for-all [some-string gen/string-ascii] (= ;(str/replace-first some-string "1" "a") ;;; will result in failing test. An example of failing test (if (str/starts-with? some-string "1") (str/replace-first some-string "1" "a") some-string) (prefix-digit-remover some-string))))
99592
(ns hello-test.core-test (:require [cljs.test :refer-macros [are async deftest is testing]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :refer-macros [for-all]] [clojure.test.check.clojure-test :refer-macros [defspec]] [cuerdas.core :as str] [hello-test.core :refer [profanity-filter http-get prefix-digit-remover]])) (deftest capitalize-test-is (testing "Test capitalize? function using is macro" (is (= "Katy" (str/capitalize "katy"))) (is (= "<NAME>" (str/capital "<NAME>"))) (is (= "<NAME>" (str/capitalize "<NAME>"))))) (deftest capitalize-test-are (testing "Test capitalize? function using are macro" (are [name-capitalized name] (= name-capitalized (str/capitalize name)) "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"))) (deftest profanity-filter-test (testing "Filter replaced bad word" (is (= "Clojure is great" (profanity-filter "Clojure is bad")))) (testing "Filter does not replace good words" (are [string result] (= result (profanity-filter string)) "Clojure is great" "Clojure is great" "Clojure is brilliant" "Clojure is brilliant"))) (deftest error-thrown-test (testing "Catching errors in ClojureScript" (is (thrown? js/Error (assoc ["dog" "cat" "parrot"] 4 "apple"))))) (deftest http-get-test (async done (http-get "https://api.github.com/users" {:with-credentials? false :query-params {"since" 135}} (fn [response] (is (= 200 (:status response))) (done))))) (defspec simple-test-check 1000 (for-all [some-string gen/string-ascii] (= (str/replace some-string "bad" "great") (profanity-filter some-string)))) (defspec prefix-digit-remover-test 1000 (for-all [some-string gen/string-ascii] (= ;(str/replace-first some-string "1" "a") ;;; will result in failing test. An example of failing test (if (str/starts-with? some-string "1") (str/replace-first some-string "1" "a") some-string) (prefix-digit-remover some-string))))
true
(ns hello-test.core-test (:require [cljs.test :refer-macros [are async deftest is testing]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :refer-macros [for-all]] [clojure.test.check.clojure-test :refer-macros [defspec]] [cuerdas.core :as str] [hello-test.core :refer [profanity-filter http-get prefix-digit-remover]])) (deftest capitalize-test-is (testing "Test capitalize? function using is macro" (is (= "Katy" (str/capitalize "katy"))) (is (= "PI:NAME:<NAME>END_PI" (str/capital "PI:NAME:<NAME>END_PI"))) (is (= "PI:NAME:<NAME>END_PI" (str/capitalize "PI:NAME:<NAME>END_PI"))))) (deftest capitalize-test-are (testing "Test capitalize? function using are macro" (are [name-capitalized name] (= name-capitalized (str/capitalize name)) "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"))) (deftest profanity-filter-test (testing "Filter replaced bad word" (is (= "Clojure is great" (profanity-filter "Clojure is bad")))) (testing "Filter does not replace good words" (are [string result] (= result (profanity-filter string)) "Clojure is great" "Clojure is great" "Clojure is brilliant" "Clojure is brilliant"))) (deftest error-thrown-test (testing "Catching errors in ClojureScript" (is (thrown? js/Error (assoc ["dog" "cat" "parrot"] 4 "apple"))))) (deftest http-get-test (async done (http-get "https://api.github.com/users" {:with-credentials? false :query-params {"since" 135}} (fn [response] (is (= 200 (:status response))) (done))))) (defspec simple-test-check 1000 (for-all [some-string gen/string-ascii] (= (str/replace some-string "bad" "great") (profanity-filter some-string)))) (defspec prefix-digit-remover-test 1000 (for-all [some-string gen/string-ascii] (= ;(str/replace-first some-string "1" "a") ;;; will result in failing test. An example of failing test (if (str/starts-with? some-string "1") (str/replace-first some-string "1" "a") some-string) (prefix-digit-remover some-string))))
[ { "context": "est-case for reactor-core.reducers.\"\n :author \"Vladimir Tsanev\"}\n reactor-core.reducer-test\n #?(:cljs (:requir", "end": 685, "score": 0.999786376953125, "start": 670, "tag": "NAME", "value": "Vladimir Tsanev" } ]
test/reactor_core/reducer_test.cljc
jaju/reactor-core-clojure
2
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "A test-case for reactor-core.reducers." :author "Vladimir Tsanev"} reactor-core.reducer-test #?(:cljs (:require-macros [cljs.test :refer [async]])) #?(:clj (:use [reactor-core.test :only [async]])) (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [reactor-core.reducers :refer []] [clojure.core.reducers :as r] [reactor-core.publisher :as p])) #?(:cljs (set! *warn-on-infer* true) :clj (set! *warn-on-reflection* true)) (t/deftest reducers-test (async done (let [reduced-flux (reduce + 0 (r/map inc (r/filter even? (p/range 1 9))))] (->> reduced-flux (p/subscribe (fn [value] (t/is (= 24 value))) (fn [e] (t/is false e) (done)) done))))) (comment (reduce + 0 (range 1 5)))
104866
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "A test-case for reactor-core.reducers." :author "<NAME>"} reactor-core.reducer-test #?(:cljs (:require-macros [cljs.test :refer [async]])) #?(:clj (:use [reactor-core.test :only [async]])) (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [reactor-core.reducers :refer []] [clojure.core.reducers :as r] [reactor-core.publisher :as p])) #?(:cljs (set! *warn-on-infer* true) :clj (set! *warn-on-reflection* true)) (t/deftest reducers-test (async done (let [reduced-flux (reduce + 0 (r/map inc (r/filter even? (p/range 1 9))))] (->> reduced-flux (p/subscribe (fn [value] (t/is (= 24 value))) (fn [e] (t/is false e) (done)) done))))) (comment (reduce + 0 (range 1 5)))
true
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "A test-case for reactor-core.reducers." :author "PI:NAME:<NAME>END_PI"} reactor-core.reducer-test #?(:cljs (:require-macros [cljs.test :refer [async]])) #?(:clj (:use [reactor-core.test :only [async]])) (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [reactor-core.reducers :refer []] [clojure.core.reducers :as r] [reactor-core.publisher :as p])) #?(:cljs (set! *warn-on-infer* true) :clj (set! *warn-on-reflection* true)) (t/deftest reducers-test (async done (let [reduced-flux (reduce + 0 (r/map inc (r/filter even? (p/range 1 9))))] (->> reduced-flux (p/subscribe (fn [value] (t/is (= 24 value))) (fn [e] (t/is false e) (done)) done))))) (comment (reduce + 0 (range 1 5)))
[ { "context": "s-2.col-xs-offset-2\n (input-text :name \"Your name\" name)]\n\n [:div.col-xs-5\n (inp", "end": 5389, "score": 0.7843997478485107, "start": 5380, "tag": "NAME", "value": "Your name" }, { "context": " :port 3000\n :host \"0.0.0.0\"})\n s))))\n\n(defn stop-server\n \"Stop", "end": 7590, "score": 0.9993764758110046, "start": 7583, "tag": "IP_ADDRESS", "value": "0.0.0.0" } ]
src/chatter/handler.clj
biiwide/track2-functional
0
(ns chatter.handler (:require [clojure.test :refer [deftest run-tests is are]] [compojure.core :refer :all] [compojure.route :as route] [ring.adapter.jetty :as jetty] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.params :refer [wrap-params]] [hiccup.page :as page]) (:import [java.util HashMap LinkedList Map] [java.util.concurrent ConcurrentHashMap ConcurrentLinkedDeque])) (defn new-mutable-conversation-db "Using simple, mutable Java collections, construct a new Conversation Database that will hold a limited number of messages." [message-limit] ;;;;; Comments show comparable Java source ;; ;; HashMap conversation = new Conversation(); ;; conversation.put( :limit, message-limit ); ;; conversation.put( :total, 0 ); ;; conversation.put( :counts, new HashMap() ); ;; conversation.put( :messages, new LinkedList() ); ;; return conversation; (doto (new HashMap) (.put :limit message-limit) (.put :total 0) (.put :counts (new HashMap)) (.put :messages (new LinkedList)))) (defn mutating-add-message "Using standard Java collections APIs, add a new message to a conversation and perform all necessary accounting." [conversation name new-message] ;;;;; Comments show comparable Java source ;; ;; Integer limit = (Integer) conversation.get( :limit ); ;; Integer total = (Integer) conversation.get( :total ); ;; Map counts = (Map) conversation.get( :counts ); ;; List = (List) messages = conversation.get( :messages ); (let [limit (.get conversation :limit) total (.get conversation :total) counts (.get conversation :counts) messages (.get conversation :messages)] ;; counts.put( name, ;; 1 + counts.getOrDefault( name, 0 ) ); (.put counts name (inc (.getOrDefault counts name 0))) ;; Map tmp = new HashMap(); ;; tmp.put( :name, name ); ;; tmp.put( :message, new-message ); ;; messages.addFirst( tmp ); (.addFirst messages (doto (new HashMap) (.put :name name) (.put :message new-message))) ;; while( limit < messages.size() ) { ;; messages.removeLast(); ;; } (loop [] (when (< limit (.size messages)) (.removeLast messages) (recur))) ;; conversation.put( :total, 1 + total ); ;; return conversation; (doto conversation (.put :total (inc total))))) (defn new-mutable-concurrent-conversation-db "Using Java concurrent collections, construct a new Conversation Database that will hold a limited number of messages" [message-limit] (doto (new ConcurrentHashMap) (.put :limit message-limit) (.put :total 0) (.put :counts (new ConcurrentHashMap)) (.put :messages (new ConcurrentLinkedDeque)))) (defn locking-add-message "Add a message to a conversation after locking the conversation" [conversation name message] (locking conversation (mutating-add-message conversation name message))) (def safe-inc "Increments a number. Treats nil as 0" (fnil inc 0)) (defn new-immutable-conversation-db [message-limit] {:limit message-limit}) (defn immutable-add-message "Uses immutable Clojure collections to combine a conversation and a new message into a new conversation" [{:keys [limit total counts messages] :as conversation} name message] {:limit limit :total (safe-inc total) :counts (update-in counts [name] safe-inc) :messages (take limit (cons {:name name :message message} messages))}) (defn new-atomic-conversation-db "Construct a new Atomic Conversation Database: Conversation data wrapped in an Atom" [message-limit] (atom (new-immutable-conversation-db message-limit))) (defn atomic-add-message "Add a message to an Atomic Conversation Database" [conversation-atom name message] (swap! conversation-atom immutable-add-message name message)) (defn desc-sort-by "Sort a collection in descending order based on the result of applying key-fn to each member." [keyfn coll] (sort-by keyfn (fn [a b] (compare b a)) coll)) (defn input-text "Return a Hiccup style input field with a label" ([name label] (input-text name label nil)) ([name label value] [:div.form-group [:label.sr-only {:for name} label] [(keyword (format "input#%s.form-control" name)) {:type "text" :name name :placeholder label :value value}]])) (defn generate-message-view "This generates the HTML for displaying messages" ([conversation] (generate-message-view conversation nil)) ([conversation name] (page/html5 [:head [:title "chatter"] [:meta {:http-equiv "refresh" :content "10"}] (page/include-css "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css") (page/include-js "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js") (page/include-css "/chatter.css")] [:body [:div.container [:h1 "Our Chat App"] [:br] [:div.row [:form {:method "POST" :action "/"} [:div.col-xs-2.col-xs-offset-2 (input-text :name "Your name" name)] [:div.col-xs-5 (input-text :msg "What to say")] [:div.col-xs-1 [:input#post.btn.btn-default {:type "submit" :value "Say It!"}]]]] [:div.row [:div.col-xs-8.col-md-9.col-lg-9 [:h3 "Conversation"] [:table#messages.table.table-striped.table-condensed (map (fn [m] [:tr [:td.name (:name m)] [:td.message (:message m)]]) (:messages conversation))]] [:div.col-xs-4.col-md-3.col-lg-3 [:h3 "Stats"] [:table#stats.table.table-striped.table-condensed (cons [:tr [:td.name "Total Messages"] [:td#total (:total conversation 0)]] (map (fn [[name count]] [:tr.count [:td.name name] [:td.count count]]) (desc-sort-by val (:counts conversation))))]]]]]))) (defonce CONVERSATION-DB (new-mutable-conversation-db 20)) (defn reset-conversation-db [constructor & constructor-args] (alter-var-root #'CONVERSATION-DB (constantly (apply constructor constructor-args)))) (defroutes app-routes (GET "/" [] (generate-message-view CONVERSATION-DB)) (POST "/" {params :params} (let [name-param (get params "name") msg-param (get params "msg") new-messages (mutating-add-message CONVERSATION-DB name-param msg-param)] (generate-message-view new-messages name-param) )) (route/resources "/") (route/not-found "This is not the page you are looking for")) (defn wrap-with-lock "Ensure concurrent requests don't compete with each" [handler] (fn [request] (locking CONVERSATION-DB (handler request)))) (def app (wrap-params app-routes)) (defonce SERVER (atom nil)) (defn start-server "Start a web server for the application" [] (swap! SERVER (fn [s] (if (nil? s) (jetty/run-jetty #'app {:join? false :port 3000 :host "0.0.0.0"}) s)))) (defn stop-server "Stop the application's web server" [] (swap! SERVER (fn [s] (when (some? s) (.stop s)))))
40422
(ns chatter.handler (:require [clojure.test :refer [deftest run-tests is are]] [compojure.core :refer :all] [compojure.route :as route] [ring.adapter.jetty :as jetty] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.params :refer [wrap-params]] [hiccup.page :as page]) (:import [java.util HashMap LinkedList Map] [java.util.concurrent ConcurrentHashMap ConcurrentLinkedDeque])) (defn new-mutable-conversation-db "Using simple, mutable Java collections, construct a new Conversation Database that will hold a limited number of messages." [message-limit] ;;;;; Comments show comparable Java source ;; ;; HashMap conversation = new Conversation(); ;; conversation.put( :limit, message-limit ); ;; conversation.put( :total, 0 ); ;; conversation.put( :counts, new HashMap() ); ;; conversation.put( :messages, new LinkedList() ); ;; return conversation; (doto (new HashMap) (.put :limit message-limit) (.put :total 0) (.put :counts (new HashMap)) (.put :messages (new LinkedList)))) (defn mutating-add-message "Using standard Java collections APIs, add a new message to a conversation and perform all necessary accounting." [conversation name new-message] ;;;;; Comments show comparable Java source ;; ;; Integer limit = (Integer) conversation.get( :limit ); ;; Integer total = (Integer) conversation.get( :total ); ;; Map counts = (Map) conversation.get( :counts ); ;; List = (List) messages = conversation.get( :messages ); (let [limit (.get conversation :limit) total (.get conversation :total) counts (.get conversation :counts) messages (.get conversation :messages)] ;; counts.put( name, ;; 1 + counts.getOrDefault( name, 0 ) ); (.put counts name (inc (.getOrDefault counts name 0))) ;; Map tmp = new HashMap(); ;; tmp.put( :name, name ); ;; tmp.put( :message, new-message ); ;; messages.addFirst( tmp ); (.addFirst messages (doto (new HashMap) (.put :name name) (.put :message new-message))) ;; while( limit < messages.size() ) { ;; messages.removeLast(); ;; } (loop [] (when (< limit (.size messages)) (.removeLast messages) (recur))) ;; conversation.put( :total, 1 + total ); ;; return conversation; (doto conversation (.put :total (inc total))))) (defn new-mutable-concurrent-conversation-db "Using Java concurrent collections, construct a new Conversation Database that will hold a limited number of messages" [message-limit] (doto (new ConcurrentHashMap) (.put :limit message-limit) (.put :total 0) (.put :counts (new ConcurrentHashMap)) (.put :messages (new ConcurrentLinkedDeque)))) (defn locking-add-message "Add a message to a conversation after locking the conversation" [conversation name message] (locking conversation (mutating-add-message conversation name message))) (def safe-inc "Increments a number. Treats nil as 0" (fnil inc 0)) (defn new-immutable-conversation-db [message-limit] {:limit message-limit}) (defn immutable-add-message "Uses immutable Clojure collections to combine a conversation and a new message into a new conversation" [{:keys [limit total counts messages] :as conversation} name message] {:limit limit :total (safe-inc total) :counts (update-in counts [name] safe-inc) :messages (take limit (cons {:name name :message message} messages))}) (defn new-atomic-conversation-db "Construct a new Atomic Conversation Database: Conversation data wrapped in an Atom" [message-limit] (atom (new-immutable-conversation-db message-limit))) (defn atomic-add-message "Add a message to an Atomic Conversation Database" [conversation-atom name message] (swap! conversation-atom immutable-add-message name message)) (defn desc-sort-by "Sort a collection in descending order based on the result of applying key-fn to each member." [keyfn coll] (sort-by keyfn (fn [a b] (compare b a)) coll)) (defn input-text "Return a Hiccup style input field with a label" ([name label] (input-text name label nil)) ([name label value] [:div.form-group [:label.sr-only {:for name} label] [(keyword (format "input#%s.form-control" name)) {:type "text" :name name :placeholder label :value value}]])) (defn generate-message-view "This generates the HTML for displaying messages" ([conversation] (generate-message-view conversation nil)) ([conversation name] (page/html5 [:head [:title "chatter"] [:meta {:http-equiv "refresh" :content "10"}] (page/include-css "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css") (page/include-js "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js") (page/include-css "/chatter.css")] [:body [:div.container [:h1 "Our Chat App"] [:br] [:div.row [:form {:method "POST" :action "/"} [:div.col-xs-2.col-xs-offset-2 (input-text :name "<NAME>" name)] [:div.col-xs-5 (input-text :msg "What to say")] [:div.col-xs-1 [:input#post.btn.btn-default {:type "submit" :value "Say It!"}]]]] [:div.row [:div.col-xs-8.col-md-9.col-lg-9 [:h3 "Conversation"] [:table#messages.table.table-striped.table-condensed (map (fn [m] [:tr [:td.name (:name m)] [:td.message (:message m)]]) (:messages conversation))]] [:div.col-xs-4.col-md-3.col-lg-3 [:h3 "Stats"] [:table#stats.table.table-striped.table-condensed (cons [:tr [:td.name "Total Messages"] [:td#total (:total conversation 0)]] (map (fn [[name count]] [:tr.count [:td.name name] [:td.count count]]) (desc-sort-by val (:counts conversation))))]]]]]))) (defonce CONVERSATION-DB (new-mutable-conversation-db 20)) (defn reset-conversation-db [constructor & constructor-args] (alter-var-root #'CONVERSATION-DB (constantly (apply constructor constructor-args)))) (defroutes app-routes (GET "/" [] (generate-message-view CONVERSATION-DB)) (POST "/" {params :params} (let [name-param (get params "name") msg-param (get params "msg") new-messages (mutating-add-message CONVERSATION-DB name-param msg-param)] (generate-message-view new-messages name-param) )) (route/resources "/") (route/not-found "This is not the page you are looking for")) (defn wrap-with-lock "Ensure concurrent requests don't compete with each" [handler] (fn [request] (locking CONVERSATION-DB (handler request)))) (def app (wrap-params app-routes)) (defonce SERVER (atom nil)) (defn start-server "Start a web server for the application" [] (swap! SERVER (fn [s] (if (nil? s) (jetty/run-jetty #'app {:join? false :port 3000 :host "0.0.0.0"}) s)))) (defn stop-server "Stop the application's web server" [] (swap! SERVER (fn [s] (when (some? s) (.stop s)))))
true
(ns chatter.handler (:require [clojure.test :refer [deftest run-tests is are]] [compojure.core :refer :all] [compojure.route :as route] [ring.adapter.jetty :as jetty] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.params :refer [wrap-params]] [hiccup.page :as page]) (:import [java.util HashMap LinkedList Map] [java.util.concurrent ConcurrentHashMap ConcurrentLinkedDeque])) (defn new-mutable-conversation-db "Using simple, mutable Java collections, construct a new Conversation Database that will hold a limited number of messages." [message-limit] ;;;;; Comments show comparable Java source ;; ;; HashMap conversation = new Conversation(); ;; conversation.put( :limit, message-limit ); ;; conversation.put( :total, 0 ); ;; conversation.put( :counts, new HashMap() ); ;; conversation.put( :messages, new LinkedList() ); ;; return conversation; (doto (new HashMap) (.put :limit message-limit) (.put :total 0) (.put :counts (new HashMap)) (.put :messages (new LinkedList)))) (defn mutating-add-message "Using standard Java collections APIs, add a new message to a conversation and perform all necessary accounting." [conversation name new-message] ;;;;; Comments show comparable Java source ;; ;; Integer limit = (Integer) conversation.get( :limit ); ;; Integer total = (Integer) conversation.get( :total ); ;; Map counts = (Map) conversation.get( :counts ); ;; List = (List) messages = conversation.get( :messages ); (let [limit (.get conversation :limit) total (.get conversation :total) counts (.get conversation :counts) messages (.get conversation :messages)] ;; counts.put( name, ;; 1 + counts.getOrDefault( name, 0 ) ); (.put counts name (inc (.getOrDefault counts name 0))) ;; Map tmp = new HashMap(); ;; tmp.put( :name, name ); ;; tmp.put( :message, new-message ); ;; messages.addFirst( tmp ); (.addFirst messages (doto (new HashMap) (.put :name name) (.put :message new-message))) ;; while( limit < messages.size() ) { ;; messages.removeLast(); ;; } (loop [] (when (< limit (.size messages)) (.removeLast messages) (recur))) ;; conversation.put( :total, 1 + total ); ;; return conversation; (doto conversation (.put :total (inc total))))) (defn new-mutable-concurrent-conversation-db "Using Java concurrent collections, construct a new Conversation Database that will hold a limited number of messages" [message-limit] (doto (new ConcurrentHashMap) (.put :limit message-limit) (.put :total 0) (.put :counts (new ConcurrentHashMap)) (.put :messages (new ConcurrentLinkedDeque)))) (defn locking-add-message "Add a message to a conversation after locking the conversation" [conversation name message] (locking conversation (mutating-add-message conversation name message))) (def safe-inc "Increments a number. Treats nil as 0" (fnil inc 0)) (defn new-immutable-conversation-db [message-limit] {:limit message-limit}) (defn immutable-add-message "Uses immutable Clojure collections to combine a conversation and a new message into a new conversation" [{:keys [limit total counts messages] :as conversation} name message] {:limit limit :total (safe-inc total) :counts (update-in counts [name] safe-inc) :messages (take limit (cons {:name name :message message} messages))}) (defn new-atomic-conversation-db "Construct a new Atomic Conversation Database: Conversation data wrapped in an Atom" [message-limit] (atom (new-immutable-conversation-db message-limit))) (defn atomic-add-message "Add a message to an Atomic Conversation Database" [conversation-atom name message] (swap! conversation-atom immutable-add-message name message)) (defn desc-sort-by "Sort a collection in descending order based on the result of applying key-fn to each member." [keyfn coll] (sort-by keyfn (fn [a b] (compare b a)) coll)) (defn input-text "Return a Hiccup style input field with a label" ([name label] (input-text name label nil)) ([name label value] [:div.form-group [:label.sr-only {:for name} label] [(keyword (format "input#%s.form-control" name)) {:type "text" :name name :placeholder label :value value}]])) (defn generate-message-view "This generates the HTML for displaying messages" ([conversation] (generate-message-view conversation nil)) ([conversation name] (page/html5 [:head [:title "chatter"] [:meta {:http-equiv "refresh" :content "10"}] (page/include-css "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css") (page/include-js "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js") (page/include-css "/chatter.css")] [:body [:div.container [:h1 "Our Chat App"] [:br] [:div.row [:form {:method "POST" :action "/"} [:div.col-xs-2.col-xs-offset-2 (input-text :name "PI:NAME:<NAME>END_PI" name)] [:div.col-xs-5 (input-text :msg "What to say")] [:div.col-xs-1 [:input#post.btn.btn-default {:type "submit" :value "Say It!"}]]]] [:div.row [:div.col-xs-8.col-md-9.col-lg-9 [:h3 "Conversation"] [:table#messages.table.table-striped.table-condensed (map (fn [m] [:tr [:td.name (:name m)] [:td.message (:message m)]]) (:messages conversation))]] [:div.col-xs-4.col-md-3.col-lg-3 [:h3 "Stats"] [:table#stats.table.table-striped.table-condensed (cons [:tr [:td.name "Total Messages"] [:td#total (:total conversation 0)]] (map (fn [[name count]] [:tr.count [:td.name name] [:td.count count]]) (desc-sort-by val (:counts conversation))))]]]]]))) (defonce CONVERSATION-DB (new-mutable-conversation-db 20)) (defn reset-conversation-db [constructor & constructor-args] (alter-var-root #'CONVERSATION-DB (constantly (apply constructor constructor-args)))) (defroutes app-routes (GET "/" [] (generate-message-view CONVERSATION-DB)) (POST "/" {params :params} (let [name-param (get params "name") msg-param (get params "msg") new-messages (mutating-add-message CONVERSATION-DB name-param msg-param)] (generate-message-view new-messages name-param) )) (route/resources "/") (route/not-found "This is not the page you are looking for")) (defn wrap-with-lock "Ensure concurrent requests don't compete with each" [handler] (fn [request] (locking CONVERSATION-DB (handler request)))) (def app (wrap-params app-routes)) (defonce SERVER (atom nil)) (defn start-server "Start a web server for the application" [] (swap! SERVER (fn [s] (if (nil? s) (jetty/run-jetty #'app {:join? false :port 3000 :host "0.0.0.0"}) s)))) (defn stop-server "Stop the application's web server" [] (swap! SERVER (fn [s] (when (some? s) (.stop s)))))
[ { "context": " [[:person/normalize-last-name \"mcnugget@mailinator.com\"]]))]\n (is (= (:person/last-name (q/pull-by-e", "end": 495, "score": 0.9999094009399414, "start": 472, "tag": "EMAIL", "value": "mcnugget@mailinator.com" }, { "context": "= (:person/last-name (q/pull-by-email updated-db \"mcnugget@mailinator.com\"))\n \"MCNUGGET\")))))\n", "end": 585, "score": 0.999919056892395, "start": 562, "tag": "EMAIL", "value": "mcnugget@mailinator.com" } ]
test/examples/schema_test.clj
zilvinasu/datomic-presentation
1
(ns examples.schema-test (:require [clojure.test :refer :all] [datomic.api :as d] [examples.fixtures :refer [with-db]] [examples.db :as db] [examples.query :as q])) (use-fixtures :each with-db) (deftest db-functions-test (testing "normalize person's last name" (let [updated-db (:db-after (d/with (db/current-db) [[:person/normalize-last-name "mcnugget@mailinator.com"]]))] (is (= (:person/last-name (q/pull-by-email updated-db "mcnugget@mailinator.com")) "MCNUGGET")))))
47385
(ns examples.schema-test (:require [clojure.test :refer :all] [datomic.api :as d] [examples.fixtures :refer [with-db]] [examples.db :as db] [examples.query :as q])) (use-fixtures :each with-db) (deftest db-functions-test (testing "normalize person's last name" (let [updated-db (:db-after (d/with (db/current-db) [[:person/normalize-last-name "<EMAIL>"]]))] (is (= (:person/last-name (q/pull-by-email updated-db "<EMAIL>")) "MCNUGGET")))))
true
(ns examples.schema-test (:require [clojure.test :refer :all] [datomic.api :as d] [examples.fixtures :refer [with-db]] [examples.db :as db] [examples.query :as q])) (use-fixtures :each with-db) (deftest db-functions-test (testing "normalize person's last name" (let [updated-db (:db-after (d/with (db/current-db) [[:person/normalize-last-name "PI:EMAIL:<EMAIL>END_PI"]]))] (is (= (:person/last-name (q/pull-by-email updated-db "PI:EMAIL:<EMAIL>END_PI")) "MCNUGGET")))))
[ { "context": "werkz.balagan.core :as b])\n\n(def friend\n {:name \"Nick\"\n :birth {:year 1985 :place \"Japan\"}\n :nickna", "end": 73, "score": 0.9988040924072266, "start": 69, "tag": "NAME", "value": "Nick" }, { "context": " :birth {:year 1985 :place \"Japan\"}\n :nickname \"nickthegreat\"})\n\n\n(b/select friend\n [:birth :year])\n\n", "end": 139, "score": 0.9995946884155273, "start": 127, "tag": "USERNAME", "value": "nickthegreat" } ]
Chapter 04 Code/code-niko/src/chapter04/somebalagan.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(require '[clojurewerkz.balagan.core :as b]) (def friend {:name "Nick" :birth {:year 1985 :place "Japan"} :nickname "nickthegreat"}) (b/select friend [:birth :year]) (b/with-paths friend [:birth] (fn [value path] (println "I am born in " (value :place)))) (b/with-paths friend [:name] (fn [value _] (println "My name is " value) [:birth] (fn [value path] (println "I am born in " (value :place))))) (b/update friend [] (b/add-field :nice-friend true) ) (b/update friend (b/mk-path [:age]) #(- 2016 (-> % :birth :year))) (b/update friend [] (b/remove-field :nickname)) (b/update friend [:birth] (b/remove-field :place))
78723
(require '[clojurewerkz.balagan.core :as b]) (def friend {:name "<NAME>" :birth {:year 1985 :place "Japan"} :nickname "nickthegreat"}) (b/select friend [:birth :year]) (b/with-paths friend [:birth] (fn [value path] (println "I am born in " (value :place)))) (b/with-paths friend [:name] (fn [value _] (println "My name is " value) [:birth] (fn [value path] (println "I am born in " (value :place))))) (b/update friend [] (b/add-field :nice-friend true) ) (b/update friend (b/mk-path [:age]) #(- 2016 (-> % :birth :year))) (b/update friend [] (b/remove-field :nickname)) (b/update friend [:birth] (b/remove-field :place))
true
(require '[clojurewerkz.balagan.core :as b]) (def friend {:name "PI:NAME:<NAME>END_PI" :birth {:year 1985 :place "Japan"} :nickname "nickthegreat"}) (b/select friend [:birth :year]) (b/with-paths friend [:birth] (fn [value path] (println "I am born in " (value :place)))) (b/with-paths friend [:name] (fn [value _] (println "My name is " value) [:birth] (fn [value path] (println "I am born in " (value :place))))) (b/update friend [] (b/add-field :nice-friend true) ) (b/update friend (b/mk-path [:age]) #(- 2016 (-> % :birth :year))) (b/update friend [] (b/remove-field :nickname)) (b/update friend [:birth] (b/remove-field :place))
[ { "context": "e:\n ```\n ((is-confirmed :password) {:password \\\"abcd\\\" :password-confirmation \\\"abcd\\\"}) ; => nil\n ((", "end": 2973, "score": 0.9942514896392822, "start": 2969, "tag": "PASSWORD", "value": "abcd" }, { "context": "ord) {:password \\\"abcd\\\" :password-confirmation \\\"abcd\\\"}) ; => nil\n ((is-confirmed :password) {:passwo", "end": 3005, "score": 0.9825617074966431, "start": 3001, "tag": "PASSWORD", "value": "abcd" }, { "context": "; => nil\n ((is-confirmed :password) {:password \\\"abcd\\\" :password-confirmation \\\"bacd\\\"}) ; => [:passwo", "end": 3064, "score": 0.9907755255699158, "start": 3060, "tag": "PASSWORD", "value": "abcd" }, { "context": "ord) {:password \\\"abcd\\\" :password-confirmation \\\"bacd\\\"}) ; => [:password-confirmation \\\"doesn't match\\", "end": 3096, "score": 0.9913415908813477, "start": 3092, "tag": "PASSWORD", "value": "bacd" }, { "context": " ```\n ((matches #\\\"\\\\d\\\" :password) {:password \\\"pass123\\\"}) ; => nil\n ((matches #\\\"\\\\d\\\" :password) {:pa", "end": 4160, "score": 0.9989264607429504, "start": 4153, "tag": "PASSWORD", "value": "pass123" }, { "context": " nil\n ((matches #\\\"\\\\d\\\" :password) {:password \\\"pass\\\"}) ; => [:password \\\"is invalid\\\"]\n ((matches #", "end": 4223, "score": 0.6062228083610535, "start": 4219, "tag": "PASSWORD", "value": "pass" }, { "context": "ssword) {:password \\\"pass\\\"}) ; => [:password \\\"is invalid\\\"]\n ((matches #\\\"\\\\d\\\" :password \\\"Uh oh\\\") {}) ", "end": 4256, "score": 0.6428084373474121, "start": 4249, "tag": "PASSWORD", "value": "invalid" }, { "context": "\n ((length-is-at-least 8 :password) {:password \\\"password\\\"}) ; => nil\n ((length-is-at-least 8 :password) ", "end": 5130, "score": 0.997138261795044, "start": 5122, "tag": "PASSWORD", "value": "password" }, { "context": "\n ((length-is-at-least 8 :password) {:password \\\"pass\\\"}) ; => [:password \\\"must be at least 8 characte", "end": 5197, "score": 0.9897868633270264, "start": 5193, "tag": "PASSWORD", "value": "pass" }, { "context": "rd \\\"pass\\\"}) ; => [:password \\\"must be at least 8 characters\\\"]\n ((length-is-at-least 8 :password \\\"Uh oh\\\") ", "end": 5249, "score": 0.6425766944885254, "start": 5239, "tag": "PASSWORD", "value": "characters" }, { "context": "haracters\\\"]\n ((length-is-at-least 8 :password \\\"Uh oh\\\") {}) ; => [:password \\\"Uh oh\\\"]\n ```\n \"\n ([m", "end": 5295, "score": 0.7496259808540344, "start": 5290, "tag": "PASSWORD", "value": "Uh oh" } ]
src/heckle/validations.cljc
nwallace/heckle
0
(ns heckle.validations (:require [heckle.core :refer [make-claim make-denial]] [clojure.string :as str])) (defn- to-sentence ([coll] (to-sentence coll " and ")) ([coll conjunction] (str/join conjunction (if-let [for-commas (seq (drop-last coll))] [(str/join ", " for-commas) (last coll)] [(last coll)])))) (defn- pluralize [number singular] (str number " " singular (when (not= number 1) "s"))) ;; general validations (defn is-present "Returns a validator fn that ensures the value of the given field is present (not nil and not a blank string). Arguments: - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"is required\") Return value: Returns a validation function that fails if the value of the given field is nil or a blank string. Example: ``` ((is-present :email) {:email \"me\"}) ; => nil ((is-present :email) {:email \"\"}) ; => [:email \"is required\"] ((is-present :email \"Uh oh\") {}) ; => [:email \"Uh oh\"] ``` " ([key] (is-present key "is required")) ([key error-msg] (make-claim #(when-let [value (get %1 key "")] (or (not (string? value)) (re-find #"\S" value))) key error-msg))) (defn is-one-of "Returns a validator fn that ensures the value of the given field is a member of the given set of permissible values. Arguments: - `collection` - the set of permissible values - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be either `(to-sentence collection)`\") Return value: Returns a validation function that fails if the value of the given field is not a member of `collection`. Example: ``` ((is-one-of #{:red :blue} :color) {:color :blue}) ; => nil ((is-one-of #{:red :blue} :color) {:color :green}) ; => [:color \"must be either :red or :blue\"] ((is-one-of #{:red :blue} :color \"Uh oh\") {}) ; => [:color \"Uh oh\"] ``` " ([collection key] (is-one-of collection key (str "must be either " (to-sentence collection " or ")))) ([collection key error-msg] (make-claim #(some #{(get %1 key)} collection) key error-msg))) (defn is-confirmed "Returns a validator fn that ensures the value of the given field matches the value of its confirmation field. Arguments: - `key` - the key whose value we will check is confirmed - `confirmation-key` - (optional) the key whose value should match that of `key` (defaults to :`key`-confirmation) - `error-msg` - (optional) custom error message (defaults to \"does not match\") Return value: Returns a validation function that fails if the value of the given field doesn't match the value of the confirmation field. Example: ``` ((is-confirmed :password) {:password \"abcd\" :password-confirmation \"abcd\"}) ; => nil ((is-confirmed :password) {:password \"abcd\" :password-confirmation \"bacd\"}) ; => [:password-confirmation \"doesn't match\"] ((is-confirmed :password :pswd-confirmation \"Uh oh\") {}) ; => [:pswd-confirmation \"Uh oh\"] ``` " ([key] (is-confirmed key (keyword (str (name key) "-confirmation")))) ([key confirmation-key] (is-confirmed key confirmation-key "does not match")) ([key confirmation-key error-msg] (make-claim #(and (contains? %1 key) (contains? %1 confirmation-key) (= (key %1) (confirmation-key %1))) confirmation-key error-msg))) ;; string validations (defn matches "Returns a validator fn that ensures the value of the given field matches the given regular expression. Arguments: - `regex` - the regular expression the value should match - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"is invalid\") Return value: Returns a validation function that fails if the value of the given field doesn't match `regex`. Example: ``` ((matches #\"\\d\" :password) {:password \"pass123\"}) ; => nil ((matches #\"\\d\" :password) {:password \"pass\"}) ; => [:password \"is invalid\"] ((matches #\"\\d\" :password \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([regex key] (matches regex key "is invalid")) ([regex key error-msg] (make-claim #(when-let [value (get %1 key "")] (re-find regex value)) key error-msg))) (defn length-is-at-least "Returns a validator fn that ensures the value of the given field is at least as long as the given length. Arguments: - `min-length` - the minimum permissible length - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be at least `min-length` characters\") Return value: Returns a validation function that fails if the value of the given field is shorter than `min-length`. Example: ``` ((length-is-at-least 8 :password) {:password \"password\"}) ; => nil ((length-is-at-least 8 :password) {:password \"pass\"}) ; => [:password \"must be at least 8 characters\"] ((length-is-at-least 8 :password \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([min-length key] (length-is-at-least min-length key (str "must be at least " (pluralize min-length "character")))) ([min-length key error-msg] (make-denial #(-> (get %1 key "") count (< min-length)) key error-msg))) (defn length-is-no-more-than "Returns a validator fn that ensures the value of the given field is at most as long as the given length. Arguments: - `max-length` - the maximum permissible length - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be no more than `(inc max-length)` characters\") Return value: Returns a validation function that fails if the value of the given field is shorter than `min-length`. Example: ``` ((length-is-no-more-than 4 :id) {:id \"abcd\"}) ; => nil ((length-is-no-more-than 4 :id) {:id \"abcde\"}) ; => [:id \"must be less than 5 characters\"] ((length-is-no-more-than 4 :id \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([max-length key] (length-is-no-more-than max-length key (str "must be less than " (pluralize (inc max-length) "character")))) ([max-length key error-msg] (make-denial #(-> (get %1 key "") count (> max-length)) key error-msg))) (defn is-at-least "Returns a validator fn that ensures the value of the given field is at least the value given. Arguments: - `bound` - the minimum permissible value - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be at least `bound`\") Return value: Returns a validation function that fails if the value of the given field is less than `bound`. Example: ``` ((is-at-least 18 :age) {:age 18}) ; => nil ((is-at-least 18 :age) {:age 17}) ; => [:age \"must be at least 18\"] ((is-at-least 18 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-at-least bound key (str "must be at least " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (not (pos? (compare bound (get %1 key))))) key error-msg))) (defn is-greater-than "Returns a validator fn that ensures the value of the given field is strictly greater than the value given. Arguments: - `bound` - the value above which valid values must be - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be greater than `bound`\") Return value: Returns a validation function that fails if the value of the given field is less than or equal to `bound`. Example: ``` ((is-greater-than 20 :age) {:age 21}) ; => nil ((is-greater-than 20 :age) {:age 20}) ; => [:age \"must be greater than 20\"] ((is-greater-than 20 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-greater-than bound key (str "must be greater than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (neg? (compare bound (get %1 key)))) key error-msg))) (defn is-less-than "Returns a validator fn that ensures the value of the given field is strictly less than the value given. Arguments: - `bound` - the value below which valid values must be - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be less than `bound`\") Return value: Returns a validation function that fails if the value of the given field is greater than or equal to `bound`. Example: ``` ((is-less-than 80 :age) {:age 79}) ; => nil ((is-less-than 80 :age) {:age 80}) ; => [:age \"must be less than 80\"] ((is-less-than 80 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-less-than bound key (str "must be less than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (pos? (compare bound (get %1 key)))) key error-msg))) (defn is-no-more-than "Returns a validator fn that ensures the value of the given field is no more than the value given. Arguments: - `bound` - the maximum permissible value - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be no more than `bound`\") Return value: Returns a validation function that fails if the value of the given field is greater than `bound`. Example: ``` ((is-no-more-than 80 :age) {:age 80}) ; => nil ((is-no-more-than 80 :age) {:age 81}) ; => [:age \"must be no more than 80\"] ((is-no-more-than 80 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-no-more-than bound key (str "must be no more than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (not (neg? (compare bound (get %1 key))))) key error-msg)))
32095
(ns heckle.validations (:require [heckle.core :refer [make-claim make-denial]] [clojure.string :as str])) (defn- to-sentence ([coll] (to-sentence coll " and ")) ([coll conjunction] (str/join conjunction (if-let [for-commas (seq (drop-last coll))] [(str/join ", " for-commas) (last coll)] [(last coll)])))) (defn- pluralize [number singular] (str number " " singular (when (not= number 1) "s"))) ;; general validations (defn is-present "Returns a validator fn that ensures the value of the given field is present (not nil and not a blank string). Arguments: - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"is required\") Return value: Returns a validation function that fails if the value of the given field is nil or a blank string. Example: ``` ((is-present :email) {:email \"me\"}) ; => nil ((is-present :email) {:email \"\"}) ; => [:email \"is required\"] ((is-present :email \"Uh oh\") {}) ; => [:email \"Uh oh\"] ``` " ([key] (is-present key "is required")) ([key error-msg] (make-claim #(when-let [value (get %1 key "")] (or (not (string? value)) (re-find #"\S" value))) key error-msg))) (defn is-one-of "Returns a validator fn that ensures the value of the given field is a member of the given set of permissible values. Arguments: - `collection` - the set of permissible values - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be either `(to-sentence collection)`\") Return value: Returns a validation function that fails if the value of the given field is not a member of `collection`. Example: ``` ((is-one-of #{:red :blue} :color) {:color :blue}) ; => nil ((is-one-of #{:red :blue} :color) {:color :green}) ; => [:color \"must be either :red or :blue\"] ((is-one-of #{:red :blue} :color \"Uh oh\") {}) ; => [:color \"Uh oh\"] ``` " ([collection key] (is-one-of collection key (str "must be either " (to-sentence collection " or ")))) ([collection key error-msg] (make-claim #(some #{(get %1 key)} collection) key error-msg))) (defn is-confirmed "Returns a validator fn that ensures the value of the given field matches the value of its confirmation field. Arguments: - `key` - the key whose value we will check is confirmed - `confirmation-key` - (optional) the key whose value should match that of `key` (defaults to :`key`-confirmation) - `error-msg` - (optional) custom error message (defaults to \"does not match\") Return value: Returns a validation function that fails if the value of the given field doesn't match the value of the confirmation field. Example: ``` ((is-confirmed :password) {:password \"<PASSWORD>\" :password-confirmation \"<PASSWORD>\"}) ; => nil ((is-confirmed :password) {:password \"<PASSWORD>\" :password-confirmation \"<PASSWORD>\"}) ; => [:password-confirmation \"doesn't match\"] ((is-confirmed :password :pswd-confirmation \"Uh oh\") {}) ; => [:pswd-confirmation \"Uh oh\"] ``` " ([key] (is-confirmed key (keyword (str (name key) "-confirmation")))) ([key confirmation-key] (is-confirmed key confirmation-key "does not match")) ([key confirmation-key error-msg] (make-claim #(and (contains? %1 key) (contains? %1 confirmation-key) (= (key %1) (confirmation-key %1))) confirmation-key error-msg))) ;; string validations (defn matches "Returns a validator fn that ensures the value of the given field matches the given regular expression. Arguments: - `regex` - the regular expression the value should match - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"is invalid\") Return value: Returns a validation function that fails if the value of the given field doesn't match `regex`. Example: ``` ((matches #\"\\d\" :password) {:password \"<PASSWORD>\"}) ; => nil ((matches #\"\\d\" :password) {:password \"<PASSWORD>\"}) ; => [:password \"is <PASSWORD>\"] ((matches #\"\\d\" :password \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([regex key] (matches regex key "is invalid")) ([regex key error-msg] (make-claim #(when-let [value (get %1 key "")] (re-find regex value)) key error-msg))) (defn length-is-at-least "Returns a validator fn that ensures the value of the given field is at least as long as the given length. Arguments: - `min-length` - the minimum permissible length - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be at least `min-length` characters\") Return value: Returns a validation function that fails if the value of the given field is shorter than `min-length`. Example: ``` ((length-is-at-least 8 :password) {:password \"<PASSWORD>\"}) ; => nil ((length-is-at-least 8 :password) {:password \"<PASSWORD>\"}) ; => [:password \"must be at least 8 <PASSWORD>\"] ((length-is-at-least 8 :password \"<PASSWORD>\") {}) ; => [:password \"Uh oh\"] ``` " ([min-length key] (length-is-at-least min-length key (str "must be at least " (pluralize min-length "character")))) ([min-length key error-msg] (make-denial #(-> (get %1 key "") count (< min-length)) key error-msg))) (defn length-is-no-more-than "Returns a validator fn that ensures the value of the given field is at most as long as the given length. Arguments: - `max-length` - the maximum permissible length - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be no more than `(inc max-length)` characters\") Return value: Returns a validation function that fails if the value of the given field is shorter than `min-length`. Example: ``` ((length-is-no-more-than 4 :id) {:id \"abcd\"}) ; => nil ((length-is-no-more-than 4 :id) {:id \"abcde\"}) ; => [:id \"must be less than 5 characters\"] ((length-is-no-more-than 4 :id \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([max-length key] (length-is-no-more-than max-length key (str "must be less than " (pluralize (inc max-length) "character")))) ([max-length key error-msg] (make-denial #(-> (get %1 key "") count (> max-length)) key error-msg))) (defn is-at-least "Returns a validator fn that ensures the value of the given field is at least the value given. Arguments: - `bound` - the minimum permissible value - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be at least `bound`\") Return value: Returns a validation function that fails if the value of the given field is less than `bound`. Example: ``` ((is-at-least 18 :age) {:age 18}) ; => nil ((is-at-least 18 :age) {:age 17}) ; => [:age \"must be at least 18\"] ((is-at-least 18 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-at-least bound key (str "must be at least " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (not (pos? (compare bound (get %1 key))))) key error-msg))) (defn is-greater-than "Returns a validator fn that ensures the value of the given field is strictly greater than the value given. Arguments: - `bound` - the value above which valid values must be - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be greater than `bound`\") Return value: Returns a validation function that fails if the value of the given field is less than or equal to `bound`. Example: ``` ((is-greater-than 20 :age) {:age 21}) ; => nil ((is-greater-than 20 :age) {:age 20}) ; => [:age \"must be greater than 20\"] ((is-greater-than 20 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-greater-than bound key (str "must be greater than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (neg? (compare bound (get %1 key)))) key error-msg))) (defn is-less-than "Returns a validator fn that ensures the value of the given field is strictly less than the value given. Arguments: - `bound` - the value below which valid values must be - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be less than `bound`\") Return value: Returns a validation function that fails if the value of the given field is greater than or equal to `bound`. Example: ``` ((is-less-than 80 :age) {:age 79}) ; => nil ((is-less-than 80 :age) {:age 80}) ; => [:age \"must be less than 80\"] ((is-less-than 80 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-less-than bound key (str "must be less than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (pos? (compare bound (get %1 key)))) key error-msg))) (defn is-no-more-than "Returns a validator fn that ensures the value of the given field is no more than the value given. Arguments: - `bound` - the maximum permissible value - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be no more than `bound`\") Return value: Returns a validation function that fails if the value of the given field is greater than `bound`. Example: ``` ((is-no-more-than 80 :age) {:age 80}) ; => nil ((is-no-more-than 80 :age) {:age 81}) ; => [:age \"must be no more than 80\"] ((is-no-more-than 80 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-no-more-than bound key (str "must be no more than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (not (neg? (compare bound (get %1 key))))) key error-msg)))
true
(ns heckle.validations (:require [heckle.core :refer [make-claim make-denial]] [clojure.string :as str])) (defn- to-sentence ([coll] (to-sentence coll " and ")) ([coll conjunction] (str/join conjunction (if-let [for-commas (seq (drop-last coll))] [(str/join ", " for-commas) (last coll)] [(last coll)])))) (defn- pluralize [number singular] (str number " " singular (when (not= number 1) "s"))) ;; general validations (defn is-present "Returns a validator fn that ensures the value of the given field is present (not nil and not a blank string). Arguments: - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"is required\") Return value: Returns a validation function that fails if the value of the given field is nil or a blank string. Example: ``` ((is-present :email) {:email \"me\"}) ; => nil ((is-present :email) {:email \"\"}) ; => [:email \"is required\"] ((is-present :email \"Uh oh\") {}) ; => [:email \"Uh oh\"] ``` " ([key] (is-present key "is required")) ([key error-msg] (make-claim #(when-let [value (get %1 key "")] (or (not (string? value)) (re-find #"\S" value))) key error-msg))) (defn is-one-of "Returns a validator fn that ensures the value of the given field is a member of the given set of permissible values. Arguments: - `collection` - the set of permissible values - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be either `(to-sentence collection)`\") Return value: Returns a validation function that fails if the value of the given field is not a member of `collection`. Example: ``` ((is-one-of #{:red :blue} :color) {:color :blue}) ; => nil ((is-one-of #{:red :blue} :color) {:color :green}) ; => [:color \"must be either :red or :blue\"] ((is-one-of #{:red :blue} :color \"Uh oh\") {}) ; => [:color \"Uh oh\"] ``` " ([collection key] (is-one-of collection key (str "must be either " (to-sentence collection " or ")))) ([collection key error-msg] (make-claim #(some #{(get %1 key)} collection) key error-msg))) (defn is-confirmed "Returns a validator fn that ensures the value of the given field matches the value of its confirmation field. Arguments: - `key` - the key whose value we will check is confirmed - `confirmation-key` - (optional) the key whose value should match that of `key` (defaults to :`key`-confirmation) - `error-msg` - (optional) custom error message (defaults to \"does not match\") Return value: Returns a validation function that fails if the value of the given field doesn't match the value of the confirmation field. Example: ``` ((is-confirmed :password) {:password \"PI:PASSWORD:<PASSWORD>END_PI\" :password-confirmation \"PI:PASSWORD:<PASSWORD>END_PI\"}) ; => nil ((is-confirmed :password) {:password \"PI:PASSWORD:<PASSWORD>END_PI\" :password-confirmation \"PI:PASSWORD:<PASSWORD>END_PI\"}) ; => [:password-confirmation \"doesn't match\"] ((is-confirmed :password :pswd-confirmation \"Uh oh\") {}) ; => [:pswd-confirmation \"Uh oh\"] ``` " ([key] (is-confirmed key (keyword (str (name key) "-confirmation")))) ([key confirmation-key] (is-confirmed key confirmation-key "does not match")) ([key confirmation-key error-msg] (make-claim #(and (contains? %1 key) (contains? %1 confirmation-key) (= (key %1) (confirmation-key %1))) confirmation-key error-msg))) ;; string validations (defn matches "Returns a validator fn that ensures the value of the given field matches the given regular expression. Arguments: - `regex` - the regular expression the value should match - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"is invalid\") Return value: Returns a validation function that fails if the value of the given field doesn't match `regex`. Example: ``` ((matches #\"\\d\" :password) {:password \"PI:PASSWORD:<PASSWORD>END_PI\"}) ; => nil ((matches #\"\\d\" :password) {:password \"PI:PASSWORD:<PASSWORD>END_PI\"}) ; => [:password \"is PI:PASSWORD:<PASSWORD>END_PI\"] ((matches #\"\\d\" :password \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([regex key] (matches regex key "is invalid")) ([regex key error-msg] (make-claim #(when-let [value (get %1 key "")] (re-find regex value)) key error-msg))) (defn length-is-at-least "Returns a validator fn that ensures the value of the given field is at least as long as the given length. Arguments: - `min-length` - the minimum permissible length - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be at least `min-length` characters\") Return value: Returns a validation function that fails if the value of the given field is shorter than `min-length`. Example: ``` ((length-is-at-least 8 :password) {:password \"PI:PASSWORD:<PASSWORD>END_PI\"}) ; => nil ((length-is-at-least 8 :password) {:password \"PI:PASSWORD:<PASSWORD>END_PI\"}) ; => [:password \"must be at least 8 PI:PASSWORD:<PASSWORD>END_PI\"] ((length-is-at-least 8 :password \"PI:PASSWORD:<PASSWORD>END_PI\") {}) ; => [:password \"Uh oh\"] ``` " ([min-length key] (length-is-at-least min-length key (str "must be at least " (pluralize min-length "character")))) ([min-length key error-msg] (make-denial #(-> (get %1 key "") count (< min-length)) key error-msg))) (defn length-is-no-more-than "Returns a validator fn that ensures the value of the given field is at most as long as the given length. Arguments: - `max-length` - the maximum permissible length - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be no more than `(inc max-length)` characters\") Return value: Returns a validation function that fails if the value of the given field is shorter than `min-length`. Example: ``` ((length-is-no-more-than 4 :id) {:id \"abcd\"}) ; => nil ((length-is-no-more-than 4 :id) {:id \"abcde\"}) ; => [:id \"must be less than 5 characters\"] ((length-is-no-more-than 4 :id \"Uh oh\") {}) ; => [:password \"Uh oh\"] ``` " ([max-length key] (length-is-no-more-than max-length key (str "must be less than " (pluralize (inc max-length) "character")))) ([max-length key error-msg] (make-denial #(-> (get %1 key "") count (> max-length)) key error-msg))) (defn is-at-least "Returns a validator fn that ensures the value of the given field is at least the value given. Arguments: - `bound` - the minimum permissible value - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be at least `bound`\") Return value: Returns a validation function that fails if the value of the given field is less than `bound`. Example: ``` ((is-at-least 18 :age) {:age 18}) ; => nil ((is-at-least 18 :age) {:age 17}) ; => [:age \"must be at least 18\"] ((is-at-least 18 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-at-least bound key (str "must be at least " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (not (pos? (compare bound (get %1 key))))) key error-msg))) (defn is-greater-than "Returns a validator fn that ensures the value of the given field is strictly greater than the value given. Arguments: - `bound` - the value above which valid values must be - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be greater than `bound`\") Return value: Returns a validation function that fails if the value of the given field is less than or equal to `bound`. Example: ``` ((is-greater-than 20 :age) {:age 21}) ; => nil ((is-greater-than 20 :age) {:age 20}) ; => [:age \"must be greater than 20\"] ((is-greater-than 20 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-greater-than bound key (str "must be greater than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (neg? (compare bound (get %1 key)))) key error-msg))) (defn is-less-than "Returns a validator fn that ensures the value of the given field is strictly less than the value given. Arguments: - `bound` - the value below which valid values must be - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be less than `bound`\") Return value: Returns a validation function that fails if the value of the given field is greater than or equal to `bound`. Example: ``` ((is-less-than 80 :age) {:age 79}) ; => nil ((is-less-than 80 :age) {:age 80}) ; => [:age \"must be less than 80\"] ((is-less-than 80 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-less-than bound key (str "must be less than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (pos? (compare bound (get %1 key)))) key error-msg))) (defn is-no-more-than "Returns a validator fn that ensures the value of the given field is no more than the value given. Arguments: - `bound` - the maximum permissible value - `key` - the key whose value we will check - `error-msg` - (optional) custom error message (defaults to \"must be no more than `bound`\") Return value: Returns a validation function that fails if the value of the given field is greater than `bound`. Example: ``` ((is-no-more-than 80 :age) {:age 80}) ; => nil ((is-no-more-than 80 :age) {:age 81}) ; => [:age \"must be no more than 80\"] ((is-no-more-than 80 :age \"Uh oh\") {}) ; => [:age \"Uh oh\"] ``` " ([bound key] (is-no-more-than bound key (str "must be no more than " bound))) ([bound key error-msg] (make-claim #(and (contains? %1 key) (not (neg? (compare bound (get %1 key))))) key error-msg)))
[ { "context": "ellow \"#FFC658\"\n :purple \"#8884D8\"\n :facebook \"#3b5998\"\n :twitter \"#00aced\"\n :linkedin \"#007bb6\"\n :pi", "end": 1904, "score": 0.7919525504112244, "start": 1898, "tag": "PASSWORD", "value": "3b5998" }, { "context": ":purple \"#8884D8\"\n :facebook \"#3b5998\"\n :twitter \"#00aced\"\n :linkedin \"#007bb6\"\n :pinterest \"#cb202", "end": 1916, "score": 0.8349950909614563, "start": 1916, "tag": "USERNAME", "value": "" }, { "context": "rple \"#8884D8\"\n :facebook \"#3b5998\"\n :twitter \"#00aced\"\n :linkedin \"#007bb6\"\n :pinterest \"#cb2027\"})\n\n", "end": 1925, "score": 0.8364251255989075, "start": 1919, "tag": "PASSWORD", "value": "00aced" }, { "context": "book \"#3b5998\"\n :twitter \"#00aced\"\n :linkedin \"#007bb6\"\n :pinterest \"#cb2027\"})\n\n(defn text-content [st", "end": 1947, "score": 0.7600415945053101, "start": 1941, "tag": "PASSWORD", "value": "007bb6" } ]
src/cljs/salava/admin/ui/statistics.cljs
discendum/salava
17
(ns salava.admin.ui.statistics (:require [reagent.core :refer [atom cursor adapt-react-class]] [reagent.session :as session] [reagent-modals.modals :as m] [clojure.string :refer [trim]] [salava.core.ui.ajax-utils :as ajax] [salava.core.ui.layout :as layout] [salava.core.ui.grid :as g] [salava.core.ui.helper :refer [path-for js-navigate-to plugin-fun]] [salava.core.i18n :refer [t]] [salava.core.helper :refer [dump]] [cljsjs.recharts] [clojure.string :refer [lower-case]] [salava.admin.ui.stats-helper :as dh] [salava.core.ui.modal :as mo])) #_(defn content [state] (let [{:keys [register-users last-month-active-users last-month-registered-users all-badges last-month-added-badges pages]} @state] [:div {:class "admin-stats"} ;[m/modal-window] [:h1 {:class "uppercase-header"} (t :admin/Statistics)] [:div.row [:div {:class "col-md-12"} [:h2.sectionheading (t :admin/Users)] [:div [:span._label.stats (t :admin/Registeredusers)] register-users] [:div [:span._label.stats (t :admin/Numberofmonthlyactiveuser)] last-month-active-users] [:div [:span._label.stats (t :admin/Numberofmonthlyregisteredusers)] last-month-registered-users] [:h2.sectionheading (t :badge/Badges)] [:div [:span._label.stats (t :admin/Totalbadges)] all-badges] [:div [:span._label.stats (t :admin/Numberofmonthlyaddedbadges) ] last-month-added-badges] [:h2.sectionheading (t :page/Pages)] [:div [:span._label.stats (t :admin/Totalpages)] pages]]]])) (def colors {:default "#82ca9d" :primary "#0275d8" :success "#5cb85c" :info "#5bc0de" :warning "#f0ad4e" :danger "#d9534f" :yellow "#FFC658" :purple "#8884D8" :facebook "#3b5998" :twitter "#00aced" :linkedin "#007bb6" :pinterest "#cb2027"}) (defn text-content [state] (reduce-kv (fn [r k v] (conj r [:div.row [:div.col-md-12 (when v [:h2.sectionheading (t (keyword (str "admin/" (name k))))]) (when (map? v) (reduce-kv (fn [x y z] (conj x [:div [:span._label.stats (t (keyword (str "admin/" (name y))))] z])) [:div] v))]])) [:div.admin-stats] (-> @state (dissoc :user-badge-correlation :visible :space-id)))) #_(defn init-social-media-stats [state] (ajax/GET (path-for "/obpv1/stats/social_media") {:handler (fn [data] ; (prn data) (reset! (cursor state [:social_media_stats]) data))})) (defn graphic-content [state] (let [{:keys [issuers users userbadges pages created issued user-badge-correlation spaces social_media_stats]} @state {:keys [factorybadges Totalbadgesno pendingbadgescount acceptedbadgescount declinedbadgescount privatebadgescount publicbadgescount internalbadgescount badgessincelastlogin badgessincelastmonth badgessince3month badgessince6month badgessince1year]} userbadges {:keys [notactivatedusers internalusers publicusers Totalusersno userssincelastlogin userssincelastmonth userssince3month userssince6month userssince1year logincountsincelastlogin]} users {:keys [pagessincelastlogin pagessince1year pagessince6month pagessince3month pagessincelastmonth internalpagescount privatepagescount publicpagescount Totalpagesno]} pages {:keys [issuerssince1year issuerssince6month issuerssince3month issuerssincelastmonth issuerssincelastlogin Totalissuersno]} issuers {:keys [Totalissuedno issuedsincelastmonth issuedsincelastlogin]} issued {:keys [Totalcreatedno createdsincelastmonth createdsincelastlogin]} created {:keys [Totalspacesno spacessincelastmonth spacessincelastlogin spacessince3month spacessince6month spacessince1year]} spaces {:keys [facebook linkedin pinterest twitter] } (:value social_media_stats) sm-share-total (+ facebook linkedin pinterest twitter)] [:div {:class "admin-stats"} [:div#panel-boxes [:div.row [dh/panel-box {:heading (t :admin/Totalusersno) :icon "fa-user-o" :info {:total Totalusersno :lastlogin userssincelastlogin :lastmonth userssincelastmonth} :type "b-user"}] [dh/panel-box {:heading (t :admin/Totalbadgesno) :icon "fa-certificate" :info {:total Totalbadgesno :lastlogin badgessincelastlogin :lastmonth badgessincelastmonth} :type "b-badge"}] [dh/panel-box {:heading (t :admin/Totalpagesno) :icon "fa-file-text-o" :info {:total Totalpagesno :lastlogin pagessincelastlogin :lastmonth pagessincelastmonth} :type "b-page"}] [dh/panel-box {:heading (t :admin/Totalissuersno) :icon "fa-building-o" :info {:total Totalissuersno :lastlogin issuerssincelastlogin :lastmonth issuerssincelastmonth} :type "b-page"}] (when created [dh/panel-box {:sbutton true :sfunc #(mo/open-modal [:admin :selfie] {}) :heading (t :badgeIssuer/Selfiebadges) :icon "fa-plus-square" :info {:total Totalcreatedno :lastlogin createdsincelastlogin :lastmonth createdsincelastmonth} :type "b-user"}]) (when spaces [dh/panel-box {:heading (t :extra-spaces/Spaces) :icon "fa-th-large" :info {:total Totalspacesno :lastlogin spacessincelastlogin :lastmonth spacessincelastmonth} :type "b-page"}])] [:div.row [dh/panel-box-chart {:size :lg ;:heading (t :admin/Sharing) :icon "fa-pie-chart" :type "b-page" :chart-type :pie ;:visibility-bar :split? true :chart-data [{:title (t :admin/badgeSource) :slices [{:name "Open Badge Factory " :value factorybadges :fill (:primary colors) :percentage (dh/%percentage factorybadges Totalbadgesno)} {:name (session/get :site-name "Passport") :value Totalissuedno :fill (:default colors) :percentage (dh/%percentage Totalissuedno Totalbadgesno)} {:name (t :admin/Other) :value (- Totalbadgesno (+ factorybadges Totalissuedno)) :fill (:yellow colors) :percentage (dh/%percentage (- Totalbadgesno (+ factorybadges Totalissuedno)) Totalbadgesno)}]} {:title (t :admin/badgeStatus) :slices [{:name (t :social/pending) :value pendingbadgescount :fill (:info colors) :percentage (dh/%percentage pendingbadgescount Totalbadgesno)} {:name (t :social/accepted) :value acceptedbadgescount :fill (:default colors) :percentage (dh/%percentage acceptedbadgescount Totalbadgesno)} {:name (t :social/declined) :value declinedbadgescount :fill (:danger colors) :percentage (dh/%percentage declinedbadgescount Totalbadgesno)}]} {:title (t :admin/userProfile) :slices [{:name (t :page/Public) :value publicusers :fill (:default colors) :percentage (dh/%percentage publicusers Totalusersno)} {:name (t :admin/Notactivated) :value notactivatedusers :fill (:danger colors) :percentage (dh/%percentage notactivatedusers Totalusersno)} {:name (t :core/Internal) :value internalusers :fill (:yellow colors) :percentage (dh/%percentage internalusers Totalusersno)}]} {:title (t :admin/badgeVisibility) :slices [{:name (t :page/Public) :value publicbadgescount :fill (:default colors) :percentage (dh/%percentage publicbadgescount Totalbadgesno)} {:name (t :page/Private) :value privatebadgescount :fill (:purple colors) :percentage (dh/%percentage privatebadgescount Totalbadgesno)} {:name (t :core/Internal) :value internalbadgescount :fill (:yellow colors) :percentage (dh/%percentage internalbadgescount Totalbadgesno)}]} {:title (t :admin/pageVisibility) :slices [{:name (t :page/Public) :value publicpagescount :fill (:default colors) :percentage (dh/%percentage publicpagescount Totalpagesno)} {:name (t :page/Private) :value privatepagescount :fill (:purple colors) :percentage (dh/%percentage privatepagescount Totalpagesno)} {:name (t :core/Internal) :value internalpagescount :fill (:yellow colors) :percentage (dh/%percentage internalpagescount Totalpagesno)}]}]}]] [dh/social-media-box state] [:div.row [dh/panel-box-chart {:size :lg :icon "fa-line-chart" :type "b-user" :chart-type :line :chart-data (as-> [{:info [{:name 12 :total (- Totalusersno userssince1year)} ;:active-users (:1yearlogincount users)} {:name 6 :total (- Totalusersno userssince6month)} ;:active-users (:6monthlogincount users)} {:name 3 :total (- Totalusersno userssince3month)} ;:active-users (:3monthlogincount users)} {:name 1 :total (- Totalusersno userssincelastmonth)} ;:active-users (:1monthlogincount users)} {:name 0 :total Totalusersno}] ;:active-users logincountsincelastlogin}] :lines [{:name (t :admin/Totalusersno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/userGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalbadgesno badgessince1year)} {:name 6 :total (- Totalbadgesno badgessince6month)} {:name 3 :total (- Totalbadgesno badgessince3month)} {:name 1 :total (- Totalbadgesno badgessincelastmonth)} {:name 0 :total Totalbadgesno}] :lines [{:name (t :admin/Totalbadgesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/badgeGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalpagesno pagessince1year)} {:name 6 :total (- Totalpagesno pagessince6month)} {:name 3 :total (- Totalpagesno pagessince3month)} {:name 1 :total (- Totalpagesno pagessincelastmonth)} {:name 0 :total Totalpagesno}] :lines [{:name (t :admin/Totalpagesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/pageGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalissuersno issuerssince1year)} {:name 6 :total (- Totalissuersno issuerssince6month)} {:name 3 :total (- Totalissuersno issuerssince3month)} {:name 1 :total (- Totalissuersno issuerssincelastmonth)} {:name 0 :total Totalissuersno}] :lines [{:name (t :admin/Totalissuersno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/issuerGrowth) :xlabel (t :admin/noofmonths)}] $ (if spaces (conj $ {:info [{:name 12 :total (- Totalspacesno spacessince1year)} {:name 6 :total (- Totalspacesno spacessince6month)} {:name 3 :total (- Totalspacesno spacessince3month)} {:name 1 :total (- Totalspacesno spacessincelastmonth)} {:name 0 :total Totalspacesno}] :lines [{:name (t :admin/Totalspacesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :extra-spaces/spaceGrowth) :xlabel (t :admin/noofmonths)}) (conj $ nil))) :tooltipLabel (t :admin/monthsago)}]] [:div.row [dh/panel-box-chart {:size :lg :icon "fa-bar-chart" :type "b-page" :chart-type :mixed :chart-data [{:info (sort-by :badge_count < user-badge-correlation) :title (t :admin/userBadgeDistribution) :elements [{:legendType "none" :name (clojure.string/lower-case (t :admin/users)) :key "user_count" :fill (:warning colors) :stackId "a" :type "bar"} {:legendType "none" :name (clojure.string/lower-case (t :admin/users)) :key "user_count" :type "line" :stroke (:primary colors) :activeDot {:r 8} :strokeWidth 3 :dot false}] :dataKeyX "badge_count" :dataKeyY "user_count" :xlabel (t :admin/noofbadges) :ylabel (t :admin/noofusers)}] :tooltipLabel (t :admin/userbadges)}]]]])) (defn export-stats [state] (let [url (if (pos? @(cursor state [:space-id])) (str "/obpv1/space/export_statistics?id=" @(cursor state [:space-id])) (str "/obpv1/admin/export_statistics"))] (js-navigate-to url))) (defn content [state] (let [visible-content (cursor state [:visible])] [:div [m/modal-window] [:div [:div.row [:div.col-md-12 [:div.btn-toolbar.pull-right {:style {:margin-bottom "20px"}} [:a.btn.btn-primary.btn-bulky {:href "#" :on-click #(if (= "text" @visible-content) (reset! visible-content "graphic") (reset! visible-content "text"))} (if (= "graphic" @visible-content) (t :admin/Plaintext) (t :admin/Showgraphicalui))] [:a.btn.btn-primary.btn-bulky {:href "#" :on-click #(export-stats state)} (t :admin/ExportCSV)]]] (into [:div] (for [f (plugin-fun (session/get :plugins) "block" "spaces_stats_dropdown")] (when f [f state]))) [:div.row [:div.col-md-12 (if (= "text" @visible-content) [text-content state] [graphic-content state])]]]]])) (defn init-data [state] (let [id (session/get-in [:user :current-space :id] 0)] (if (pos? id) (ajax/POST (path-for (str "/obpv1/space/stats/" id)) {:handler (fn [data] (reset! state (assoc data :visible "graphic" :space-id id)))}) (ajax/GET (path-for "/obpv1/admin/stats") {:handler (fn [data] (reset! state (assoc data :visible "graphic")))})))) (defn handler [site-navi] (let [state (atom {:register-users nil :last-month-active-users nil :last-month-registered-users nil :all-badges nil :last-month-added-badges nil :pages nil :visible "graphic" :social_media_stats {}})] (init-data state) (fn [] (layout/default site-navi (content state))))) (comment (def sample-data2 (repeatedly 50 #(hash-map :badge_count (rand-int 185) :user_count (rand-int 500)))) (def sample-data [{:badge_count 182 :user_count 1}{:badge_count 122 :user_count 1}{:badge_count 116 :user_count 1}{:badge_count 115 :user_count 2} {:badge_count 110 :user_count 2}{:badge_count 107 :user_count 1}{:badge_count 103 :user_count 3}{:badge_count 101 :user_count 2} {:badge_count 99 :user_count 3}{:badge_count 93 :user_count 1}{:badge_count 86 :user_count 1}{:badge_count 83 :user_count 1} {:badge_count 82 :user_count 1}{:badge_count 81 :user_count 1}{:badge_count 80 :user_count 2}{:badge_count 79 :user_count 1} {:badge_count 78 :user_count 1}{:badge_count 77 :user_count 1}{:badge_count 76 :user_count 3}{:badge_count 74 :user_count 3} {:badge_count 73 :user_count 2}{:badge_count 72 :user_count 2}{:badge_count 71 :user_count 4}{:badge_count 70 :user_count 1} {:badge_count 69 :user_count 2}{:badge_count 68 :user_count 1}{:badge_count 67 :user_count 3}{:badge_count 66 :user_count 4} {:badge_count 65 :user_count 4}{:badge_count 64 :user_count 2}{:badge_count 63 :user_count 2}{:badge_count 62 :user_count 3} {:badge_count 61 :user_count 2}{:badge_count 60 :user_count 8}{:badge_count 59 :user_count 4}{:badge_count 58 :user_count 3} {:badge_count 55 :user_count 1}{:badge_count 54 :user_count 3}{:badge_count 53 :user_count 1}{:badge_count 52 :user_count 3} {:badge_count 51 :user_count 2}{:badge_count 50 :user_count 3}{:badge_count 49 :user_count 6}{:badge_count 48 :user_count 4} {:badge_count 47 :user_count 7}{:badge_count 46 :user_count 4}{:badge_count 45 :user_count 8}{:badge_count 44 :user_count 3} {:badge_count 43 :user_count 6}{:badge_count 42 :user_count 6}{:badge_count 41 :user_count 13}{:badge_count 40 :user_count 7} {:badge_count 39 :user_count 12}{:badge_count 38 :user_count 13}{:badge_count 37 :user_count 17}{:badge_count 36 :user_count 13} {:badge_count 35 :user_count 15}{:badge_count 34 :user_count 21}{:badge_count 33 :user_count 26}{:badge_count 32 :user_count 23} {:badge_count 31 :user_count 21}{:badge_count 30 :user_count 28} {:badge_count 29 :user_count 24}{:badge_count 28 :user_count 12}{:badge_count 27 :user_count 36} {:badge_count 26 :user_count 47} {:badge_count 25 :user_count 57}{:badge_count 24 :user_count 100} {:badge_count 23 :user_count 49} {:badge_count 22 :user_count 55} {:badge_count 21 :user_count 80} {:badge_count 20 :user_count 58} {:badge_count 19 :user_count 52} {:badge_count 18 :user_count 101} {:badge_count 17 :user_count 139} {:badge_count 16 :user_count 248} {:badge_count 15 :user_count 434} {:badge_count 14 :user_count 263} {:badge_count 13 :user_count 383} {:badge_count 12 :user_count 401} {:badge_count 11 :user_count 397} {:badge_count 10 :user_count 503} {:badge_count 9 :user_count 734} {:badge_count 8 :user_count 1102} {:badge_count 7 :user_count 1927} {:badge_count 6 :user_count 1146} {:badge_count 5 :user_count 1761} {:badge_count 4 :user_count 1740} {:badge_count 3 :user_count 2492}{:badge_count 2 :user_count 5459} {:badge_count 1 :user_count 25968}]))
107224
(ns salava.admin.ui.statistics (:require [reagent.core :refer [atom cursor adapt-react-class]] [reagent.session :as session] [reagent-modals.modals :as m] [clojure.string :refer [trim]] [salava.core.ui.ajax-utils :as ajax] [salava.core.ui.layout :as layout] [salava.core.ui.grid :as g] [salava.core.ui.helper :refer [path-for js-navigate-to plugin-fun]] [salava.core.i18n :refer [t]] [salava.core.helper :refer [dump]] [cljsjs.recharts] [clojure.string :refer [lower-case]] [salava.admin.ui.stats-helper :as dh] [salava.core.ui.modal :as mo])) #_(defn content [state] (let [{:keys [register-users last-month-active-users last-month-registered-users all-badges last-month-added-badges pages]} @state] [:div {:class "admin-stats"} ;[m/modal-window] [:h1 {:class "uppercase-header"} (t :admin/Statistics)] [:div.row [:div {:class "col-md-12"} [:h2.sectionheading (t :admin/Users)] [:div [:span._label.stats (t :admin/Registeredusers)] register-users] [:div [:span._label.stats (t :admin/Numberofmonthlyactiveuser)] last-month-active-users] [:div [:span._label.stats (t :admin/Numberofmonthlyregisteredusers)] last-month-registered-users] [:h2.sectionheading (t :badge/Badges)] [:div [:span._label.stats (t :admin/Totalbadges)] all-badges] [:div [:span._label.stats (t :admin/Numberofmonthlyaddedbadges) ] last-month-added-badges] [:h2.sectionheading (t :page/Pages)] [:div [:span._label.stats (t :admin/Totalpages)] pages]]]])) (def colors {:default "#82ca9d" :primary "#0275d8" :success "#5cb85c" :info "#5bc0de" :warning "#f0ad4e" :danger "#d9534f" :yellow "#FFC658" :purple "#8884D8" :facebook "#<PASSWORD>" :twitter "#<PASSWORD>" :linkedin "#<PASSWORD>" :pinterest "#cb2027"}) (defn text-content [state] (reduce-kv (fn [r k v] (conj r [:div.row [:div.col-md-12 (when v [:h2.sectionheading (t (keyword (str "admin/" (name k))))]) (when (map? v) (reduce-kv (fn [x y z] (conj x [:div [:span._label.stats (t (keyword (str "admin/" (name y))))] z])) [:div] v))]])) [:div.admin-stats] (-> @state (dissoc :user-badge-correlation :visible :space-id)))) #_(defn init-social-media-stats [state] (ajax/GET (path-for "/obpv1/stats/social_media") {:handler (fn [data] ; (prn data) (reset! (cursor state [:social_media_stats]) data))})) (defn graphic-content [state] (let [{:keys [issuers users userbadges pages created issued user-badge-correlation spaces social_media_stats]} @state {:keys [factorybadges Totalbadgesno pendingbadgescount acceptedbadgescount declinedbadgescount privatebadgescount publicbadgescount internalbadgescount badgessincelastlogin badgessincelastmonth badgessince3month badgessince6month badgessince1year]} userbadges {:keys [notactivatedusers internalusers publicusers Totalusersno userssincelastlogin userssincelastmonth userssince3month userssince6month userssince1year logincountsincelastlogin]} users {:keys [pagessincelastlogin pagessince1year pagessince6month pagessince3month pagessincelastmonth internalpagescount privatepagescount publicpagescount Totalpagesno]} pages {:keys [issuerssince1year issuerssince6month issuerssince3month issuerssincelastmonth issuerssincelastlogin Totalissuersno]} issuers {:keys [Totalissuedno issuedsincelastmonth issuedsincelastlogin]} issued {:keys [Totalcreatedno createdsincelastmonth createdsincelastlogin]} created {:keys [Totalspacesno spacessincelastmonth spacessincelastlogin spacessince3month spacessince6month spacessince1year]} spaces {:keys [facebook linkedin pinterest twitter] } (:value social_media_stats) sm-share-total (+ facebook linkedin pinterest twitter)] [:div {:class "admin-stats"} [:div#panel-boxes [:div.row [dh/panel-box {:heading (t :admin/Totalusersno) :icon "fa-user-o" :info {:total Totalusersno :lastlogin userssincelastlogin :lastmonth userssincelastmonth} :type "b-user"}] [dh/panel-box {:heading (t :admin/Totalbadgesno) :icon "fa-certificate" :info {:total Totalbadgesno :lastlogin badgessincelastlogin :lastmonth badgessincelastmonth} :type "b-badge"}] [dh/panel-box {:heading (t :admin/Totalpagesno) :icon "fa-file-text-o" :info {:total Totalpagesno :lastlogin pagessincelastlogin :lastmonth pagessincelastmonth} :type "b-page"}] [dh/panel-box {:heading (t :admin/Totalissuersno) :icon "fa-building-o" :info {:total Totalissuersno :lastlogin issuerssincelastlogin :lastmonth issuerssincelastmonth} :type "b-page"}] (when created [dh/panel-box {:sbutton true :sfunc #(mo/open-modal [:admin :selfie] {}) :heading (t :badgeIssuer/Selfiebadges) :icon "fa-plus-square" :info {:total Totalcreatedno :lastlogin createdsincelastlogin :lastmonth createdsincelastmonth} :type "b-user"}]) (when spaces [dh/panel-box {:heading (t :extra-spaces/Spaces) :icon "fa-th-large" :info {:total Totalspacesno :lastlogin spacessincelastlogin :lastmonth spacessincelastmonth} :type "b-page"}])] [:div.row [dh/panel-box-chart {:size :lg ;:heading (t :admin/Sharing) :icon "fa-pie-chart" :type "b-page" :chart-type :pie ;:visibility-bar :split? true :chart-data [{:title (t :admin/badgeSource) :slices [{:name "Open Badge Factory " :value factorybadges :fill (:primary colors) :percentage (dh/%percentage factorybadges Totalbadgesno)} {:name (session/get :site-name "Passport") :value Totalissuedno :fill (:default colors) :percentage (dh/%percentage Totalissuedno Totalbadgesno)} {:name (t :admin/Other) :value (- Totalbadgesno (+ factorybadges Totalissuedno)) :fill (:yellow colors) :percentage (dh/%percentage (- Totalbadgesno (+ factorybadges Totalissuedno)) Totalbadgesno)}]} {:title (t :admin/badgeStatus) :slices [{:name (t :social/pending) :value pendingbadgescount :fill (:info colors) :percentage (dh/%percentage pendingbadgescount Totalbadgesno)} {:name (t :social/accepted) :value acceptedbadgescount :fill (:default colors) :percentage (dh/%percentage acceptedbadgescount Totalbadgesno)} {:name (t :social/declined) :value declinedbadgescount :fill (:danger colors) :percentage (dh/%percentage declinedbadgescount Totalbadgesno)}]} {:title (t :admin/userProfile) :slices [{:name (t :page/Public) :value publicusers :fill (:default colors) :percentage (dh/%percentage publicusers Totalusersno)} {:name (t :admin/Notactivated) :value notactivatedusers :fill (:danger colors) :percentage (dh/%percentage notactivatedusers Totalusersno)} {:name (t :core/Internal) :value internalusers :fill (:yellow colors) :percentage (dh/%percentage internalusers Totalusersno)}]} {:title (t :admin/badgeVisibility) :slices [{:name (t :page/Public) :value publicbadgescount :fill (:default colors) :percentage (dh/%percentage publicbadgescount Totalbadgesno)} {:name (t :page/Private) :value privatebadgescount :fill (:purple colors) :percentage (dh/%percentage privatebadgescount Totalbadgesno)} {:name (t :core/Internal) :value internalbadgescount :fill (:yellow colors) :percentage (dh/%percentage internalbadgescount Totalbadgesno)}]} {:title (t :admin/pageVisibility) :slices [{:name (t :page/Public) :value publicpagescount :fill (:default colors) :percentage (dh/%percentage publicpagescount Totalpagesno)} {:name (t :page/Private) :value privatepagescount :fill (:purple colors) :percentage (dh/%percentage privatepagescount Totalpagesno)} {:name (t :core/Internal) :value internalpagescount :fill (:yellow colors) :percentage (dh/%percentage internalpagescount Totalpagesno)}]}]}]] [dh/social-media-box state] [:div.row [dh/panel-box-chart {:size :lg :icon "fa-line-chart" :type "b-user" :chart-type :line :chart-data (as-> [{:info [{:name 12 :total (- Totalusersno userssince1year)} ;:active-users (:1yearlogincount users)} {:name 6 :total (- Totalusersno userssince6month)} ;:active-users (:6monthlogincount users)} {:name 3 :total (- Totalusersno userssince3month)} ;:active-users (:3monthlogincount users)} {:name 1 :total (- Totalusersno userssincelastmonth)} ;:active-users (:1monthlogincount users)} {:name 0 :total Totalusersno}] ;:active-users logincountsincelastlogin}] :lines [{:name (t :admin/Totalusersno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/userGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalbadgesno badgessince1year)} {:name 6 :total (- Totalbadgesno badgessince6month)} {:name 3 :total (- Totalbadgesno badgessince3month)} {:name 1 :total (- Totalbadgesno badgessincelastmonth)} {:name 0 :total Totalbadgesno}] :lines [{:name (t :admin/Totalbadgesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/badgeGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalpagesno pagessince1year)} {:name 6 :total (- Totalpagesno pagessince6month)} {:name 3 :total (- Totalpagesno pagessince3month)} {:name 1 :total (- Totalpagesno pagessincelastmonth)} {:name 0 :total Totalpagesno}] :lines [{:name (t :admin/Totalpagesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/pageGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalissuersno issuerssince1year)} {:name 6 :total (- Totalissuersno issuerssince6month)} {:name 3 :total (- Totalissuersno issuerssince3month)} {:name 1 :total (- Totalissuersno issuerssincelastmonth)} {:name 0 :total Totalissuersno}] :lines [{:name (t :admin/Totalissuersno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/issuerGrowth) :xlabel (t :admin/noofmonths)}] $ (if spaces (conj $ {:info [{:name 12 :total (- Totalspacesno spacessince1year)} {:name 6 :total (- Totalspacesno spacessince6month)} {:name 3 :total (- Totalspacesno spacessince3month)} {:name 1 :total (- Totalspacesno spacessincelastmonth)} {:name 0 :total Totalspacesno}] :lines [{:name (t :admin/Totalspacesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :extra-spaces/spaceGrowth) :xlabel (t :admin/noofmonths)}) (conj $ nil))) :tooltipLabel (t :admin/monthsago)}]] [:div.row [dh/panel-box-chart {:size :lg :icon "fa-bar-chart" :type "b-page" :chart-type :mixed :chart-data [{:info (sort-by :badge_count < user-badge-correlation) :title (t :admin/userBadgeDistribution) :elements [{:legendType "none" :name (clojure.string/lower-case (t :admin/users)) :key "user_count" :fill (:warning colors) :stackId "a" :type "bar"} {:legendType "none" :name (clojure.string/lower-case (t :admin/users)) :key "user_count" :type "line" :stroke (:primary colors) :activeDot {:r 8} :strokeWidth 3 :dot false}] :dataKeyX "badge_count" :dataKeyY "user_count" :xlabel (t :admin/noofbadges) :ylabel (t :admin/noofusers)}] :tooltipLabel (t :admin/userbadges)}]]]])) (defn export-stats [state] (let [url (if (pos? @(cursor state [:space-id])) (str "/obpv1/space/export_statistics?id=" @(cursor state [:space-id])) (str "/obpv1/admin/export_statistics"))] (js-navigate-to url))) (defn content [state] (let [visible-content (cursor state [:visible])] [:div [m/modal-window] [:div [:div.row [:div.col-md-12 [:div.btn-toolbar.pull-right {:style {:margin-bottom "20px"}} [:a.btn.btn-primary.btn-bulky {:href "#" :on-click #(if (= "text" @visible-content) (reset! visible-content "graphic") (reset! visible-content "text"))} (if (= "graphic" @visible-content) (t :admin/Plaintext) (t :admin/Showgraphicalui))] [:a.btn.btn-primary.btn-bulky {:href "#" :on-click #(export-stats state)} (t :admin/ExportCSV)]]] (into [:div] (for [f (plugin-fun (session/get :plugins) "block" "spaces_stats_dropdown")] (when f [f state]))) [:div.row [:div.col-md-12 (if (= "text" @visible-content) [text-content state] [graphic-content state])]]]]])) (defn init-data [state] (let [id (session/get-in [:user :current-space :id] 0)] (if (pos? id) (ajax/POST (path-for (str "/obpv1/space/stats/" id)) {:handler (fn [data] (reset! state (assoc data :visible "graphic" :space-id id)))}) (ajax/GET (path-for "/obpv1/admin/stats") {:handler (fn [data] (reset! state (assoc data :visible "graphic")))})))) (defn handler [site-navi] (let [state (atom {:register-users nil :last-month-active-users nil :last-month-registered-users nil :all-badges nil :last-month-added-badges nil :pages nil :visible "graphic" :social_media_stats {}})] (init-data state) (fn [] (layout/default site-navi (content state))))) (comment (def sample-data2 (repeatedly 50 #(hash-map :badge_count (rand-int 185) :user_count (rand-int 500)))) (def sample-data [{:badge_count 182 :user_count 1}{:badge_count 122 :user_count 1}{:badge_count 116 :user_count 1}{:badge_count 115 :user_count 2} {:badge_count 110 :user_count 2}{:badge_count 107 :user_count 1}{:badge_count 103 :user_count 3}{:badge_count 101 :user_count 2} {:badge_count 99 :user_count 3}{:badge_count 93 :user_count 1}{:badge_count 86 :user_count 1}{:badge_count 83 :user_count 1} {:badge_count 82 :user_count 1}{:badge_count 81 :user_count 1}{:badge_count 80 :user_count 2}{:badge_count 79 :user_count 1} {:badge_count 78 :user_count 1}{:badge_count 77 :user_count 1}{:badge_count 76 :user_count 3}{:badge_count 74 :user_count 3} {:badge_count 73 :user_count 2}{:badge_count 72 :user_count 2}{:badge_count 71 :user_count 4}{:badge_count 70 :user_count 1} {:badge_count 69 :user_count 2}{:badge_count 68 :user_count 1}{:badge_count 67 :user_count 3}{:badge_count 66 :user_count 4} {:badge_count 65 :user_count 4}{:badge_count 64 :user_count 2}{:badge_count 63 :user_count 2}{:badge_count 62 :user_count 3} {:badge_count 61 :user_count 2}{:badge_count 60 :user_count 8}{:badge_count 59 :user_count 4}{:badge_count 58 :user_count 3} {:badge_count 55 :user_count 1}{:badge_count 54 :user_count 3}{:badge_count 53 :user_count 1}{:badge_count 52 :user_count 3} {:badge_count 51 :user_count 2}{:badge_count 50 :user_count 3}{:badge_count 49 :user_count 6}{:badge_count 48 :user_count 4} {:badge_count 47 :user_count 7}{:badge_count 46 :user_count 4}{:badge_count 45 :user_count 8}{:badge_count 44 :user_count 3} {:badge_count 43 :user_count 6}{:badge_count 42 :user_count 6}{:badge_count 41 :user_count 13}{:badge_count 40 :user_count 7} {:badge_count 39 :user_count 12}{:badge_count 38 :user_count 13}{:badge_count 37 :user_count 17}{:badge_count 36 :user_count 13} {:badge_count 35 :user_count 15}{:badge_count 34 :user_count 21}{:badge_count 33 :user_count 26}{:badge_count 32 :user_count 23} {:badge_count 31 :user_count 21}{:badge_count 30 :user_count 28} {:badge_count 29 :user_count 24}{:badge_count 28 :user_count 12}{:badge_count 27 :user_count 36} {:badge_count 26 :user_count 47} {:badge_count 25 :user_count 57}{:badge_count 24 :user_count 100} {:badge_count 23 :user_count 49} {:badge_count 22 :user_count 55} {:badge_count 21 :user_count 80} {:badge_count 20 :user_count 58} {:badge_count 19 :user_count 52} {:badge_count 18 :user_count 101} {:badge_count 17 :user_count 139} {:badge_count 16 :user_count 248} {:badge_count 15 :user_count 434} {:badge_count 14 :user_count 263} {:badge_count 13 :user_count 383} {:badge_count 12 :user_count 401} {:badge_count 11 :user_count 397} {:badge_count 10 :user_count 503} {:badge_count 9 :user_count 734} {:badge_count 8 :user_count 1102} {:badge_count 7 :user_count 1927} {:badge_count 6 :user_count 1146} {:badge_count 5 :user_count 1761} {:badge_count 4 :user_count 1740} {:badge_count 3 :user_count 2492}{:badge_count 2 :user_count 5459} {:badge_count 1 :user_count 25968}]))
true
(ns salava.admin.ui.statistics (:require [reagent.core :refer [atom cursor adapt-react-class]] [reagent.session :as session] [reagent-modals.modals :as m] [clojure.string :refer [trim]] [salava.core.ui.ajax-utils :as ajax] [salava.core.ui.layout :as layout] [salava.core.ui.grid :as g] [salava.core.ui.helper :refer [path-for js-navigate-to plugin-fun]] [salava.core.i18n :refer [t]] [salava.core.helper :refer [dump]] [cljsjs.recharts] [clojure.string :refer [lower-case]] [salava.admin.ui.stats-helper :as dh] [salava.core.ui.modal :as mo])) #_(defn content [state] (let [{:keys [register-users last-month-active-users last-month-registered-users all-badges last-month-added-badges pages]} @state] [:div {:class "admin-stats"} ;[m/modal-window] [:h1 {:class "uppercase-header"} (t :admin/Statistics)] [:div.row [:div {:class "col-md-12"} [:h2.sectionheading (t :admin/Users)] [:div [:span._label.stats (t :admin/Registeredusers)] register-users] [:div [:span._label.stats (t :admin/Numberofmonthlyactiveuser)] last-month-active-users] [:div [:span._label.stats (t :admin/Numberofmonthlyregisteredusers)] last-month-registered-users] [:h2.sectionheading (t :badge/Badges)] [:div [:span._label.stats (t :admin/Totalbadges)] all-badges] [:div [:span._label.stats (t :admin/Numberofmonthlyaddedbadges) ] last-month-added-badges] [:h2.sectionheading (t :page/Pages)] [:div [:span._label.stats (t :admin/Totalpages)] pages]]]])) (def colors {:default "#82ca9d" :primary "#0275d8" :success "#5cb85c" :info "#5bc0de" :warning "#f0ad4e" :danger "#d9534f" :yellow "#FFC658" :purple "#8884D8" :facebook "#PI:PASSWORD:<PASSWORD>END_PI" :twitter "#PI:PASSWORD:<PASSWORD>END_PI" :linkedin "#PI:PASSWORD:<PASSWORD>END_PI" :pinterest "#cb2027"}) (defn text-content [state] (reduce-kv (fn [r k v] (conj r [:div.row [:div.col-md-12 (when v [:h2.sectionheading (t (keyword (str "admin/" (name k))))]) (when (map? v) (reduce-kv (fn [x y z] (conj x [:div [:span._label.stats (t (keyword (str "admin/" (name y))))] z])) [:div] v))]])) [:div.admin-stats] (-> @state (dissoc :user-badge-correlation :visible :space-id)))) #_(defn init-social-media-stats [state] (ajax/GET (path-for "/obpv1/stats/social_media") {:handler (fn [data] ; (prn data) (reset! (cursor state [:social_media_stats]) data))})) (defn graphic-content [state] (let [{:keys [issuers users userbadges pages created issued user-badge-correlation spaces social_media_stats]} @state {:keys [factorybadges Totalbadgesno pendingbadgescount acceptedbadgescount declinedbadgescount privatebadgescount publicbadgescount internalbadgescount badgessincelastlogin badgessincelastmonth badgessince3month badgessince6month badgessince1year]} userbadges {:keys [notactivatedusers internalusers publicusers Totalusersno userssincelastlogin userssincelastmonth userssince3month userssince6month userssince1year logincountsincelastlogin]} users {:keys [pagessincelastlogin pagessince1year pagessince6month pagessince3month pagessincelastmonth internalpagescount privatepagescount publicpagescount Totalpagesno]} pages {:keys [issuerssince1year issuerssince6month issuerssince3month issuerssincelastmonth issuerssincelastlogin Totalissuersno]} issuers {:keys [Totalissuedno issuedsincelastmonth issuedsincelastlogin]} issued {:keys [Totalcreatedno createdsincelastmonth createdsincelastlogin]} created {:keys [Totalspacesno spacessincelastmonth spacessincelastlogin spacessince3month spacessince6month spacessince1year]} spaces {:keys [facebook linkedin pinterest twitter] } (:value social_media_stats) sm-share-total (+ facebook linkedin pinterest twitter)] [:div {:class "admin-stats"} [:div#panel-boxes [:div.row [dh/panel-box {:heading (t :admin/Totalusersno) :icon "fa-user-o" :info {:total Totalusersno :lastlogin userssincelastlogin :lastmonth userssincelastmonth} :type "b-user"}] [dh/panel-box {:heading (t :admin/Totalbadgesno) :icon "fa-certificate" :info {:total Totalbadgesno :lastlogin badgessincelastlogin :lastmonth badgessincelastmonth} :type "b-badge"}] [dh/panel-box {:heading (t :admin/Totalpagesno) :icon "fa-file-text-o" :info {:total Totalpagesno :lastlogin pagessincelastlogin :lastmonth pagessincelastmonth} :type "b-page"}] [dh/panel-box {:heading (t :admin/Totalissuersno) :icon "fa-building-o" :info {:total Totalissuersno :lastlogin issuerssincelastlogin :lastmonth issuerssincelastmonth} :type "b-page"}] (when created [dh/panel-box {:sbutton true :sfunc #(mo/open-modal [:admin :selfie] {}) :heading (t :badgeIssuer/Selfiebadges) :icon "fa-plus-square" :info {:total Totalcreatedno :lastlogin createdsincelastlogin :lastmonth createdsincelastmonth} :type "b-user"}]) (when spaces [dh/panel-box {:heading (t :extra-spaces/Spaces) :icon "fa-th-large" :info {:total Totalspacesno :lastlogin spacessincelastlogin :lastmonth spacessincelastmonth} :type "b-page"}])] [:div.row [dh/panel-box-chart {:size :lg ;:heading (t :admin/Sharing) :icon "fa-pie-chart" :type "b-page" :chart-type :pie ;:visibility-bar :split? true :chart-data [{:title (t :admin/badgeSource) :slices [{:name "Open Badge Factory " :value factorybadges :fill (:primary colors) :percentage (dh/%percentage factorybadges Totalbadgesno)} {:name (session/get :site-name "Passport") :value Totalissuedno :fill (:default colors) :percentage (dh/%percentage Totalissuedno Totalbadgesno)} {:name (t :admin/Other) :value (- Totalbadgesno (+ factorybadges Totalissuedno)) :fill (:yellow colors) :percentage (dh/%percentage (- Totalbadgesno (+ factorybadges Totalissuedno)) Totalbadgesno)}]} {:title (t :admin/badgeStatus) :slices [{:name (t :social/pending) :value pendingbadgescount :fill (:info colors) :percentage (dh/%percentage pendingbadgescount Totalbadgesno)} {:name (t :social/accepted) :value acceptedbadgescount :fill (:default colors) :percentage (dh/%percentage acceptedbadgescount Totalbadgesno)} {:name (t :social/declined) :value declinedbadgescount :fill (:danger colors) :percentage (dh/%percentage declinedbadgescount Totalbadgesno)}]} {:title (t :admin/userProfile) :slices [{:name (t :page/Public) :value publicusers :fill (:default colors) :percentage (dh/%percentage publicusers Totalusersno)} {:name (t :admin/Notactivated) :value notactivatedusers :fill (:danger colors) :percentage (dh/%percentage notactivatedusers Totalusersno)} {:name (t :core/Internal) :value internalusers :fill (:yellow colors) :percentage (dh/%percentage internalusers Totalusersno)}]} {:title (t :admin/badgeVisibility) :slices [{:name (t :page/Public) :value publicbadgescount :fill (:default colors) :percentage (dh/%percentage publicbadgescount Totalbadgesno)} {:name (t :page/Private) :value privatebadgescount :fill (:purple colors) :percentage (dh/%percentage privatebadgescount Totalbadgesno)} {:name (t :core/Internal) :value internalbadgescount :fill (:yellow colors) :percentage (dh/%percentage internalbadgescount Totalbadgesno)}]} {:title (t :admin/pageVisibility) :slices [{:name (t :page/Public) :value publicpagescount :fill (:default colors) :percentage (dh/%percentage publicpagescount Totalpagesno)} {:name (t :page/Private) :value privatepagescount :fill (:purple colors) :percentage (dh/%percentage privatepagescount Totalpagesno)} {:name (t :core/Internal) :value internalpagescount :fill (:yellow colors) :percentage (dh/%percentage internalpagescount Totalpagesno)}]}]}]] [dh/social-media-box state] [:div.row [dh/panel-box-chart {:size :lg :icon "fa-line-chart" :type "b-user" :chart-type :line :chart-data (as-> [{:info [{:name 12 :total (- Totalusersno userssince1year)} ;:active-users (:1yearlogincount users)} {:name 6 :total (- Totalusersno userssince6month)} ;:active-users (:6monthlogincount users)} {:name 3 :total (- Totalusersno userssince3month)} ;:active-users (:3monthlogincount users)} {:name 1 :total (- Totalusersno userssincelastmonth)} ;:active-users (:1monthlogincount users)} {:name 0 :total Totalusersno}] ;:active-users logincountsincelastlogin}] :lines [{:name (t :admin/Totalusersno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/userGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalbadgesno badgessince1year)} {:name 6 :total (- Totalbadgesno badgessince6month)} {:name 3 :total (- Totalbadgesno badgessince3month)} {:name 1 :total (- Totalbadgesno badgessincelastmonth)} {:name 0 :total Totalbadgesno}] :lines [{:name (t :admin/Totalbadgesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/badgeGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalpagesno pagessince1year)} {:name 6 :total (- Totalpagesno pagessince6month)} {:name 3 :total (- Totalpagesno pagessince3month)} {:name 1 :total (- Totalpagesno pagessincelastmonth)} {:name 0 :total Totalpagesno}] :lines [{:name (t :admin/Totalpagesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/pageGrowth) :xlabel (t :admin/noofmonths)} {:info [{:name 12 :total (- Totalissuersno issuerssince1year)} {:name 6 :total (- Totalissuersno issuerssince6month)} {:name 3 :total (- Totalissuersno issuerssince3month)} {:name 1 :total (- Totalissuersno issuerssincelastmonth)} {:name 0 :total Totalissuersno}] :lines [{:name (t :admin/Totalissuersno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :admin/issuerGrowth) :xlabel (t :admin/noofmonths)}] $ (if spaces (conj $ {:info [{:name 12 :total (- Totalspacesno spacessince1year)} {:name 6 :total (- Totalspacesno spacessince6month)} {:name 3 :total (- Totalspacesno spacessince3month)} {:name 1 :total (- Totalspacesno spacessincelastmonth)} {:name 0 :total Totalspacesno}] :lines [{:name (t :admin/Totalspacesno) :key "total" :stroke (:primary colors) :activeDot {:r 10} :strokeWidth 3}] :title (t :extra-spaces/spaceGrowth) :xlabel (t :admin/noofmonths)}) (conj $ nil))) :tooltipLabel (t :admin/monthsago)}]] [:div.row [dh/panel-box-chart {:size :lg :icon "fa-bar-chart" :type "b-page" :chart-type :mixed :chart-data [{:info (sort-by :badge_count < user-badge-correlation) :title (t :admin/userBadgeDistribution) :elements [{:legendType "none" :name (clojure.string/lower-case (t :admin/users)) :key "user_count" :fill (:warning colors) :stackId "a" :type "bar"} {:legendType "none" :name (clojure.string/lower-case (t :admin/users)) :key "user_count" :type "line" :stroke (:primary colors) :activeDot {:r 8} :strokeWidth 3 :dot false}] :dataKeyX "badge_count" :dataKeyY "user_count" :xlabel (t :admin/noofbadges) :ylabel (t :admin/noofusers)}] :tooltipLabel (t :admin/userbadges)}]]]])) (defn export-stats [state] (let [url (if (pos? @(cursor state [:space-id])) (str "/obpv1/space/export_statistics?id=" @(cursor state [:space-id])) (str "/obpv1/admin/export_statistics"))] (js-navigate-to url))) (defn content [state] (let [visible-content (cursor state [:visible])] [:div [m/modal-window] [:div [:div.row [:div.col-md-12 [:div.btn-toolbar.pull-right {:style {:margin-bottom "20px"}} [:a.btn.btn-primary.btn-bulky {:href "#" :on-click #(if (= "text" @visible-content) (reset! visible-content "graphic") (reset! visible-content "text"))} (if (= "graphic" @visible-content) (t :admin/Plaintext) (t :admin/Showgraphicalui))] [:a.btn.btn-primary.btn-bulky {:href "#" :on-click #(export-stats state)} (t :admin/ExportCSV)]]] (into [:div] (for [f (plugin-fun (session/get :plugins) "block" "spaces_stats_dropdown")] (when f [f state]))) [:div.row [:div.col-md-12 (if (= "text" @visible-content) [text-content state] [graphic-content state])]]]]])) (defn init-data [state] (let [id (session/get-in [:user :current-space :id] 0)] (if (pos? id) (ajax/POST (path-for (str "/obpv1/space/stats/" id)) {:handler (fn [data] (reset! state (assoc data :visible "graphic" :space-id id)))}) (ajax/GET (path-for "/obpv1/admin/stats") {:handler (fn [data] (reset! state (assoc data :visible "graphic")))})))) (defn handler [site-navi] (let [state (atom {:register-users nil :last-month-active-users nil :last-month-registered-users nil :all-badges nil :last-month-added-badges nil :pages nil :visible "graphic" :social_media_stats {}})] (init-data state) (fn [] (layout/default site-navi (content state))))) (comment (def sample-data2 (repeatedly 50 #(hash-map :badge_count (rand-int 185) :user_count (rand-int 500)))) (def sample-data [{:badge_count 182 :user_count 1}{:badge_count 122 :user_count 1}{:badge_count 116 :user_count 1}{:badge_count 115 :user_count 2} {:badge_count 110 :user_count 2}{:badge_count 107 :user_count 1}{:badge_count 103 :user_count 3}{:badge_count 101 :user_count 2} {:badge_count 99 :user_count 3}{:badge_count 93 :user_count 1}{:badge_count 86 :user_count 1}{:badge_count 83 :user_count 1} {:badge_count 82 :user_count 1}{:badge_count 81 :user_count 1}{:badge_count 80 :user_count 2}{:badge_count 79 :user_count 1} {:badge_count 78 :user_count 1}{:badge_count 77 :user_count 1}{:badge_count 76 :user_count 3}{:badge_count 74 :user_count 3} {:badge_count 73 :user_count 2}{:badge_count 72 :user_count 2}{:badge_count 71 :user_count 4}{:badge_count 70 :user_count 1} {:badge_count 69 :user_count 2}{:badge_count 68 :user_count 1}{:badge_count 67 :user_count 3}{:badge_count 66 :user_count 4} {:badge_count 65 :user_count 4}{:badge_count 64 :user_count 2}{:badge_count 63 :user_count 2}{:badge_count 62 :user_count 3} {:badge_count 61 :user_count 2}{:badge_count 60 :user_count 8}{:badge_count 59 :user_count 4}{:badge_count 58 :user_count 3} {:badge_count 55 :user_count 1}{:badge_count 54 :user_count 3}{:badge_count 53 :user_count 1}{:badge_count 52 :user_count 3} {:badge_count 51 :user_count 2}{:badge_count 50 :user_count 3}{:badge_count 49 :user_count 6}{:badge_count 48 :user_count 4} {:badge_count 47 :user_count 7}{:badge_count 46 :user_count 4}{:badge_count 45 :user_count 8}{:badge_count 44 :user_count 3} {:badge_count 43 :user_count 6}{:badge_count 42 :user_count 6}{:badge_count 41 :user_count 13}{:badge_count 40 :user_count 7} {:badge_count 39 :user_count 12}{:badge_count 38 :user_count 13}{:badge_count 37 :user_count 17}{:badge_count 36 :user_count 13} {:badge_count 35 :user_count 15}{:badge_count 34 :user_count 21}{:badge_count 33 :user_count 26}{:badge_count 32 :user_count 23} {:badge_count 31 :user_count 21}{:badge_count 30 :user_count 28} {:badge_count 29 :user_count 24}{:badge_count 28 :user_count 12}{:badge_count 27 :user_count 36} {:badge_count 26 :user_count 47} {:badge_count 25 :user_count 57}{:badge_count 24 :user_count 100} {:badge_count 23 :user_count 49} {:badge_count 22 :user_count 55} {:badge_count 21 :user_count 80} {:badge_count 20 :user_count 58} {:badge_count 19 :user_count 52} {:badge_count 18 :user_count 101} {:badge_count 17 :user_count 139} {:badge_count 16 :user_count 248} {:badge_count 15 :user_count 434} {:badge_count 14 :user_count 263} {:badge_count 13 :user_count 383} {:badge_count 12 :user_count 401} {:badge_count 11 :user_count 397} {:badge_count 10 :user_count 503} {:badge_count 9 :user_count 734} {:badge_count 8 :user_count 1102} {:badge_count 7 :user_count 1927} {:badge_count 6 :user_count 1146} {:badge_count 5 :user_count 1761} {:badge_count 4 :user_count 1740} {:badge_count 3 :user_count 2492}{:badge_count 2 :user_count 5459} {:badge_count 1 :user_count 25968}]))
[ { "context": " (case (chrome-port/get-name client-port)\n \"Dirac Marionettist\" (let [context {:chrome-event-handler go-process-", "end": 1820, "score": 0.9882721900939941, "start": 1802, "tag": "NAME", "value": "Dirac Marionettist" } ]
src/background/dirac/background/chrome.cljs
mbertheau/dirac
802
(ns dirac.background.chrome (:require [chromex.chrome-event-channel :refer [make-chrome-event-channel]] [chromex.ext.browser-action :as browser-action] [chromex.ext.commands :as commands] [chromex.ext.runtime :as runtime] [chromex.ext.tabs :as tabs] [chromex.ext.windows :as windows] [chromex.protocols.chrome-port :as chrome-port] [dirac.background.devtools :as devtools] [dirac.background.logging :refer [error info log warn]] [dirac.background.marion :as marion] [dirac.background.state :as state] [dirac.background.tools :as tools] [dirac.shared.async :refer [<! go go-channel put!]] [oops.core :refer [oapply ocall oget oset!]])) (declare go-process-chrome-event!) ; -- event handlers --------------------------------------------------------------------------------------------------------- (defn go-handle-command! [command & args] (log "handling command" command args) (marion/post-feedback-event! (str "handling command: " command)) (case command "open-dirac-devtools" (apply tools/go-open-dirac-devtools-in-active-tab! args) "close-dirac-devtools" (apply tools/go-close-dirac-devtools! args) "focus-best-console-prompt" (apply tools/go-focus-best-console-prompt! args) (go (warn "received unrecognized command:" command)))) (defn go-handle-on-tab-removed! [tab-id _remove-info] (go (when (devtools/frontend-connected? tab-id) (devtools/unregister! tab-id)))) (defn go-handle-on-tab-updated! [tab-id _change-info _tab] (go (devtools/go-update-action-button! tab-id))) (defn go-handle-external-client-connection! [client-port] (go (case (chrome-port/get-name client-port) "Dirac Marionettist" (let [context {:chrome-event-handler go-process-chrome-event!}] (marion/go-handle-marion-client-connection! context client-port)) (warn "external connection attempt from unrecognized client" client-port)))) ; -- main event loop -------------------------------------------------------------------------------------------------------- (defn go-process-chrome-event! [event] (log "dispatch chrome event" event) (let [[event-id event-args] event] (case event-id ::browser-action/on-clicked (apply tools/go-activate-or-open-dirac-devtools! event-args) ::commands/on-command (apply go-handle-command! event-args) ::tabs/on-removed (apply go-handle-on-tab-removed! event-args) ::tabs/on-updated (apply go-handle-on-tab-updated! event-args) ::runtime/on-connect-external (apply go-handle-external-client-connection! event-args) (go)))) (defn go-run-chrome-event-loop! [chrome-event-channel] (go (log "starting main event loop...") (loop [] (when-some [event (<! chrome-event-channel)] (<! (go-process-chrome-event! event)) (recur))) (log "leaving main event loop"))) (defn go-init-and-run-chrome-event-loop! [] (let [channel (make-chrome-event-channel (go-channel))] (state/set-chrome-event-channel! channel) (tabs/tap-all-events channel) (runtime/tap-all-events channel) (windows/tap-all-events channel) (browser-action/tap-on-clicked-events channel) (commands/tap-on-command-events channel) (go-run-chrome-event-loop! channel)))
81573
(ns dirac.background.chrome (:require [chromex.chrome-event-channel :refer [make-chrome-event-channel]] [chromex.ext.browser-action :as browser-action] [chromex.ext.commands :as commands] [chromex.ext.runtime :as runtime] [chromex.ext.tabs :as tabs] [chromex.ext.windows :as windows] [chromex.protocols.chrome-port :as chrome-port] [dirac.background.devtools :as devtools] [dirac.background.logging :refer [error info log warn]] [dirac.background.marion :as marion] [dirac.background.state :as state] [dirac.background.tools :as tools] [dirac.shared.async :refer [<! go go-channel put!]] [oops.core :refer [oapply ocall oget oset!]])) (declare go-process-chrome-event!) ; -- event handlers --------------------------------------------------------------------------------------------------------- (defn go-handle-command! [command & args] (log "handling command" command args) (marion/post-feedback-event! (str "handling command: " command)) (case command "open-dirac-devtools" (apply tools/go-open-dirac-devtools-in-active-tab! args) "close-dirac-devtools" (apply tools/go-close-dirac-devtools! args) "focus-best-console-prompt" (apply tools/go-focus-best-console-prompt! args) (go (warn "received unrecognized command:" command)))) (defn go-handle-on-tab-removed! [tab-id _remove-info] (go (when (devtools/frontend-connected? tab-id) (devtools/unregister! tab-id)))) (defn go-handle-on-tab-updated! [tab-id _change-info _tab] (go (devtools/go-update-action-button! tab-id))) (defn go-handle-external-client-connection! [client-port] (go (case (chrome-port/get-name client-port) "<NAME>" (let [context {:chrome-event-handler go-process-chrome-event!}] (marion/go-handle-marion-client-connection! context client-port)) (warn "external connection attempt from unrecognized client" client-port)))) ; -- main event loop -------------------------------------------------------------------------------------------------------- (defn go-process-chrome-event! [event] (log "dispatch chrome event" event) (let [[event-id event-args] event] (case event-id ::browser-action/on-clicked (apply tools/go-activate-or-open-dirac-devtools! event-args) ::commands/on-command (apply go-handle-command! event-args) ::tabs/on-removed (apply go-handle-on-tab-removed! event-args) ::tabs/on-updated (apply go-handle-on-tab-updated! event-args) ::runtime/on-connect-external (apply go-handle-external-client-connection! event-args) (go)))) (defn go-run-chrome-event-loop! [chrome-event-channel] (go (log "starting main event loop...") (loop [] (when-some [event (<! chrome-event-channel)] (<! (go-process-chrome-event! event)) (recur))) (log "leaving main event loop"))) (defn go-init-and-run-chrome-event-loop! [] (let [channel (make-chrome-event-channel (go-channel))] (state/set-chrome-event-channel! channel) (tabs/tap-all-events channel) (runtime/tap-all-events channel) (windows/tap-all-events channel) (browser-action/tap-on-clicked-events channel) (commands/tap-on-command-events channel) (go-run-chrome-event-loop! channel)))
true
(ns dirac.background.chrome (:require [chromex.chrome-event-channel :refer [make-chrome-event-channel]] [chromex.ext.browser-action :as browser-action] [chromex.ext.commands :as commands] [chromex.ext.runtime :as runtime] [chromex.ext.tabs :as tabs] [chromex.ext.windows :as windows] [chromex.protocols.chrome-port :as chrome-port] [dirac.background.devtools :as devtools] [dirac.background.logging :refer [error info log warn]] [dirac.background.marion :as marion] [dirac.background.state :as state] [dirac.background.tools :as tools] [dirac.shared.async :refer [<! go go-channel put!]] [oops.core :refer [oapply ocall oget oset!]])) (declare go-process-chrome-event!) ; -- event handlers --------------------------------------------------------------------------------------------------------- (defn go-handle-command! [command & args] (log "handling command" command args) (marion/post-feedback-event! (str "handling command: " command)) (case command "open-dirac-devtools" (apply tools/go-open-dirac-devtools-in-active-tab! args) "close-dirac-devtools" (apply tools/go-close-dirac-devtools! args) "focus-best-console-prompt" (apply tools/go-focus-best-console-prompt! args) (go (warn "received unrecognized command:" command)))) (defn go-handle-on-tab-removed! [tab-id _remove-info] (go (when (devtools/frontend-connected? tab-id) (devtools/unregister! tab-id)))) (defn go-handle-on-tab-updated! [tab-id _change-info _tab] (go (devtools/go-update-action-button! tab-id))) (defn go-handle-external-client-connection! [client-port] (go (case (chrome-port/get-name client-port) "PI:NAME:<NAME>END_PI" (let [context {:chrome-event-handler go-process-chrome-event!}] (marion/go-handle-marion-client-connection! context client-port)) (warn "external connection attempt from unrecognized client" client-port)))) ; -- main event loop -------------------------------------------------------------------------------------------------------- (defn go-process-chrome-event! [event] (log "dispatch chrome event" event) (let [[event-id event-args] event] (case event-id ::browser-action/on-clicked (apply tools/go-activate-or-open-dirac-devtools! event-args) ::commands/on-command (apply go-handle-command! event-args) ::tabs/on-removed (apply go-handle-on-tab-removed! event-args) ::tabs/on-updated (apply go-handle-on-tab-updated! event-args) ::runtime/on-connect-external (apply go-handle-external-client-connection! event-args) (go)))) (defn go-run-chrome-event-loop! [chrome-event-channel] (go (log "starting main event loop...") (loop [] (when-some [event (<! chrome-event-channel)] (<! (go-process-chrome-event! event)) (recur))) (log "leaving main event loop"))) (defn go-init-and-run-chrome-event-loop! [] (let [channel (make-chrome-event-channel (go-channel))] (state/set-chrome-event-channel! channel) (tabs/tap-all-events channel) (runtime/tap-all-events channel) (windows/tap-all-events channel) (browser-action/tap-on-clicked-events channel) (commands/tap-on-command-events channel) (go-run-chrome-event-loop! channel)))