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": "List) person))\n\n; Data seeds\n(def wille (Person. \"Wille\"))\n(def becka (Person. \"Becka\"))\n(def jacob (Pers", "end": 509, "score": 0.9711285829544067, "start": 504, "tag": "NAME", "value": "Wille" }, { "context": "def wille (Person. \"Wille\"))\n(def becka (Person. \"Becka\"))\n(def jacob (Person. \"Jacob\"))\n(def vigge (Pers", "end": 539, "score": 0.9979965686798096, "start": 534, "tag": "NAME", "value": "Becka" }, { "context": "def becka (Person. \"Becka\"))\n(def jacob (Person. \"Jacob\"))\n(def vigge (Person. \"Vigge\"))\n(def sigge (Pers", "end": 569, "score": 0.9988198280334473, "start": 564, "tag": "NAME", "value": "Jacob" }, { "context": ". \"Becka\"))\n(def jacob (Person. \"Jacob\"))\n(def vigge (Person. \"Vigge\"))\n(def sigge (Person. \"Sigge\"))\n", "end": 583, "score": 0.6763707995414734, "start": 581, "tag": "NAME", "value": "ge" }, { "context": "def jacob (Person. \"Jacob\"))\n(def vigge (Person. \"Vigge\"))\n(def sigge (Person. \"Sigge\"))\n; Add contacts\n(", "end": 599, "score": 0.9972284436225891, "start": 594, "tag": "NAME", "value": "Vigge" }, { "context": "def vigge (Person. \"Vigge\"))\n(def sigge (Person. \"Sigge\"))\n; Add contacts\n(def contactList (ContactList. ", "end": 629, "score": 0.9889897108078003, "start": 624, "tag": "NAME", "value": "Sigge" } ]
contact_list.clj
buren/polyglot-contact-list
0
(ns contactlist) (defrecord Person [name]) (defn sayHiTo [person otherPerson] (str "Hi " (:name person) ", my name is " (:name otherPerson) ".")) (defrecord ContactList [owner contacts]) (defn getContactsByName [contactList name] (filter #(.startsWith (.name %) name) (:contacts contactList))) (defn getContactByName [contactList name] (first (getContactsByName contactList name))) (defn addContact [contactList person] (conj (:contacts contactList) person)) ; Data seeds (def wille (Person. "Wille")) (def becka (Person. "Becka")) (def jacob (Person. "Jacob")) (def vigge (Person. "Vigge")) (def sigge (Person. "Sigge")) ; Add contacts (def contactList (ContactList. wille [becka jacob vigge])) (def contactList (ContactList. wille (addContact contactList sigge))) ; Prints (println (sayHiTo wille becka)) (println (:name (getContactByName contactList (:name becka)))) (println (:name (getContactByName contactList "Ja")))
85300
(ns contactlist) (defrecord Person [name]) (defn sayHiTo [person otherPerson] (str "Hi " (:name person) ", my name is " (:name otherPerson) ".")) (defrecord ContactList [owner contacts]) (defn getContactsByName [contactList name] (filter #(.startsWith (.name %) name) (:contacts contactList))) (defn getContactByName [contactList name] (first (getContactsByName contactList name))) (defn addContact [contactList person] (conj (:contacts contactList) person)) ; Data seeds (def wille (Person. "<NAME>")) (def becka (Person. "<NAME>")) (def jacob (Person. "<NAME>")) (def vig<NAME> (Person. "<NAME>")) (def sigge (Person. "<NAME>")) ; Add contacts (def contactList (ContactList. wille [becka jacob vigge])) (def contactList (ContactList. wille (addContact contactList sigge))) ; Prints (println (sayHiTo wille becka)) (println (:name (getContactByName contactList (:name becka)))) (println (:name (getContactByName contactList "Ja")))
true
(ns contactlist) (defrecord Person [name]) (defn sayHiTo [person otherPerson] (str "Hi " (:name person) ", my name is " (:name otherPerson) ".")) (defrecord ContactList [owner contacts]) (defn getContactsByName [contactList name] (filter #(.startsWith (.name %) name) (:contacts contactList))) (defn getContactByName [contactList name] (first (getContactsByName contactList name))) (defn addContact [contactList person] (conj (:contacts contactList) person)) ; Data seeds (def wille (Person. "PI:NAME:<NAME>END_PI")) (def becka (Person. "PI:NAME:<NAME>END_PI")) (def jacob (Person. "PI:NAME:<NAME>END_PI")) (def vigPI:NAME:<NAME>END_PI (Person. "PI:NAME:<NAME>END_PI")) (def sigge (Person. "PI:NAME:<NAME>END_PI")) ; Add contacts (def contactList (ContactList. wille [becka jacob vigge])) (def contactList (ContactList. wille (addContact contactList sigge))) ; Prints (println (sayHiTo wille becka)) (println (:name (getContactByName contactList (:name becka)))) (println (:name (getContactByName contactList "Ja")))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998058676719666, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/uuid.clj
OctavioBR/healthcheck
14
; 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 clojure.uuid) (defn- default-uuid-reader [form] {:pre [(string? form)]} (java.util.UUID/fromString form)) (defmethod print-method java.util.UUID [uuid ^java.io.Writer w] (.write w (str "#uuid \"" (str uuid) "\""))) (defmethod print-dup java.util.UUID [o w] (print-method o w))
79954
; 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 clojure.uuid) (defn- default-uuid-reader [form] {:pre [(string? form)]} (java.util.UUID/fromString form)) (defmethod print-method java.util.UUID [uuid ^java.io.Writer w] (.write w (str "#uuid \"" (str uuid) "\""))) (defmethod print-dup java.util.UUID [o w] (print-method o w))
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 clojure.uuid) (defn- default-uuid-reader [form] {:pre [(string? form)]} (java.util.UUID/fromString form)) (defmethod print-method java.util.UUID [uuid ^java.io.Writer w] (.write w (str "#uuid \"" (str uuid) "\""))) (defmethod print-dup java.util.UUID [o w] (print-method o w))
[ { "context": "env (rand-env \"prod\")\n :key (rand-key \"service1\")\n :version \"1", "end": 721, "score": 0.8012000918388367, "start": 717, "tag": "KEY", "value": "rand" }, { "context": "env \"prod\")\n :key (rand-key \"service1\")\n :version \"1.2.3\"\n ", "end": 735, "score": 0.7890143394470215, "start": 727, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3", "end": 1146, "score": 0.7507119178771973, "start": 1141, "tag": "KEY", "value": "rand-" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n ", "end": 1159, "score": 0.9520845413208008, "start": 1151, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3", "end": 1700, "score": 0.7275378704071045, "start": 1695, "tag": "KEY", "value": "rand-" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n ", "end": 1713, "score": 0.917622983455658, "start": 1705, "tag": "KEY", "value": "service1" }, { "context": " (load {:env env\n :key (rand-key \"service2\")\n :versio", "end": 2058, "score": 0.7417075634002686, "start": 2053, "tag": "KEY", "value": "rand-" }, { "context": "nv env\n :key (rand-key \"service2\")\n :version ver}))\n ", "end": 2071, "score": 0.8312431573867798, "start": 2063, "tag": "KEY", "value": "service2" }, { "context": " [env (rand-env \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n ", "end": 2332, "score": 0.7328547239303589, "start": 2328, "tag": "KEY", "value": "rand" }, { "context": "rand-env \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n en", "end": 2346, "score": 0.9906848073005676, "start": 2338, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n ", "end": 3290, "score": 0.8542529940605164, "start": 3282, "tag": "KEY", "value": "rand-key" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n ", "end": 3300, "score": 0.9939786195755005, "start": 3292, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3", "end": 4583, "score": 0.8483455181121826, "start": 4578, "tag": "KEY", "value": "rand-" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n ver \"1.2.3\"\n ", "end": 4596, "score": 0.9948660135269165, "start": 4588, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n entry1 {:env", "end": 5721, "score": 0.7830588221549988, "start": 5717, "tag": "KEY", "value": "rand" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 5735, "score": 0.9893831014633179, "start": 5727, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n entry1 {:env", "end": 6712, "score": 0.8523134589195251, "start": 6708, "tag": "KEY", "value": "rand" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 6726, "score": 0.9849551916122437, "start": 6718, "tag": "KEY", "value": "service1" }, { "context": " env2 (rand-env \"dev\")\n\n key1 (rand-key \"serviceb\")\n key2 (rand-key \"se", "end": 7790, "score": 0.7795679569244385, "start": 7786, "tag": "KEY", "value": "rand" }, { "context": " (rand-env \"dev\")\n\n key1 (rand-key \"serviceb\")\n key2 (rand-key \"servicea\")\n ", "end": 7804, "score": 0.9913612604141235, "start": 7796, "tag": "KEY", "value": "serviceb" }, { "context": " key1 (rand-key \"serviceb\")\n key2 (rand-key \"servicea\")\n entry1 {:env e", "end": 7832, "score": 0.7817617058753967, "start": 7828, "tag": "KEY", "value": "rand" }, { "context": "nd-key \"serviceb\")\n key2 (rand-key \"servicea\")\n entry1 {:env env1\n ", "end": 7846, "score": 0.9771696329116821, "start": 7838, "tag": "KEY", "value": "servicea" }, { "context": "d-env \"prod\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 10670, "score": 0.8455348014831543, "start": 10662, "tag": "KEY", "value": "service1" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 11822, "score": 0.9030575752258301, "start": 11814, "tag": "KEY", "value": "service1" }, { "context": " (rand-env \"prod\")\n key (rand-key \"service1\")\n entry1 {:env ", "end": 12829, "score": 0.6474299430847168, "start": 12824, "tag": "KEY", "value": "rand-" }, { "context": "nv \"prod\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 12842, "score": 0.9740604162216187, "start": 12834, "tag": "KEY", "value": "service1" }, { "context": "key key\n :version \"1.2.5\"\n :value \"some-config", "end": 13139, "score": 0.7074850797653198, "start": 13138, "tag": "IP_ADDRESS", "value": "5" }, { "context": "d\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 13839, "score": 0.650154173374176, "start": 13838, "tag": "KEY", "value": "1" }, { "context": "d\")\n key (rand-key \"service1\")\n entry1 {:env env\n ", "end": 14852, "score": 0.6979696750640869, "start": 14851, "tag": "KEY", "value": "1" } ]
1config-core/test/com/brunobonacci/oneconfig/backend_test.clj
obohrer/1config
1
(ns com.brunobonacci.oneconfig.backend-test (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [in-memory-config-backend]] [com.brunobonacci.oneconfig.backends.dynamo :refer [dynamo-config-backend]] [midje.sweet :refer :all])) (defn uuid [] (str (java.util.UUID/randomUUID))) (defn rand-env [env] (str env "-" (uuid) )) (defn rand-key [key] (str key "-" (uuid) )) (defn compatibility-tests [store] (facts "config-backend: can store a value and read it back given a env, key and version" (let [entry {:env (rand-env "prod") :key (rand-key "service1") :version "1.2.3" :value "some-config"}] (-> store (save entry) (load (dissoc entry :value))) => (contains entry))) (facts "config-backend: loading a key which doesn't exist returns nil" (fact " > different environment" (let [env (rand-env "prod") key (rand-key "service1") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"}] (-> store (save entry1) (load {:env (rand-env "dev") :key key :version ver})) => nil)) (fact " > different key" (let [env (rand-env "prod") key (rand-key "service1") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"}] (-> store (save entry1) (load {:env env :key (rand-key "service2") :version ver})) => nil)) ) (facts "config-backend: storing multiple updates for the same env, key and version, only return last one" (let [env (rand-env "prod") key (rand-key "service1") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version ver})) => (contains entry3))) (facts "config-backend: you can load a specific change-num if it exists" (fact " > the change is returned when it exists" (let [env (rand-env "prod") key (rand-key "service1") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} store2 (-> store (save entry1) (save entry2)) cnum (:change-num (load store2 {:env env :key key :version ver})) store3 (save store2 entry3)] (load store3 {:env env :key key :version ver :change-num cnum}) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "service1") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version ver :change-num 10})) => nil)) ) (facts "config-backend: `load` returns the exact version when found or nil" (fact " > the specific version is returned when it exists" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.5"})) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.7"})) => nil)) ) (facts "config-backend: `list` returns all enties that match filters and sorted according to :key :env :version :change-num" (let [env1 (rand-env "prod") env2 (rand-env "dev") key1 (rand-key "serviceb") key2 (rand-key "servicea") entry1 {:env env1 :key key1 :version "1.2.3" :value "some-config1"} entry2 {:env env1 :key key1 :version "1.2.3" :value "some-config2"} entry3 {:env env1 :key key1 :version "1.2.5" :value "some-config3"} entry4 {:env env2 :key key1 :version "1.3.0" :value "some-config4"} entry5 {:env env1 :key key2 :version "1.3.0" :value "some-config5"} entry6 {:env env1 :key key1 :version "1.22.5" :value "some-config3"} entry7 {:env env1 :key key1 :version "1.3.5" :value "some-config3"} store (-> store (save entry2) (save entry1) (save entry3) (save entry4) (save entry5) (save entry6) (save entry7))] (fact "env filter returns entries that match" (->> (list store {:env env1}) (map #(dissoc % :change-num :content-type :backend))) => [(dissoc entry5 :value) (dissoc entry2 :value) (dissoc entry1 :value) (dissoc entry3 :value) (dissoc entry7 :value) (dissoc entry6 :value)]) (fact "key filter returns entries that match" (->> (list store {:key key2}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry5 :value))])) (fact "version filter returns entries that match and sorted by order inserted" (->> (list store {:version "1.2.3"}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry2 :value)) (contains (dissoc entry1 :value))])) (fact "Can combine filters" (->> (list store {:version "1.3.0" :env env2}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry4 :value)) ]))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.7"})) => nil)) ) (facts "config-backend: `find` returns a less-or-equal version (in semantic version terms) or nil of not found " (fact " > the specific version is returned when it exists" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.5"})) => (contains entry2))) (fact " > the less-or-equal version is returned when exact match is not found" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.7"})) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.1.7"})) => nil)) (fact " > semantic version comparison should be used rather than lexicographic" (let [env (rand-env "prod") key (rand-key "service1") entry1 {:env env :key key :version "1.1.5" :value "some-config1"} entry2 {:env env :key key :version "1.3.0" :value "some-config2"} entry3 {:env env :key key :version "1.10.7" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.0"})) => (contains entry1))) ) ) (facts "(*) compatibility tests for: in-memory-config-backend" (compatibility-tests (in-memory-config-backend))) (facts "(*) compatibility tests for: dynamo-config-backend" :integration ;; to run locally/repl requires ;; (System/setProperty "aws.accessKeyId" "xxx") ;; (System/setProperty "aws.secretKey" "xxx") (compatibility-tests (dynamo-config-backend {:table "1ConfigTest" :endpoint "eu-west-1"})))
85332
(ns com.brunobonacci.oneconfig.backend-test (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [in-memory-config-backend]] [com.brunobonacci.oneconfig.backends.dynamo :refer [dynamo-config-backend]] [midje.sweet :refer :all])) (defn uuid [] (str (java.util.UUID/randomUUID))) (defn rand-env [env] (str env "-" (uuid) )) (defn rand-key [key] (str key "-" (uuid) )) (defn compatibility-tests [store] (facts "config-backend: can store a value and read it back given a env, key and version" (let [entry {:env (rand-env "prod") :key (<KEY>-key "<KEY>") :version "1.2.3" :value "some-config"}] (-> store (save entry) (load (dissoc entry :value))) => (contains entry))) (facts "config-backend: loading a key which doesn't exist returns nil" (fact " > different environment" (let [env (rand-env "prod") key (<KEY>key "<KEY>") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"}] (-> store (save entry1) (load {:env (rand-env "dev") :key key :version ver})) => nil)) (fact " > different key" (let [env (rand-env "prod") key (<KEY>key "<KEY>") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"}] (-> store (save entry1) (load {:env env :key (<KEY>key "<KEY>") :version ver})) => nil)) ) (facts "config-backend: storing multiple updates for the same env, key and version, only return last one" (let [env (rand-env "prod") key (<KEY>-key "<KEY>") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version ver})) => (contains entry3))) (facts "config-backend: you can load a specific change-num if it exists" (fact " > the change is returned when it exists" (let [env (rand-env "prod") key (<KEY> "<KEY>") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} store2 (-> store (save entry1) (save entry2)) cnum (:change-num (load store2 {:env env :key key :version ver})) store3 (save store2 entry3)] (load store3 {:env env :key key :version ver :change-num cnum}) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (<KEY>key "<KEY>") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version ver :change-num 10})) => nil)) ) (facts "config-backend: `load` returns the exact version when found or nil" (fact " > the specific version is returned when it exists" (let [env (rand-env "prod") key (<KEY>-key "<KEY>") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.5"})) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (<KEY>-key "<KEY>") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.7"})) => nil)) ) (facts "config-backend: `list` returns all enties that match filters and sorted according to :key :env :version :change-num" (let [env1 (rand-env "prod") env2 (rand-env "dev") key1 (<KEY>-key "<KEY>") key2 (<KEY>-key "<KEY>") entry1 {:env env1 :key key1 :version "1.2.3" :value "some-config1"} entry2 {:env env1 :key key1 :version "1.2.3" :value "some-config2"} entry3 {:env env1 :key key1 :version "1.2.5" :value "some-config3"} entry4 {:env env2 :key key1 :version "1.3.0" :value "some-config4"} entry5 {:env env1 :key key2 :version "1.3.0" :value "some-config5"} entry6 {:env env1 :key key1 :version "1.22.5" :value "some-config3"} entry7 {:env env1 :key key1 :version "1.3.5" :value "some-config3"} store (-> store (save entry2) (save entry1) (save entry3) (save entry4) (save entry5) (save entry6) (save entry7))] (fact "env filter returns entries that match" (->> (list store {:env env1}) (map #(dissoc % :change-num :content-type :backend))) => [(dissoc entry5 :value) (dissoc entry2 :value) (dissoc entry1 :value) (dissoc entry3 :value) (dissoc entry7 :value) (dissoc entry6 :value)]) (fact "key filter returns entries that match" (->> (list store {:key key2}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry5 :value))])) (fact "version filter returns entries that match and sorted by order inserted" (->> (list store {:version "1.2.3"}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry2 :value)) (contains (dissoc entry1 :value))])) (fact "Can combine filters" (->> (list store {:version "1.3.0" :env env2}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry4 :value)) ]))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "<KEY>") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.7"})) => nil)) ) (facts "config-backend: `find` returns a less-or-equal version (in semantic version terms) or nil of not found " (fact " > the specific version is returned when it exists" (let [env (rand-env "prod") key (rand-key "<KEY>") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.5"})) => (contains entry2))) (fact " > the less-or-equal version is returned when exact match is not found" (let [env (rand-env "prod") key (<KEY>key "<KEY>") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.7"})) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "service<KEY>") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.1.7"})) => nil)) (fact " > semantic version comparison should be used rather than lexicographic" (let [env (rand-env "prod") key (rand-key "service<KEY>") entry1 {:env env :key key :version "1.1.5" :value "some-config1"} entry2 {:env env :key key :version "1.3.0" :value "some-config2"} entry3 {:env env :key key :version "1.10.7" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.0"})) => (contains entry1))) ) ) (facts "(*) compatibility tests for: in-memory-config-backend" (compatibility-tests (in-memory-config-backend))) (facts "(*) compatibility tests for: dynamo-config-backend" :integration ;; to run locally/repl requires ;; (System/setProperty "aws.accessKeyId" "xxx") ;; (System/setProperty "aws.secretKey" "xxx") (compatibility-tests (dynamo-config-backend {:table "1ConfigTest" :endpoint "eu-west-1"})))
true
(ns com.brunobonacci.oneconfig.backend-test (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [in-memory-config-backend]] [com.brunobonacci.oneconfig.backends.dynamo :refer [dynamo-config-backend]] [midje.sweet :refer :all])) (defn uuid [] (str (java.util.UUID/randomUUID))) (defn rand-env [env] (str env "-" (uuid) )) (defn rand-key [key] (str key "-" (uuid) )) (defn compatibility-tests [store] (facts "config-backend: can store a value and read it back given a env, key and version" (let [entry {:env (rand-env "prod") :key (PI:KEY:<KEY>END_PI-key "PI:KEY:<KEY>END_PI") :version "1.2.3" :value "some-config"}] (-> store (save entry) (load (dissoc entry :value))) => (contains entry))) (facts "config-backend: loading a key which doesn't exist returns nil" (fact " > different environment" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PIkey "PI:KEY:<KEY>END_PI") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"}] (-> store (save entry1) (load {:env (rand-env "dev") :key key :version ver})) => nil)) (fact " > different key" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PIkey "PI:KEY:<KEY>END_PI") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"}] (-> store (save entry1) (load {:env env :key (PI:KEY:<KEY>END_PIkey "PI:KEY:<KEY>END_PI") :version ver})) => nil)) ) (facts "config-backend: storing multiple updates for the same env, key and version, only return last one" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PI-key "PI:KEY:<KEY>END_PI") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version ver})) => (contains entry3))) (facts "config-backend: you can load a specific change-num if it exists" (fact " > the change is returned when it exists" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} store2 (-> store (save entry1) (save entry2)) cnum (:change-num (load store2 {:env env :key key :version ver})) store3 (save store2 entry3)] (load store3 {:env env :key key :version ver :change-num cnum}) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PIkey "PI:KEY:<KEY>END_PI") ver "1.2.3" entry1 {:env env :key key :version ver :value "some-config1"} entry2 {:env env :key key :version ver :value "some-config2"} entry3 {:env env :key key :version ver :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version ver :change-num 10})) => nil)) ) (facts "config-backend: `load` returns the exact version when found or nil" (fact " > the specific version is returned when it exists" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PI-key "PI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.5"})) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PI-key "PI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.7"})) => nil)) ) (facts "config-backend: `list` returns all enties that match filters and sorted according to :key :env :version :change-num" (let [env1 (rand-env "prod") env2 (rand-env "dev") key1 (PI:KEY:<KEY>END_PI-key "PI:KEY:<KEY>END_PI") key2 (PI:KEY:<KEY>END_PI-key "PI:KEY:<KEY>END_PI") entry1 {:env env1 :key key1 :version "1.2.3" :value "some-config1"} entry2 {:env env1 :key key1 :version "1.2.3" :value "some-config2"} entry3 {:env env1 :key key1 :version "1.2.5" :value "some-config3"} entry4 {:env env2 :key key1 :version "1.3.0" :value "some-config4"} entry5 {:env env1 :key key2 :version "1.3.0" :value "some-config5"} entry6 {:env env1 :key key1 :version "1.22.5" :value "some-config3"} entry7 {:env env1 :key key1 :version "1.3.5" :value "some-config3"} store (-> store (save entry2) (save entry1) (save entry3) (save entry4) (save entry5) (save entry6) (save entry7))] (fact "env filter returns entries that match" (->> (list store {:env env1}) (map #(dissoc % :change-num :content-type :backend))) => [(dissoc entry5 :value) (dissoc entry2 :value) (dissoc entry1 :value) (dissoc entry3 :value) (dissoc entry7 :value) (dissoc entry6 :value)]) (fact "key filter returns entries that match" (->> (list store {:key key2}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry5 :value))])) (fact "version filter returns entries that match and sorted by order inserted" (->> (list store {:version "1.2.3"}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry2 :value)) (contains (dissoc entry1 :value))])) (fact "Can combine filters" (->> (list store {:version "1.3.0" :env env2}) (map #(dissoc % :change-num :content-type))) => (contains [(contains (dissoc entry4 :value)) ]))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "PI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (load {:env env :key key :version "1.2.7"})) => nil)) ) (facts "config-backend: `find` returns a less-or-equal version (in semantic version terms) or nil of not found " (fact " > the specific version is returned when it exists" (let [env (rand-env "prod") key (rand-key "PI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.5"})) => (contains entry2))) (fact " > the less-or-equal version is returned when exact match is not found" (let [env (rand-env "prod") key (PI:KEY:<KEY>END_PIkey "PI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.7"})) => (contains entry2))) (fact " > nil is returned when it doesn't exists" (let [env (rand-env "prod") key (rand-key "servicePI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.2.3" :value "some-config1"} entry2 {:env env :key key :version "1.2.5" :value "some-config2"} entry3 {:env env :key key :version "1.3.0" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.1.7"})) => nil)) (fact " > semantic version comparison should be used rather than lexicographic" (let [env (rand-env "prod") key (rand-key "servicePI:KEY:<KEY>END_PI") entry1 {:env env :key key :version "1.1.5" :value "some-config1"} entry2 {:env env :key key :version "1.3.0" :value "some-config2"} entry3 {:env env :key key :version "1.10.7" :value "some-config3"} ] (-> store (save entry1) (save entry2) (save entry3) (find {:env env :key key :version "1.2.0"})) => (contains entry1))) ) ) (facts "(*) compatibility tests for: in-memory-config-backend" (compatibility-tests (in-memory-config-backend))) (facts "(*) compatibility tests for: dynamo-config-backend" :integration ;; to run locally/repl requires ;; (System/setProperty "aws.accessKeyId" "xxx") ;; (System/setProperty "aws.secretKey" "xxx") (compatibility-tests (dynamo-config-backend {:table "1ConfigTest" :endpoint "eu-west-1"})))
[ { "context": "->field :key :value Setting)]\n (if (= key \"settings-last-updated\")\n (cache/update-settings-last-updated!)", "end": 1402, "score": 0.9798887372016907, "start": 1381, "tag": "KEY", "value": "settings-last-updated" } ]
c#-metabase/src/metabase/cmd/rotate_encryption_key.clj
hanakhry/Crime_Admin
0
(ns metabase.cmd.rotate-encryption-key (:require [cheshire.core :as json] [clojure.java.jdbc :as jdbc] [metabase.db :as mdb] [metabase.db.connection :as mdb.conn] [metabase.models :refer [Database Setting]] [metabase.models.setting.cache :as cache] [metabase.util.encryption :as encrypt] [metabase.util.i18n :refer [trs]] [toucan.db :as db])) (defn rotate-encryption-key! "Rotate the current configured db using the current MB_ENCRYPTION_SECRET_KEY env var and `to-key` argument." [to-key] (mdb/setup-db!) (let [encrypt-fn (if to-key (partial encrypt/maybe-encrypt (encrypt/validate-and-hash-secret-key to-key)) identity)] (jdbc/with-db-transaction [t-conn (mdb.conn/jdbc-spec)] (doseq [[id details] (db/select-id->field :details Database)] (when (encrypt/possibly-encrypted-string? details) (throw (ex-info (trs "Can't decrypt app db with MB_ENCRYPTION_SECRET_KEY") {:database-id id}))) (jdbc/update! t-conn :metabase_database {:details (encrypt-fn (json/encode details))} ["metabase_database.id = ?" id])) (doseq [[key value] (db/select-field->field :key :value Setting)] (if (= key "settings-last-updated") (cache/update-settings-last-updated!) (jdbc/update! t-conn :setting {:value (encrypt-fn value)} ["setting.key = ?" key]))))))
13712
(ns metabase.cmd.rotate-encryption-key (:require [cheshire.core :as json] [clojure.java.jdbc :as jdbc] [metabase.db :as mdb] [metabase.db.connection :as mdb.conn] [metabase.models :refer [Database Setting]] [metabase.models.setting.cache :as cache] [metabase.util.encryption :as encrypt] [metabase.util.i18n :refer [trs]] [toucan.db :as db])) (defn rotate-encryption-key! "Rotate the current configured db using the current MB_ENCRYPTION_SECRET_KEY env var and `to-key` argument." [to-key] (mdb/setup-db!) (let [encrypt-fn (if to-key (partial encrypt/maybe-encrypt (encrypt/validate-and-hash-secret-key to-key)) identity)] (jdbc/with-db-transaction [t-conn (mdb.conn/jdbc-spec)] (doseq [[id details] (db/select-id->field :details Database)] (when (encrypt/possibly-encrypted-string? details) (throw (ex-info (trs "Can't decrypt app db with MB_ENCRYPTION_SECRET_KEY") {:database-id id}))) (jdbc/update! t-conn :metabase_database {:details (encrypt-fn (json/encode details))} ["metabase_database.id = ?" id])) (doseq [[key value] (db/select-field->field :key :value Setting)] (if (= key "<KEY>") (cache/update-settings-last-updated!) (jdbc/update! t-conn :setting {:value (encrypt-fn value)} ["setting.key = ?" key]))))))
true
(ns metabase.cmd.rotate-encryption-key (:require [cheshire.core :as json] [clojure.java.jdbc :as jdbc] [metabase.db :as mdb] [metabase.db.connection :as mdb.conn] [metabase.models :refer [Database Setting]] [metabase.models.setting.cache :as cache] [metabase.util.encryption :as encrypt] [metabase.util.i18n :refer [trs]] [toucan.db :as db])) (defn rotate-encryption-key! "Rotate the current configured db using the current MB_ENCRYPTION_SECRET_KEY env var and `to-key` argument." [to-key] (mdb/setup-db!) (let [encrypt-fn (if to-key (partial encrypt/maybe-encrypt (encrypt/validate-and-hash-secret-key to-key)) identity)] (jdbc/with-db-transaction [t-conn (mdb.conn/jdbc-spec)] (doseq [[id details] (db/select-id->field :details Database)] (when (encrypt/possibly-encrypted-string? details) (throw (ex-info (trs "Can't decrypt app db with MB_ENCRYPTION_SECRET_KEY") {:database-id id}))) (jdbc/update! t-conn :metabase_database {:details (encrypt-fn (json/encode details))} ["metabase_database.id = ?" id])) (doseq [[key value] (db/select-field->field :key :value Setting)] (if (= key "PI:KEY:<KEY>END_PI") (cache/update-settings-last-updated!) (jdbc/update! t-conn :setting {:value (encrypt-fn value)} ["setting.key = ?" key]))))))
[ { "context": ".test.std\n\n \"Testing `convex.std`.\"\n\n {:author \"Adam Helinski\"}\n\n (:refer-clojure :exclude [+\n ", "end": 73, "score": 0.9984833002090454, "start": 60, "tag": "NAME", "value": "Adam Helinski" } ]
project/cvm/src/clj/test/convex/test/std.clj
rosejn/convex.cljc
30
(ns convex.test.std "Testing `convex.std`." {:author "Adam Helinski"} (:refer-clojure :exclude [+ - * < <= == >= > assoc concat conj cons contains? count dec dissoc empty empty? find get hash-map hash-set inc into keys list merge mod name next nth reverse str vals vector zero?]) (:require [clojure.test :as T] [convex.cell :as $.cell] [convex.ref :as $.ref] [convex.std :as $.std])) ;;;;;;;;;; Casts (T/deftest str (T/is (= ($.cell/* "[:a :b]") ($.std/str ($.cell/* [:a :b]))))) ;;;;;;;;;; Collection constructors (let [k ($.cell/blob (byte-array [0]))] (T/deftest blob-map (T/is (= ($.cell/blob-map) ($.std/blob-map))) (T/is (= ($.cell/blob-map [[k ($.cell/* :a)]]) ($.std/blob-map k ($.cell/* :a)))) (T/is (thrown? IllegalArgumentException ($.std/blob-map k))))) (T/deftest hash-map (T/is (= ($.cell/* {}) ($.std/hash-map))) (T/is (= ($.cell/* {:a :b}) ($.std/hash-map ($.cell/* :a) ($.cell/* :b)))) (T/is (thrown? IllegalArgumentException ($.std/hash-map ($.cell/* :a))))) (T/deftest hash-set (T/is (= ($.cell/* #{}) ($.std/hash-set))) (T/is (= ($.cell/* #{:a :b}) ($.std/hash-set ($.cell/* :a) ($.cell/* :b))))) (T/deftest list (T/is (= ($.cell/* ()) ($.std/list))) (T/is (= ($.cell/* (:a :b)) ($.std/list ($.cell/* :a) ($.cell/* :b))))) (T/deftest vector (T/is (= ($.cell/* []) ($.std/vector))) (T/is (= ($.cell/* [:a :b]) ($.std/vector ($.cell/* :a) ($.cell/* :b))))) ;;;;;;;;;; Collection generics (T/deftest into (T/is (let [k ($.cell/blob (byte-array [0]))] (= ($.std/blob-map k ($.cell/* :a)) ($.std/into ($.cell/blob-map) ($.cell/* [[~k :a]]))))) (T/is (= ($.cell/* [:foo 2 3 4]) ($.std/into ($.cell/* [:foo]) (map $.std/inc) ($.cell/* (1 2 3)))))) ;;;;;;;;;; Comparators (T/deftest < (T/is (true? ($.std/< ($.cell/* 42) ($.cell/* 100)))) (T/is (false? ($.std/< ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/< ($.cell/* 42) ($.cell/* 1)))) (T/is (true? ($.std/< ($.cell/* 42.0) ($.cell/* 100)))) (T/is (false? ($.std/< ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/< ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest <= (T/is (true? ($.std/<= ($.cell/* 42) ($.cell/* 100)))) (T/is (true? ($.std/<= ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/<= ($.cell/* 42) ($.cell/* 1)))) (T/is (true? ($.std/<= ($.cell/* 42.0) ($.cell/* 100)))) (T/is (true? ($.std/<= ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/<= ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest == (T/is (true? ($.std/== ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/== ($.cell/* 1) ($.cell/* 42)))) (T/is (true? ($.std/== ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/== ($.cell/* 1.0) ($.cell/* 42))))) (T/deftest >= (T/is (false? ($.std/>= ($.cell/* 42) ($.cell/* 100)))) (T/is (true? ($.std/>= ($.cell/* 42) ($.cell/* 42)))) (T/is (true? ($.std/>= ($.cell/* 42) ($.cell/* 1)))) (T/is (false? ($.std/>= ($.cell/* 42.0) ($.cell/* 100)))) (T/is (true? ($.std/>= ($.cell/* 42.0) ($.cell/* 42)))) (T/is (true? ($.std/>= ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest > (T/is (false? ($.std/> ($.cell/* 42) ($.cell/* 100)))) (T/is (false? ($.std/> ($.cell/* 42) ($.cell/* 42)))) (T/is (true? ($.std/> ($.cell/* 42) ($.cell/* 1)))) (T/is (false? ($.std/> ($.cell/* 42.0) ($.cell/* 100)))) (T/is (false? ($.std/> ($.cell/* 42.0) ($.cell/* 42)))) (T/is (true? ($.std/> ($.cell/* 42.0) ($.cell/* 1))))) ;;;;;;;;;; Countable (T/deftest count (T/is (= 2 ($.std/count ($.cell/* (:a :b))))) (T/is (= 2 ($.std/count ($.cell/* [:a :b])))) (T/is (= 2 ($.std/count ($.cell/* {:a :b :c :d})))) (T/is (= 2 ($.std/count ($.cell/* #{:a :b})))) (T/is (= 2 ($.std/count ($.cell/* "ab")))) (T/is (= 2 ($.std/count ($.cell/blob (byte-array [1 2])))))) (T/deftest empty? (T/is ($.std/empty? ($.cell/* ()))) (T/is (not ($.std/empty? ($.cell/* (:a))))) (T/is ($.std/empty? ($.cell/* []))) (T/is (not ($.std/empty? ($.cell/* [:a])))) (T/is ($.std/empty? ($.cell/* {}))) (T/is (not ($.std/empty? ($.cell/* {:a :b})))) (T/is ($.std/empty? ($.cell/* #{}))) (T/is (not ($.std/empty? ($.cell/* #{:a})))) (T/is ($.std/empty? ($.cell/* ""))) (T/is (not ($.std/empty? ($.cell/* "a")))) (T/is ($.std/empty? ($.cell/blob (byte-array 0)))) (T/is (not ($.std/empty? ($.cell/blob (byte-array 1)))))) (let [a ($.cell/* :a)] (T/deftest nth (T/is (= a ($.std/nth ($.cell/* (:a :b)) 0))) (T/is (= a ($.std/nth ($.cell/* [:a :b]) 0))) (T/is (= ($.cell/* [:a :b]) ($.std/nth ($.cell/* {:a :b}) 0))) (T/is (= a ($.std/nth ($.cell/* #{:a}) 0))) (T/is (= ($.cell/* \a) ($.std/nth ($.cell/* "ab") 0))) (T/is (= ($.cell/byte 1) ($.std/nth ($.cell/blob (byte-array [1 2])) 0))))) (let [a ($.cell/* :a)] (T/deftest nth-ref (T/is (= a (-> ($.std/nth-ref ($.cell/* (:a :b)) 0) $.ref/resolve))) (T/is (= a (-> ($.std/nth-ref ($.cell/* [:a :b]) 0) $.ref/resolve))) (T/is (= ($.cell/* [:a :b]) (-> ($.std/nth-ref ($.cell/* {:a :b}) 0) $.ref/resolve))) (T/is (= a (-> ($.std/nth-ref ($.cell/* #{:a}) 0) $.ref/resolve))) (T/is (= ($.cell/* \a) (-> ($.std/nth-ref ($.cell/* "ab") 0) $.ref/resolve)) (T/is (= ($.cell/byte 1) (-> ($.std/nth-ref ($.cell/blob (byte-array [1 2])) 0) $.ref/resolve)))))) ;;;;;;;;;; Data structure (T/deftest assoc (T/is (= ($.cell/* (:b)) ($.std/assoc ($.cell/* (:a)) ($.cell/* 0) ($.cell/* :b)))) (T/is (= ($.cell/* [:b]) ($.std/assoc ($.cell/* [:a]) ($.cell/* 0) ($.cell/* :b)))) (T/is (= ($.cell/* {:a :c}) ($.std/assoc ($.cell/* {:a :b}) ($.cell/* :a) ($.cell/* :c)))) (T/is (= ($.cell/* #{:a :b}) ($.std/assoc ($.cell/* #{:a}) ($.cell/* :b) ($.cell/* true)))) (T/is (= ($.cell/* #{:a}) ($.std/assoc ($.cell/* #{:a :b}) ($.cell/* :b) ($.cell/* false))))) (T/deftest conj (T/is (= ($.cell/* (:b :a)) ($.std/conj ($.cell/* (:a)) ($.cell/* :b)))) (T/is (= ($.cell/* [:a :b]) ($.std/conj ($.cell/* [:a]) ($.cell/* :b)))) (T/is (= ($.cell/* {:a :b :c :d}) ($.std/conj ($.cell/* {:a :b}) ($.cell/* [:c :d])))) (T/is (= ($.cell/* #{:a :b}) ($.std/conj ($.cell/* #{:a}) ($.cell/* :b))))) (T/deftest contains? (T/is ($.std/contains? ($.cell/* (:a)) ($.cell/* 0))) (T/is (not ($.std/contains? ($.cell/* (:a)) ($.cell/* 1)))) (T/is ($.std/contains? ($.cell/* [:a]) ($.cell/* 0))) (T/is (not ($.std/contains? ($.cell/* [:a]) ($.cell/* 1)))) (T/is ($.std/contains? ($.cell/* {:a :b}) ($.cell/* :a))) (T/is (not ($.std/contains? ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is ($.std/contains? ($.cell/* #{:a}) ($.cell/* :a))) (T/is (not ($.std/contains? ($.cell/* #{:a}) ($.cell/* :b))))) (T/deftest empty (T/is (= ($.cell/* ()) ($.std/empty ($.cell/* (:a))))) (T/is (= ($.cell/* []) ($.std/empty ($.cell/* [:a])))) (T/is (= ($.cell/* {}) ($.std/empty ($.cell/* {:a :b})))) (T/is (= ($.cell/* #{}) ($.std/empty ($.cell/* #{:a}))))) (let [a ($.cell/* :a) b ($.cell/* :b)] (T/deftest get (T/is (= a ($.std/get ($.cell/* (:a)) ($.cell/* 0)))) (T/is (= a ($.std/get ($.cell/* [:a]) ($.cell/* 0)))) (T/is (= b ($.std/get ($.cell/* {:a :b}) a))) (T/is (= nil ($.std/get ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is (= ($.cell/* :not-found) ($.std/get ($.cell/* {:a :b}) ($.cell/* :c) ($.cell/* :not-found)))) (T/is (= ($.cell/* true) ($.std/get ($.cell/* #{:a}) a))) (T/is (= ($.cell/* false) ($.std/get ($.cell/* #{:a}) b))) (T/is (= ($.cell/* :not-found) ($.std/get ($.cell/* #{:a}) b ($.cell/* :not-found)))))) ;;;;;;;;;; Long (T/deftest dec (T/is (= ($.cell/* 41) ($.std/dec ($.cell/* 42))))) (T/deftest mod (T/is (= ($.cell/* 2) ($.std/mod ($.cell/* 2) ($.cell/* 5))))) (T/deftest inc (T/is (= ($.cell/* 43) ($.std/inc ($.cell/* 42))))) ;;;;;;;;;; Map (T/deftest dissoc (T/is (= ($.cell/* {}) ($.std/dissoc nil ($.cell/* :a)))) (T/is (= ($.cell/* {:a :b}) ($.std/dissoc ($.cell/* {:a :b :c :d}) ($.cell/* :c)))) (T/is (= ($.cell/blob-map) (let [b ($.cell/blob (byte-array [0]))] ($.std/dissoc ($.cell/blob-map [[b ($.cell/* :a)]]) b))))) (T/deftest find (T/is (nil? ($.std/find nil ($.cell/* :a)))) (T/is (nil? ($.std/find ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is (= ($.cell/* [:a :b]) ($.std/find ($.cell/* {:a :b}) ($.cell/* :a)))) (T/is (nil? ($.std/find ($.cell/blob-map [[($.cell/blob (byte-array [0])) ($.cell/* :a)]]) ($.cell/blob (byte-array [1]))))) (let [k ($.cell/blob (byte-array [0]))] (T/is (= ($.cell/* [~k ~($.cell/* :a)]) ($.std/find ($.cell/blob-map [[k ($.cell/* :a)]]) k))))) (T/deftest keys (T/is (= ($.cell/* []) ($.std/keys ($.cell/* {})))) (T/is (= ($.cell/* [:a]) ($.std/keys ($.cell/* {:a :b})))) (T/is (= ($.cell/* []) ($.std/keys ($.cell/blob-map)))) (let [k ($.cell/blob (byte-array [0]))] (T/is (= ($.cell/* [~k]) ($.std/keys ($.cell/blob-map [[k ($.cell/* :a)]])))))) (T/deftest merge (T/is (= ($.cell/* {}) ($.std/merge nil nil))) (T/is (= ($.cell/* {:a :b}) ($.std/merge ($.cell/* {:a :b}) nil))) (T/is (= ($.cell/* {:a :b}) ($.std/merge nil ($.cell/* {:a :b})))) (T/is (= ($.cell/* {:a :b :c :d}) ($.std/merge ($.cell/* {:a :b}) ($.cell/* {:c :d}))))) (T/deftest values (T/is (= ($.cell/* []) ($.std/vals ($.cell/* {})))) (T/is (= ($.cell/* [:b]) ($.std/vals ($.cell/* {:a :b})))) (T/is (= ($.cell/* []) ($.std/vals ($.cell/blob-map)))) (T/is (= ($.cell/* [:a]) ($.std/vals ($.cell/blob-map [[($.cell/blob (byte-array [0])) ($.cell/* :a)]]))))) ;;;;;;;;;; Math (T/deftest + (T/is (= ($.cell/* 10) ($.std/+ ($.cell/* 5) ($.cell/* 5)))) (T/is (= ($.cell/* 10.0) ($.std/+ ($.cell/* 5.0) ($.cell/* 5))))) (T/deftest - (T/is (= ($.cell/* 5) ($.std/- ($.cell/* 10) ($.cell/* 5)))) (T/is (= ($.cell/* 5.0) ($.std/- ($.cell/* 10.0) ($.cell/* 5))))) (T/deftest * (T/is (= ($.cell/* 50) ($.std/* ($.cell/* 10) ($.cell/* 5)))) (T/is (= ($.cell/* 50.0) ($.std/* ($.cell/* 10.0) ($.cell/* 5))))) (T/deftest abs (T/is (= ($.cell/* 42) ($.std/abs ($.cell/* 42)))) (T/is (= ($.cell/* 42) ($.std/abs ($.cell/* -42)))) (T/is (= ($.cell/* 42.24) ($.std/abs ($.cell/* 42.24)))) (T/is (= ($.cell/* 42.24) ($.std/abs ($.cell/* -42.24))))) (T/deftest ceil (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 42)))) (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 41.01)))) (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 41.99))))) (T/deftest div (T/is (= ($.cell/* 5.0) ($.std/div ($.cell/* 10) ($.cell/* 2)))) (T/is (= ($.cell/* 4.0) ($.std/div ($.cell/* 24) ($.cell/* 2) ($.cell/* 3))))) (T/deftest exp (T/is ($.std/double? ($.std/exp ($.cell/* 1))))) (T/deftest floor (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42)))) (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42.01)))) (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42.99))))) (T/deftest nan? (T/is (true? ($.std/nan? ($.cell/* ##NaN)))) (T/is (false? ($.std/nan? ($.cell/* 42.24))))) (T/deftest pow (T/is (= ($.cell/* 9.0) ($.std/pow ($.cell/* 3) ($.cell/* 2))))) (T/deftest signum (T/is (= ($.cell/* 1) ($.std/signum ($.cell/* 42)))) (T/is (= ($.cell/* -1) ($.std/signum ($.cell/* -42)))) (T/is (= ($.cell/* 0) ($.std/signum ($.cell/* 0)))) (T/is (= ($.cell/* 1.0) ($.std/signum ($.cell/* 42.0)))) (T/is (= ($.cell/* -1.0) ($.std/signum ($.cell/* -42.0)))) (T/is (= ($.cell/* 0.0) ($.std/signum ($.cell/* 0.0))))) (T/deftest sqrt (T/is (= ($.cell/* 4.0) ($.std/sqrt ($.cell/* 16.0))))) (T/deftest zero? (T/is (true? ($.std/zero? ($.cell/* 0)))) (T/is (true? ($.std/zero? ($.cell/* 0.0)))) (T/is (true? ($.std/zero? ($.cell/* -0.0)))) (T/is (false? ($.std/zero? ($.cell/* 1)))) (T/is (false? ($.std/zero? ($.cell/* []))))) ;;;;;;;;;; Sequence (T/deftest concat (T/is (nil? ($.std/concat nil nil))) (T/is (= ($.cell/* [:a]) ($.std/concat ($.cell/* [:a]) nil))) (T/is (= ($.cell/* [:a]) ($.std/concat nil ($.cell/* [:a])))) (T/is (= ($.cell/* (:a :b)) ($.std/concat ($.cell/* (:a)) ($.cell/* (:b))))) (T/is (= ($.cell/* (:a)) ($.std/concat ($.cell/* (:a)) nil))) (T/is (= ($.cell/* (:a)) ($.std/concat nil ($.cell/* (:a))))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* [:b])))) (T/is (= ($.cell/* [:a]) ($.std/concat ($.cell/* [:a]) nil))) (T/is (= ($.cell/* [:a]) ($.std/concat nil ($.cell/* [:a])))) (T/is (= ($.cell/* (:a :b)) ($.std/concat ($.cell/* (:a)) ($.cell/* [:b])))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* (:b))))) (T/is (= ($.cell/* [:a [:b :c]]) ($.std/concat ($.cell/* [:a]) ($.cell/* {:b :c})))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* #{:b}))))) (T/deftest cons (T/is (= ($.cell/* (:a)) ($.std/cons ($.cell/* :a) nil))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* (:a))))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* [:a])))) (T/is (= ($.cell/* (:c [:a :b])) ($.std/cons ($.cell/* :c) ($.cell/* {:a :b})))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* #{:a}))))) (T/deftest next (T/is (nil? ($.std/next ($.cell/* ())))) (T/is (nil? ($.std/next ($.cell/* (:a))))) (T/is (= ($.cell/* (:b)) ($.std/next ($.cell/* (:a :b))))) (T/is (nil? ($.std/next ($.cell/* [])))) (T/is (nil? ($.std/next ($.cell/* [:a])))) (T/is (= ($.cell/* [:b]) ($.std/next ($.cell/* [:a :b])))) (T/is (nil? ($.std/next ($.cell/* {})))) (T/is (nil? ($.std/next ($.cell/* {:a :b})))) (T/is (not ($.std/empty? ($.std/next ($.cell/* {:a :b :c :d}))))) (T/is (nil? ($.std/next ($.cell/* #{})))) (T/is (nil? ($.std/next ($.cell/* #{:a})))) (T/is (not ($.std/empty? ($.std/next ($.cell/* #{:a :b})))))) (T/deftest reverse (T/is (nil? ($.std/reverse nil))) (T/is (= ($.cell/* [:c :b :a]) ($.std/reverse ($.cell/* (:a :b :c))))) (T/is (= ($.cell/* (:c :b :a)) ($.std/reverse ($.cell/* [:a :b :c]))))) ;;;;;;;;;; Set (T/deftest difference (T/is (= ($.cell/* #{}) ($.std/difference nil nil))) (T/is (= ($.cell/* #{1}) ($.std/difference ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{}) ($.std/difference nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{}) ($.std/difference ($.cell/* #{1}) ($.cell/* #{1})))) (T/is (= ($.cell/* #{1 2}) ($.std/difference ($.cell/* #{1 2}) ($.cell/* #{3 4})))) (T/is (= ($.cell/* #{1}) ($.std/difference ($.cell/* #{1 2}) ($.cell/* #{2 3}))))) (T/deftest intersection (T/is (= ($.cell/* #{}) ($.std/intersection nil nil))) (T/is (= ($.cell/* #{}) ($.std/intersection ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{}) ($.std/intersection nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{2}) ($.std/intersection ($.cell/* #{1 2}) ($.cell/* #{2 3})))) (T/is (= ($.cell/* #{}) ($.std/intersection ($.cell/* #{1 2}) ($.cell/* #{3 4}))))) (T/deftest subset? (T/is (true? ($.std/subset? nil nil))) (T/is (true? ($.std/subset? nil ($.cell/* #{1})))) (T/is (false? ($.std/subset? ($.cell/* #{1}) nil))) (T/is (true? ($.std/subset? ($.cell/* #{1}) ($.cell/* #{1 2})))) (T/is (false? ($.std/subset? ($.cell/* #{1}) ($.cell/* #{2}))))) (T/deftest union (T/is (= ($.cell/* #{}) ($.std/union nil nil))) (T/is (= ($.cell/* #{1}) ($.std/union ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{1}) ($.std/union nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{1 2 3}) ($.std/union ($.cell/* #{1 2}) ($.cell/* #{2 3}))))) ;;;;;;;;; Symbolic (let [s ($.cell/* "test")] (T/deftest name (T/is (= s ($.std/name s))) (T/is (= s ($.std/name ($.cell/* test)))) (T/is (= s ($.std/name ($.cell/* :test))))))
34768
(ns convex.test.std "Testing `convex.std`." {:author "<NAME>"} (:refer-clojure :exclude [+ - * < <= == >= > assoc concat conj cons contains? count dec dissoc empty empty? find get hash-map hash-set inc into keys list merge mod name next nth reverse str vals vector zero?]) (:require [clojure.test :as T] [convex.cell :as $.cell] [convex.ref :as $.ref] [convex.std :as $.std])) ;;;;;;;;;; Casts (T/deftest str (T/is (= ($.cell/* "[:a :b]") ($.std/str ($.cell/* [:a :b]))))) ;;;;;;;;;; Collection constructors (let [k ($.cell/blob (byte-array [0]))] (T/deftest blob-map (T/is (= ($.cell/blob-map) ($.std/blob-map))) (T/is (= ($.cell/blob-map [[k ($.cell/* :a)]]) ($.std/blob-map k ($.cell/* :a)))) (T/is (thrown? IllegalArgumentException ($.std/blob-map k))))) (T/deftest hash-map (T/is (= ($.cell/* {}) ($.std/hash-map))) (T/is (= ($.cell/* {:a :b}) ($.std/hash-map ($.cell/* :a) ($.cell/* :b)))) (T/is (thrown? IllegalArgumentException ($.std/hash-map ($.cell/* :a))))) (T/deftest hash-set (T/is (= ($.cell/* #{}) ($.std/hash-set))) (T/is (= ($.cell/* #{:a :b}) ($.std/hash-set ($.cell/* :a) ($.cell/* :b))))) (T/deftest list (T/is (= ($.cell/* ()) ($.std/list))) (T/is (= ($.cell/* (:a :b)) ($.std/list ($.cell/* :a) ($.cell/* :b))))) (T/deftest vector (T/is (= ($.cell/* []) ($.std/vector))) (T/is (= ($.cell/* [:a :b]) ($.std/vector ($.cell/* :a) ($.cell/* :b))))) ;;;;;;;;;; Collection generics (T/deftest into (T/is (let [k ($.cell/blob (byte-array [0]))] (= ($.std/blob-map k ($.cell/* :a)) ($.std/into ($.cell/blob-map) ($.cell/* [[~k :a]]))))) (T/is (= ($.cell/* [:foo 2 3 4]) ($.std/into ($.cell/* [:foo]) (map $.std/inc) ($.cell/* (1 2 3)))))) ;;;;;;;;;; Comparators (T/deftest < (T/is (true? ($.std/< ($.cell/* 42) ($.cell/* 100)))) (T/is (false? ($.std/< ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/< ($.cell/* 42) ($.cell/* 1)))) (T/is (true? ($.std/< ($.cell/* 42.0) ($.cell/* 100)))) (T/is (false? ($.std/< ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/< ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest <= (T/is (true? ($.std/<= ($.cell/* 42) ($.cell/* 100)))) (T/is (true? ($.std/<= ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/<= ($.cell/* 42) ($.cell/* 1)))) (T/is (true? ($.std/<= ($.cell/* 42.0) ($.cell/* 100)))) (T/is (true? ($.std/<= ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/<= ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest == (T/is (true? ($.std/== ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/== ($.cell/* 1) ($.cell/* 42)))) (T/is (true? ($.std/== ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/== ($.cell/* 1.0) ($.cell/* 42))))) (T/deftest >= (T/is (false? ($.std/>= ($.cell/* 42) ($.cell/* 100)))) (T/is (true? ($.std/>= ($.cell/* 42) ($.cell/* 42)))) (T/is (true? ($.std/>= ($.cell/* 42) ($.cell/* 1)))) (T/is (false? ($.std/>= ($.cell/* 42.0) ($.cell/* 100)))) (T/is (true? ($.std/>= ($.cell/* 42.0) ($.cell/* 42)))) (T/is (true? ($.std/>= ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest > (T/is (false? ($.std/> ($.cell/* 42) ($.cell/* 100)))) (T/is (false? ($.std/> ($.cell/* 42) ($.cell/* 42)))) (T/is (true? ($.std/> ($.cell/* 42) ($.cell/* 1)))) (T/is (false? ($.std/> ($.cell/* 42.0) ($.cell/* 100)))) (T/is (false? ($.std/> ($.cell/* 42.0) ($.cell/* 42)))) (T/is (true? ($.std/> ($.cell/* 42.0) ($.cell/* 1))))) ;;;;;;;;;; Countable (T/deftest count (T/is (= 2 ($.std/count ($.cell/* (:a :b))))) (T/is (= 2 ($.std/count ($.cell/* [:a :b])))) (T/is (= 2 ($.std/count ($.cell/* {:a :b :c :d})))) (T/is (= 2 ($.std/count ($.cell/* #{:a :b})))) (T/is (= 2 ($.std/count ($.cell/* "ab")))) (T/is (= 2 ($.std/count ($.cell/blob (byte-array [1 2])))))) (T/deftest empty? (T/is ($.std/empty? ($.cell/* ()))) (T/is (not ($.std/empty? ($.cell/* (:a))))) (T/is ($.std/empty? ($.cell/* []))) (T/is (not ($.std/empty? ($.cell/* [:a])))) (T/is ($.std/empty? ($.cell/* {}))) (T/is (not ($.std/empty? ($.cell/* {:a :b})))) (T/is ($.std/empty? ($.cell/* #{}))) (T/is (not ($.std/empty? ($.cell/* #{:a})))) (T/is ($.std/empty? ($.cell/* ""))) (T/is (not ($.std/empty? ($.cell/* "a")))) (T/is ($.std/empty? ($.cell/blob (byte-array 0)))) (T/is (not ($.std/empty? ($.cell/blob (byte-array 1)))))) (let [a ($.cell/* :a)] (T/deftest nth (T/is (= a ($.std/nth ($.cell/* (:a :b)) 0))) (T/is (= a ($.std/nth ($.cell/* [:a :b]) 0))) (T/is (= ($.cell/* [:a :b]) ($.std/nth ($.cell/* {:a :b}) 0))) (T/is (= a ($.std/nth ($.cell/* #{:a}) 0))) (T/is (= ($.cell/* \a) ($.std/nth ($.cell/* "ab") 0))) (T/is (= ($.cell/byte 1) ($.std/nth ($.cell/blob (byte-array [1 2])) 0))))) (let [a ($.cell/* :a)] (T/deftest nth-ref (T/is (= a (-> ($.std/nth-ref ($.cell/* (:a :b)) 0) $.ref/resolve))) (T/is (= a (-> ($.std/nth-ref ($.cell/* [:a :b]) 0) $.ref/resolve))) (T/is (= ($.cell/* [:a :b]) (-> ($.std/nth-ref ($.cell/* {:a :b}) 0) $.ref/resolve))) (T/is (= a (-> ($.std/nth-ref ($.cell/* #{:a}) 0) $.ref/resolve))) (T/is (= ($.cell/* \a) (-> ($.std/nth-ref ($.cell/* "ab") 0) $.ref/resolve)) (T/is (= ($.cell/byte 1) (-> ($.std/nth-ref ($.cell/blob (byte-array [1 2])) 0) $.ref/resolve)))))) ;;;;;;;;;; Data structure (T/deftest assoc (T/is (= ($.cell/* (:b)) ($.std/assoc ($.cell/* (:a)) ($.cell/* 0) ($.cell/* :b)))) (T/is (= ($.cell/* [:b]) ($.std/assoc ($.cell/* [:a]) ($.cell/* 0) ($.cell/* :b)))) (T/is (= ($.cell/* {:a :c}) ($.std/assoc ($.cell/* {:a :b}) ($.cell/* :a) ($.cell/* :c)))) (T/is (= ($.cell/* #{:a :b}) ($.std/assoc ($.cell/* #{:a}) ($.cell/* :b) ($.cell/* true)))) (T/is (= ($.cell/* #{:a}) ($.std/assoc ($.cell/* #{:a :b}) ($.cell/* :b) ($.cell/* false))))) (T/deftest conj (T/is (= ($.cell/* (:b :a)) ($.std/conj ($.cell/* (:a)) ($.cell/* :b)))) (T/is (= ($.cell/* [:a :b]) ($.std/conj ($.cell/* [:a]) ($.cell/* :b)))) (T/is (= ($.cell/* {:a :b :c :d}) ($.std/conj ($.cell/* {:a :b}) ($.cell/* [:c :d])))) (T/is (= ($.cell/* #{:a :b}) ($.std/conj ($.cell/* #{:a}) ($.cell/* :b))))) (T/deftest contains? (T/is ($.std/contains? ($.cell/* (:a)) ($.cell/* 0))) (T/is (not ($.std/contains? ($.cell/* (:a)) ($.cell/* 1)))) (T/is ($.std/contains? ($.cell/* [:a]) ($.cell/* 0))) (T/is (not ($.std/contains? ($.cell/* [:a]) ($.cell/* 1)))) (T/is ($.std/contains? ($.cell/* {:a :b}) ($.cell/* :a))) (T/is (not ($.std/contains? ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is ($.std/contains? ($.cell/* #{:a}) ($.cell/* :a))) (T/is (not ($.std/contains? ($.cell/* #{:a}) ($.cell/* :b))))) (T/deftest empty (T/is (= ($.cell/* ()) ($.std/empty ($.cell/* (:a))))) (T/is (= ($.cell/* []) ($.std/empty ($.cell/* [:a])))) (T/is (= ($.cell/* {}) ($.std/empty ($.cell/* {:a :b})))) (T/is (= ($.cell/* #{}) ($.std/empty ($.cell/* #{:a}))))) (let [a ($.cell/* :a) b ($.cell/* :b)] (T/deftest get (T/is (= a ($.std/get ($.cell/* (:a)) ($.cell/* 0)))) (T/is (= a ($.std/get ($.cell/* [:a]) ($.cell/* 0)))) (T/is (= b ($.std/get ($.cell/* {:a :b}) a))) (T/is (= nil ($.std/get ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is (= ($.cell/* :not-found) ($.std/get ($.cell/* {:a :b}) ($.cell/* :c) ($.cell/* :not-found)))) (T/is (= ($.cell/* true) ($.std/get ($.cell/* #{:a}) a))) (T/is (= ($.cell/* false) ($.std/get ($.cell/* #{:a}) b))) (T/is (= ($.cell/* :not-found) ($.std/get ($.cell/* #{:a}) b ($.cell/* :not-found)))))) ;;;;;;;;;; Long (T/deftest dec (T/is (= ($.cell/* 41) ($.std/dec ($.cell/* 42))))) (T/deftest mod (T/is (= ($.cell/* 2) ($.std/mod ($.cell/* 2) ($.cell/* 5))))) (T/deftest inc (T/is (= ($.cell/* 43) ($.std/inc ($.cell/* 42))))) ;;;;;;;;;; Map (T/deftest dissoc (T/is (= ($.cell/* {}) ($.std/dissoc nil ($.cell/* :a)))) (T/is (= ($.cell/* {:a :b}) ($.std/dissoc ($.cell/* {:a :b :c :d}) ($.cell/* :c)))) (T/is (= ($.cell/blob-map) (let [b ($.cell/blob (byte-array [0]))] ($.std/dissoc ($.cell/blob-map [[b ($.cell/* :a)]]) b))))) (T/deftest find (T/is (nil? ($.std/find nil ($.cell/* :a)))) (T/is (nil? ($.std/find ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is (= ($.cell/* [:a :b]) ($.std/find ($.cell/* {:a :b}) ($.cell/* :a)))) (T/is (nil? ($.std/find ($.cell/blob-map [[($.cell/blob (byte-array [0])) ($.cell/* :a)]]) ($.cell/blob (byte-array [1]))))) (let [k ($.cell/blob (byte-array [0]))] (T/is (= ($.cell/* [~k ~($.cell/* :a)]) ($.std/find ($.cell/blob-map [[k ($.cell/* :a)]]) k))))) (T/deftest keys (T/is (= ($.cell/* []) ($.std/keys ($.cell/* {})))) (T/is (= ($.cell/* [:a]) ($.std/keys ($.cell/* {:a :b})))) (T/is (= ($.cell/* []) ($.std/keys ($.cell/blob-map)))) (let [k ($.cell/blob (byte-array [0]))] (T/is (= ($.cell/* [~k]) ($.std/keys ($.cell/blob-map [[k ($.cell/* :a)]])))))) (T/deftest merge (T/is (= ($.cell/* {}) ($.std/merge nil nil))) (T/is (= ($.cell/* {:a :b}) ($.std/merge ($.cell/* {:a :b}) nil))) (T/is (= ($.cell/* {:a :b}) ($.std/merge nil ($.cell/* {:a :b})))) (T/is (= ($.cell/* {:a :b :c :d}) ($.std/merge ($.cell/* {:a :b}) ($.cell/* {:c :d}))))) (T/deftest values (T/is (= ($.cell/* []) ($.std/vals ($.cell/* {})))) (T/is (= ($.cell/* [:b]) ($.std/vals ($.cell/* {:a :b})))) (T/is (= ($.cell/* []) ($.std/vals ($.cell/blob-map)))) (T/is (= ($.cell/* [:a]) ($.std/vals ($.cell/blob-map [[($.cell/blob (byte-array [0])) ($.cell/* :a)]]))))) ;;;;;;;;;; Math (T/deftest + (T/is (= ($.cell/* 10) ($.std/+ ($.cell/* 5) ($.cell/* 5)))) (T/is (= ($.cell/* 10.0) ($.std/+ ($.cell/* 5.0) ($.cell/* 5))))) (T/deftest - (T/is (= ($.cell/* 5) ($.std/- ($.cell/* 10) ($.cell/* 5)))) (T/is (= ($.cell/* 5.0) ($.std/- ($.cell/* 10.0) ($.cell/* 5))))) (T/deftest * (T/is (= ($.cell/* 50) ($.std/* ($.cell/* 10) ($.cell/* 5)))) (T/is (= ($.cell/* 50.0) ($.std/* ($.cell/* 10.0) ($.cell/* 5))))) (T/deftest abs (T/is (= ($.cell/* 42) ($.std/abs ($.cell/* 42)))) (T/is (= ($.cell/* 42) ($.std/abs ($.cell/* -42)))) (T/is (= ($.cell/* 42.24) ($.std/abs ($.cell/* 42.24)))) (T/is (= ($.cell/* 42.24) ($.std/abs ($.cell/* -42.24))))) (T/deftest ceil (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 42)))) (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 41.01)))) (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 41.99))))) (T/deftest div (T/is (= ($.cell/* 5.0) ($.std/div ($.cell/* 10) ($.cell/* 2)))) (T/is (= ($.cell/* 4.0) ($.std/div ($.cell/* 24) ($.cell/* 2) ($.cell/* 3))))) (T/deftest exp (T/is ($.std/double? ($.std/exp ($.cell/* 1))))) (T/deftest floor (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42)))) (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42.01)))) (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42.99))))) (T/deftest nan? (T/is (true? ($.std/nan? ($.cell/* ##NaN)))) (T/is (false? ($.std/nan? ($.cell/* 42.24))))) (T/deftest pow (T/is (= ($.cell/* 9.0) ($.std/pow ($.cell/* 3) ($.cell/* 2))))) (T/deftest signum (T/is (= ($.cell/* 1) ($.std/signum ($.cell/* 42)))) (T/is (= ($.cell/* -1) ($.std/signum ($.cell/* -42)))) (T/is (= ($.cell/* 0) ($.std/signum ($.cell/* 0)))) (T/is (= ($.cell/* 1.0) ($.std/signum ($.cell/* 42.0)))) (T/is (= ($.cell/* -1.0) ($.std/signum ($.cell/* -42.0)))) (T/is (= ($.cell/* 0.0) ($.std/signum ($.cell/* 0.0))))) (T/deftest sqrt (T/is (= ($.cell/* 4.0) ($.std/sqrt ($.cell/* 16.0))))) (T/deftest zero? (T/is (true? ($.std/zero? ($.cell/* 0)))) (T/is (true? ($.std/zero? ($.cell/* 0.0)))) (T/is (true? ($.std/zero? ($.cell/* -0.0)))) (T/is (false? ($.std/zero? ($.cell/* 1)))) (T/is (false? ($.std/zero? ($.cell/* []))))) ;;;;;;;;;; Sequence (T/deftest concat (T/is (nil? ($.std/concat nil nil))) (T/is (= ($.cell/* [:a]) ($.std/concat ($.cell/* [:a]) nil))) (T/is (= ($.cell/* [:a]) ($.std/concat nil ($.cell/* [:a])))) (T/is (= ($.cell/* (:a :b)) ($.std/concat ($.cell/* (:a)) ($.cell/* (:b))))) (T/is (= ($.cell/* (:a)) ($.std/concat ($.cell/* (:a)) nil))) (T/is (= ($.cell/* (:a)) ($.std/concat nil ($.cell/* (:a))))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* [:b])))) (T/is (= ($.cell/* [:a]) ($.std/concat ($.cell/* [:a]) nil))) (T/is (= ($.cell/* [:a]) ($.std/concat nil ($.cell/* [:a])))) (T/is (= ($.cell/* (:a :b)) ($.std/concat ($.cell/* (:a)) ($.cell/* [:b])))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* (:b))))) (T/is (= ($.cell/* [:a [:b :c]]) ($.std/concat ($.cell/* [:a]) ($.cell/* {:b :c})))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* #{:b}))))) (T/deftest cons (T/is (= ($.cell/* (:a)) ($.std/cons ($.cell/* :a) nil))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* (:a))))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* [:a])))) (T/is (= ($.cell/* (:c [:a :b])) ($.std/cons ($.cell/* :c) ($.cell/* {:a :b})))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* #{:a}))))) (T/deftest next (T/is (nil? ($.std/next ($.cell/* ())))) (T/is (nil? ($.std/next ($.cell/* (:a))))) (T/is (= ($.cell/* (:b)) ($.std/next ($.cell/* (:a :b))))) (T/is (nil? ($.std/next ($.cell/* [])))) (T/is (nil? ($.std/next ($.cell/* [:a])))) (T/is (= ($.cell/* [:b]) ($.std/next ($.cell/* [:a :b])))) (T/is (nil? ($.std/next ($.cell/* {})))) (T/is (nil? ($.std/next ($.cell/* {:a :b})))) (T/is (not ($.std/empty? ($.std/next ($.cell/* {:a :b :c :d}))))) (T/is (nil? ($.std/next ($.cell/* #{})))) (T/is (nil? ($.std/next ($.cell/* #{:a})))) (T/is (not ($.std/empty? ($.std/next ($.cell/* #{:a :b})))))) (T/deftest reverse (T/is (nil? ($.std/reverse nil))) (T/is (= ($.cell/* [:c :b :a]) ($.std/reverse ($.cell/* (:a :b :c))))) (T/is (= ($.cell/* (:c :b :a)) ($.std/reverse ($.cell/* [:a :b :c]))))) ;;;;;;;;;; Set (T/deftest difference (T/is (= ($.cell/* #{}) ($.std/difference nil nil))) (T/is (= ($.cell/* #{1}) ($.std/difference ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{}) ($.std/difference nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{}) ($.std/difference ($.cell/* #{1}) ($.cell/* #{1})))) (T/is (= ($.cell/* #{1 2}) ($.std/difference ($.cell/* #{1 2}) ($.cell/* #{3 4})))) (T/is (= ($.cell/* #{1}) ($.std/difference ($.cell/* #{1 2}) ($.cell/* #{2 3}))))) (T/deftest intersection (T/is (= ($.cell/* #{}) ($.std/intersection nil nil))) (T/is (= ($.cell/* #{}) ($.std/intersection ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{}) ($.std/intersection nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{2}) ($.std/intersection ($.cell/* #{1 2}) ($.cell/* #{2 3})))) (T/is (= ($.cell/* #{}) ($.std/intersection ($.cell/* #{1 2}) ($.cell/* #{3 4}))))) (T/deftest subset? (T/is (true? ($.std/subset? nil nil))) (T/is (true? ($.std/subset? nil ($.cell/* #{1})))) (T/is (false? ($.std/subset? ($.cell/* #{1}) nil))) (T/is (true? ($.std/subset? ($.cell/* #{1}) ($.cell/* #{1 2})))) (T/is (false? ($.std/subset? ($.cell/* #{1}) ($.cell/* #{2}))))) (T/deftest union (T/is (= ($.cell/* #{}) ($.std/union nil nil))) (T/is (= ($.cell/* #{1}) ($.std/union ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{1}) ($.std/union nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{1 2 3}) ($.std/union ($.cell/* #{1 2}) ($.cell/* #{2 3}))))) ;;;;;;;;; Symbolic (let [s ($.cell/* "test")] (T/deftest name (T/is (= s ($.std/name s))) (T/is (= s ($.std/name ($.cell/* test)))) (T/is (= s ($.std/name ($.cell/* :test))))))
true
(ns convex.test.std "Testing `convex.std`." {:author "PI:NAME:<NAME>END_PI"} (:refer-clojure :exclude [+ - * < <= == >= > assoc concat conj cons contains? count dec dissoc empty empty? find get hash-map hash-set inc into keys list merge mod name next nth reverse str vals vector zero?]) (:require [clojure.test :as T] [convex.cell :as $.cell] [convex.ref :as $.ref] [convex.std :as $.std])) ;;;;;;;;;; Casts (T/deftest str (T/is (= ($.cell/* "[:a :b]") ($.std/str ($.cell/* [:a :b]))))) ;;;;;;;;;; Collection constructors (let [k ($.cell/blob (byte-array [0]))] (T/deftest blob-map (T/is (= ($.cell/blob-map) ($.std/blob-map))) (T/is (= ($.cell/blob-map [[k ($.cell/* :a)]]) ($.std/blob-map k ($.cell/* :a)))) (T/is (thrown? IllegalArgumentException ($.std/blob-map k))))) (T/deftest hash-map (T/is (= ($.cell/* {}) ($.std/hash-map))) (T/is (= ($.cell/* {:a :b}) ($.std/hash-map ($.cell/* :a) ($.cell/* :b)))) (T/is (thrown? IllegalArgumentException ($.std/hash-map ($.cell/* :a))))) (T/deftest hash-set (T/is (= ($.cell/* #{}) ($.std/hash-set))) (T/is (= ($.cell/* #{:a :b}) ($.std/hash-set ($.cell/* :a) ($.cell/* :b))))) (T/deftest list (T/is (= ($.cell/* ()) ($.std/list))) (T/is (= ($.cell/* (:a :b)) ($.std/list ($.cell/* :a) ($.cell/* :b))))) (T/deftest vector (T/is (= ($.cell/* []) ($.std/vector))) (T/is (= ($.cell/* [:a :b]) ($.std/vector ($.cell/* :a) ($.cell/* :b))))) ;;;;;;;;;; Collection generics (T/deftest into (T/is (let [k ($.cell/blob (byte-array [0]))] (= ($.std/blob-map k ($.cell/* :a)) ($.std/into ($.cell/blob-map) ($.cell/* [[~k :a]]))))) (T/is (= ($.cell/* [:foo 2 3 4]) ($.std/into ($.cell/* [:foo]) (map $.std/inc) ($.cell/* (1 2 3)))))) ;;;;;;;;;; Comparators (T/deftest < (T/is (true? ($.std/< ($.cell/* 42) ($.cell/* 100)))) (T/is (false? ($.std/< ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/< ($.cell/* 42) ($.cell/* 1)))) (T/is (true? ($.std/< ($.cell/* 42.0) ($.cell/* 100)))) (T/is (false? ($.std/< ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/< ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest <= (T/is (true? ($.std/<= ($.cell/* 42) ($.cell/* 100)))) (T/is (true? ($.std/<= ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/<= ($.cell/* 42) ($.cell/* 1)))) (T/is (true? ($.std/<= ($.cell/* 42.0) ($.cell/* 100)))) (T/is (true? ($.std/<= ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/<= ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest == (T/is (true? ($.std/== ($.cell/* 42) ($.cell/* 42)))) (T/is (false? ($.std/== ($.cell/* 1) ($.cell/* 42)))) (T/is (true? ($.std/== ($.cell/* 42.0) ($.cell/* 42)))) (T/is (false? ($.std/== ($.cell/* 1.0) ($.cell/* 42))))) (T/deftest >= (T/is (false? ($.std/>= ($.cell/* 42) ($.cell/* 100)))) (T/is (true? ($.std/>= ($.cell/* 42) ($.cell/* 42)))) (T/is (true? ($.std/>= ($.cell/* 42) ($.cell/* 1)))) (T/is (false? ($.std/>= ($.cell/* 42.0) ($.cell/* 100)))) (T/is (true? ($.std/>= ($.cell/* 42.0) ($.cell/* 42)))) (T/is (true? ($.std/>= ($.cell/* 42.0) ($.cell/* 1))))) (T/deftest > (T/is (false? ($.std/> ($.cell/* 42) ($.cell/* 100)))) (T/is (false? ($.std/> ($.cell/* 42) ($.cell/* 42)))) (T/is (true? ($.std/> ($.cell/* 42) ($.cell/* 1)))) (T/is (false? ($.std/> ($.cell/* 42.0) ($.cell/* 100)))) (T/is (false? ($.std/> ($.cell/* 42.0) ($.cell/* 42)))) (T/is (true? ($.std/> ($.cell/* 42.0) ($.cell/* 1))))) ;;;;;;;;;; Countable (T/deftest count (T/is (= 2 ($.std/count ($.cell/* (:a :b))))) (T/is (= 2 ($.std/count ($.cell/* [:a :b])))) (T/is (= 2 ($.std/count ($.cell/* {:a :b :c :d})))) (T/is (= 2 ($.std/count ($.cell/* #{:a :b})))) (T/is (= 2 ($.std/count ($.cell/* "ab")))) (T/is (= 2 ($.std/count ($.cell/blob (byte-array [1 2])))))) (T/deftest empty? (T/is ($.std/empty? ($.cell/* ()))) (T/is (not ($.std/empty? ($.cell/* (:a))))) (T/is ($.std/empty? ($.cell/* []))) (T/is (not ($.std/empty? ($.cell/* [:a])))) (T/is ($.std/empty? ($.cell/* {}))) (T/is (not ($.std/empty? ($.cell/* {:a :b})))) (T/is ($.std/empty? ($.cell/* #{}))) (T/is (not ($.std/empty? ($.cell/* #{:a})))) (T/is ($.std/empty? ($.cell/* ""))) (T/is (not ($.std/empty? ($.cell/* "a")))) (T/is ($.std/empty? ($.cell/blob (byte-array 0)))) (T/is (not ($.std/empty? ($.cell/blob (byte-array 1)))))) (let [a ($.cell/* :a)] (T/deftest nth (T/is (= a ($.std/nth ($.cell/* (:a :b)) 0))) (T/is (= a ($.std/nth ($.cell/* [:a :b]) 0))) (T/is (= ($.cell/* [:a :b]) ($.std/nth ($.cell/* {:a :b}) 0))) (T/is (= a ($.std/nth ($.cell/* #{:a}) 0))) (T/is (= ($.cell/* \a) ($.std/nth ($.cell/* "ab") 0))) (T/is (= ($.cell/byte 1) ($.std/nth ($.cell/blob (byte-array [1 2])) 0))))) (let [a ($.cell/* :a)] (T/deftest nth-ref (T/is (= a (-> ($.std/nth-ref ($.cell/* (:a :b)) 0) $.ref/resolve))) (T/is (= a (-> ($.std/nth-ref ($.cell/* [:a :b]) 0) $.ref/resolve))) (T/is (= ($.cell/* [:a :b]) (-> ($.std/nth-ref ($.cell/* {:a :b}) 0) $.ref/resolve))) (T/is (= a (-> ($.std/nth-ref ($.cell/* #{:a}) 0) $.ref/resolve))) (T/is (= ($.cell/* \a) (-> ($.std/nth-ref ($.cell/* "ab") 0) $.ref/resolve)) (T/is (= ($.cell/byte 1) (-> ($.std/nth-ref ($.cell/blob (byte-array [1 2])) 0) $.ref/resolve)))))) ;;;;;;;;;; Data structure (T/deftest assoc (T/is (= ($.cell/* (:b)) ($.std/assoc ($.cell/* (:a)) ($.cell/* 0) ($.cell/* :b)))) (T/is (= ($.cell/* [:b]) ($.std/assoc ($.cell/* [:a]) ($.cell/* 0) ($.cell/* :b)))) (T/is (= ($.cell/* {:a :c}) ($.std/assoc ($.cell/* {:a :b}) ($.cell/* :a) ($.cell/* :c)))) (T/is (= ($.cell/* #{:a :b}) ($.std/assoc ($.cell/* #{:a}) ($.cell/* :b) ($.cell/* true)))) (T/is (= ($.cell/* #{:a}) ($.std/assoc ($.cell/* #{:a :b}) ($.cell/* :b) ($.cell/* false))))) (T/deftest conj (T/is (= ($.cell/* (:b :a)) ($.std/conj ($.cell/* (:a)) ($.cell/* :b)))) (T/is (= ($.cell/* [:a :b]) ($.std/conj ($.cell/* [:a]) ($.cell/* :b)))) (T/is (= ($.cell/* {:a :b :c :d}) ($.std/conj ($.cell/* {:a :b}) ($.cell/* [:c :d])))) (T/is (= ($.cell/* #{:a :b}) ($.std/conj ($.cell/* #{:a}) ($.cell/* :b))))) (T/deftest contains? (T/is ($.std/contains? ($.cell/* (:a)) ($.cell/* 0))) (T/is (not ($.std/contains? ($.cell/* (:a)) ($.cell/* 1)))) (T/is ($.std/contains? ($.cell/* [:a]) ($.cell/* 0))) (T/is (not ($.std/contains? ($.cell/* [:a]) ($.cell/* 1)))) (T/is ($.std/contains? ($.cell/* {:a :b}) ($.cell/* :a))) (T/is (not ($.std/contains? ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is ($.std/contains? ($.cell/* #{:a}) ($.cell/* :a))) (T/is (not ($.std/contains? ($.cell/* #{:a}) ($.cell/* :b))))) (T/deftest empty (T/is (= ($.cell/* ()) ($.std/empty ($.cell/* (:a))))) (T/is (= ($.cell/* []) ($.std/empty ($.cell/* [:a])))) (T/is (= ($.cell/* {}) ($.std/empty ($.cell/* {:a :b})))) (T/is (= ($.cell/* #{}) ($.std/empty ($.cell/* #{:a}))))) (let [a ($.cell/* :a) b ($.cell/* :b)] (T/deftest get (T/is (= a ($.std/get ($.cell/* (:a)) ($.cell/* 0)))) (T/is (= a ($.std/get ($.cell/* [:a]) ($.cell/* 0)))) (T/is (= b ($.std/get ($.cell/* {:a :b}) a))) (T/is (= nil ($.std/get ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is (= ($.cell/* :not-found) ($.std/get ($.cell/* {:a :b}) ($.cell/* :c) ($.cell/* :not-found)))) (T/is (= ($.cell/* true) ($.std/get ($.cell/* #{:a}) a))) (T/is (= ($.cell/* false) ($.std/get ($.cell/* #{:a}) b))) (T/is (= ($.cell/* :not-found) ($.std/get ($.cell/* #{:a}) b ($.cell/* :not-found)))))) ;;;;;;;;;; Long (T/deftest dec (T/is (= ($.cell/* 41) ($.std/dec ($.cell/* 42))))) (T/deftest mod (T/is (= ($.cell/* 2) ($.std/mod ($.cell/* 2) ($.cell/* 5))))) (T/deftest inc (T/is (= ($.cell/* 43) ($.std/inc ($.cell/* 42))))) ;;;;;;;;;; Map (T/deftest dissoc (T/is (= ($.cell/* {}) ($.std/dissoc nil ($.cell/* :a)))) (T/is (= ($.cell/* {:a :b}) ($.std/dissoc ($.cell/* {:a :b :c :d}) ($.cell/* :c)))) (T/is (= ($.cell/blob-map) (let [b ($.cell/blob (byte-array [0]))] ($.std/dissoc ($.cell/blob-map [[b ($.cell/* :a)]]) b))))) (T/deftest find (T/is (nil? ($.std/find nil ($.cell/* :a)))) (T/is (nil? ($.std/find ($.cell/* {:a :b}) ($.cell/* :c)))) (T/is (= ($.cell/* [:a :b]) ($.std/find ($.cell/* {:a :b}) ($.cell/* :a)))) (T/is (nil? ($.std/find ($.cell/blob-map [[($.cell/blob (byte-array [0])) ($.cell/* :a)]]) ($.cell/blob (byte-array [1]))))) (let [k ($.cell/blob (byte-array [0]))] (T/is (= ($.cell/* [~k ~($.cell/* :a)]) ($.std/find ($.cell/blob-map [[k ($.cell/* :a)]]) k))))) (T/deftest keys (T/is (= ($.cell/* []) ($.std/keys ($.cell/* {})))) (T/is (= ($.cell/* [:a]) ($.std/keys ($.cell/* {:a :b})))) (T/is (= ($.cell/* []) ($.std/keys ($.cell/blob-map)))) (let [k ($.cell/blob (byte-array [0]))] (T/is (= ($.cell/* [~k]) ($.std/keys ($.cell/blob-map [[k ($.cell/* :a)]])))))) (T/deftest merge (T/is (= ($.cell/* {}) ($.std/merge nil nil))) (T/is (= ($.cell/* {:a :b}) ($.std/merge ($.cell/* {:a :b}) nil))) (T/is (= ($.cell/* {:a :b}) ($.std/merge nil ($.cell/* {:a :b})))) (T/is (= ($.cell/* {:a :b :c :d}) ($.std/merge ($.cell/* {:a :b}) ($.cell/* {:c :d}))))) (T/deftest values (T/is (= ($.cell/* []) ($.std/vals ($.cell/* {})))) (T/is (= ($.cell/* [:b]) ($.std/vals ($.cell/* {:a :b})))) (T/is (= ($.cell/* []) ($.std/vals ($.cell/blob-map)))) (T/is (= ($.cell/* [:a]) ($.std/vals ($.cell/blob-map [[($.cell/blob (byte-array [0])) ($.cell/* :a)]]))))) ;;;;;;;;;; Math (T/deftest + (T/is (= ($.cell/* 10) ($.std/+ ($.cell/* 5) ($.cell/* 5)))) (T/is (= ($.cell/* 10.0) ($.std/+ ($.cell/* 5.0) ($.cell/* 5))))) (T/deftest - (T/is (= ($.cell/* 5) ($.std/- ($.cell/* 10) ($.cell/* 5)))) (T/is (= ($.cell/* 5.0) ($.std/- ($.cell/* 10.0) ($.cell/* 5))))) (T/deftest * (T/is (= ($.cell/* 50) ($.std/* ($.cell/* 10) ($.cell/* 5)))) (T/is (= ($.cell/* 50.0) ($.std/* ($.cell/* 10.0) ($.cell/* 5))))) (T/deftest abs (T/is (= ($.cell/* 42) ($.std/abs ($.cell/* 42)))) (T/is (= ($.cell/* 42) ($.std/abs ($.cell/* -42)))) (T/is (= ($.cell/* 42.24) ($.std/abs ($.cell/* 42.24)))) (T/is (= ($.cell/* 42.24) ($.std/abs ($.cell/* -42.24))))) (T/deftest ceil (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 42)))) (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 41.01)))) (T/is (= ($.cell/* 42.0) ($.std/ceil ($.cell/* 41.99))))) (T/deftest div (T/is (= ($.cell/* 5.0) ($.std/div ($.cell/* 10) ($.cell/* 2)))) (T/is (= ($.cell/* 4.0) ($.std/div ($.cell/* 24) ($.cell/* 2) ($.cell/* 3))))) (T/deftest exp (T/is ($.std/double? ($.std/exp ($.cell/* 1))))) (T/deftest floor (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42)))) (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42.01)))) (T/is (= ($.cell/* 42.0) ($.std/floor ($.cell/* 42.99))))) (T/deftest nan? (T/is (true? ($.std/nan? ($.cell/* ##NaN)))) (T/is (false? ($.std/nan? ($.cell/* 42.24))))) (T/deftest pow (T/is (= ($.cell/* 9.0) ($.std/pow ($.cell/* 3) ($.cell/* 2))))) (T/deftest signum (T/is (= ($.cell/* 1) ($.std/signum ($.cell/* 42)))) (T/is (= ($.cell/* -1) ($.std/signum ($.cell/* -42)))) (T/is (= ($.cell/* 0) ($.std/signum ($.cell/* 0)))) (T/is (= ($.cell/* 1.0) ($.std/signum ($.cell/* 42.0)))) (T/is (= ($.cell/* -1.0) ($.std/signum ($.cell/* -42.0)))) (T/is (= ($.cell/* 0.0) ($.std/signum ($.cell/* 0.0))))) (T/deftest sqrt (T/is (= ($.cell/* 4.0) ($.std/sqrt ($.cell/* 16.0))))) (T/deftest zero? (T/is (true? ($.std/zero? ($.cell/* 0)))) (T/is (true? ($.std/zero? ($.cell/* 0.0)))) (T/is (true? ($.std/zero? ($.cell/* -0.0)))) (T/is (false? ($.std/zero? ($.cell/* 1)))) (T/is (false? ($.std/zero? ($.cell/* []))))) ;;;;;;;;;; Sequence (T/deftest concat (T/is (nil? ($.std/concat nil nil))) (T/is (= ($.cell/* [:a]) ($.std/concat ($.cell/* [:a]) nil))) (T/is (= ($.cell/* [:a]) ($.std/concat nil ($.cell/* [:a])))) (T/is (= ($.cell/* (:a :b)) ($.std/concat ($.cell/* (:a)) ($.cell/* (:b))))) (T/is (= ($.cell/* (:a)) ($.std/concat ($.cell/* (:a)) nil))) (T/is (= ($.cell/* (:a)) ($.std/concat nil ($.cell/* (:a))))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* [:b])))) (T/is (= ($.cell/* [:a]) ($.std/concat ($.cell/* [:a]) nil))) (T/is (= ($.cell/* [:a]) ($.std/concat nil ($.cell/* [:a])))) (T/is (= ($.cell/* (:a :b)) ($.std/concat ($.cell/* (:a)) ($.cell/* [:b])))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* (:b))))) (T/is (= ($.cell/* [:a [:b :c]]) ($.std/concat ($.cell/* [:a]) ($.cell/* {:b :c})))) (T/is (= ($.cell/* [:a :b]) ($.std/concat ($.cell/* [:a]) ($.cell/* #{:b}))))) (T/deftest cons (T/is (= ($.cell/* (:a)) ($.std/cons ($.cell/* :a) nil))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* (:a))))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* [:a])))) (T/is (= ($.cell/* (:c [:a :b])) ($.std/cons ($.cell/* :c) ($.cell/* {:a :b})))) (T/is (= ($.cell/* (:b :a)) ($.std/cons ($.cell/* :b) ($.cell/* #{:a}))))) (T/deftest next (T/is (nil? ($.std/next ($.cell/* ())))) (T/is (nil? ($.std/next ($.cell/* (:a))))) (T/is (= ($.cell/* (:b)) ($.std/next ($.cell/* (:a :b))))) (T/is (nil? ($.std/next ($.cell/* [])))) (T/is (nil? ($.std/next ($.cell/* [:a])))) (T/is (= ($.cell/* [:b]) ($.std/next ($.cell/* [:a :b])))) (T/is (nil? ($.std/next ($.cell/* {})))) (T/is (nil? ($.std/next ($.cell/* {:a :b})))) (T/is (not ($.std/empty? ($.std/next ($.cell/* {:a :b :c :d}))))) (T/is (nil? ($.std/next ($.cell/* #{})))) (T/is (nil? ($.std/next ($.cell/* #{:a})))) (T/is (not ($.std/empty? ($.std/next ($.cell/* #{:a :b})))))) (T/deftest reverse (T/is (nil? ($.std/reverse nil))) (T/is (= ($.cell/* [:c :b :a]) ($.std/reverse ($.cell/* (:a :b :c))))) (T/is (= ($.cell/* (:c :b :a)) ($.std/reverse ($.cell/* [:a :b :c]))))) ;;;;;;;;;; Set (T/deftest difference (T/is (= ($.cell/* #{}) ($.std/difference nil nil))) (T/is (= ($.cell/* #{1}) ($.std/difference ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{}) ($.std/difference nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{}) ($.std/difference ($.cell/* #{1}) ($.cell/* #{1})))) (T/is (= ($.cell/* #{1 2}) ($.std/difference ($.cell/* #{1 2}) ($.cell/* #{3 4})))) (T/is (= ($.cell/* #{1}) ($.std/difference ($.cell/* #{1 2}) ($.cell/* #{2 3}))))) (T/deftest intersection (T/is (= ($.cell/* #{}) ($.std/intersection nil nil))) (T/is (= ($.cell/* #{}) ($.std/intersection ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{}) ($.std/intersection nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{2}) ($.std/intersection ($.cell/* #{1 2}) ($.cell/* #{2 3})))) (T/is (= ($.cell/* #{}) ($.std/intersection ($.cell/* #{1 2}) ($.cell/* #{3 4}))))) (T/deftest subset? (T/is (true? ($.std/subset? nil nil))) (T/is (true? ($.std/subset? nil ($.cell/* #{1})))) (T/is (false? ($.std/subset? ($.cell/* #{1}) nil))) (T/is (true? ($.std/subset? ($.cell/* #{1}) ($.cell/* #{1 2})))) (T/is (false? ($.std/subset? ($.cell/* #{1}) ($.cell/* #{2}))))) (T/deftest union (T/is (= ($.cell/* #{}) ($.std/union nil nil))) (T/is (= ($.cell/* #{1}) ($.std/union ($.cell/* #{1}) nil))) (T/is (= ($.cell/* #{1}) ($.std/union nil ($.cell/* #{1})))) (T/is (= ($.cell/* #{1 2 3}) ($.std/union ($.cell/* #{1 2}) ($.cell/* #{2 3}))))) ;;;;;;;;; Symbolic (let [s ($.cell/* "test")] (T/deftest name (T/is (= s ($.std/name s))) (T/is (= s ($.std/name ($.cell/* test)))) (T/is (= s ($.std/name ($.cell/* :test))))))
[ { "context": "1505 -118.274 2 101.0]\n [98 \"Lucky Baldwin's Pub\" 7 34.1454 -118.149 2 100.0]]\n ", "end": 6270, "score": 0.6239919662475586, "start": 6264, "tag": "NAME", "value": "aldwin" }, { "context": "lated columns play well with joins\"\n (is (= \"Simcha Yan\"\n (-> (mt/run-mbql-query checkins\n ", "end": 14552, "score": 0.9997464418411255, "start": 14542, "tag": "NAME", "value": "Simcha Yan" }, { "context": " 4 10.0646 -165.374 3 4.0]\n [2 \"Stout Burgers & Beers\" 11 34.0996 -118.329 2 3.0]\n ", "end": 17508, "score": 0.5815352201461792, "start": 17495, "tag": "NAME", "value": "Stout Burgers" }, { "context": "65.374 3 4.0]\n [2 \"Stout Burgers & Beers\" 11 34.0996 -118.329 2 3.0]\n [3 \"The", "end": 17516, "score": 0.5225000381469727, "start": 17513, "tag": "NAME", "value": "ers" } ]
c#-metabase/test/metabase/query_processor_test/expressions_test.clj
hanakhry/Crime_Admin
0
(ns metabase.query-processor-test.expressions-test "Tests for expressions (calculated columns)." (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [java-time :as t] [medley.core :as m] [metabase.driver :as driver] [metabase.query-processor :as qp] [metabase.sync :as sync] [metabase.test :as mt] [metabase.test.data.one-off-dbs :as one-off-dbs] [metabase.util :as u] [metabase.util.date-2 :as u.date])) (deftest basic-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Do a basic query including an expression" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 5.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 4.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 4.0] [4 "Wurstküche" 29 33.9997 -118.465 2 4.0] [5 "Brite Spot Family Restaurant" 20 34.0778 -118.261 2 4.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:my-cool-new-field [:+ $price 2]} :limit 5 :order-by [[:asc $id]]}))))))) (deftest floating-point-division-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Make sure FLOATING POINT division is done" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 1.5] ; 3 / 2 SHOULD BE 1.5, NOT 1 (!) [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 1.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:my-cool-new-field [:/ $price 2]} :limit 3 :order-by [[:asc $id]]}))))) (testing "Make sure FLOATING POINT division is done when dividing by expressions/fields" (is (= [[0.6] [0.5] [0.5]] (mt/formatted-rows [1.0] (mt/run-mbql-query venues {:expressions {:big-price [:+ $price 2] :my-cool-new-field [:/ $price [:expression "big-price"]]} :fields [[:expression "my-cool-new-field"]] :limit 3 :order-by [[:asc $id]]}))))))) (deftest nested-expressions-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we do NESTED EXPRESSIONS ?" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 3.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 2.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 2.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:wow [:- [:* $price 2] [:+ $price 0]]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest multiple-expressions-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we have MULTIPLE EXPRESSIONS?" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 2.0 4.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0 3.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 1.0 3.0]] (mt/formatted-rows [int str int 4.0 4.0 int float float] (mt/run-mbql-query venues {:expressions {:x [:- $price 1] :y [:+ $price 1]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest expressions-in-fields-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we refer to expressions inside a FIELDS clause?" (is (= [[4] [4] [5]] (mt/formatted-rows [int] (mt/run-mbql-query venues {:expressions {:x [:+ $price $id]} :fields [[:expression :x]] :limit 3 :order-by [[:asc $id]]}))))))) (deftest dont-return-expressions-if-fields-is-explicit-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (let [query (mt/mbql-query venues {:expressions {"Price + 1" [:+ $price 1] "1 + 1" [:+ 1 1]} :fields [$price [:expression "1 + 1"]] :order-by [[:asc $id]] :limit 3})] (testing "If an explicit `:fields` clause is present, expressions *not* in that clause should not come back" (is (= [[3 2] [2 2] [2 2]] (mt/formatted-rows [int int] (qp/process-query query))))) (testing "If `:fields` is not explicit, then return all the expressions" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4 2] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3 2] [3 "The Apple Pan" 11 34.0406 -118.428 2 3 2]] (mt/formatted-rows [int str int 4.0 4.0 int int int] (qp/process-query (m/dissoc-in query [:query :fields])))))) (testing "When aggregating, expressions that aren't used shouldn't come back" (is (= [[2 22] [3 59] [4 13]] (mt/formatted-rows [int int] (mt/run-mbql-query venues {:expressions {"Price + 1" [:+ $price 1] "1 + 1" [:+ 1 1]} :aggregation [:count] :breakout [[:expression "Price + 1"]] :order-by [[:asc [:expression "Price + 1"]]] :limit 3})))))))) (deftest expressions-in-order-by-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we refer to expressions inside an ORDER BY clause?" (is (= [[100 "Mohawk Bend" 46 34.0777 -118.265 2 102.0] [99 "Golden Road Brewing" 10 34.1505 -118.274 2 101.0] [98 "Lucky Baldwin's Pub" 7 34.1454 -118.149 2 100.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:x [:+ $price $id]} :limit 3 :order-by [[:desc [:expression :x]]]}))))))) (deftest aggregate-breakout-expression-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we AGGREGATE + BREAKOUT by an EXPRESSION?" (is (= [[2 22] [4 59] [6 13] [8 6]] (mt/formatted-rows [int int] (mt/run-mbql-query venues {:expressions {:x [:* $price 2.0]} :aggregation [[:count]] :breakout [[:expression :x]]}))))))) (deftest expressions-should-include-type-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Custom aggregation expressions should include their type" (let [cols (mt/cols (mt/run-mbql-query venues {:aggregation [[:aggregation-options [:sum [:* $price -1]] {:name "x"}]] :breakout [$category_id]}))] (testing (format "cols = %s" (u/pprint-to-str cols)) (is (= #{"x" (mt/format-name "category_id")} (set (map :name cols)))) (let [name->base-type (into {} (map (juxt :name :base_type) cols))] (testing "x" (is (isa? (name->base-type "x") :type/Number))) (testing "category_id" (is (isa? (name->base-type (mt/format-name "category_id")) :type/Number))))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | HANDLING NULLS AND ZEROES | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; "bird scarcity" is a scientific metric based on the number of birds seen in a given day ;; (at least for the purposes of the tests below) ;; ;; e.g. scarcity = 100.0 / num-birds (defn- calculate-bird-scarcity* [formula filter-clause] (mt/formatted-rows [2.0] (mt/dataset daily-bird-counts (mt/run-mbql-query bird-count {:expressions {"bird-scarcity" formula} :fields [[:expression "bird-scarcity"]] :filter filter-clause :order-by [[:asc $date]] :limit 10})))) (defmacro ^:private calculate-bird-scarcity [formula & [filter-clause]] `(mt/dataset ~'daily-bird-counts (mt/$ids ~'bird-count (calculate-bird-scarcity* ~formula ~filter-clause)))) (deftest nulls-and-zeroes-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing (str "hey... expressions should work if they are just a Field! (Also, this lets us take a peek at the " "raw values being used to calculate the formulas below, so we can tell at a glance if they're right " "without referring to the EDN def)") (is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]] (calculate-bird-scarcity $count)))) (testing (str "do expressions automatically handle division by zero? Should return `nil` in the results for places " "where that was attempted") (is (= [[nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [9.09] [7.14]] (calculate-bird-scarcity [:/ 100.0 $count] [:!= $count nil])))) (testing (str "do expressions handle division by `nil`? Should return `nil` in the results for places where that " "was attempted") (is (= [[nil] [10.0] [12.5] [20.0] [20.0] [nil] [9.09] [7.14] [12.5] [7.14]] (calculate-bird-scarcity [:/ 100.0 $count] [:or [:= $count nil] [:!= $count 0]])))) (testing "can we handle BOTH NULLS AND ZEROES AT THE SAME TIME????" (is (= [[nil] [nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:/ 100.0 $count])))) (testing "ok, what if we use multiple args to divide, and more than one is zero?" (is (= [[nil] [nil] [nil] [1.0] [1.56] [4.0] [4.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:/ 100.0 $count $count])))) (testing "are nulls/zeroes still handled appropriately when nested inside other expressions?" (is (= [[nil] [nil] [nil] [20.0] [25.0] [40.0] [40.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:* [:/ 100.0 $count] 2])))) (testing (str "if a zero is present in the NUMERATOR we should return ZERO and not NULL " "(`0 / 10 = 0`; `10 / 0 = NULL`, at least as far as MBQL is concerned)") (is (= [[nil] [0.0] [0.0] [1.0] [0.8] [0.5] [0.5] [nil] [0.0] [0.0]] (calculate-bird-scarcity [:/ $count 10])))) (testing "can addition handle nulls & zeroes?" (is (= [[nil] [10.0] [10.0] [20.0] [18.0] [15.0] [15.0] [nil] [10.0] [10.0]] (calculate-bird-scarcity [:+ $count 10])))) (testing "can subtraction handle nulls & zeroes?" (is (= [[nil] [10.0] [10.0] [0.0] [2.0] [5.0] [5.0] [nil] [10.0] [10.0]] (calculate-bird-scarcity [:- 10 $count])))) (testing "can multiplications handle nulls & zeros?" (is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]] (calculate-bird-scarcity [:* 1 $count])))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | DATETIME EXTRACTION AND MANIPULATION | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- robust-dates [strs] ;; TIMEZONE FIXME — SQLite shouldn't return strings. And for whatever weird reason it's truncating to date as well? (let [format-fn (if (= driver/*driver* :sqlite) #(u.date/format-sql (t/local-date-time (t/local-date %) (t/local-time 0))) u.date/format)] (for [s strs] [(format-fn (u.date/parse s "UTC"))]))) (deftest temporal-arithmetic-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Test that we can do datetime arithemtics using MBQL `:interval` clause in expressions" (is (= (robust-dates ["2014-09-02T13:45:00" "2014-07-02T09:30:00" "2014-07-01T10:30:00"]) (mt/with-temporary-setting-values [report-timezone "UTC"] (-> (mt/run-mbql-query users {:expressions {:prev_month [:+ $last_login [:interval -31 :day]]} :fields [[:expression :prev_month]] :limit 3 :order-by [[:asc $name]]}) mt/rows))))) (testing "Test interaction of datetime arithmetics with truncation" (is (= (robust-dates ["2014-09-02T00:00:00" "2014-07-02T00:00:00" "2014-07-01T00:00:00"]) (mt/with-temporary-setting-values [report-timezone "UTC"] (-> (mt/run-mbql-query users {:expressions {:prev_month [:+ !day.last_login [:interval -31 :day]]} :fields [[:expression :prev_month]] :limit 3 :order-by [[:asc $name]]}) mt/rows))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | JOINS | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest expressions+joins-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join) (testing "Do calculated columns play well with joins" (is (= "Simcha Yan" (-> (mt/run-mbql-query checkins {:expressions {:prev_month [:+ $date [:interval -31 :day]]} :fields [[:field (mt/id :users :name) {:join-alias "users__via__user_id"}] [:expression :prev_month]] :limit 1 :order-by [[:asc $date]] :joins [{:strategy :left-join :source-table (mt/id :users) :alias "users__via__user_id" :condition [:= $user_id [:field (mt/id :users :id) {:join-alias "users__via__user_id"}]]}]}) mt/rows ffirst)))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | MISC BUG FIXES | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; Make sure no part of query compilation is lazy as that won't play well with dynamic bindings. ;; This is not an issue limited to expressions, but using expressions is the most straightforward ;; way to reproducing it. (deftest no-lazyness-test (one-off-dbs/with-blank-db (let [ ;; need more fields than seq chunking size fields (repeatedly 1000 gensym)] (doseq [statement ["drop table if exists \"LOTS_OF_FIELDS\";" (format "create table \"LOTS_OF_FIELDS\" (a integer, b integer, %s);" (str/join ", " (for [field-name fields] (str (name field-name) " integer")))) (format "insert into \"LOTS_OF_FIELDS\" values(%s);" (str/join "," (range (+ (count fields) 2))))]] (jdbc/execute! one-off-dbs/*conn* [statement])) (sync/sync-database! (mt/db)) (is (= 1 (->> (mt/run-mbql-query lots_of_fields {:expressions {:c [:+ [:field (mt/id :lots_of_fields :a) nil] [:field (mt/id :lots_of_fields :b) nil]]} :fields (concat [[:expression :c]] (for [field fields] [:field (mt/id :lots_of_fields (keyword field)) nil]))}) (mt/formatted-rows [int]) ffirst)))))) (deftest expression-with-slashes (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Make sure an expression with a / in its name works (#12305)" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 3.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:TEST/my-cool-new-field [:+ $price 1]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest expression-using-aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we use aggregations from previous steps in expressions (#12762)" (is (= [["20th Century Cafe" 2 2 0] [ "25°" 2 2 0] ["33 Taps" 2 2 0]] (mt/formatted-rows [str int int int] (mt/run-mbql-query venues {:source-query {:source-table (mt/id :venues) :aggregation [[:min (mt/id :venues :price)] [:max (mt/id :venues :price)]] :breakout [[:field (mt/id :venues :name) nil]] :limit 3} :expressions {:price-range [:- [:field "max" {:base-type :type/Number}] [:field "min" {:base-type :type/Number}]]}}))))))) (deftest fk-field-and-duplicate-names-test ;; Redshift hangs on sample-dataset -- See #14784 (mt/test-drivers (disj (mt/normal-drivers-with-feature :expressions :foreign-keys) :redshift) (testing "Expressions with `fk->` fields and duplicate names should work correctly (#14854)" (mt/dataset sample-dataset (let [results (mt/run-mbql-query orders {:expressions {"CE" [:case [[[:> $discount 0] $created_at]] {:default $product_id->products.created_at}]} :order-by [[:asc $id]] :limit 2})] (is (= ["ID" "User ID" "Product ID" "Subtotal" "Tax" "Total" "Discount" "Created At" "Quantity" "CE"] (map :display_name (mt/cols results)))) (is (= [[1 1 14 37.7 2.1 39.7 nil "2019-02-11T21:40:27.892Z" 2 "2017-12-31T14:41:56.87Z"] [2 1 123 110.9 6.1 117.0 nil "2018-05-15T08:04:04.58Z" 3 "2017-11-16T13:53:14.232Z"]] (mt/formatted-rows [int int int 1.0 1.0 1.0 identity str int str] results)))))))) (deftest string-operations-from-subquery (mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex) (testing "regex-match-first and replace work when evaluated against a subquery (#14873)" (mt/dataset test-data (let [r-word "r_word" no-sp "no_spaces" id (mt/id :venues :id) results (mt/run-mbql-query venues {:expressions {r-word [:regex-match-first [:field-id (mt/id :venues :name)] "^R[^ ]+"] no-sp [:replace [:field-id (mt/id :venues :name)] " " ""]} :source-query {:source-table $$venues} :fields [$name [:expression r-word] [:expression no-sp]] :filter [:= $id 1 95] :order-by [[:asc $id]]})] (is (= ["Name" r-word no-sp] (map :display_name (mt/cols results)))) (is (= [["Red Medicine" "Red" "RedMedicine"] ["Rush Street" "Rush" "RushStreet"]] (mt/formatted-rows [str str str] results))))))))
49429
(ns metabase.query-processor-test.expressions-test "Tests for expressions (calculated columns)." (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [java-time :as t] [medley.core :as m] [metabase.driver :as driver] [metabase.query-processor :as qp] [metabase.sync :as sync] [metabase.test :as mt] [metabase.test.data.one-off-dbs :as one-off-dbs] [metabase.util :as u] [metabase.util.date-2 :as u.date])) (deftest basic-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Do a basic query including an expression" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 5.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 4.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 4.0] [4 "Wurstküche" 29 33.9997 -118.465 2 4.0] [5 "Brite Spot Family Restaurant" 20 34.0778 -118.261 2 4.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:my-cool-new-field [:+ $price 2]} :limit 5 :order-by [[:asc $id]]}))))))) (deftest floating-point-division-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Make sure FLOATING POINT division is done" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 1.5] ; 3 / 2 SHOULD BE 1.5, NOT 1 (!) [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 1.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:my-cool-new-field [:/ $price 2]} :limit 3 :order-by [[:asc $id]]}))))) (testing "Make sure FLOATING POINT division is done when dividing by expressions/fields" (is (= [[0.6] [0.5] [0.5]] (mt/formatted-rows [1.0] (mt/run-mbql-query venues {:expressions {:big-price [:+ $price 2] :my-cool-new-field [:/ $price [:expression "big-price"]]} :fields [[:expression "my-cool-new-field"]] :limit 3 :order-by [[:asc $id]]}))))))) (deftest nested-expressions-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we do NESTED EXPRESSIONS ?" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 3.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 2.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 2.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:wow [:- [:* $price 2] [:+ $price 0]]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest multiple-expressions-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we have MULTIPLE EXPRESSIONS?" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 2.0 4.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0 3.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 1.0 3.0]] (mt/formatted-rows [int str int 4.0 4.0 int float float] (mt/run-mbql-query venues {:expressions {:x [:- $price 1] :y [:+ $price 1]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest expressions-in-fields-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we refer to expressions inside a FIELDS clause?" (is (= [[4] [4] [5]] (mt/formatted-rows [int] (mt/run-mbql-query venues {:expressions {:x [:+ $price $id]} :fields [[:expression :x]] :limit 3 :order-by [[:asc $id]]}))))))) (deftest dont-return-expressions-if-fields-is-explicit-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (let [query (mt/mbql-query venues {:expressions {"Price + 1" [:+ $price 1] "1 + 1" [:+ 1 1]} :fields [$price [:expression "1 + 1"]] :order-by [[:asc $id]] :limit 3})] (testing "If an explicit `:fields` clause is present, expressions *not* in that clause should not come back" (is (= [[3 2] [2 2] [2 2]] (mt/formatted-rows [int int] (qp/process-query query))))) (testing "If `:fields` is not explicit, then return all the expressions" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4 2] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3 2] [3 "The Apple Pan" 11 34.0406 -118.428 2 3 2]] (mt/formatted-rows [int str int 4.0 4.0 int int int] (qp/process-query (m/dissoc-in query [:query :fields])))))) (testing "When aggregating, expressions that aren't used shouldn't come back" (is (= [[2 22] [3 59] [4 13]] (mt/formatted-rows [int int] (mt/run-mbql-query venues {:expressions {"Price + 1" [:+ $price 1] "1 + 1" [:+ 1 1]} :aggregation [:count] :breakout [[:expression "Price + 1"]] :order-by [[:asc [:expression "Price + 1"]]] :limit 3})))))))) (deftest expressions-in-order-by-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we refer to expressions inside an ORDER BY clause?" (is (= [[100 "Mohawk Bend" 46 34.0777 -118.265 2 102.0] [99 "Golden Road Brewing" 10 34.1505 -118.274 2 101.0] [98 "Lucky B<NAME>'s Pub" 7 34.1454 -118.149 2 100.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:x [:+ $price $id]} :limit 3 :order-by [[:desc [:expression :x]]]}))))))) (deftest aggregate-breakout-expression-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we AGGREGATE + BREAKOUT by an EXPRESSION?" (is (= [[2 22] [4 59] [6 13] [8 6]] (mt/formatted-rows [int int] (mt/run-mbql-query venues {:expressions {:x [:* $price 2.0]} :aggregation [[:count]] :breakout [[:expression :x]]}))))))) (deftest expressions-should-include-type-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Custom aggregation expressions should include their type" (let [cols (mt/cols (mt/run-mbql-query venues {:aggregation [[:aggregation-options [:sum [:* $price -1]] {:name "x"}]] :breakout [$category_id]}))] (testing (format "cols = %s" (u/pprint-to-str cols)) (is (= #{"x" (mt/format-name "category_id")} (set (map :name cols)))) (let [name->base-type (into {} (map (juxt :name :base_type) cols))] (testing "x" (is (isa? (name->base-type "x") :type/Number))) (testing "category_id" (is (isa? (name->base-type (mt/format-name "category_id")) :type/Number))))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | HANDLING NULLS AND ZEROES | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; "bird scarcity" is a scientific metric based on the number of birds seen in a given day ;; (at least for the purposes of the tests below) ;; ;; e.g. scarcity = 100.0 / num-birds (defn- calculate-bird-scarcity* [formula filter-clause] (mt/formatted-rows [2.0] (mt/dataset daily-bird-counts (mt/run-mbql-query bird-count {:expressions {"bird-scarcity" formula} :fields [[:expression "bird-scarcity"]] :filter filter-clause :order-by [[:asc $date]] :limit 10})))) (defmacro ^:private calculate-bird-scarcity [formula & [filter-clause]] `(mt/dataset ~'daily-bird-counts (mt/$ids ~'bird-count (calculate-bird-scarcity* ~formula ~filter-clause)))) (deftest nulls-and-zeroes-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing (str "hey... expressions should work if they are just a Field! (Also, this lets us take a peek at the " "raw values being used to calculate the formulas below, so we can tell at a glance if they're right " "without referring to the EDN def)") (is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]] (calculate-bird-scarcity $count)))) (testing (str "do expressions automatically handle division by zero? Should return `nil` in the results for places " "where that was attempted") (is (= [[nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [9.09] [7.14]] (calculate-bird-scarcity [:/ 100.0 $count] [:!= $count nil])))) (testing (str "do expressions handle division by `nil`? Should return `nil` in the results for places where that " "was attempted") (is (= [[nil] [10.0] [12.5] [20.0] [20.0] [nil] [9.09] [7.14] [12.5] [7.14]] (calculate-bird-scarcity [:/ 100.0 $count] [:or [:= $count nil] [:!= $count 0]])))) (testing "can we handle BOTH NULLS AND ZEROES AT THE SAME TIME????" (is (= [[nil] [nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:/ 100.0 $count])))) (testing "ok, what if we use multiple args to divide, and more than one is zero?" (is (= [[nil] [nil] [nil] [1.0] [1.56] [4.0] [4.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:/ 100.0 $count $count])))) (testing "are nulls/zeroes still handled appropriately when nested inside other expressions?" (is (= [[nil] [nil] [nil] [20.0] [25.0] [40.0] [40.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:* [:/ 100.0 $count] 2])))) (testing (str "if a zero is present in the NUMERATOR we should return ZERO and not NULL " "(`0 / 10 = 0`; `10 / 0 = NULL`, at least as far as MBQL is concerned)") (is (= [[nil] [0.0] [0.0] [1.0] [0.8] [0.5] [0.5] [nil] [0.0] [0.0]] (calculate-bird-scarcity [:/ $count 10])))) (testing "can addition handle nulls & zeroes?" (is (= [[nil] [10.0] [10.0] [20.0] [18.0] [15.0] [15.0] [nil] [10.0] [10.0]] (calculate-bird-scarcity [:+ $count 10])))) (testing "can subtraction handle nulls & zeroes?" (is (= [[nil] [10.0] [10.0] [0.0] [2.0] [5.0] [5.0] [nil] [10.0] [10.0]] (calculate-bird-scarcity [:- 10 $count])))) (testing "can multiplications handle nulls & zeros?" (is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]] (calculate-bird-scarcity [:* 1 $count])))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | DATETIME EXTRACTION AND MANIPULATION | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- robust-dates [strs] ;; TIMEZONE FIXME — SQLite shouldn't return strings. And for whatever weird reason it's truncating to date as well? (let [format-fn (if (= driver/*driver* :sqlite) #(u.date/format-sql (t/local-date-time (t/local-date %) (t/local-time 0))) u.date/format)] (for [s strs] [(format-fn (u.date/parse s "UTC"))]))) (deftest temporal-arithmetic-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Test that we can do datetime arithemtics using MBQL `:interval` clause in expressions" (is (= (robust-dates ["2014-09-02T13:45:00" "2014-07-02T09:30:00" "2014-07-01T10:30:00"]) (mt/with-temporary-setting-values [report-timezone "UTC"] (-> (mt/run-mbql-query users {:expressions {:prev_month [:+ $last_login [:interval -31 :day]]} :fields [[:expression :prev_month]] :limit 3 :order-by [[:asc $name]]}) mt/rows))))) (testing "Test interaction of datetime arithmetics with truncation" (is (= (robust-dates ["2014-09-02T00:00:00" "2014-07-02T00:00:00" "2014-07-01T00:00:00"]) (mt/with-temporary-setting-values [report-timezone "UTC"] (-> (mt/run-mbql-query users {:expressions {:prev_month [:+ !day.last_login [:interval -31 :day]]} :fields [[:expression :prev_month]] :limit 3 :order-by [[:asc $name]]}) mt/rows))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | JOINS | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest expressions+joins-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join) (testing "Do calculated columns play well with joins" (is (= "<NAME>" (-> (mt/run-mbql-query checkins {:expressions {:prev_month [:+ $date [:interval -31 :day]]} :fields [[:field (mt/id :users :name) {:join-alias "users__via__user_id"}] [:expression :prev_month]] :limit 1 :order-by [[:asc $date]] :joins [{:strategy :left-join :source-table (mt/id :users) :alias "users__via__user_id" :condition [:= $user_id [:field (mt/id :users :id) {:join-alias "users__via__user_id"}]]}]}) mt/rows ffirst)))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | MISC BUG FIXES | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; Make sure no part of query compilation is lazy as that won't play well with dynamic bindings. ;; This is not an issue limited to expressions, but using expressions is the most straightforward ;; way to reproducing it. (deftest no-lazyness-test (one-off-dbs/with-blank-db (let [ ;; need more fields than seq chunking size fields (repeatedly 1000 gensym)] (doseq [statement ["drop table if exists \"LOTS_OF_FIELDS\";" (format "create table \"LOTS_OF_FIELDS\" (a integer, b integer, %s);" (str/join ", " (for [field-name fields] (str (name field-name) " integer")))) (format "insert into \"LOTS_OF_FIELDS\" values(%s);" (str/join "," (range (+ (count fields) 2))))]] (jdbc/execute! one-off-dbs/*conn* [statement])) (sync/sync-database! (mt/db)) (is (= 1 (->> (mt/run-mbql-query lots_of_fields {:expressions {:c [:+ [:field (mt/id :lots_of_fields :a) nil] [:field (mt/id :lots_of_fields :b) nil]]} :fields (concat [[:expression :c]] (for [field fields] [:field (mt/id :lots_of_fields (keyword field)) nil]))}) (mt/formatted-rows [int]) ffirst)))))) (deftest expression-with-slashes (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Make sure an expression with a / in its name works (#12305)" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4.0] [2 "<NAME> & Be<NAME>" 11 34.0996 -118.329 2 3.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 3.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:TEST/my-cool-new-field [:+ $price 1]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest expression-using-aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we use aggregations from previous steps in expressions (#12762)" (is (= [["20th Century Cafe" 2 2 0] [ "25°" 2 2 0] ["33 Taps" 2 2 0]] (mt/formatted-rows [str int int int] (mt/run-mbql-query venues {:source-query {:source-table (mt/id :venues) :aggregation [[:min (mt/id :venues :price)] [:max (mt/id :venues :price)]] :breakout [[:field (mt/id :venues :name) nil]] :limit 3} :expressions {:price-range [:- [:field "max" {:base-type :type/Number}] [:field "min" {:base-type :type/Number}]]}}))))))) (deftest fk-field-and-duplicate-names-test ;; Redshift hangs on sample-dataset -- See #14784 (mt/test-drivers (disj (mt/normal-drivers-with-feature :expressions :foreign-keys) :redshift) (testing "Expressions with `fk->` fields and duplicate names should work correctly (#14854)" (mt/dataset sample-dataset (let [results (mt/run-mbql-query orders {:expressions {"CE" [:case [[[:> $discount 0] $created_at]] {:default $product_id->products.created_at}]} :order-by [[:asc $id]] :limit 2})] (is (= ["ID" "User ID" "Product ID" "Subtotal" "Tax" "Total" "Discount" "Created At" "Quantity" "CE"] (map :display_name (mt/cols results)))) (is (= [[1 1 14 37.7 2.1 39.7 nil "2019-02-11T21:40:27.892Z" 2 "2017-12-31T14:41:56.87Z"] [2 1 123 110.9 6.1 117.0 nil "2018-05-15T08:04:04.58Z" 3 "2017-11-16T13:53:14.232Z"]] (mt/formatted-rows [int int int 1.0 1.0 1.0 identity str int str] results)))))))) (deftest string-operations-from-subquery (mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex) (testing "regex-match-first and replace work when evaluated against a subquery (#14873)" (mt/dataset test-data (let [r-word "r_word" no-sp "no_spaces" id (mt/id :venues :id) results (mt/run-mbql-query venues {:expressions {r-word [:regex-match-first [:field-id (mt/id :venues :name)] "^R[^ ]+"] no-sp [:replace [:field-id (mt/id :venues :name)] " " ""]} :source-query {:source-table $$venues} :fields [$name [:expression r-word] [:expression no-sp]] :filter [:= $id 1 95] :order-by [[:asc $id]]})] (is (= ["Name" r-word no-sp] (map :display_name (mt/cols results)))) (is (= [["Red Medicine" "Red" "RedMedicine"] ["Rush Street" "Rush" "RushStreet"]] (mt/formatted-rows [str str str] results))))))))
true
(ns metabase.query-processor-test.expressions-test "Tests for expressions (calculated columns)." (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [java-time :as t] [medley.core :as m] [metabase.driver :as driver] [metabase.query-processor :as qp] [metabase.sync :as sync] [metabase.test :as mt] [metabase.test.data.one-off-dbs :as one-off-dbs] [metabase.util :as u] [metabase.util.date-2 :as u.date])) (deftest basic-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Do a basic query including an expression" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 5.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 4.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 4.0] [4 "Wurstküche" 29 33.9997 -118.465 2 4.0] [5 "Brite Spot Family Restaurant" 20 34.0778 -118.261 2 4.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:my-cool-new-field [:+ $price 2]} :limit 5 :order-by [[:asc $id]]}))))))) (deftest floating-point-division-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Make sure FLOATING POINT division is done" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 1.5] ; 3 / 2 SHOULD BE 1.5, NOT 1 (!) [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 1.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:my-cool-new-field [:/ $price 2]} :limit 3 :order-by [[:asc $id]]}))))) (testing "Make sure FLOATING POINT division is done when dividing by expressions/fields" (is (= [[0.6] [0.5] [0.5]] (mt/formatted-rows [1.0] (mt/run-mbql-query venues {:expressions {:big-price [:+ $price 2] :my-cool-new-field [:/ $price [:expression "big-price"]]} :fields [[:expression "my-cool-new-field"]] :limit 3 :order-by [[:asc $id]]}))))))) (deftest nested-expressions-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we do NESTED EXPRESSIONS ?" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 3.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 2.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 2.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:wow [:- [:* $price 2] [:+ $price 0]]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest multiple-expressions-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we have MULTIPLE EXPRESSIONS?" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 2.0 4.0] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0 3.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 1.0 3.0]] (mt/formatted-rows [int str int 4.0 4.0 int float float] (mt/run-mbql-query venues {:expressions {:x [:- $price 1] :y [:+ $price 1]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest expressions-in-fields-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we refer to expressions inside a FIELDS clause?" (is (= [[4] [4] [5]] (mt/formatted-rows [int] (mt/run-mbql-query venues {:expressions {:x [:+ $price $id]} :fields [[:expression :x]] :limit 3 :order-by [[:asc $id]]}))))))) (deftest dont-return-expressions-if-fields-is-explicit-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (let [query (mt/mbql-query venues {:expressions {"Price + 1" [:+ $price 1] "1 + 1" [:+ 1 1]} :fields [$price [:expression "1 + 1"]] :order-by [[:asc $id]] :limit 3})] (testing "If an explicit `:fields` clause is present, expressions *not* in that clause should not come back" (is (= [[3 2] [2 2] [2 2]] (mt/formatted-rows [int int] (qp/process-query query))))) (testing "If `:fields` is not explicit, then return all the expressions" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4 2] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3 2] [3 "The Apple Pan" 11 34.0406 -118.428 2 3 2]] (mt/formatted-rows [int str int 4.0 4.0 int int int] (qp/process-query (m/dissoc-in query [:query :fields])))))) (testing "When aggregating, expressions that aren't used shouldn't come back" (is (= [[2 22] [3 59] [4 13]] (mt/formatted-rows [int int] (mt/run-mbql-query venues {:expressions {"Price + 1" [:+ $price 1] "1 + 1" [:+ 1 1]} :aggregation [:count] :breakout [[:expression "Price + 1"]] :order-by [[:asc [:expression "Price + 1"]]] :limit 3})))))))) (deftest expressions-in-order-by-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we refer to expressions inside an ORDER BY clause?" (is (= [[100 "Mohawk Bend" 46 34.0777 -118.265 2 102.0] [99 "Golden Road Brewing" 10 34.1505 -118.274 2 101.0] [98 "Lucky BPI:NAME:<NAME>END_PI's Pub" 7 34.1454 -118.149 2 100.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:x [:+ $price $id]} :limit 3 :order-by [[:desc [:expression :x]]]}))))))) (deftest aggregate-breakout-expression-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we AGGREGATE + BREAKOUT by an EXPRESSION?" (is (= [[2 22] [4 59] [6 13] [8 6]] (mt/formatted-rows [int int] (mt/run-mbql-query venues {:expressions {:x [:* $price 2.0]} :aggregation [[:count]] :breakout [[:expression :x]]}))))))) (deftest expressions-should-include-type-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Custom aggregation expressions should include their type" (let [cols (mt/cols (mt/run-mbql-query venues {:aggregation [[:aggregation-options [:sum [:* $price -1]] {:name "x"}]] :breakout [$category_id]}))] (testing (format "cols = %s" (u/pprint-to-str cols)) (is (= #{"x" (mt/format-name "category_id")} (set (map :name cols)))) (let [name->base-type (into {} (map (juxt :name :base_type) cols))] (testing "x" (is (isa? (name->base-type "x") :type/Number))) (testing "category_id" (is (isa? (name->base-type (mt/format-name "category_id")) :type/Number))))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | HANDLING NULLS AND ZEROES | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; "bird scarcity" is a scientific metric based on the number of birds seen in a given day ;; (at least for the purposes of the tests below) ;; ;; e.g. scarcity = 100.0 / num-birds (defn- calculate-bird-scarcity* [formula filter-clause] (mt/formatted-rows [2.0] (mt/dataset daily-bird-counts (mt/run-mbql-query bird-count {:expressions {"bird-scarcity" formula} :fields [[:expression "bird-scarcity"]] :filter filter-clause :order-by [[:asc $date]] :limit 10})))) (defmacro ^:private calculate-bird-scarcity [formula & [filter-clause]] `(mt/dataset ~'daily-bird-counts (mt/$ids ~'bird-count (calculate-bird-scarcity* ~formula ~filter-clause)))) (deftest nulls-and-zeroes-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing (str "hey... expressions should work if they are just a Field! (Also, this lets us take a peek at the " "raw values being used to calculate the formulas below, so we can tell at a glance if they're right " "without referring to the EDN def)") (is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]] (calculate-bird-scarcity $count)))) (testing (str "do expressions automatically handle division by zero? Should return `nil` in the results for places " "where that was attempted") (is (= [[nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [9.09] [7.14]] (calculate-bird-scarcity [:/ 100.0 $count] [:!= $count nil])))) (testing (str "do expressions handle division by `nil`? Should return `nil` in the results for places where that " "was attempted") (is (= [[nil] [10.0] [12.5] [20.0] [20.0] [nil] [9.09] [7.14] [12.5] [7.14]] (calculate-bird-scarcity [:/ 100.0 $count] [:or [:= $count nil] [:!= $count 0]])))) (testing "can we handle BOTH NULLS AND ZEROES AT THE SAME TIME????" (is (= [[nil] [nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:/ 100.0 $count])))) (testing "ok, what if we use multiple args to divide, and more than one is zero?" (is (= [[nil] [nil] [nil] [1.0] [1.56] [4.0] [4.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:/ 100.0 $count $count])))) (testing "are nulls/zeroes still handled appropriately when nested inside other expressions?" (is (= [[nil] [nil] [nil] [20.0] [25.0] [40.0] [40.0] [nil] [nil] [nil]] (calculate-bird-scarcity [:* [:/ 100.0 $count] 2])))) (testing (str "if a zero is present in the NUMERATOR we should return ZERO and not NULL " "(`0 / 10 = 0`; `10 / 0 = NULL`, at least as far as MBQL is concerned)") (is (= [[nil] [0.0] [0.0] [1.0] [0.8] [0.5] [0.5] [nil] [0.0] [0.0]] (calculate-bird-scarcity [:/ $count 10])))) (testing "can addition handle nulls & zeroes?" (is (= [[nil] [10.0] [10.0] [20.0] [18.0] [15.0] [15.0] [nil] [10.0] [10.0]] (calculate-bird-scarcity [:+ $count 10])))) (testing "can subtraction handle nulls & zeroes?" (is (= [[nil] [10.0] [10.0] [0.0] [2.0] [5.0] [5.0] [nil] [10.0] [10.0]] (calculate-bird-scarcity [:- 10 $count])))) (testing "can multiplications handle nulls & zeros?" (is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]] (calculate-bird-scarcity [:* 1 $count])))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | DATETIME EXTRACTION AND MANIPULATION | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- robust-dates [strs] ;; TIMEZONE FIXME — SQLite shouldn't return strings. And for whatever weird reason it's truncating to date as well? (let [format-fn (if (= driver/*driver* :sqlite) #(u.date/format-sql (t/local-date-time (t/local-date %) (t/local-time 0))) u.date/format)] (for [s strs] [(format-fn (u.date/parse s "UTC"))]))) (deftest temporal-arithmetic-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Test that we can do datetime arithemtics using MBQL `:interval` clause in expressions" (is (= (robust-dates ["2014-09-02T13:45:00" "2014-07-02T09:30:00" "2014-07-01T10:30:00"]) (mt/with-temporary-setting-values [report-timezone "UTC"] (-> (mt/run-mbql-query users {:expressions {:prev_month [:+ $last_login [:interval -31 :day]]} :fields [[:expression :prev_month]] :limit 3 :order-by [[:asc $name]]}) mt/rows))))) (testing "Test interaction of datetime arithmetics with truncation" (is (= (robust-dates ["2014-09-02T00:00:00" "2014-07-02T00:00:00" "2014-07-01T00:00:00"]) (mt/with-temporary-setting-values [report-timezone "UTC"] (-> (mt/run-mbql-query users {:expressions {:prev_month [:+ !day.last_login [:interval -31 :day]]} :fields [[:expression :prev_month]] :limit 3 :order-by [[:asc $name]]}) mt/rows))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | JOINS | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest expressions+joins-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join) (testing "Do calculated columns play well with joins" (is (= "PI:NAME:<NAME>END_PI" (-> (mt/run-mbql-query checkins {:expressions {:prev_month [:+ $date [:interval -31 :day]]} :fields [[:field (mt/id :users :name) {:join-alias "users__via__user_id"}] [:expression :prev_month]] :limit 1 :order-by [[:asc $date]] :joins [{:strategy :left-join :source-table (mt/id :users) :alias "users__via__user_id" :condition [:= $user_id [:field (mt/id :users :id) {:join-alias "users__via__user_id"}]]}]}) mt/rows ffirst)))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | MISC BUG FIXES | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; Make sure no part of query compilation is lazy as that won't play well with dynamic bindings. ;; This is not an issue limited to expressions, but using expressions is the most straightforward ;; way to reproducing it. (deftest no-lazyness-test (one-off-dbs/with-blank-db (let [ ;; need more fields than seq chunking size fields (repeatedly 1000 gensym)] (doseq [statement ["drop table if exists \"LOTS_OF_FIELDS\";" (format "create table \"LOTS_OF_FIELDS\" (a integer, b integer, %s);" (str/join ", " (for [field-name fields] (str (name field-name) " integer")))) (format "insert into \"LOTS_OF_FIELDS\" values(%s);" (str/join "," (range (+ (count fields) 2))))]] (jdbc/execute! one-off-dbs/*conn* [statement])) (sync/sync-database! (mt/db)) (is (= 1 (->> (mt/run-mbql-query lots_of_fields {:expressions {:c [:+ [:field (mt/id :lots_of_fields :a) nil] [:field (mt/id :lots_of_fields :b) nil]]} :fields (concat [[:expression :c]] (for [field fields] [:field (mt/id :lots_of_fields (keyword field)) nil]))}) (mt/formatted-rows [int]) ffirst)))))) (deftest expression-with-slashes (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Make sure an expression with a / in its name works (#12305)" (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4.0] [2 "PI:NAME:<NAME>END_PI & BePI:NAME:<NAME>END_PI" 11 34.0996 -118.329 2 3.0] [3 "The Apple Pan" 11 34.0406 -118.428 2 3.0]] (mt/formatted-rows [int str int 4.0 4.0 int float] (mt/run-mbql-query venues {:expressions {:TEST/my-cool-new-field [:+ $price 1]} :limit 3 :order-by [[:asc $id]]}))))))) (deftest expression-using-aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :expressions) (testing "Can we use aggregations from previous steps in expressions (#12762)" (is (= [["20th Century Cafe" 2 2 0] [ "25°" 2 2 0] ["33 Taps" 2 2 0]] (mt/formatted-rows [str int int int] (mt/run-mbql-query venues {:source-query {:source-table (mt/id :venues) :aggregation [[:min (mt/id :venues :price)] [:max (mt/id :venues :price)]] :breakout [[:field (mt/id :venues :name) nil]] :limit 3} :expressions {:price-range [:- [:field "max" {:base-type :type/Number}] [:field "min" {:base-type :type/Number}]]}}))))))) (deftest fk-field-and-duplicate-names-test ;; Redshift hangs on sample-dataset -- See #14784 (mt/test-drivers (disj (mt/normal-drivers-with-feature :expressions :foreign-keys) :redshift) (testing "Expressions with `fk->` fields and duplicate names should work correctly (#14854)" (mt/dataset sample-dataset (let [results (mt/run-mbql-query orders {:expressions {"CE" [:case [[[:> $discount 0] $created_at]] {:default $product_id->products.created_at}]} :order-by [[:asc $id]] :limit 2})] (is (= ["ID" "User ID" "Product ID" "Subtotal" "Tax" "Total" "Discount" "Created At" "Quantity" "CE"] (map :display_name (mt/cols results)))) (is (= [[1 1 14 37.7 2.1 39.7 nil "2019-02-11T21:40:27.892Z" 2 "2017-12-31T14:41:56.87Z"] [2 1 123 110.9 6.1 117.0 nil "2018-05-15T08:04:04.58Z" 3 "2017-11-16T13:53:14.232Z"]] (mt/formatted-rows [int int int 1.0 1.0 1.0 identity str int str] results)))))))) (deftest string-operations-from-subquery (mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex) (testing "regex-match-first and replace work when evaluated against a subquery (#14873)" (mt/dataset test-data (let [r-word "r_word" no-sp "no_spaces" id (mt/id :venues :id) results (mt/run-mbql-query venues {:expressions {r-word [:regex-match-first [:field-id (mt/id :venues :name)] "^R[^ ]+"] no-sp [:replace [:field-id (mt/id :venues :name)] " " ""]} :source-query {:source-table $$venues} :fields [$name [:expression r-word] [:expression no-sp]] :filter [:= $id 1 95] :order-by [[:asc $id]]})] (is (= ["Name" r-word no-sp] (map :display_name (mt/cols results)))) (is (= [["Red Medicine" "Red" "RedMedicine"] ["Rush Street" "Rush" "RushStreet"]] (mt/formatted-rows [str str str] results))))))))
[ { "context": "ith-temporary-setting-values [email-from-address \"metamailman@metabase.com\"]\n (mt/with-fake-inbox\n (with-redefs ", "end": 2294, "score": 0.9999294281005859, "start": 2270, "tag": "EMAIL", "value": "metamailman@metabase.com" }, { "context": " (let [results @mt/inbox]\n (is (= {\"rasta@metabase.com\" [{:from \"metamailman@metabase.com\"\n ", "end": 2618, "score": 0.9999276399612427, "start": 2600, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": " (is (= {\"rasta@metabase.com\" [{:from \"metamailman@metabase.com\"\n :to ", "end": 2656, "score": 0.9999302625656128, "start": 2632, "tag": "EMAIL", "value": "metamailman@metabase.com" }, { "context": " :to [\"rasta@metabase.com\"]\n :subje", "end": 2728, "score": 0.9999284744262695, "start": 2710, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "Pulse\"}]}\n (m/dissoc-in results [\"rasta@metabase.com\" 0 :body])))\n (get-in results [\"rasta@me", "end": 2862, "score": 0.9999257922172546, "start": 2844, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "base.com\" 0 :body])))\n (get-in results [\"rasta@metabase.com\" 0 :body 0 :result]))))))\n\n(deftest e2e-sandboxed", "end": 2922, "score": 0.9999254941940308, "start": 2904, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": " :email \"rasta@metabase.com\"}]}]})\n (let [[{html :content} {at", "end": 6636, "score": 0.9999262690544128, "start": 6618, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "ntent} {attachment :content}] (get-in @mt/inbox [\"rasta@metabase.com\" 0 :body])]\n (testing \"email\"\n ", "end": 6744, "score": 0.9999254941940308, "start": 6726, "tag": "EMAIL", "value": "rasta@metabase.com" }, { "context": "t} {attachment :content}] (get-in email-results [\"rasta@metabase.com\" 0 :body])]\n (testing \"email\"\n ", "end": 8510, "score": 0.9999250173568726, "start": 8492, "tag": "EMAIL", "value": "rasta@metabase.com" } ]
c#-metabase/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
hanakhry/Crime_Admin
0
(ns metabase-enterprise.sandbox.pulse-test (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.test :refer :all] [medley.core :as m] [metabase.email.messages :as messages] [metabase.models :refer [Card Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.pulse :as models.pulse] [metabase.pulse :as pulse] [metabase.pulse.test-util :as pulse.tu] [metabase.query-processor :as qp] [metabase.test :as mt] [metabase.util :as u])) (deftest sandboxed-pulse-test (testing "Pulses should get sent with the row-level restrictions of the User that created them." (letfn [(send-pulse-created-by-user! [user-kw] (mt/with-gtaps {:gtaps {:venues {:query (mt/mbql-query venues) :remappings {:cat ["variable" [:field (mt/id :venues :category_id) nil]]}}} :attributes {"cat" 50}} (mt/with-temp Card [card {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}] ;; `with-gtaps` binds the current test user; we don't want that falsely affecting results (mt/with-test-user nil (pulse.tu/send-pulse-created-by-user! user-kw card)))))] (is (= [[100]] (send-pulse-created-by-user! :crowberto))) (is (= [[10]] (send-pulse-created-by-user! :rasta)))))) (defn- pulse-results "Results for creating and running a Pulse." [query] (mt/with-temp* [Card [pulse-card {:dataset_query query}] Pulse [pulse {:name "Test Pulse"}] PulseCard [_ {:pulse_id (:id pulse), :card_id (:id pulse-card)}] PulseChannel [pc {:channel_type :email :pulse_id (:id pulse) :enabled true}] PulseChannelRecipient [_ {:pulse_channel_id (:id pc) :user_id (mt/user->id :rasta)}]] (mt/with-temporary-setting-values [email-from-address "metamailman@metabase.com"] (mt/with-fake-inbox (with-redefs [messages/render-pulse-email (fn [_ _ [{:keys [result]}]] [{:result result}])] (mt/with-test-user nil (pulse/send-pulse! pulse))) (let [results @mt/inbox] (is (= {"rasta@metabase.com" [{:from "metamailman@metabase.com" :to ["rasta@metabase.com"] :subject "Pulse: Test Pulse"}]} (m/dissoc-in results ["rasta@metabase.com" 0 :body]))) (get-in results ["rasta@metabase.com" 0 :body 0 :result])))))) (deftest e2e-sandboxed-pulse-test (testing "Sending Pulses w/ sandboxing, end-to-end" (mt/with-gtaps {:gtaps {:venues {:query (mt/mbql-query venues {:filter [:= $price 3]})}}} (let [query (mt/mbql-query venues {:aggregation [[:count]] :breakout [$price]})] (is (= [[3 13]] (mt/formatted-rows [int int] (mt/with-test-user :rasta (qp/process-query query)))) "Basic sanity check: make sure the query is properly set up to apply GTAPs") (testing "GTAPs should apply to Pulses — they should get the same results as if running that query normally" (is (= [[3 13]] (mt/rows (pulse-results query))))))))) (defn- html->row-count [html] (or (some->> html (re-find #"of <strong.+>(\d+)</strong> rows") second Integer/parseUnsignedInt) html)) (defn- csv->row-count [attachment-url] (when attachment-url (with-open [reader (io/reader attachment-url)] (count (csv/read-csv reader))))) (deftest user-attributes-test (testing "Pulses should be sandboxed correctly by User login_attributes" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp Card [card {:dataset_query query}] (testing "Sanity check: make sure user is seeing sandboxed results outside of Pulses" (testing "ad-hoc query" (is (= 22 (count (mt/rows (qp/process-query query)))))) (testing "in a Saved Question" (is (= 22 (count (mt/rows (mt/user-http-request :rasta :post 202 (format "card/%d/query" (u/the-id card))))))))) (testing "Pulse should be sandboxed" (is (= 22 (count (mt/rows (pulse-results query)))))))))))) (deftest pulse-preview-test (testing "Pulse preview endpoints should be sandboxed" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp Card [card {:dataset_query query}] (testing "GET /api/pulse/preview_card/:id" (is (= 22 (html->row-count (mt/user-http-request :rasta :get 200 (format "pulse/preview_card/%d" (u/the-id card))))))) (testing "POST /api/pulse/test" (mt/with-fake-inbox (mt/user-http-request :rasta :post 200 "pulse/test" {:name "venues" :cards [{:id (u/the-id card) :include_csv true :include_xls false}] :channels [{:channel_type :email :enabled :true :recipients [{:id (mt/user->id :rasta) :email "rasta@metabase.com"}]}]}) (let [[{html :content} {attachment :content}] (get-in @mt/inbox ["rasta@metabase.com" 0 :body])] (testing "email" (is (= 22 (html->row-count html)))) (testing "CSV attachment" ;; one extra row because first row is column names (is (= 23 (csv->row-count attachment))))))))))))) (deftest csv-downloads-test (testing "CSV/XLSX downloads should be sandboxed" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp* [Card [{card-id :id} {:dataset_query query}] Pulse [{pulse-id :id} {:name "Pulse Name" :skip_if_empty false}] PulseCard [_ {:pulse_id pulse-id :card_id card-id :position 0}] PulseChannel [{pc-id :id} {:pulse_id pulse-id}] PulseChannelRecipient [_ {:user_id (mt/user->id :rasta) :pulse_channel_id pc-id}]] (mt/with-fake-inbox (mt/with-test-user nil (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id))) (let [email-results @mt/inbox [{html :content} {attachment :content}] (get-in email-results ["rasta@metabase.com" 0 :body])] (testing "email" (is (= 22 (html->row-count html)))) (testing "CSV attachment" (is (= 23 (csv->row-count attachment))))))))))))
57255
(ns metabase-enterprise.sandbox.pulse-test (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.test :refer :all] [medley.core :as m] [metabase.email.messages :as messages] [metabase.models :refer [Card Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.pulse :as models.pulse] [metabase.pulse :as pulse] [metabase.pulse.test-util :as pulse.tu] [metabase.query-processor :as qp] [metabase.test :as mt] [metabase.util :as u])) (deftest sandboxed-pulse-test (testing "Pulses should get sent with the row-level restrictions of the User that created them." (letfn [(send-pulse-created-by-user! [user-kw] (mt/with-gtaps {:gtaps {:venues {:query (mt/mbql-query venues) :remappings {:cat ["variable" [:field (mt/id :venues :category_id) nil]]}}} :attributes {"cat" 50}} (mt/with-temp Card [card {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}] ;; `with-gtaps` binds the current test user; we don't want that falsely affecting results (mt/with-test-user nil (pulse.tu/send-pulse-created-by-user! user-kw card)))))] (is (= [[100]] (send-pulse-created-by-user! :crowberto))) (is (= [[10]] (send-pulse-created-by-user! :rasta)))))) (defn- pulse-results "Results for creating and running a Pulse." [query] (mt/with-temp* [Card [pulse-card {:dataset_query query}] Pulse [pulse {:name "Test Pulse"}] PulseCard [_ {:pulse_id (:id pulse), :card_id (:id pulse-card)}] PulseChannel [pc {:channel_type :email :pulse_id (:id pulse) :enabled true}] PulseChannelRecipient [_ {:pulse_channel_id (:id pc) :user_id (mt/user->id :rasta)}]] (mt/with-temporary-setting-values [email-from-address "<EMAIL>"] (mt/with-fake-inbox (with-redefs [messages/render-pulse-email (fn [_ _ [{:keys [result]}]] [{:result result}])] (mt/with-test-user nil (pulse/send-pulse! pulse))) (let [results @mt/inbox] (is (= {"<EMAIL>" [{:from "<EMAIL>" :to ["<EMAIL>"] :subject "Pulse: Test Pulse"}]} (m/dissoc-in results ["<EMAIL>" 0 :body]))) (get-in results ["<EMAIL>" 0 :body 0 :result])))))) (deftest e2e-sandboxed-pulse-test (testing "Sending Pulses w/ sandboxing, end-to-end" (mt/with-gtaps {:gtaps {:venues {:query (mt/mbql-query venues {:filter [:= $price 3]})}}} (let [query (mt/mbql-query venues {:aggregation [[:count]] :breakout [$price]})] (is (= [[3 13]] (mt/formatted-rows [int int] (mt/with-test-user :rasta (qp/process-query query)))) "Basic sanity check: make sure the query is properly set up to apply GTAPs") (testing "GTAPs should apply to Pulses — they should get the same results as if running that query normally" (is (= [[3 13]] (mt/rows (pulse-results query))))))))) (defn- html->row-count [html] (or (some->> html (re-find #"of <strong.+>(\d+)</strong> rows") second Integer/parseUnsignedInt) html)) (defn- csv->row-count [attachment-url] (when attachment-url (with-open [reader (io/reader attachment-url)] (count (csv/read-csv reader))))) (deftest user-attributes-test (testing "Pulses should be sandboxed correctly by User login_attributes" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp Card [card {:dataset_query query}] (testing "Sanity check: make sure user is seeing sandboxed results outside of Pulses" (testing "ad-hoc query" (is (= 22 (count (mt/rows (qp/process-query query)))))) (testing "in a Saved Question" (is (= 22 (count (mt/rows (mt/user-http-request :rasta :post 202 (format "card/%d/query" (u/the-id card))))))))) (testing "Pulse should be sandboxed" (is (= 22 (count (mt/rows (pulse-results query)))))))))))) (deftest pulse-preview-test (testing "Pulse preview endpoints should be sandboxed" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp Card [card {:dataset_query query}] (testing "GET /api/pulse/preview_card/:id" (is (= 22 (html->row-count (mt/user-http-request :rasta :get 200 (format "pulse/preview_card/%d" (u/the-id card))))))) (testing "POST /api/pulse/test" (mt/with-fake-inbox (mt/user-http-request :rasta :post 200 "pulse/test" {:name "venues" :cards [{:id (u/the-id card) :include_csv true :include_xls false}] :channels [{:channel_type :email :enabled :true :recipients [{:id (mt/user->id :rasta) :email "<EMAIL>"}]}]}) (let [[{html :content} {attachment :content}] (get-in @mt/inbox ["<EMAIL>" 0 :body])] (testing "email" (is (= 22 (html->row-count html)))) (testing "CSV attachment" ;; one extra row because first row is column names (is (= 23 (csv->row-count attachment))))))))))))) (deftest csv-downloads-test (testing "CSV/XLSX downloads should be sandboxed" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp* [Card [{card-id :id} {:dataset_query query}] Pulse [{pulse-id :id} {:name "Pulse Name" :skip_if_empty false}] PulseCard [_ {:pulse_id pulse-id :card_id card-id :position 0}] PulseChannel [{pc-id :id} {:pulse_id pulse-id}] PulseChannelRecipient [_ {:user_id (mt/user->id :rasta) :pulse_channel_id pc-id}]] (mt/with-fake-inbox (mt/with-test-user nil (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id))) (let [email-results @mt/inbox [{html :content} {attachment :content}] (get-in email-results ["<EMAIL>" 0 :body])] (testing "email" (is (= 22 (html->row-count html)))) (testing "CSV attachment" (is (= 23 (csv->row-count attachment))))))))))))
true
(ns metabase-enterprise.sandbox.pulse-test (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.test :refer :all] [medley.core :as m] [metabase.email.messages :as messages] [metabase.models :refer [Card Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.pulse :as models.pulse] [metabase.pulse :as pulse] [metabase.pulse.test-util :as pulse.tu] [metabase.query-processor :as qp] [metabase.test :as mt] [metabase.util :as u])) (deftest sandboxed-pulse-test (testing "Pulses should get sent with the row-level restrictions of the User that created them." (letfn [(send-pulse-created-by-user! [user-kw] (mt/with-gtaps {:gtaps {:venues {:query (mt/mbql-query venues) :remappings {:cat ["variable" [:field (mt/id :venues :category_id) nil]]}}} :attributes {"cat" 50}} (mt/with-temp Card [card {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}] ;; `with-gtaps` binds the current test user; we don't want that falsely affecting results (mt/with-test-user nil (pulse.tu/send-pulse-created-by-user! user-kw card)))))] (is (= [[100]] (send-pulse-created-by-user! :crowberto))) (is (= [[10]] (send-pulse-created-by-user! :rasta)))))) (defn- pulse-results "Results for creating and running a Pulse." [query] (mt/with-temp* [Card [pulse-card {:dataset_query query}] Pulse [pulse {:name "Test Pulse"}] PulseCard [_ {:pulse_id (:id pulse), :card_id (:id pulse-card)}] PulseChannel [pc {:channel_type :email :pulse_id (:id pulse) :enabled true}] PulseChannelRecipient [_ {:pulse_channel_id (:id pc) :user_id (mt/user->id :rasta)}]] (mt/with-temporary-setting-values [email-from-address "PI:EMAIL:<EMAIL>END_PI"] (mt/with-fake-inbox (with-redefs [messages/render-pulse-email (fn [_ _ [{:keys [result]}]] [{:result result}])] (mt/with-test-user nil (pulse/send-pulse! pulse))) (let [results @mt/inbox] (is (= {"PI:EMAIL:<EMAIL>END_PI" [{:from "PI:EMAIL:<EMAIL>END_PI" :to ["PI:EMAIL:<EMAIL>END_PI"] :subject "Pulse: Test Pulse"}]} (m/dissoc-in results ["PI:EMAIL:<EMAIL>END_PI" 0 :body]))) (get-in results ["PI:EMAIL:<EMAIL>END_PI" 0 :body 0 :result])))))) (deftest e2e-sandboxed-pulse-test (testing "Sending Pulses w/ sandboxing, end-to-end" (mt/with-gtaps {:gtaps {:venues {:query (mt/mbql-query venues {:filter [:= $price 3]})}}} (let [query (mt/mbql-query venues {:aggregation [[:count]] :breakout [$price]})] (is (= [[3 13]] (mt/formatted-rows [int int] (mt/with-test-user :rasta (qp/process-query query)))) "Basic sanity check: make sure the query is properly set up to apply GTAPs") (testing "GTAPs should apply to Pulses — they should get the same results as if running that query normally" (is (= [[3 13]] (mt/rows (pulse-results query))))))))) (defn- html->row-count [html] (or (some->> html (re-find #"of <strong.+>(\d+)</strong> rows") second Integer/parseUnsignedInt) html)) (defn- csv->row-count [attachment-url] (when attachment-url (with-open [reader (io/reader attachment-url)] (count (csv/read-csv reader))))) (deftest user-attributes-test (testing "Pulses should be sandboxed correctly by User login_attributes" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp Card [card {:dataset_query query}] (testing "Sanity check: make sure user is seeing sandboxed results outside of Pulses" (testing "ad-hoc query" (is (= 22 (count (mt/rows (qp/process-query query)))))) (testing "in a Saved Question" (is (= 22 (count (mt/rows (mt/user-http-request :rasta :post 202 (format "card/%d/query" (u/the-id card))))))))) (testing "Pulse should be sandboxed" (is (= 22 (count (mt/rows (pulse-results query)))))))))))) (deftest pulse-preview-test (testing "Pulse preview endpoints should be sandboxed" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp Card [card {:dataset_query query}] (testing "GET /api/pulse/preview_card/:id" (is (= 22 (html->row-count (mt/user-http-request :rasta :get 200 (format "pulse/preview_card/%d" (u/the-id card))))))) (testing "POST /api/pulse/test" (mt/with-fake-inbox (mt/user-http-request :rasta :post 200 "pulse/test" {:name "venues" :cards [{:id (u/the-id card) :include_csv true :include_xls false}] :channels [{:channel_type :email :enabled :true :recipients [{:id (mt/user->id :rasta) :email "PI:EMAIL:<EMAIL>END_PI"}]}]}) (let [[{html :content} {attachment :content}] (get-in @mt/inbox ["PI:EMAIL:<EMAIL>END_PI" 0 :body])] (testing "email" (is (= 22 (html->row-count html)))) (testing "CSV attachment" ;; one extra row because first row is column names (is (= 23 (csv->row-count attachment))))))))))))) (deftest csv-downloads-test (testing "CSV/XLSX downloads should be sandboxed" (mt/with-gtaps {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}} :attributes {"price" "1"}} (let [query (mt/mbql-query venues)] (mt/with-test-user :rasta (mt/with-temp* [Card [{card-id :id} {:dataset_query query}] Pulse [{pulse-id :id} {:name "Pulse Name" :skip_if_empty false}] PulseCard [_ {:pulse_id pulse-id :card_id card-id :position 0}] PulseChannel [{pc-id :id} {:pulse_id pulse-id}] PulseChannelRecipient [_ {:user_id (mt/user->id :rasta) :pulse_channel_id pc-id}]] (mt/with-fake-inbox (mt/with-test-user nil (pulse/send-pulse! (models.pulse/retrieve-pulse pulse-id))) (let [email-results @mt/inbox [{html :content} {attachment :content}] (get-in email-results ["PI:EMAIL:<EMAIL>END_PI" 0 :body])] (testing "email" (is (= 22 (html->row-count html)))) (testing "CSV attachment" (is (= 23 (csv->row-count attachment))))))))))))
[ { "context": "d is not\n `reduced`\n\n ```clojure\n (-> {:name \\\"Ivan\\\" :age 17}\n (then #(update % :age inc)))\n =", "end": 9218, "score": 0.9996825456619263, "start": 9214, "tag": "NAME", "value": "Ivan" }, { "context": "\n (then #(update % :age inc)))\n => {:name \\\"Ivan\\\", :age 18}\n ```\"\n [x f]\n (if (core/and (not (", "end": 9283, "score": 0.9996845126152039, "start": 9279, "tag": "NAME", "value": "Ivan" }, { "context": "s [[isa?]] condition\n\n ```clojure\n (-> {:name \\\"Ivan\\\" :age 17}\n (then-if (comp (partial <= 18) :", "end": 9536, "score": 0.9996999502182007, "start": 9532, "tag": "NAME", "value": "Ivan" }, { "context": "8) :age) #(assoc % :adult false)))\n => {:name \\\"Ivan\\\", :age 17, :adult false}\n ```\"\n [x pred f]\n (", "end": 9702, "score": 0.999732494354248, "start": 9698, "tag": "NAME", "value": "Ivan" }, { "context": " if `x` is [[fail?]]\n\n ```clojure\n (-> {:name \\\"Ivan\\\" :age 17}\n (then-if (comp (partial <= 18) :", "end": 9942, "score": 0.9996373653411865, "start": 9938, "tag": "NAME", "value": "Ivan" }, { "context": "s [[isa?]] condition\n\n ```clojure\n (-> {:name \\\"Ivan\\\" :age 17}\n (then-if (comp (partial <= 18) :", "end": 10428, "score": 0.9996706247329712, "start": 10424, "tag": "NAME", "value": "Ivan" }, { "context": "s [[isa?]] condition\n\n ```clojure\n (-> {:name \\\"Ivan\\\" :age 17}\n (then-if (comp (partial <= 18) :", "end": 10955, "score": 0.9974625706672668, "start": 10951, "tag": "NAME", "value": "Ivan" }, { "context": "ause \\\"user is underage\\\"\n :data {:user {:name \\\"Ivan\\\", :age 17, :adult false}}\n :via\n [{:type ribel", "end": 11275, "score": 0.9979164004325867, "start": 11271, "tag": "NAME", "value": "Ivan" }, { "context": "age \\\"user is underage\\\"\n :data {:user {:name \\\"Ivan\\\", :age 17, :adult false}}}]\n :trace\n []}\n ```", "end": 11400, "score": 0.9978824257850647, "start": 11396, "tag": "NAME", "value": "Ivan" } ]
src/main/ribelo/fatum.cljc
ribelo/fatum
6
(ns ribelo.fatum (:refer-clojure :exclude [-> ->> isa? and or every? some]) #?(:cljs (:require-macros [ribelo.fatum :refer [catching catch-errors attempt -> ->> when-ok if-ok and or]])) (:require #?(:clj [clojure.core :as core] :cljs [cljs.core :as core])) #?(:clj (:import (ribelo.fatum Fail)))) #?(:clj (defmacro -if-clj [then & [else]] (if (:ns &env) else then))) #?(:cljs (defn ^{:jsdoc ["@constructor"]} Fail [msg data] (this-as this (set! (.-message ^js this) msg) (set! (.-data ^js this) data) (set! (.-get ^js this) (fn ([k] (-lookup data k)) ([k not-found] (-lookup data k not-found)))) this))) #?(:cljs (set! (.. ^js Fail -prototype -__proto__) (.-prototype ^js ExceptionInfo))) #?(:cljs (extend-type Fail ILookup (-lookup [this k] (.get this k)) IAssociative (-contains-key? [this k] (-contains-key? (.-data this) k)) (-assoc [this k v] (Fail. (.-message this) (-assoc (.-data this) k v))) IEquiv (-equiv [this o] (core/and (instance? js/Error o) (= (.-message this) (.-message o)) (= (.-data this) (.-data o)))) IEmptyableCollection (-empty [this] (Fail. (.-message this) {})))) (defn fail "returns [[Fail]] for flexibility, the `data` can be either a map, an explicit kv collection or a variadic kv collection " ([] (Fail. nil {})) ([msg] (Fail. msg {})) ([msg data] (Fail. msg (cond (map? data) data (nil? data) {} (sequential? data) (apply array-map data)))) ([msg k v & kvs] (Fail. msg (apply array-map k v kvs)))) (defn fail! "throw [[Fail]] see [[fail]]" ([] (throw (fail))) ([msg] (throw (fail msg))) ([msg data] (throw (fail msg data))) ([msg k v & kvs] (throw (apply fail msg k v kvs)))) (defn fail? "check if `x` is instance of `Exception` in clj or `js/Error` in cljs" [x] #?(:clj (instance? java.lang.Exception x) :cljs (instance? js/Error x))) (defn ensure-fail "ensure that `Exception` `err` is [[Fail]]" [x] (if (core/and (fail? x) #?(:clj (instance? java.lang.Exception x) :cljs (instance? js/Error x))) (fail (ex-message x) (ex-data x)) x)) (defn ok? "check if `x` is not [[Fail]]" [x] (not (fail? x))) (defn exception-info? "check if `x` is `ExceptionInfo`" [x] #?(:clj (instance? clojure.lang.IExceptionInfo x) :cljs (instance? ExceptionInfo x))) (defn -match-map? "chech if `x` has every `kv` from `m`" [x m] (when (core/or (map? x) (exception-info? x)) (reduce-kv (fn [_ k v] (if (= v (get x k)) true (reduced false))) true m))) (defn isa? "check if `x` meets `pred`, or whether `Exception` has in `ex-data` under the key `k` the value `v` ```clojure (isa? 1 number?) => true ``` ```clojure (isa? java.lang.ArithmeticException (catching (/ 1 0))) => true ``` ```clojure (isa? {:a 1 :b 2} {:a 1}) => true ``` ```clojure (isa? {:a 1 :b 2} {:c 3}) => false ```" [x pred] #?(:clj (cond (class? pred) (instance? pred x) (keyword? pred) (true? (get x pred)) (fn? pred) (pred x) (map? pred) (-match-map? x pred)) :cljs (cond (keyword? pred) (true? (get x pred)) (fn? pred) (core/or (instance? pred x) (pred x)) (map? pred) (-match-map? x pred)))) (defmacro catching "`try` to execute `expr`, if `catch` an error returns it itself ```clojure (catching (/ 1 0) => nil ``` ```clojure (catching (/ 1 0) e e) => java.lang.ArithmeticException ```" ([expr ] `(catching ~expr ~'_ nil)) ([expr err catch] `(-if-clj (try ~expr (catch Exception ~err ~catch)) (try ~expr (catch :default ~err ~catch)))) ([expr err catch finally] `(-if-clj (try ~expr (catch Exception ~err ~catch) (finally ~finally)) (try ~expr (catch :default ~err ~catch) (finally ~finally))))) #?(:clj (defmacro catch-errors "like [[catching]], but returns a vector where the first element is the result of executing the `body` and the second is an `Exception` ```clojure (catch-errors (/ 1 1)) => [1 nil] ``` ```clojure (catch-errors (/ 1 0)) => [nil java.lang.ArithmeticException] ```" [& body] `(catching [(do ~@body) nil] e# [nil (ensure-fail e#)]))) #?(:clj (defmacro attempt "like [[catching]], but takes `body` as argument ```clojure (attempt (/ 1 1)) => 1 ``` ```clojure (attempt (/ 1 0)) => #error { :cause \"Divide by zero\" :data {} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {}}] :trace []} ```" [& body] `(catching (do ~@body) e# (ensure-fail e#)))) #?(:clj (defmacro when-ok "Like `clojure.core/when` however if first arg is binding vector behave like `clojure.core/when-let`, but can bind multiple values. check if all tests/bindings are [[ok?]], else return [[Fail]] with attached var & failing expresions ```clojure (when-ok (/ 1 1) :ok) => :ok ``` ```clojure(when-ok nil :ok) => :ok ``` ```clojure (when-ok (/ 1 0) :ok => #error { :cause \"Divide by zero\" :data {:binding test, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding test, :expr (/ 1 0)}}] :trace []} ``` ```clojure (when-ok [x (/ 1 0)] :ok) => #error { :cause \"Divide by zero\" :data {:binding x, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding x, :expr (/ 1 0)}}] :trace []} ``` " ([test-or-bindings & body] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (when-let [] true) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (when-ok ~(vec bnext) ~@body) (fail (ex-message b2#) (merge (ex-data b2#) {::binding '~b1 ::expr '~b2}))))) `(do ~@body))) `(when-ok [~'test ~test-or-bindings] ~@body))))) #?(:clj (defmacro when-ok! "Like `clojure.core/when` however if first arg is binding vector behave like `clojure.core/when-let`, but can bind multiple values. check if all tests/bindings are [[ok?]], else throw [[Fail]] with attached var & failing expresions ```clojure (when-ok (/ 1 1) :ok) => :ok ``` ```clojure(when-ok nil :ok) => :ok ``` ```clojure (when-ok (/ 1 0) :ok => #error { :cause \"Divide by zero\" :data {:binding test, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding test, :expr (/ 1 0)}}] :trace []} ``` ```clojure (when-ok [x (/ 1 0)] :ok) => #error { :cause \"Divide by zero\" :data {:binding x, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding x, :expr (/ 1 0)}}] :trace []} ``` " ([test-or-bindings & body] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (when-let [] true) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (when-ok ~(vec bnext) ~@body) (fail! (ex-message b2#) (merge (ex-data b2#) {::binding '~b1 ::expr '~b2}))))) `(do ~@body))) `(when-ok [~'test ~test-or-bindings] ~@body))))) #?(:clj (defmacro if-ok "Like `core/if-let` but can bind multiple values. execute `then` if all tests are `ok?` ```clojure (if-ok (/ 1 1) :ok :err) => :ok ``` ```clojure (if-ok (/ 1 1) :ok :err) => :err ``` ```clojure (if-ok nil :ok :err) => :ok ```" {:style/indent 1} ([test-or-bindings then ] `(when-ok ~test-or-bindings ~then)) ([test-or-bindings then else] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (if-let [] true false) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (if-ok ~(vec bnext) ~then ~else) (let [~b1 (assoc ~b1 :binding '~b1 :expr '~b2)] ~else)))) then)) `(if (ok? ~test-or-bindings) ~then ~else))))) (defn call "[[attempt]] to call function `f` on value `x` ```clojure (call 1 inc) => 2 ``` ```clojure (call \"1\" inc) => #error { :cause \"class java.lang.String cannot be cast to class java.lang.Number ...\" :data {} :via [{:type ribelo.fatum.Fail :message \"class java.lang.String cannot be cast to class java.lang.Number ... \" :data {}}] :trace []} ```` " [x f] (attempt (f x))) (defn then "[[attempt]] to call function `f` on value `x` if `x` is [[ok?]] and is not `reduced` ```clojure (-> {:name \"Ivan\" :age 17} (then #(update % :age inc))) => {:name \"Ivan\", :age 18} ```" [x f] (if (core/and (not (reduced? x)) (ok? x)) (attempt (f x)) x)) (defn then-if "[[attempt]] to call function `f` on value `x` if `x` is [[ok?]], not `reduced` and meets [[isa?]] condition ```clojure (-> {:name \"Ivan\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false))) => {:name \"Ivan\", :age 17, :adult false} ```" [x pred f] (if (core/and (not (reduced? x)) (ok? x) (isa? x pred)) (attempt (f x)) x)) (defn catch "[[attempt]] to call function `f` on value `x` if `x` is [[fail?]] ```clojure (-> {:name \"Ivan\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" #(find % :age)) (catch-if (constantly :err))) => :err ```" [x f] (if (fail? x) (attempt (f x)) x)) (defn catch-if "[[attempt]] to call function `f` on value `x` if `x` is [[fail?]], not `reduced` and meets [[isa?]] condition ```clojure (-> {:name \"Ivan\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" #(find % :age)) (catch-if (comp (partial > 18) :age) (constantly :err))) => :err ```" [x pred f] (if (core/and (fail? x) (isa? x pred)) (attempt (f x)) x)) (defn fail-if "return [[fail]] with optional `msg` and `data` if `x` is [[ok?]] and meets [[isa?]] condition ```clojure (-> {:name \"Ivan\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" (juxt (constantly :user) identity))) => #error { :cause \"user is underage\" :data {:user {:name \"Ivan\", :age 17, :adult false}} :via [{:type ribelo.fatum.Fail :message \"user is underage\" :data {:user {:name \"Ivan\", :age 17, :adult false}}}] :trace []} ```" ([x pred] (if (core/and (ok? x) (isa? (unreduced x) pred)) (fail) x)) ([x pred msg] (if (core/and (ok? x) (isa? (unreduced x) pred)) (fail msg) x)) ([x pred msg data-or-fn] (if (core/and (ok? x) (isa? (unreduced x) pred)) (if (fn? data-or-fn) (fail msg (data-or-fn x)) (fail msg data-or-fn)) x))) (defn throw-if "throw [[fail!]] with optional `msg` and `data` if `x` is [[ok?]] and meets [[isa?]] condition see [[fail-if]]" ([x pred] (if-ok [result (fail-if x pred)] result (throw result))) ([x pred msg-or-fn] (if-ok [result (fail-if x pred msg-or-fn)] result (throw result))) ([x pred msg data] (if-ok [result (fail-if x pred msg data)] result (throw result)))) (defn finally "[[attempt]] to call function `f` on `unreduced` value of `x`. return `x` unchanged and `unreduced`." [x f] (attempt (f (unreduced x))) (unreduced x)) (defn maybe-throw "`throw` `x` if `x` meets [[fail?]]" [x] (when (fail? x) (throw x))) (defn thru "[[attempt]] to call function `f` on `unreduced` value of `x`. return `x` unchanged. used for side effects" [x f] (attempt (f (unreduced x))) x) (defn thru-if "[[attempt]] to call function `f` on `unreduced` value of `x` if `unreduced` `x` meets [[isa?]] condition. return `x` unchanged. used for side effects" ([x pred f] (if (isa? (unreduced x) pred) (do (f (unreduced x)) x) x))) (defn every? [pred xs] (core/or (reduce (fn [_ x] (if (pred x) true (reduced false))) true xs) (fail "not every?" {:pred pred :xs xs}))) (defn some [pred xs] (core/or (reduce (fn [_ x] (if (pred x) (reduced true) false)) false xs) (fail "not some" {:pred pred :xs xs}))) #?(:clj (defmacro and ([] true) ([x] (when-ok x x)) ([x & next] `(let [and# ~x] (if (ok? and#) (and ~@next) and#))))) #?(:clj (defmacro or ([] true) ([x] (when-ok x x)) ([x & next] `(let [or# ~x] (if (ok? or#) or# (or ~@next)))))) #?(:clj (defmacro -> "like `clojure.core/->` but `expr` is wrapped in [[attempt]], and the following functions in [[then]]" [expr & more] (let [ok (gensym "ok_")] `(core/-> (attempt ~expr) ~@(map (fn [elem] `(then (fn [~ok] ~(if (list? elem) `(when-ok [x# (~(first elem) ~ok ~@(rest elem))] x#) `(when-ok [x# (~elem ~ok)] x#))))) more))))) #?(:clj (defmacro ->> "like `clojure.core/->>` but `expr` is wrapped in [[attempt]], and the following functions in [[then]]" [expr & more] (let [ok (gensym "ok_")] `(core/->> (attempt ~expr) ~@(map (fn [elem] `(then (fn [~ok] ~(if (list? elem) `(when-ok [x# (~(first elem) ~ok ~@(rest elem))] x#) `(when-ok [x# (~elem ~ok)] x#))))) more))))) #?(:cljs (def ^:no-doc transit-write-handlers {Fail (reify Object (tag [_ _] "f/fail") (rep [_ ^js err] [(ex-message err) (ex-data err)]) (stringRep [_ _] nil) (verboseHandler [_] nil))})) #?(:cljs (def ^:no-doc transit-read-handlers {"f/fail" (fn [[msg data]] (fail msg data))}))
57352
(ns ribelo.fatum (:refer-clojure :exclude [-> ->> isa? and or every? some]) #?(:cljs (:require-macros [ribelo.fatum :refer [catching catch-errors attempt -> ->> when-ok if-ok and or]])) (:require #?(:clj [clojure.core :as core] :cljs [cljs.core :as core])) #?(:clj (:import (ribelo.fatum Fail)))) #?(:clj (defmacro -if-clj [then & [else]] (if (:ns &env) else then))) #?(:cljs (defn ^{:jsdoc ["@constructor"]} Fail [msg data] (this-as this (set! (.-message ^js this) msg) (set! (.-data ^js this) data) (set! (.-get ^js this) (fn ([k] (-lookup data k)) ([k not-found] (-lookup data k not-found)))) this))) #?(:cljs (set! (.. ^js Fail -prototype -__proto__) (.-prototype ^js ExceptionInfo))) #?(:cljs (extend-type Fail ILookup (-lookup [this k] (.get this k)) IAssociative (-contains-key? [this k] (-contains-key? (.-data this) k)) (-assoc [this k v] (Fail. (.-message this) (-assoc (.-data this) k v))) IEquiv (-equiv [this o] (core/and (instance? js/Error o) (= (.-message this) (.-message o)) (= (.-data this) (.-data o)))) IEmptyableCollection (-empty [this] (Fail. (.-message this) {})))) (defn fail "returns [[Fail]] for flexibility, the `data` can be either a map, an explicit kv collection or a variadic kv collection " ([] (Fail. nil {})) ([msg] (Fail. msg {})) ([msg data] (Fail. msg (cond (map? data) data (nil? data) {} (sequential? data) (apply array-map data)))) ([msg k v & kvs] (Fail. msg (apply array-map k v kvs)))) (defn fail! "throw [[Fail]] see [[fail]]" ([] (throw (fail))) ([msg] (throw (fail msg))) ([msg data] (throw (fail msg data))) ([msg k v & kvs] (throw (apply fail msg k v kvs)))) (defn fail? "check if `x` is instance of `Exception` in clj or `js/Error` in cljs" [x] #?(:clj (instance? java.lang.Exception x) :cljs (instance? js/Error x))) (defn ensure-fail "ensure that `Exception` `err` is [[Fail]]" [x] (if (core/and (fail? x) #?(:clj (instance? java.lang.Exception x) :cljs (instance? js/Error x))) (fail (ex-message x) (ex-data x)) x)) (defn ok? "check if `x` is not [[Fail]]" [x] (not (fail? x))) (defn exception-info? "check if `x` is `ExceptionInfo`" [x] #?(:clj (instance? clojure.lang.IExceptionInfo x) :cljs (instance? ExceptionInfo x))) (defn -match-map? "chech if `x` has every `kv` from `m`" [x m] (when (core/or (map? x) (exception-info? x)) (reduce-kv (fn [_ k v] (if (= v (get x k)) true (reduced false))) true m))) (defn isa? "check if `x` meets `pred`, or whether `Exception` has in `ex-data` under the key `k` the value `v` ```clojure (isa? 1 number?) => true ``` ```clojure (isa? java.lang.ArithmeticException (catching (/ 1 0))) => true ``` ```clojure (isa? {:a 1 :b 2} {:a 1}) => true ``` ```clojure (isa? {:a 1 :b 2} {:c 3}) => false ```" [x pred] #?(:clj (cond (class? pred) (instance? pred x) (keyword? pred) (true? (get x pred)) (fn? pred) (pred x) (map? pred) (-match-map? x pred)) :cljs (cond (keyword? pred) (true? (get x pred)) (fn? pred) (core/or (instance? pred x) (pred x)) (map? pred) (-match-map? x pred)))) (defmacro catching "`try` to execute `expr`, if `catch` an error returns it itself ```clojure (catching (/ 1 0) => nil ``` ```clojure (catching (/ 1 0) e e) => java.lang.ArithmeticException ```" ([expr ] `(catching ~expr ~'_ nil)) ([expr err catch] `(-if-clj (try ~expr (catch Exception ~err ~catch)) (try ~expr (catch :default ~err ~catch)))) ([expr err catch finally] `(-if-clj (try ~expr (catch Exception ~err ~catch) (finally ~finally)) (try ~expr (catch :default ~err ~catch) (finally ~finally))))) #?(:clj (defmacro catch-errors "like [[catching]], but returns a vector where the first element is the result of executing the `body` and the second is an `Exception` ```clojure (catch-errors (/ 1 1)) => [1 nil] ``` ```clojure (catch-errors (/ 1 0)) => [nil java.lang.ArithmeticException] ```" [& body] `(catching [(do ~@body) nil] e# [nil (ensure-fail e#)]))) #?(:clj (defmacro attempt "like [[catching]], but takes `body` as argument ```clojure (attempt (/ 1 1)) => 1 ``` ```clojure (attempt (/ 1 0)) => #error { :cause \"Divide by zero\" :data {} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {}}] :trace []} ```" [& body] `(catching (do ~@body) e# (ensure-fail e#)))) #?(:clj (defmacro when-ok "Like `clojure.core/when` however if first arg is binding vector behave like `clojure.core/when-let`, but can bind multiple values. check if all tests/bindings are [[ok?]], else return [[Fail]] with attached var & failing expresions ```clojure (when-ok (/ 1 1) :ok) => :ok ``` ```clojure(when-ok nil :ok) => :ok ``` ```clojure (when-ok (/ 1 0) :ok => #error { :cause \"Divide by zero\" :data {:binding test, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding test, :expr (/ 1 0)}}] :trace []} ``` ```clojure (when-ok [x (/ 1 0)] :ok) => #error { :cause \"Divide by zero\" :data {:binding x, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding x, :expr (/ 1 0)}}] :trace []} ``` " ([test-or-bindings & body] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (when-let [] true) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (when-ok ~(vec bnext) ~@body) (fail (ex-message b2#) (merge (ex-data b2#) {::binding '~b1 ::expr '~b2}))))) `(do ~@body))) `(when-ok [~'test ~test-or-bindings] ~@body))))) #?(:clj (defmacro when-ok! "Like `clojure.core/when` however if first arg is binding vector behave like `clojure.core/when-let`, but can bind multiple values. check if all tests/bindings are [[ok?]], else throw [[Fail]] with attached var & failing expresions ```clojure (when-ok (/ 1 1) :ok) => :ok ``` ```clojure(when-ok nil :ok) => :ok ``` ```clojure (when-ok (/ 1 0) :ok => #error { :cause \"Divide by zero\" :data {:binding test, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding test, :expr (/ 1 0)}}] :trace []} ``` ```clojure (when-ok [x (/ 1 0)] :ok) => #error { :cause \"Divide by zero\" :data {:binding x, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding x, :expr (/ 1 0)}}] :trace []} ``` " ([test-or-bindings & body] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (when-let [] true) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (when-ok ~(vec bnext) ~@body) (fail! (ex-message b2#) (merge (ex-data b2#) {::binding '~b1 ::expr '~b2}))))) `(do ~@body))) `(when-ok [~'test ~test-or-bindings] ~@body))))) #?(:clj (defmacro if-ok "Like `core/if-let` but can bind multiple values. execute `then` if all tests are `ok?` ```clojure (if-ok (/ 1 1) :ok :err) => :ok ``` ```clojure (if-ok (/ 1 1) :ok :err) => :err ``` ```clojure (if-ok nil :ok :err) => :ok ```" {:style/indent 1} ([test-or-bindings then ] `(when-ok ~test-or-bindings ~then)) ([test-or-bindings then else] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (if-let [] true false) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (if-ok ~(vec bnext) ~then ~else) (let [~b1 (assoc ~b1 :binding '~b1 :expr '~b2)] ~else)))) then)) `(if (ok? ~test-or-bindings) ~then ~else))))) (defn call "[[attempt]] to call function `f` on value `x` ```clojure (call 1 inc) => 2 ``` ```clojure (call \"1\" inc) => #error { :cause \"class java.lang.String cannot be cast to class java.lang.Number ...\" :data {} :via [{:type ribelo.fatum.Fail :message \"class java.lang.String cannot be cast to class java.lang.Number ... \" :data {}}] :trace []} ```` " [x f] (attempt (f x))) (defn then "[[attempt]] to call function `f` on value `x` if `x` is [[ok?]] and is not `reduced` ```clojure (-> {:name \"<NAME>\" :age 17} (then #(update % :age inc))) => {:name \"<NAME>\", :age 18} ```" [x f] (if (core/and (not (reduced? x)) (ok? x)) (attempt (f x)) x)) (defn then-if "[[attempt]] to call function `f` on value `x` if `x` is [[ok?]], not `reduced` and meets [[isa?]] condition ```clojure (-> {:name \"<NAME>\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false))) => {:name \"<NAME>\", :age 17, :adult false} ```" [x pred f] (if (core/and (not (reduced? x)) (ok? x) (isa? x pred)) (attempt (f x)) x)) (defn catch "[[attempt]] to call function `f` on value `x` if `x` is [[fail?]] ```clojure (-> {:name \"<NAME>\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" #(find % :age)) (catch-if (constantly :err))) => :err ```" [x f] (if (fail? x) (attempt (f x)) x)) (defn catch-if "[[attempt]] to call function `f` on value `x` if `x` is [[fail?]], not `reduced` and meets [[isa?]] condition ```clojure (-> {:name \"<NAME>\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" #(find % :age)) (catch-if (comp (partial > 18) :age) (constantly :err))) => :err ```" [x pred f] (if (core/and (fail? x) (isa? x pred)) (attempt (f x)) x)) (defn fail-if "return [[fail]] with optional `msg` and `data` if `x` is [[ok?]] and meets [[isa?]] condition ```clojure (-> {:name \"<NAME>\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" (juxt (constantly :user) identity))) => #error { :cause \"user is underage\" :data {:user {:name \"<NAME>\", :age 17, :adult false}} :via [{:type ribelo.fatum.Fail :message \"user is underage\" :data {:user {:name \"<NAME>\", :age 17, :adult false}}}] :trace []} ```" ([x pred] (if (core/and (ok? x) (isa? (unreduced x) pred)) (fail) x)) ([x pred msg] (if (core/and (ok? x) (isa? (unreduced x) pred)) (fail msg) x)) ([x pred msg data-or-fn] (if (core/and (ok? x) (isa? (unreduced x) pred)) (if (fn? data-or-fn) (fail msg (data-or-fn x)) (fail msg data-or-fn)) x))) (defn throw-if "throw [[fail!]] with optional `msg` and `data` if `x` is [[ok?]] and meets [[isa?]] condition see [[fail-if]]" ([x pred] (if-ok [result (fail-if x pred)] result (throw result))) ([x pred msg-or-fn] (if-ok [result (fail-if x pred msg-or-fn)] result (throw result))) ([x pred msg data] (if-ok [result (fail-if x pred msg data)] result (throw result)))) (defn finally "[[attempt]] to call function `f` on `unreduced` value of `x`. return `x` unchanged and `unreduced`." [x f] (attempt (f (unreduced x))) (unreduced x)) (defn maybe-throw "`throw` `x` if `x` meets [[fail?]]" [x] (when (fail? x) (throw x))) (defn thru "[[attempt]] to call function `f` on `unreduced` value of `x`. return `x` unchanged. used for side effects" [x f] (attempt (f (unreduced x))) x) (defn thru-if "[[attempt]] to call function `f` on `unreduced` value of `x` if `unreduced` `x` meets [[isa?]] condition. return `x` unchanged. used for side effects" ([x pred f] (if (isa? (unreduced x) pred) (do (f (unreduced x)) x) x))) (defn every? [pred xs] (core/or (reduce (fn [_ x] (if (pred x) true (reduced false))) true xs) (fail "not every?" {:pred pred :xs xs}))) (defn some [pred xs] (core/or (reduce (fn [_ x] (if (pred x) (reduced true) false)) false xs) (fail "not some" {:pred pred :xs xs}))) #?(:clj (defmacro and ([] true) ([x] (when-ok x x)) ([x & next] `(let [and# ~x] (if (ok? and#) (and ~@next) and#))))) #?(:clj (defmacro or ([] true) ([x] (when-ok x x)) ([x & next] `(let [or# ~x] (if (ok? or#) or# (or ~@next)))))) #?(:clj (defmacro -> "like `clojure.core/->` but `expr` is wrapped in [[attempt]], and the following functions in [[then]]" [expr & more] (let [ok (gensym "ok_")] `(core/-> (attempt ~expr) ~@(map (fn [elem] `(then (fn [~ok] ~(if (list? elem) `(when-ok [x# (~(first elem) ~ok ~@(rest elem))] x#) `(when-ok [x# (~elem ~ok)] x#))))) more))))) #?(:clj (defmacro ->> "like `clojure.core/->>` but `expr` is wrapped in [[attempt]], and the following functions in [[then]]" [expr & more] (let [ok (gensym "ok_")] `(core/->> (attempt ~expr) ~@(map (fn [elem] `(then (fn [~ok] ~(if (list? elem) `(when-ok [x# (~(first elem) ~ok ~@(rest elem))] x#) `(when-ok [x# (~elem ~ok)] x#))))) more))))) #?(:cljs (def ^:no-doc transit-write-handlers {Fail (reify Object (tag [_ _] "f/fail") (rep [_ ^js err] [(ex-message err) (ex-data err)]) (stringRep [_ _] nil) (verboseHandler [_] nil))})) #?(:cljs (def ^:no-doc transit-read-handlers {"f/fail" (fn [[msg data]] (fail msg data))}))
true
(ns ribelo.fatum (:refer-clojure :exclude [-> ->> isa? and or every? some]) #?(:cljs (:require-macros [ribelo.fatum :refer [catching catch-errors attempt -> ->> when-ok if-ok and or]])) (:require #?(:clj [clojure.core :as core] :cljs [cljs.core :as core])) #?(:clj (:import (ribelo.fatum Fail)))) #?(:clj (defmacro -if-clj [then & [else]] (if (:ns &env) else then))) #?(:cljs (defn ^{:jsdoc ["@constructor"]} Fail [msg data] (this-as this (set! (.-message ^js this) msg) (set! (.-data ^js this) data) (set! (.-get ^js this) (fn ([k] (-lookup data k)) ([k not-found] (-lookup data k not-found)))) this))) #?(:cljs (set! (.. ^js Fail -prototype -__proto__) (.-prototype ^js ExceptionInfo))) #?(:cljs (extend-type Fail ILookup (-lookup [this k] (.get this k)) IAssociative (-contains-key? [this k] (-contains-key? (.-data this) k)) (-assoc [this k v] (Fail. (.-message this) (-assoc (.-data this) k v))) IEquiv (-equiv [this o] (core/and (instance? js/Error o) (= (.-message this) (.-message o)) (= (.-data this) (.-data o)))) IEmptyableCollection (-empty [this] (Fail. (.-message this) {})))) (defn fail "returns [[Fail]] for flexibility, the `data` can be either a map, an explicit kv collection or a variadic kv collection " ([] (Fail. nil {})) ([msg] (Fail. msg {})) ([msg data] (Fail. msg (cond (map? data) data (nil? data) {} (sequential? data) (apply array-map data)))) ([msg k v & kvs] (Fail. msg (apply array-map k v kvs)))) (defn fail! "throw [[Fail]] see [[fail]]" ([] (throw (fail))) ([msg] (throw (fail msg))) ([msg data] (throw (fail msg data))) ([msg k v & kvs] (throw (apply fail msg k v kvs)))) (defn fail? "check if `x` is instance of `Exception` in clj or `js/Error` in cljs" [x] #?(:clj (instance? java.lang.Exception x) :cljs (instance? js/Error x))) (defn ensure-fail "ensure that `Exception` `err` is [[Fail]]" [x] (if (core/and (fail? x) #?(:clj (instance? java.lang.Exception x) :cljs (instance? js/Error x))) (fail (ex-message x) (ex-data x)) x)) (defn ok? "check if `x` is not [[Fail]]" [x] (not (fail? x))) (defn exception-info? "check if `x` is `ExceptionInfo`" [x] #?(:clj (instance? clojure.lang.IExceptionInfo x) :cljs (instance? ExceptionInfo x))) (defn -match-map? "chech if `x` has every `kv` from `m`" [x m] (when (core/or (map? x) (exception-info? x)) (reduce-kv (fn [_ k v] (if (= v (get x k)) true (reduced false))) true m))) (defn isa? "check if `x` meets `pred`, or whether `Exception` has in `ex-data` under the key `k` the value `v` ```clojure (isa? 1 number?) => true ``` ```clojure (isa? java.lang.ArithmeticException (catching (/ 1 0))) => true ``` ```clojure (isa? {:a 1 :b 2} {:a 1}) => true ``` ```clojure (isa? {:a 1 :b 2} {:c 3}) => false ```" [x pred] #?(:clj (cond (class? pred) (instance? pred x) (keyword? pred) (true? (get x pred)) (fn? pred) (pred x) (map? pred) (-match-map? x pred)) :cljs (cond (keyword? pred) (true? (get x pred)) (fn? pred) (core/or (instance? pred x) (pred x)) (map? pred) (-match-map? x pred)))) (defmacro catching "`try` to execute `expr`, if `catch` an error returns it itself ```clojure (catching (/ 1 0) => nil ``` ```clojure (catching (/ 1 0) e e) => java.lang.ArithmeticException ```" ([expr ] `(catching ~expr ~'_ nil)) ([expr err catch] `(-if-clj (try ~expr (catch Exception ~err ~catch)) (try ~expr (catch :default ~err ~catch)))) ([expr err catch finally] `(-if-clj (try ~expr (catch Exception ~err ~catch) (finally ~finally)) (try ~expr (catch :default ~err ~catch) (finally ~finally))))) #?(:clj (defmacro catch-errors "like [[catching]], but returns a vector where the first element is the result of executing the `body` and the second is an `Exception` ```clojure (catch-errors (/ 1 1)) => [1 nil] ``` ```clojure (catch-errors (/ 1 0)) => [nil java.lang.ArithmeticException] ```" [& body] `(catching [(do ~@body) nil] e# [nil (ensure-fail e#)]))) #?(:clj (defmacro attempt "like [[catching]], but takes `body` as argument ```clojure (attempt (/ 1 1)) => 1 ``` ```clojure (attempt (/ 1 0)) => #error { :cause \"Divide by zero\" :data {} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {}}] :trace []} ```" [& body] `(catching (do ~@body) e# (ensure-fail e#)))) #?(:clj (defmacro when-ok "Like `clojure.core/when` however if first arg is binding vector behave like `clojure.core/when-let`, but can bind multiple values. check if all tests/bindings are [[ok?]], else return [[Fail]] with attached var & failing expresions ```clojure (when-ok (/ 1 1) :ok) => :ok ``` ```clojure(when-ok nil :ok) => :ok ``` ```clojure (when-ok (/ 1 0) :ok => #error { :cause \"Divide by zero\" :data {:binding test, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding test, :expr (/ 1 0)}}] :trace []} ``` ```clojure (when-ok [x (/ 1 0)] :ok) => #error { :cause \"Divide by zero\" :data {:binding x, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding x, :expr (/ 1 0)}}] :trace []} ``` " ([test-or-bindings & body] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (when-let [] true) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (when-ok ~(vec bnext) ~@body) (fail (ex-message b2#) (merge (ex-data b2#) {::binding '~b1 ::expr '~b2}))))) `(do ~@body))) `(when-ok [~'test ~test-or-bindings] ~@body))))) #?(:clj (defmacro when-ok! "Like `clojure.core/when` however if first arg is binding vector behave like `clojure.core/when-let`, but can bind multiple values. check if all tests/bindings are [[ok?]], else throw [[Fail]] with attached var & failing expresions ```clojure (when-ok (/ 1 1) :ok) => :ok ``` ```clojure(when-ok nil :ok) => :ok ``` ```clojure (when-ok (/ 1 0) :ok => #error { :cause \"Divide by zero\" :data {:binding test, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding test, :expr (/ 1 0)}}] :trace []} ``` ```clojure (when-ok [x (/ 1 0)] :ok) => #error { :cause \"Divide by zero\" :data {:binding x, :expr (/ 1 0)} :via [{:type ribelo.fatum.Fail :message \"Divide by zero\" :data {:binding x, :expr (/ 1 0)}}] :trace []} ``` " ([test-or-bindings & body] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (when-let [] true) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (when-ok ~(vec bnext) ~@body) (fail! (ex-message b2#) (merge (ex-data b2#) {::binding '~b1 ::expr '~b2}))))) `(do ~@body))) `(when-ok [~'test ~test-or-bindings] ~@body))))) #?(:clj (defmacro if-ok "Like `core/if-let` but can bind multiple values. execute `then` if all tests are `ok?` ```clojure (if-ok (/ 1 1) :ok :err) => :ok ``` ```clojure (if-ok (/ 1 1) :ok :err) => :err ``` ```clojure (if-ok nil :ok :err) => :ok ```" {:style/indent 1} ([test-or-bindings then ] `(when-ok ~test-or-bindings ~then)) ([test-or-bindings then else] (if (vector? test-or-bindings) (let [s (seq test-or-bindings)] (if s ; (if-let [] true false) => true (let [[b1 b2 & bnext] s] `(let [b2# (attempt ~b2) ~b1 b2#] (if (ok? b2#) (if-ok ~(vec bnext) ~then ~else) (let [~b1 (assoc ~b1 :binding '~b1 :expr '~b2)] ~else)))) then)) `(if (ok? ~test-or-bindings) ~then ~else))))) (defn call "[[attempt]] to call function `f` on value `x` ```clojure (call 1 inc) => 2 ``` ```clojure (call \"1\" inc) => #error { :cause \"class java.lang.String cannot be cast to class java.lang.Number ...\" :data {} :via [{:type ribelo.fatum.Fail :message \"class java.lang.String cannot be cast to class java.lang.Number ... \" :data {}}] :trace []} ```` " [x f] (attempt (f x))) (defn then "[[attempt]] to call function `f` on value `x` if `x` is [[ok?]] and is not `reduced` ```clojure (-> {:name \"PI:NAME:<NAME>END_PI\" :age 17} (then #(update % :age inc))) => {:name \"PI:NAME:<NAME>END_PI\", :age 18} ```" [x f] (if (core/and (not (reduced? x)) (ok? x)) (attempt (f x)) x)) (defn then-if "[[attempt]] to call function `f` on value `x` if `x` is [[ok?]], not `reduced` and meets [[isa?]] condition ```clojure (-> {:name \"PI:NAME:<NAME>END_PI\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false))) => {:name \"PI:NAME:<NAME>END_PI\", :age 17, :adult false} ```" [x pred f] (if (core/and (not (reduced? x)) (ok? x) (isa? x pred)) (attempt (f x)) x)) (defn catch "[[attempt]] to call function `f` on value `x` if `x` is [[fail?]] ```clojure (-> {:name \"PI:NAME:<NAME>END_PI\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" #(find % :age)) (catch-if (constantly :err))) => :err ```" [x f] (if (fail? x) (attempt (f x)) x)) (defn catch-if "[[attempt]] to call function `f` on value `x` if `x` is [[fail?]], not `reduced` and meets [[isa?]] condition ```clojure (-> {:name \"PI:NAME:<NAME>END_PI\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" #(find % :age)) (catch-if (comp (partial > 18) :age) (constantly :err))) => :err ```" [x pred f] (if (core/and (fail? x) (isa? x pred)) (attempt (f x)) x)) (defn fail-if "return [[fail]] with optional `msg` and `data` if `x` is [[ok?]] and meets [[isa?]] condition ```clojure (-> {:name \"PI:NAME:<NAME>END_PI\" :age 17} (then-if (comp (partial <= 18) :age) #(assoc % :adult true)) (then-if (comp (partial > 18) :age) #(assoc % :adult false)) (fail-if (complement (comp :adult)) \"user is underage\" (juxt (constantly :user) identity))) => #error { :cause \"user is underage\" :data {:user {:name \"PI:NAME:<NAME>END_PI\", :age 17, :adult false}} :via [{:type ribelo.fatum.Fail :message \"user is underage\" :data {:user {:name \"PI:NAME:<NAME>END_PI\", :age 17, :adult false}}}] :trace []} ```" ([x pred] (if (core/and (ok? x) (isa? (unreduced x) pred)) (fail) x)) ([x pred msg] (if (core/and (ok? x) (isa? (unreduced x) pred)) (fail msg) x)) ([x pred msg data-or-fn] (if (core/and (ok? x) (isa? (unreduced x) pred)) (if (fn? data-or-fn) (fail msg (data-or-fn x)) (fail msg data-or-fn)) x))) (defn throw-if "throw [[fail!]] with optional `msg` and `data` if `x` is [[ok?]] and meets [[isa?]] condition see [[fail-if]]" ([x pred] (if-ok [result (fail-if x pred)] result (throw result))) ([x pred msg-or-fn] (if-ok [result (fail-if x pred msg-or-fn)] result (throw result))) ([x pred msg data] (if-ok [result (fail-if x pred msg data)] result (throw result)))) (defn finally "[[attempt]] to call function `f` on `unreduced` value of `x`. return `x` unchanged and `unreduced`." [x f] (attempt (f (unreduced x))) (unreduced x)) (defn maybe-throw "`throw` `x` if `x` meets [[fail?]]" [x] (when (fail? x) (throw x))) (defn thru "[[attempt]] to call function `f` on `unreduced` value of `x`. return `x` unchanged. used for side effects" [x f] (attempt (f (unreduced x))) x) (defn thru-if "[[attempt]] to call function `f` on `unreduced` value of `x` if `unreduced` `x` meets [[isa?]] condition. return `x` unchanged. used for side effects" ([x pred f] (if (isa? (unreduced x) pred) (do (f (unreduced x)) x) x))) (defn every? [pred xs] (core/or (reduce (fn [_ x] (if (pred x) true (reduced false))) true xs) (fail "not every?" {:pred pred :xs xs}))) (defn some [pred xs] (core/or (reduce (fn [_ x] (if (pred x) (reduced true) false)) false xs) (fail "not some" {:pred pred :xs xs}))) #?(:clj (defmacro and ([] true) ([x] (when-ok x x)) ([x & next] `(let [and# ~x] (if (ok? and#) (and ~@next) and#))))) #?(:clj (defmacro or ([] true) ([x] (when-ok x x)) ([x & next] `(let [or# ~x] (if (ok? or#) or# (or ~@next)))))) #?(:clj (defmacro -> "like `clojure.core/->` but `expr` is wrapped in [[attempt]], and the following functions in [[then]]" [expr & more] (let [ok (gensym "ok_")] `(core/-> (attempt ~expr) ~@(map (fn [elem] `(then (fn [~ok] ~(if (list? elem) `(when-ok [x# (~(first elem) ~ok ~@(rest elem))] x#) `(when-ok [x# (~elem ~ok)] x#))))) more))))) #?(:clj (defmacro ->> "like `clojure.core/->>` but `expr` is wrapped in [[attempt]], and the following functions in [[then]]" [expr & more] (let [ok (gensym "ok_")] `(core/->> (attempt ~expr) ~@(map (fn [elem] `(then (fn [~ok] ~(if (list? elem) `(when-ok [x# (~(first elem) ~ok ~@(rest elem))] x#) `(when-ok [x# (~elem ~ok)] x#))))) more))))) #?(:cljs (def ^:no-doc transit-write-handlers {Fail (reify Object (tag [_ _] "f/fail") (rep [_ ^js err] [(ex-message err) (ex-data err)]) (stringRep [_ _] nil) (verboseHandler [_] nil))})) #?(:cljs (def ^:no-doc transit-read-handlers {"f/fail" (fn [[msg data]] (fail msg data))}))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.test.nettio.file", "end": 597, "score": 0.9998586773872375, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/test/clojure/czlab/test/nettio/files.clj
llnek/nettio
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.test.nettio.files "Sample netty file server." (:gen-class) (:require [clojure.java.io :as io] [clojure.string :as cs] [czlab.basal.proc :as p] [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.basal.io :as i] [czlab.niou.core :as cc] [czlab.nettio.server :as sv]) (:import [java.io IOException File] [java.net URI] [czlab.niou Headers] [czlab.basal XData])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* false) (c/defonce- svr (atom nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- reply-get-vfile [req ^XData xdata] (let [{:keys [keep-alive?]} req clen (.size xdata) res (-> (cc/http-result req) (cc/res-body-set (.fileRef xdata))) ^Headers hds (:headers res)] (c/debug "flushing file of %s bytes to client." clen) (.add hds "content-length" (str clen)) (.add hds "Content-Type" "application/octet-stream") ;(.add hds "Transfer-Encoding" "chunked") (.add hds "Connection" (if keep-alive? "keep-alive" "close")) (cc/reply-result res))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fputter [req fname udir] (c/debug "fPutter file= %s." (io/file udir fname)) (let [vdir (io/file udir) ^XData body (:body req)] (if (.isFile body) (c/debug "fPutter orig= %s." (.fileRef body))) (-> (cc/http-result req (try (i/save-file vdir fname body) 200 (catch Throwable _ 500))) cc/reply-result))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fgetter [req fname udir] (c/debug "fGetter: file= %s." (io/file udir fname)) (let [vdir (io/file udir) ^XData f (i/get-file vdir fname)] (if (.hasContent f) (reply-get-vfile req f) (-> (cc/http-result 204) cc/reply-result)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- h1proxy [udir] (fn [req] (let [{:keys [uri2 request-method]} req path (.getPath ^URI uri2) pos (cs/last-index-of path \/) p (if (nil? pos) path (subs path (+ 1 pos))) nm (c/stror p (str (u/jid<>) ".dat"))] (c/debug "udir= %s." udir) (c/debug "%s: uri= %s, file= %s." request-method path nm) (condp = request-method :get (fgetter req nm udir) :post (fputter req nm udir) (-> (cc/http-result req 405) cc/reply-result))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; make a In memory File Server (defn file-server<> "A file server which can get/put files." [& args] (let [{:keys [udir] :as args'} (merge {:udir (i/file-repo)} (c/kvs->map args))] (sv/web-server-module<> (assoc args' :user-cb (h1proxy udir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; filesvr host port vdir (defn finz-server [] (when @svr (c/stop @svr) (reset! svr nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; filesvr host port vdir (defn -main [& args] (cond (< (count args) 3) (println "usage: filesvr host port <rootdir>") :else (let [{:keys [host port] :as w} (-> (file-server<> :udir (nth args 2)) (c/start {:host (nth args 0) :port (c/s->int (nth args 1) 8080)}))] (p/exit-hook #(c/stop w)) (reset! svr w) (u/block!)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
85460
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.test.nettio.files "Sample netty file server." (:gen-class) (:require [clojure.java.io :as io] [clojure.string :as cs] [czlab.basal.proc :as p] [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.basal.io :as i] [czlab.niou.core :as cc] [czlab.nettio.server :as sv]) (:import [java.io IOException File] [java.net URI] [czlab.niou Headers] [czlab.basal XData])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* false) (c/defonce- svr (atom nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- reply-get-vfile [req ^XData xdata] (let [{:keys [keep-alive?]} req clen (.size xdata) res (-> (cc/http-result req) (cc/res-body-set (.fileRef xdata))) ^Headers hds (:headers res)] (c/debug "flushing file of %s bytes to client." clen) (.add hds "content-length" (str clen)) (.add hds "Content-Type" "application/octet-stream") ;(.add hds "Transfer-Encoding" "chunked") (.add hds "Connection" (if keep-alive? "keep-alive" "close")) (cc/reply-result res))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fputter [req fname udir] (c/debug "fPutter file= %s." (io/file udir fname)) (let [vdir (io/file udir) ^XData body (:body req)] (if (.isFile body) (c/debug "fPutter orig= %s." (.fileRef body))) (-> (cc/http-result req (try (i/save-file vdir fname body) 200 (catch Throwable _ 500))) cc/reply-result))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fgetter [req fname udir] (c/debug "fGetter: file= %s." (io/file udir fname)) (let [vdir (io/file udir) ^XData f (i/get-file vdir fname)] (if (.hasContent f) (reply-get-vfile req f) (-> (cc/http-result 204) cc/reply-result)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- h1proxy [udir] (fn [req] (let [{:keys [uri2 request-method]} req path (.getPath ^URI uri2) pos (cs/last-index-of path \/) p (if (nil? pos) path (subs path (+ 1 pos))) nm (c/stror p (str (u/jid<>) ".dat"))] (c/debug "udir= %s." udir) (c/debug "%s: uri= %s, file= %s." request-method path nm) (condp = request-method :get (fgetter req nm udir) :post (fputter req nm udir) (-> (cc/http-result req 405) cc/reply-result))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; make a In memory File Server (defn file-server<> "A file server which can get/put files." [& args] (let [{:keys [udir] :as args'} (merge {:udir (i/file-repo)} (c/kvs->map args))] (sv/web-server-module<> (assoc args' :user-cb (h1proxy udir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; filesvr host port vdir (defn finz-server [] (when @svr (c/stop @svr) (reset! svr nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; filesvr host port vdir (defn -main [& args] (cond (< (count args) 3) (println "usage: filesvr host port <rootdir>") :else (let [{:keys [host port] :as w} (-> (file-server<> :udir (nth args 2)) (c/start {:host (nth args 0) :port (c/s->int (nth args 1) 8080)}))] (p/exit-hook #(c/stop w)) (reset! svr w) (u/block!)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.test.nettio.files "Sample netty file server." (:gen-class) (:require [clojure.java.io :as io] [clojure.string :as cs] [czlab.basal.proc :as p] [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.basal.io :as i] [czlab.niou.core :as cc] [czlab.nettio.server :as sv]) (:import [java.io IOException File] [java.net URI] [czlab.niou Headers] [czlab.basal XData])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* false) (c/defonce- svr (atom nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- reply-get-vfile [req ^XData xdata] (let [{:keys [keep-alive?]} req clen (.size xdata) res (-> (cc/http-result req) (cc/res-body-set (.fileRef xdata))) ^Headers hds (:headers res)] (c/debug "flushing file of %s bytes to client." clen) (.add hds "content-length" (str clen)) (.add hds "Content-Type" "application/octet-stream") ;(.add hds "Transfer-Encoding" "chunked") (.add hds "Connection" (if keep-alive? "keep-alive" "close")) (cc/reply-result res))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fputter [req fname udir] (c/debug "fPutter file= %s." (io/file udir fname)) (let [vdir (io/file udir) ^XData body (:body req)] (if (.isFile body) (c/debug "fPutter orig= %s." (.fileRef body))) (-> (cc/http-result req (try (i/save-file vdir fname body) 200 (catch Throwable _ 500))) cc/reply-result))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fgetter [req fname udir] (c/debug "fGetter: file= %s." (io/file udir fname)) (let [vdir (io/file udir) ^XData f (i/get-file vdir fname)] (if (.hasContent f) (reply-get-vfile req f) (-> (cc/http-result 204) cc/reply-result)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- h1proxy [udir] (fn [req] (let [{:keys [uri2 request-method]} req path (.getPath ^URI uri2) pos (cs/last-index-of path \/) p (if (nil? pos) path (subs path (+ 1 pos))) nm (c/stror p (str (u/jid<>) ".dat"))] (c/debug "udir= %s." udir) (c/debug "%s: uri= %s, file= %s." request-method path nm) (condp = request-method :get (fgetter req nm udir) :post (fputter req nm udir) (-> (cc/http-result req 405) cc/reply-result))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; make a In memory File Server (defn file-server<> "A file server which can get/put files." [& args] (let [{:keys [udir] :as args'} (merge {:udir (i/file-repo)} (c/kvs->map args))] (sv/web-server-module<> (assoc args' :user-cb (h1proxy udir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; filesvr host port vdir (defn finz-server [] (when @svr (c/stop @svr) (reset! svr nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; filesvr host port vdir (defn -main [& args] (cond (< (count args) 3) (println "usage: filesvr host port <rootdir>") :else (let [{:keys [host port] :as w} (-> (file-server<> :udir (nth args 2)) (c/start {:host (nth args 0) :port (c/s->int (nth args 1) 8080)}))] (p/exit-hook #(c/stop w)) (reset! svr w) (u/block!)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": "\n (:refer-clojure :exclude [byte])\n #^{:author \"Nurullah Akkaya\",\n :doc \"Firmata Library for Clojure.\"}\n (:u", "end": 85, "score": 0.9998813271522522, "start": 70, "tag": "NAME", "value": "Nurullah Akkaya" } ]
src/clodiuno/firmata.clj
rwaldron/clodiuno
0
(ns clodiuno.firmata (:refer-clojure :exclude [byte]) #^{:author "Nurullah Akkaya", :doc "Firmata Library for Clojure."} (:use clodiuno.core) (:import (java.io InputStream) (gnu.io SerialPort CommPortIdentifier SerialPortEventListener SerialPortEvent NoSuchPortException))) (def DIGITAL-MESSAGE 0x90) ;;send data for a digital port (def ANALOG-MESSAGE 0xE0) ;;send data for an analog pin (or PWM) (def REPORT-ANALOG 0xC0) ;;enable analog input by pin # (def REPORT-DIGITAL 0xD0) ;;enable digital input by port (def SET-PIN-MODE 0xF4) ;;set a pin to INPUT/OUTPUT/PWM/etc (def REPORT-VERSION 0xF9) ;;report firmware version (def SYSTEM-RESET 0xFF) ;;reset from MIDI (def START-SYSEX 0xF0) ;;start a MIDI SysEx message (def END-SYSEX 0xF7) ;;end a MIDI SysEx message (def baudrate 57600) (def arduino-port-count 7) (defn- byte [v] (.byteValue (- v 256))) ;; ;; Serial Setup ;; (defn- port-identifier "Given a port name return its identifier." [port-name] (try (let [ports (CommPortIdentifier/getPortIdentifiers)] (loop [port (.nextElement ports) name (.getName port)] (if (= name port-name) port (recur (.nextElement ports) (.getName port))))) (catch Exception e (throw (NoSuchPortException.))))) (defn- open "Open serial interface." [identifier] (doto (.open identifier "clojure" 1) (.setSerialPortParams baudrate SerialPort/DATABITS_8 SerialPort/STOPBITS_1 SerialPort/PARITY_NONE))) (defmethod close :firmata [conn] (.close (:port @conn))) (defn- listener "f will be called whenever there is data availible on the stream." [f] (proxy [SerialPortEventListener] [] (serialEvent [event] (if (= (.getEventType event) SerialPortEvent/DATA_AVAILABLE) (f))))) (defn- write-bytes [conn & bs] (let [out (.getOutputStream (:port @conn))] (doseq [b bs] (.write out b)) (.flush out))) (defn- bits [n] (map #(bit-and (bit-shift-right n %) 1) (range 8))) (defn- numb [bits] (int (BigInteger. (apply str bits) 2))) (defn- assoc-in! [r ks v] (dosync (alter r assoc-in ks v))) ;; ;; Firmata Calls ;; (defmethod enable-pin :firmata [conn type pin] (cond (= type :analog) (write-bytes conn (bit-or REPORT-ANALOG pin) 1) (= type :digital) (write-bytes conn (bit-or REPORT-DIGITAL (int (/ pin 8))) 1) :default (throw (Exception. "Unknown pin type.")))) (defmethod disable-pin :firmata [conn type pin] (cond (= type :analog) (write-bytes conn (bit-or REPORT-ANALOG pin) 0) (= type :digital) (write-bytes conn (bit-or REPORT-DIGITAL (int (/ pin 8))) 0) :default (throw (Exception. "Unknown pin type.")))) (defmethod pin-mode :firmata [conn pin mode] (write-bytes conn SET-PIN-MODE pin mode)) (defmethod digital-write :firmata [conn pin value] (let [port (int (/ pin 8)) vals ((@conn :digital-out) port) beg (take (mod pin 8) vals) end (drop (inc (mod pin 8)) vals) state (concat beg [value] end)] (assoc-in! conn [:digital-out port] state) (write-bytes conn (bit-or DIGITAL-MESSAGE port) (numb (reverse state)) 0))) (defmethod digital-read :firmata [conn pin] (let [port (int (/ pin 8)) vals ((@conn :digital-in) port)] (first (drop (mod pin 8) vals)))) (defmethod analog-read :firmata [conn pin] ((@conn :analog) pin)) (defmethod analog-write :firmata [conn pin val] (write-bytes conn (bit-or ANALOG-MESSAGE (bit-and pin 0x0F)) (bit-and val 0x7F) (bit-shift-right val 7))) (defn- read-multibyte [in] (let [lsb (.read in) msb (.read in) val (bit-or (bit-shift-left msb 7) lsb)] [lsb msb val])) (defn- process-input "Parse input from firmata." [conn in] (while (> (.available in) 2) (let [data (.read in)] (cond (= (bit-and data 0xF0) ANALOG-MESSAGE) (let [pin (bit-and data 0x0F) [_ _ val] (read-multibyte in)] (assoc-in! conn [:analog pin] val)) (= (bit-and data 0xF0) DIGITAL-MESSAGE) (let [port (bit-and data 0x0F) [lsb msb val] (read-multibyte in)] (assoc-in! conn [:digital-in port] (bits val))) (= data REPORT-VERSION) (assoc-in! conn [:version] [(.read in) (.read in)]))))) (defmethod arduino :firmata [type port] (let [port (open (port-identifier port)) conn (ref {:port port :interface :firmata})] (doto port (.addEventListener (listener #(process-input conn (.getInputStream (:port @conn))))) (.notifyOnDataAvailable true)) (while (nil? (:version @conn)) (Thread/sleep 100)) (dotimes [i arduino-port-count] (assoc-in! conn [:digital-out i] (repeat 8 0))) (dotimes [i arduino-port-count] (assoc-in! conn [:digital-in i] (repeat 8 0))) conn))
61821
(ns clodiuno.firmata (:refer-clojure :exclude [byte]) #^{:author "<NAME>", :doc "Firmata Library for Clojure."} (:use clodiuno.core) (:import (java.io InputStream) (gnu.io SerialPort CommPortIdentifier SerialPortEventListener SerialPortEvent NoSuchPortException))) (def DIGITAL-MESSAGE 0x90) ;;send data for a digital port (def ANALOG-MESSAGE 0xE0) ;;send data for an analog pin (or PWM) (def REPORT-ANALOG 0xC0) ;;enable analog input by pin # (def REPORT-DIGITAL 0xD0) ;;enable digital input by port (def SET-PIN-MODE 0xF4) ;;set a pin to INPUT/OUTPUT/PWM/etc (def REPORT-VERSION 0xF9) ;;report firmware version (def SYSTEM-RESET 0xFF) ;;reset from MIDI (def START-SYSEX 0xF0) ;;start a MIDI SysEx message (def END-SYSEX 0xF7) ;;end a MIDI SysEx message (def baudrate 57600) (def arduino-port-count 7) (defn- byte [v] (.byteValue (- v 256))) ;; ;; Serial Setup ;; (defn- port-identifier "Given a port name return its identifier." [port-name] (try (let [ports (CommPortIdentifier/getPortIdentifiers)] (loop [port (.nextElement ports) name (.getName port)] (if (= name port-name) port (recur (.nextElement ports) (.getName port))))) (catch Exception e (throw (NoSuchPortException.))))) (defn- open "Open serial interface." [identifier] (doto (.open identifier "clojure" 1) (.setSerialPortParams baudrate SerialPort/DATABITS_8 SerialPort/STOPBITS_1 SerialPort/PARITY_NONE))) (defmethod close :firmata [conn] (.close (:port @conn))) (defn- listener "f will be called whenever there is data availible on the stream." [f] (proxy [SerialPortEventListener] [] (serialEvent [event] (if (= (.getEventType event) SerialPortEvent/DATA_AVAILABLE) (f))))) (defn- write-bytes [conn & bs] (let [out (.getOutputStream (:port @conn))] (doseq [b bs] (.write out b)) (.flush out))) (defn- bits [n] (map #(bit-and (bit-shift-right n %) 1) (range 8))) (defn- numb [bits] (int (BigInteger. (apply str bits) 2))) (defn- assoc-in! [r ks v] (dosync (alter r assoc-in ks v))) ;; ;; Firmata Calls ;; (defmethod enable-pin :firmata [conn type pin] (cond (= type :analog) (write-bytes conn (bit-or REPORT-ANALOG pin) 1) (= type :digital) (write-bytes conn (bit-or REPORT-DIGITAL (int (/ pin 8))) 1) :default (throw (Exception. "Unknown pin type.")))) (defmethod disable-pin :firmata [conn type pin] (cond (= type :analog) (write-bytes conn (bit-or REPORT-ANALOG pin) 0) (= type :digital) (write-bytes conn (bit-or REPORT-DIGITAL (int (/ pin 8))) 0) :default (throw (Exception. "Unknown pin type.")))) (defmethod pin-mode :firmata [conn pin mode] (write-bytes conn SET-PIN-MODE pin mode)) (defmethod digital-write :firmata [conn pin value] (let [port (int (/ pin 8)) vals ((@conn :digital-out) port) beg (take (mod pin 8) vals) end (drop (inc (mod pin 8)) vals) state (concat beg [value] end)] (assoc-in! conn [:digital-out port] state) (write-bytes conn (bit-or DIGITAL-MESSAGE port) (numb (reverse state)) 0))) (defmethod digital-read :firmata [conn pin] (let [port (int (/ pin 8)) vals ((@conn :digital-in) port)] (first (drop (mod pin 8) vals)))) (defmethod analog-read :firmata [conn pin] ((@conn :analog) pin)) (defmethod analog-write :firmata [conn pin val] (write-bytes conn (bit-or ANALOG-MESSAGE (bit-and pin 0x0F)) (bit-and val 0x7F) (bit-shift-right val 7))) (defn- read-multibyte [in] (let [lsb (.read in) msb (.read in) val (bit-or (bit-shift-left msb 7) lsb)] [lsb msb val])) (defn- process-input "Parse input from firmata." [conn in] (while (> (.available in) 2) (let [data (.read in)] (cond (= (bit-and data 0xF0) ANALOG-MESSAGE) (let [pin (bit-and data 0x0F) [_ _ val] (read-multibyte in)] (assoc-in! conn [:analog pin] val)) (= (bit-and data 0xF0) DIGITAL-MESSAGE) (let [port (bit-and data 0x0F) [lsb msb val] (read-multibyte in)] (assoc-in! conn [:digital-in port] (bits val))) (= data REPORT-VERSION) (assoc-in! conn [:version] [(.read in) (.read in)]))))) (defmethod arduino :firmata [type port] (let [port (open (port-identifier port)) conn (ref {:port port :interface :firmata})] (doto port (.addEventListener (listener #(process-input conn (.getInputStream (:port @conn))))) (.notifyOnDataAvailable true)) (while (nil? (:version @conn)) (Thread/sleep 100)) (dotimes [i arduino-port-count] (assoc-in! conn [:digital-out i] (repeat 8 0))) (dotimes [i arduino-port-count] (assoc-in! conn [:digital-in i] (repeat 8 0))) conn))
true
(ns clodiuno.firmata (:refer-clojure :exclude [byte]) #^{:author "PI:NAME:<NAME>END_PI", :doc "Firmata Library for Clojure."} (:use clodiuno.core) (:import (java.io InputStream) (gnu.io SerialPort CommPortIdentifier SerialPortEventListener SerialPortEvent NoSuchPortException))) (def DIGITAL-MESSAGE 0x90) ;;send data for a digital port (def ANALOG-MESSAGE 0xE0) ;;send data for an analog pin (or PWM) (def REPORT-ANALOG 0xC0) ;;enable analog input by pin # (def REPORT-DIGITAL 0xD0) ;;enable digital input by port (def SET-PIN-MODE 0xF4) ;;set a pin to INPUT/OUTPUT/PWM/etc (def REPORT-VERSION 0xF9) ;;report firmware version (def SYSTEM-RESET 0xFF) ;;reset from MIDI (def START-SYSEX 0xF0) ;;start a MIDI SysEx message (def END-SYSEX 0xF7) ;;end a MIDI SysEx message (def baudrate 57600) (def arduino-port-count 7) (defn- byte [v] (.byteValue (- v 256))) ;; ;; Serial Setup ;; (defn- port-identifier "Given a port name return its identifier." [port-name] (try (let [ports (CommPortIdentifier/getPortIdentifiers)] (loop [port (.nextElement ports) name (.getName port)] (if (= name port-name) port (recur (.nextElement ports) (.getName port))))) (catch Exception e (throw (NoSuchPortException.))))) (defn- open "Open serial interface." [identifier] (doto (.open identifier "clojure" 1) (.setSerialPortParams baudrate SerialPort/DATABITS_8 SerialPort/STOPBITS_1 SerialPort/PARITY_NONE))) (defmethod close :firmata [conn] (.close (:port @conn))) (defn- listener "f will be called whenever there is data availible on the stream." [f] (proxy [SerialPortEventListener] [] (serialEvent [event] (if (= (.getEventType event) SerialPortEvent/DATA_AVAILABLE) (f))))) (defn- write-bytes [conn & bs] (let [out (.getOutputStream (:port @conn))] (doseq [b bs] (.write out b)) (.flush out))) (defn- bits [n] (map #(bit-and (bit-shift-right n %) 1) (range 8))) (defn- numb [bits] (int (BigInteger. (apply str bits) 2))) (defn- assoc-in! [r ks v] (dosync (alter r assoc-in ks v))) ;; ;; Firmata Calls ;; (defmethod enable-pin :firmata [conn type pin] (cond (= type :analog) (write-bytes conn (bit-or REPORT-ANALOG pin) 1) (= type :digital) (write-bytes conn (bit-or REPORT-DIGITAL (int (/ pin 8))) 1) :default (throw (Exception. "Unknown pin type.")))) (defmethod disable-pin :firmata [conn type pin] (cond (= type :analog) (write-bytes conn (bit-or REPORT-ANALOG pin) 0) (= type :digital) (write-bytes conn (bit-or REPORT-DIGITAL (int (/ pin 8))) 0) :default (throw (Exception. "Unknown pin type.")))) (defmethod pin-mode :firmata [conn pin mode] (write-bytes conn SET-PIN-MODE pin mode)) (defmethod digital-write :firmata [conn pin value] (let [port (int (/ pin 8)) vals ((@conn :digital-out) port) beg (take (mod pin 8) vals) end (drop (inc (mod pin 8)) vals) state (concat beg [value] end)] (assoc-in! conn [:digital-out port] state) (write-bytes conn (bit-or DIGITAL-MESSAGE port) (numb (reverse state)) 0))) (defmethod digital-read :firmata [conn pin] (let [port (int (/ pin 8)) vals ((@conn :digital-in) port)] (first (drop (mod pin 8) vals)))) (defmethod analog-read :firmata [conn pin] ((@conn :analog) pin)) (defmethod analog-write :firmata [conn pin val] (write-bytes conn (bit-or ANALOG-MESSAGE (bit-and pin 0x0F)) (bit-and val 0x7F) (bit-shift-right val 7))) (defn- read-multibyte [in] (let [lsb (.read in) msb (.read in) val (bit-or (bit-shift-left msb 7) lsb)] [lsb msb val])) (defn- process-input "Parse input from firmata." [conn in] (while (> (.available in) 2) (let [data (.read in)] (cond (= (bit-and data 0xF0) ANALOG-MESSAGE) (let [pin (bit-and data 0x0F) [_ _ val] (read-multibyte in)] (assoc-in! conn [:analog pin] val)) (= (bit-and data 0xF0) DIGITAL-MESSAGE) (let [port (bit-and data 0x0F) [lsb msb val] (read-multibyte in)] (assoc-in! conn [:digital-in port] (bits val))) (= data REPORT-VERSION) (assoc-in! conn [:version] [(.read in) (.read in)]))))) (defmethod arduino :firmata [type port] (let [port (open (port-identifier port)) conn (ref {:port port :interface :firmata})] (doto port (.addEventListener (listener #(process-input conn (.getInputStream (:port @conn))))) (.notifyOnDataAvailable true)) (while (nil? (:version @conn)) (Thread/sleep 100)) (dotimes [i arduino-port-count] (assoc-in! conn [:digital-out i] (repeat 8 0))) (dotimes [i arduino-port-count] (assoc-in! conn [:digital-in i] (repeat 8 0))) conn))
[ { "context": "ter-key.json\"))\n(def token-expiring-in-year-2515 \"eyJraWQiOiJ0ZXN0LWtleSIsImFsZyI6IlJTMjU2In0.eyJpc3MiOiJJU1NVRVIiLCJhdWQiOiJDTElFTlRfSUQiLCJleHAiOjE3MjA3OTkzMjUyLCJpYXQiOjE0Mzk5OTI3NDAsInN1YiI6IlNVQkpFQ1QiLCJyb2xlIjoiYWRtaW4iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZW1haWwiOiJlbWFpbEBhZGRyZXNzLmNvbSJ9.PQWWJQGECzC8EchkfwGjQBBUfhFGoLDOjZ1Ohl1t-eo8rXDO4FxONk3rYEY9v01fVg3pzQW8zLJYcZ73gyE2ju8feHhwS8wYwcsgKq6XC-Zr9LwRJIeFpZoVcgMpvW21UHX1bxAhHE7WM_UzSerKtGkIuK21XraGVTiIB-0o8eWOJX0Rud8FXC3Cr0LdZeqDytPZDwM1Pbcr0eFyfNq9ngi75BFNTGHCMLGshJGt1LvQhDtTWifXDlwW5uk-kuOVavnQGK_i7qvrcy8c7lFCCPqd5X3x6EZJyfk-BZGgDT1ySwdM2EjRAi1W1nPAmdWms9rts0rkbk_Q73gEkWQpOw\")\n\n;token-content is the decoded version of token", "end": 1216, "score": 0.99932461977005, "start": 629, "tag": "KEY", "value": "eyJraWQiOiJ0ZXN0LWtleSIsImFsZyI6IlJTMjU2In0.eyJpc3MiOiJJU1NVRVIiLCJhdWQiOiJDTElFTlRfSUQiLCJleHAiOjE3MjA3OTkzMjUyLCJpYXQiOjE0Mzk5OTI3NDAsInN1YiI6IlNVQkpFQ1QiLCJyb2xlIjoiYWRtaW4iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZW1haWwiOiJlbWFpbEBhZGRyZXNzLmNvbSJ9.PQWWJQGECzC8EchkfwGjQBBUfhFGoLDOjZ1Ohl1t-eo8rXDO4FxONk3rYEY9v01fVg3pzQW8zLJYcZ73gyE2ju8feHhwS8wYwcsgKq6XC-Zr9LwRJIeFpZoVcgMpvW21UHX1bxAhHE7WM_UzSerKtGkIuK21XraGVTiIB-0o8eWOJX0Rud8FXC3Cr0LdZeqDytPZDwM1Pbcr0eFyfNq9ngi75BFNTGHCMLGshJGt1LvQhDtTWifXDlwW5uk-kuOVavnQGK_i7qvrcy8c7lFCCPqd5X3x6EZJyfk-BZGgDT1ySwdM2EjRAi1W1nPAmdWms9rts0rkbk_Q73gEkWQpOw" }, { "context": "ent {:aud \"CLIENT_ID\"\n :email \"email@address.com\"\n :email_verified true\n ", "end": 1413, "score": 0.9999070167541504, "start": 1396, "tag": "EMAIL", "value": "email@address.com" }, { "context": " :auth-provider-user-email \"email@address.com\"\n :sign-in-re", "end": 2536, "score": 0.9999035000801086, "start": 2519, "tag": "EMAIL", "value": "email@address.com" }, { "context": " :session {:auth-provider-user-id \"d-cent-SUBJECT\"\n :sign-in-re", "end": 4308, "score": 0.4768323302268982, "start": 4301, "tag": "USERNAME", "value": "SUBJECT" } ]
test/objective8/unit/workflows/stonecutter_test.clj
d-cent/objective8
23
(ns objective8.unit.workflows.stonecutter-test (:require [midje.sweet :refer :all] [stonecutter-oauth.client :as soc] [stonecutter-oauth.jwt :as so-jwt] [objective8.utils :as utils] [objective8.front-end.workflows.stonecutter :refer :all] [objective8.config :as config])) (def openid-test-config (soc/configure "ISSUER" "CLIENT_ID" "<client-secret>" "<callback-uri>" :protocol :openid)) (def test-auth-provider-public-key (slurp "./test/objective8/unit/workflows/test-stonecutter-key.json")) (def token-expiring-in-year-2515 "eyJraWQiOiJ0ZXN0LWtleSIsImFsZyI6IlJTMjU2In0.eyJpc3MiOiJJU1NVRVIiLCJhdWQiOiJDTElFTlRfSUQiLCJleHAiOjE3MjA3OTkzMjUyLCJpYXQiOjE0Mzk5OTI3NDAsInN1YiI6IlNVQkpFQ1QiLCJyb2xlIjoiYWRtaW4iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZW1haWwiOiJlbWFpbEBhZGRyZXNzLmNvbSJ9.PQWWJQGECzC8EchkfwGjQBBUfhFGoLDOjZ1Ohl1t-eo8rXDO4FxONk3rYEY9v01fVg3pzQW8zLJYcZ73gyE2ju8feHhwS8wYwcsgKq6XC-Zr9LwRJIeFpZoVcgMpvW21UHX1bxAhHE7WM_UzSerKtGkIuK21XraGVTiIB-0o8eWOJX0Rud8FXC3Cr0LdZeqDytPZDwM1Pbcr0eFyfNq9ngi75BFNTGHCMLGshJGt1LvQhDtTWifXDlwW5uk-kuOVavnQGK_i7qvrcy8c7lFCCPqd5X3x6EZJyfk-BZGgDT1ySwdM2EjRAi1W1nPAmdWms9rts0rkbk_Q73gEkWQpOw") ;token-content is the decoded version of token-expiring-in-year-2515 signed with test-auth-provider-public-key (def token-content {:aud "CLIENT_ID" :email "email@address.com" :email_verified true :exp 17207993252 :iat 1439992740 :iss "ISSUER" :role "admin" :sub "SUBJECT"}) (fact "stonecutter-sign-in generates the correct response" (stonecutter-sign-in {:stonecutter-config openid-test-config}) => ...stonecutter-sign-in-response... (provided (soc/authorisation-redirect-response openid-test-config) => ...stonecutter-sign-in-response...)) (facts "about stonecutter-callback" (fact "stonecutter-callback redirects to the sign-in workflow with the auth-provider-user-id and auth-provider-user-email set in the session" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id "d-cent-SUBJECT" :auth-provider-user-email "email@address.com" :sign-in-referrer ...refer...}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key)) (fact "redirects to invalid-configuration page when unable to retrieve token from auth server" (against-background (soc/request-access-token! anything anything) =throws=> (Exception. "Some exception")) (get-in (stonecutter-callback {:stonecutter-config ...config... :params {:code ...auth-code...}}) [:status]) => 302 (get-in (stonecutter-callback {:stonecutter-config ...config... :params {:code ...auth-code...}}) [:headers "Location"]) => (contains (utils/path-for :fe/error-configuration))) (fact "redirects to referrer when access denied" (stonecutter-callback {:params {:error "access_denied"} :session {:sign-in-referrer "/objectives/1"}}) => (contains {:status 302 :headers (contains {"Location" (contains "/objectives/1")})})) (tabular (fact "redirects to the sign-in page with flash message set in the session when email is invalid" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id "d-cent-SUBJECT" :sign-in-referrer ...refer...} :flash {:validation :auth-email}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key (so-jwt/decode openid-test-config token-expiring-in-year-2515 test-auth-provider-public-key) => (assoc token-content :email ?stonecutter-email))) ?stonecutter-email "invalid" " " nil) (binding [config/environment (assoc config/environment :private-mode-enabled "true")] (fact "redirects to unauthorised error page when user is not trusted and private mode config variable is set to true" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/authorisation")}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key (so-jwt/decode openid-test-config token-expiring-in-year-2515 test-auth-provider-public-key) => (assoc token-content :role "untrusted"))))) (facts "about wrap-stonecutter-config" (fact "includes the stonecutter configuration in the request when the configuration is valid" (let [handler (wrap-stonecutter-config identity ...valid-stonecutter-config... ...invalid-handler...)] (handler {}) => {:stonecutter-config ...valid-stonecutter-config...})) (fact "defaults to invalid-handler when configuration is invalid" (wrap-stonecutter-config identity :invalid-configuration ...invalid-handler...) => ...invalid-handler...)) (fact "invalid-handler redirects to the invalid configuration error page" (invalid-configuration-handler {}) => (contains {:status 302 :headers (contains {"Location" (contains "/error/configuration")})}))
41185
(ns objective8.unit.workflows.stonecutter-test (:require [midje.sweet :refer :all] [stonecutter-oauth.client :as soc] [stonecutter-oauth.jwt :as so-jwt] [objective8.utils :as utils] [objective8.front-end.workflows.stonecutter :refer :all] [objective8.config :as config])) (def openid-test-config (soc/configure "ISSUER" "CLIENT_ID" "<client-secret>" "<callback-uri>" :protocol :openid)) (def test-auth-provider-public-key (slurp "./test/objective8/unit/workflows/test-stonecutter-key.json")) (def token-expiring-in-year-2515 "<KEY>") ;token-content is the decoded version of token-expiring-in-year-2515 signed with test-auth-provider-public-key (def token-content {:aud "CLIENT_ID" :email "<EMAIL>" :email_verified true :exp 17207993252 :iat 1439992740 :iss "ISSUER" :role "admin" :sub "SUBJECT"}) (fact "stonecutter-sign-in generates the correct response" (stonecutter-sign-in {:stonecutter-config openid-test-config}) => ...stonecutter-sign-in-response... (provided (soc/authorisation-redirect-response openid-test-config) => ...stonecutter-sign-in-response...)) (facts "about stonecutter-callback" (fact "stonecutter-callback redirects to the sign-in workflow with the auth-provider-user-id and auth-provider-user-email set in the session" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id "d-cent-SUBJECT" :auth-provider-user-email "<EMAIL>" :sign-in-referrer ...refer...}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key)) (fact "redirects to invalid-configuration page when unable to retrieve token from auth server" (against-background (soc/request-access-token! anything anything) =throws=> (Exception. "Some exception")) (get-in (stonecutter-callback {:stonecutter-config ...config... :params {:code ...auth-code...}}) [:status]) => 302 (get-in (stonecutter-callback {:stonecutter-config ...config... :params {:code ...auth-code...}}) [:headers "Location"]) => (contains (utils/path-for :fe/error-configuration))) (fact "redirects to referrer when access denied" (stonecutter-callback {:params {:error "access_denied"} :session {:sign-in-referrer "/objectives/1"}}) => (contains {:status 302 :headers (contains {"Location" (contains "/objectives/1")})})) (tabular (fact "redirects to the sign-in page with flash message set in the session when email is invalid" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id "d-cent-SUBJECT" :sign-in-referrer ...refer...} :flash {:validation :auth-email}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key (so-jwt/decode openid-test-config token-expiring-in-year-2515 test-auth-provider-public-key) => (assoc token-content :email ?stonecutter-email))) ?stonecutter-email "invalid" " " nil) (binding [config/environment (assoc config/environment :private-mode-enabled "true")] (fact "redirects to unauthorised error page when user is not trusted and private mode config variable is set to true" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/authorisation")}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key (so-jwt/decode openid-test-config token-expiring-in-year-2515 test-auth-provider-public-key) => (assoc token-content :role "untrusted"))))) (facts "about wrap-stonecutter-config" (fact "includes the stonecutter configuration in the request when the configuration is valid" (let [handler (wrap-stonecutter-config identity ...valid-stonecutter-config... ...invalid-handler...)] (handler {}) => {:stonecutter-config ...valid-stonecutter-config...})) (fact "defaults to invalid-handler when configuration is invalid" (wrap-stonecutter-config identity :invalid-configuration ...invalid-handler...) => ...invalid-handler...)) (fact "invalid-handler redirects to the invalid configuration error page" (invalid-configuration-handler {}) => (contains {:status 302 :headers (contains {"Location" (contains "/error/configuration")})}))
true
(ns objective8.unit.workflows.stonecutter-test (:require [midje.sweet :refer :all] [stonecutter-oauth.client :as soc] [stonecutter-oauth.jwt :as so-jwt] [objective8.utils :as utils] [objective8.front-end.workflows.stonecutter :refer :all] [objective8.config :as config])) (def openid-test-config (soc/configure "ISSUER" "CLIENT_ID" "<client-secret>" "<callback-uri>" :protocol :openid)) (def test-auth-provider-public-key (slurp "./test/objective8/unit/workflows/test-stonecutter-key.json")) (def token-expiring-in-year-2515 "PI:KEY:<KEY>END_PI") ;token-content is the decoded version of token-expiring-in-year-2515 signed with test-auth-provider-public-key (def token-content {:aud "CLIENT_ID" :email "PI:EMAIL:<EMAIL>END_PI" :email_verified true :exp 17207993252 :iat 1439992740 :iss "ISSUER" :role "admin" :sub "SUBJECT"}) (fact "stonecutter-sign-in generates the correct response" (stonecutter-sign-in {:stonecutter-config openid-test-config}) => ...stonecutter-sign-in-response... (provided (soc/authorisation-redirect-response openid-test-config) => ...stonecutter-sign-in-response...)) (facts "about stonecutter-callback" (fact "stonecutter-callback redirects to the sign-in workflow with the auth-provider-user-id and auth-provider-user-email set in the session" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id "d-cent-SUBJECT" :auth-provider-user-email "PI:EMAIL:<EMAIL>END_PI" :sign-in-referrer ...refer...}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key)) (fact "redirects to invalid-configuration page when unable to retrieve token from auth server" (against-background (soc/request-access-token! anything anything) =throws=> (Exception. "Some exception")) (get-in (stonecutter-callback {:stonecutter-config ...config... :params {:code ...auth-code...}}) [:status]) => 302 (get-in (stonecutter-callback {:stonecutter-config ...config... :params {:code ...auth-code...}}) [:headers "Location"]) => (contains (utils/path-for :fe/error-configuration))) (fact "redirects to referrer when access denied" (stonecutter-callback {:params {:error "access_denied"} :session {:sign-in-referrer "/objectives/1"}}) => (contains {:status 302 :headers (contains {"Location" (contains "/objectives/1")})})) (tabular (fact "redirects to the sign-in page with flash message set in the session when email is invalid" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/sign-up")} :session {:auth-provider-user-id "d-cent-SUBJECT" :sign-in-referrer ...refer...} :flash {:validation :auth-email}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key (so-jwt/decode openid-test-config token-expiring-in-year-2515 test-auth-provider-public-key) => (assoc token-content :email ?stonecutter-email))) ?stonecutter-email "invalid" " " nil) (binding [config/environment (assoc config/environment :private-mode-enabled "true")] (fact "redirects to unauthorised error page when user is not trusted and private mode config variable is set to true" (stonecutter-callback {:stonecutter-config openid-test-config :params {:code ...auth-code...} :session {:sign-in-referrer ...refer...}}) => (contains {:status 302 :headers {"Location" (str utils/host-url "/authorisation")}}) (provided (soc/request-access-token! openid-test-config ...auth-code...) => {:id_token token-expiring-in-year-2515} (so-jwt/get-public-key-string-from-jwk-set-url "ISSUER/api/jwk-set") => test-auth-provider-public-key (so-jwt/decode openid-test-config token-expiring-in-year-2515 test-auth-provider-public-key) => (assoc token-content :role "untrusted"))))) (facts "about wrap-stonecutter-config" (fact "includes the stonecutter configuration in the request when the configuration is valid" (let [handler (wrap-stonecutter-config identity ...valid-stonecutter-config... ...invalid-handler...)] (handler {}) => {:stonecutter-config ...valid-stonecutter-config...})) (fact "defaults to invalid-handler when configuration is invalid" (wrap-stonecutter-config identity :invalid-configuration ...invalid-handler...) => ...invalid-handler...)) (fact "invalid-handler redirects to the invalid configuration error page" (invalid-configuration-handler {}) => (contains {:status 302 :headers (contains {"Location" (contains "/error/configuration")})}))
[ { "context": "D)\n :name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"", "end": 886, "score": 0.999793529510498, "start": 882, "tag": "NAME", "value": "Ivan" }, { "context": " :name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"]", "end": 893, "score": 0.9995381236076355, "start": 889, "tag": "NAME", "value": "Petr" }, { "context": " :name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ", "end": 902, "score": 0.9995253682136536, "start": 896, "tag": "NAME", "value": "Sergei" }, { "context": " :name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ", "end": 909, "score": 0.9994097948074341, "start": 905, "tag": "NAME", "value": "Oleg" }, { "context": "me (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ", "end": 916, "score": 0.9971944689750671, "start": 912, "tag": "NAME", "value": "Yuri" }, { "context": " (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n :last-", "end": 925, "score": 0.9987720847129822, "start": 919, "tag": "NAME", "value": "Dmitry" }, { "context": "h [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n :last-name (ra", "end": 933, "score": 0.9976314306259155, "start": 928, "tag": "NAME", "value": "Fedor" }, { "context": "\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n :last-name (rand-nth [", "end": 941, "score": 0.998853862285614, "start": 936, "tag": "NAME", "value": "Denis" }, { "context": "])\n :last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Vorono", "end": 998, "score": 0.9962387084960938, "start": 992, "tag": "NAME", "value": "Ivanov" }, { "context": " :last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ", "end": 1007, "score": 0.9728041887283325, "start": 1001, "tag": "NAME", "value": "Petrov" }, { "context": " :last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ", "end": 1017, "score": 0.9960446357727051, "start": 1010, "tag": "NAME", "value": "Sidorov" }, { "context": "last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ", "end": 1027, "score": 0.9969364404678345, "start": 1020, "tag": "NAME", "value": "Kovalev" }, { "context": "(rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n :sex (", "end": 1039, "score": 0.9989956021308899, "start": 1030, "tag": "NAME", "value": "Kuznetsov" }, { "context": "Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n :sex (rand-nth [", "end": 1049, "score": 0.9980850219726562, "start": 1042, "tag": "NAME", "value": "Voronoi" } ]
test/crux/fixtures.clj
keesterbrugge/crux
0
(ns crux.fixtures (:require [clojure.test :as t] [clojure.test.check.clojure-test :as tcct] [clojure.java.io :as io] [crux.bootstrap :as b] [crux.codec :as c] [crux.db :as db] [crux.http-server :as srv] [crux.io :as cio] [crux.kafka.embedded :as ek] [crux.kafka :as k] [crux.kv :as kv] [crux.tx :as tx] [crux.index :as idx] [crux.lru :as lru]) (:import java.io.Closeable [java.util Properties UUID] org.apache.kafka.clients.admin.AdminClient org.apache.kafka.clients.producer.KafkaProducer org.apache.kafka.clients.consumer.KafkaConsumer [crux.api Crux ICruxAPI])) (defn random-person [] {:crux.db/id (UUID/randomUUID) :name (rand-nth ["Ivan" "Petr" "Sergei" "Oleg" "Yuri" "Dmitry" "Fedor" "Denis"]) :last-name (rand-nth ["Ivanov" "Petrov" "Sidorov" "Kovalev" "Kuznetsov" "Voronoi"]) :sex (rand-nth [:male :female]) :age (rand-int 100) :salary (rand-int 100000)}) (defn maps->tx-ops [maps ts] (vec (for [m maps] [:crux.tx/put (:crux.db/id m) m ts]))) (defn kv-tx-log ([kv] (tx/->KvTxLog kv (idx/->KvObjectStore kv))) ([kv object-store] (tx/->KvTxLog kv object-store))) (defn transact-entity-maps! ([kv entities] (transact-entity-maps! kv entities (cio/next-monotonic-date))) ([kv entities ts] (let [tx-log (kv-tx-log kv) tx-ops (maps->tx-ops entities ts)] @(db/submit-tx tx-log tx-ops) entities))) (defn entities->delete-tx-ops [entities ts] (vec (for [e entities] [:crux.tx/delete e ts]))) (defn delete-entities! ([kv entities] (delete-entities! kv entities (cio/next-monotonic-date))) ([kv entities ts] (let [tx-log (kv-tx-log kv) tx-ops (entities->delete-tx-ops entities ts)] @(db/submit-tx tx-log tx-ops) entities))) (defn transact-people! ([kv people-mixins] (transact-people! kv people-mixins (cio/next-monotonic-date))) ([kv people-mixins ts] (transact-entity-maps! kv (->> people-mixins (map merge (repeatedly random-person))) ts))) (def ^:dynamic *kv*) (def ^:dynamic *kv-backend* "crux.kv.rocksdb.RocksKv") (def ^:dynamic *check-and-store-index-version* true) (defn kv-object-store-w-cache [kv] (lru/->CachedObjectStore (lru/new-cache (:doc-cache-size b/default-options)) (b/start-object-store {:kv kv} b/default-options))) (defn kv-tx-log-w-cache [kv] (tx/->KvTxLog kv (kv-object-store-w-cache kv))) (defn without-kv-index-version [f] (binding [*check-and-store-index-version* false] (f))) (defn with-kv-store [f] (let [db-dir (cio/create-tmpdir "kv-store")] (try (binding [*kv* (b/start-kv-store {:db-dir (str db-dir) :kv-backend *kv-backend* :crux.index/check-and-store-index-version *check-and-store-index-version*})] (with-open [*kv* ^Closeable *kv*] (f))) (finally (cio/delete-dir db-dir))))) (defn with-memdb [f] (binding [*kv-backend* "crux.kv.memdb.MemKv"] (t/testing "MemDB" (f)))) (defn with-rocksdb [f] (binding [*kv-backend* "crux.kv.rocksdb.RocksKv"] (t/testing "RocksDB" (f)))) (defn with-rocksdb-jnr [f] (binding [*kv-backend* "crux.kv.rocksdb.jnr.RocksJNRKv"] (t/testing "RocksJNRDB" (f)))) (defn with-lmdb [f] (binding [*kv-backend* "crux.kv.lmdb.LMDBKv"] (t/testing "LMDB" (f)))) (defn with-lmdb-jnr [f] (binding [*kv-backend* "crux.kv.lmdb.jnr.LMDBJNRKv"] (t/testing "LMDBJNR" (f)))) (defn with-each-kv-store-implementation [f] (doseq [with-kv-store-implementation [with-memdb with-rocksdb with-rocksdb-jnr with-lmdb with-lmdb-jnr]] (with-kv-store-implementation f))) (def ^:dynamic *kafka-bootstrap-servers*) (defn write-kafka-meta-properties [log-dir broker-id] (let [meta-properties (io/file log-dir "meta.properties")] (when-not (.exists meta-properties) (io/make-parents meta-properties) (with-open [out (io/output-stream meta-properties)] (doto (Properties.) (.setProperty "version" "0") (.setProperty "broker.id" (str broker-id)) (.store out "")))))) (def ^:dynamic ^AdminClient *admin-client*) (defn with-embedded-kafka-cluster [f] (let [zookeeper-data-dir (cio/create-tmpdir "zookeeper") zookeeper-port (cio/free-port) kafka-log-dir (doto (cio/create-tmpdir "kafka-log") (write-kafka-meta-properties ek/*broker-id*)) kafka-port (cio/free-port)] (try (with-open [embedded-kafka (ek/start-embedded-kafka #:crux.kafka.embedded{:zookeeper-data-dir (str zookeeper-data-dir) :zookeeper-port zookeeper-port :kafka-log-dir (str kafka-log-dir) :kafka-port kafka-port}) admin-client (k/create-admin-client {"bootstrap.servers" (get-in embedded-kafka [:options :bootstrap-servers])})] (binding [*admin-client* admin-client *kafka-bootstrap-servers* (get-in embedded-kafka [:options :bootstrap-servers])] (f))) (finally (cio/delete-dir kafka-log-dir) (cio/delete-dir zookeeper-data-dir))))) (def ^:dynamic ^KafkaProducer *producer*) (def ^:dynamic ^KafkaConsumer *consumer*) (def ^:dynamic *consumer-options* {}) (defn with-kafka-client [f & {:keys [consumer-options]}] (with-open [producer (k/create-producer {"bootstrap.servers" *kafka-bootstrap-servers*}) consumer (k/create-consumer (merge {"bootstrap.servers" *kafka-bootstrap-servers* "group.id" (str (UUID/randomUUID))} *consumer-options*))] (binding [*producer* producer *consumer* consumer] (f)))) (def ^:dynamic *api-url*) (def ^:dynamic ^ICruxAPI *api*) (def ^:dynamic ^ICruxAPI *cluster-node*) (defn with-cluster-node [f] (assert (bound? #'*kafka-bootstrap-servers*)) (assert (not (bound? #'*kv*))) (let [server-port (cio/free-port) db-dir (str (cio/create-tmpdir "kv-store")) test-id (UUID/randomUUID) tx-topic (str "tx-topic-" test-id) doc-topic (str "doc-topic-" test-id) options {:server-port server-port :db-dir db-dir :tx-topic tx-topic :doc-topic doc-topic :kv-backend *kv-backend* :bootstrap-servers *kafka-bootstrap-servers*}] (try (with-open [cluster-node (Crux/startClusterNode options) http-server (srv/start-http-server cluster-node options)] (binding [*cluster-node* cluster-node *api* cluster-node *api-url* (str "http://" ek/*host* ":" server-port)] (f))) (finally (cio/delete-dir db-dir))))) (defn with-standalone-system [f] (assert (not (bound? #'*kv*))) (let [db-dir (str (cio/create-tmpdir "kv-store")) options {:db-dir db-dir :kv-backend *kv-backend*}] (try (with-open [standalone-system (Crux/startStandaloneSystem options)] (binding [*api* standalone-system] (f))) (finally (cio/delete-dir db-dir))))) (defn with-standalone-system-using-event-log [f] (assert (not (bound? #'*kv*))) (let [db-dir (str (cio/create-tmpdir "kv-store")) event-log-dir (str (cio/create-tmpdir "event-log-dir")) options {:db-dir db-dir :event-log-dir event-log-dir :kv-backend *kv-backend*}] (try (with-open [standalone-system (Crux/startStandaloneSystem options)] (binding [*api* standalone-system] (f))) (finally (cio/delete-dir db-dir) (cio/delete-dir event-log-dir))))) (defn with-api-client [f] (assert (bound? #'*api-url*)) (with-open [api-client (Crux/newApiClient *api-url*)] (binding [*api* api-client] (f)))) (defn with-each-api-implementation [f] (t/testing "Local API ClusterNode" (with-cluster-node f)) (t/testing "Local API StandaloneSystem" (with-standalone-system f)) (t/testing "Local API StandaloneSystem using event log" (with-standalone-system-using-event-log f)) (t/testing "Remote API" (with-cluster-node #(with-api-client f)))) (defn with-silent-test-check [f] (binding [tcct/*report-completion* false] (f)))
106467
(ns crux.fixtures (:require [clojure.test :as t] [clojure.test.check.clojure-test :as tcct] [clojure.java.io :as io] [crux.bootstrap :as b] [crux.codec :as c] [crux.db :as db] [crux.http-server :as srv] [crux.io :as cio] [crux.kafka.embedded :as ek] [crux.kafka :as k] [crux.kv :as kv] [crux.tx :as tx] [crux.index :as idx] [crux.lru :as lru]) (:import java.io.Closeable [java.util Properties UUID] org.apache.kafka.clients.admin.AdminClient org.apache.kafka.clients.producer.KafkaProducer org.apache.kafka.clients.consumer.KafkaConsumer [crux.api Crux ICruxAPI])) (defn random-person [] {:crux.db/id (UUID/randomUUID) :name (rand-nth ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) :last-name (rand-nth ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) :sex (rand-nth [:male :female]) :age (rand-int 100) :salary (rand-int 100000)}) (defn maps->tx-ops [maps ts] (vec (for [m maps] [:crux.tx/put (:crux.db/id m) m ts]))) (defn kv-tx-log ([kv] (tx/->KvTxLog kv (idx/->KvObjectStore kv))) ([kv object-store] (tx/->KvTxLog kv object-store))) (defn transact-entity-maps! ([kv entities] (transact-entity-maps! kv entities (cio/next-monotonic-date))) ([kv entities ts] (let [tx-log (kv-tx-log kv) tx-ops (maps->tx-ops entities ts)] @(db/submit-tx tx-log tx-ops) entities))) (defn entities->delete-tx-ops [entities ts] (vec (for [e entities] [:crux.tx/delete e ts]))) (defn delete-entities! ([kv entities] (delete-entities! kv entities (cio/next-monotonic-date))) ([kv entities ts] (let [tx-log (kv-tx-log kv) tx-ops (entities->delete-tx-ops entities ts)] @(db/submit-tx tx-log tx-ops) entities))) (defn transact-people! ([kv people-mixins] (transact-people! kv people-mixins (cio/next-monotonic-date))) ([kv people-mixins ts] (transact-entity-maps! kv (->> people-mixins (map merge (repeatedly random-person))) ts))) (def ^:dynamic *kv*) (def ^:dynamic *kv-backend* "crux.kv.rocksdb.RocksKv") (def ^:dynamic *check-and-store-index-version* true) (defn kv-object-store-w-cache [kv] (lru/->CachedObjectStore (lru/new-cache (:doc-cache-size b/default-options)) (b/start-object-store {:kv kv} b/default-options))) (defn kv-tx-log-w-cache [kv] (tx/->KvTxLog kv (kv-object-store-w-cache kv))) (defn without-kv-index-version [f] (binding [*check-and-store-index-version* false] (f))) (defn with-kv-store [f] (let [db-dir (cio/create-tmpdir "kv-store")] (try (binding [*kv* (b/start-kv-store {:db-dir (str db-dir) :kv-backend *kv-backend* :crux.index/check-and-store-index-version *check-and-store-index-version*})] (with-open [*kv* ^Closeable *kv*] (f))) (finally (cio/delete-dir db-dir))))) (defn with-memdb [f] (binding [*kv-backend* "crux.kv.memdb.MemKv"] (t/testing "MemDB" (f)))) (defn with-rocksdb [f] (binding [*kv-backend* "crux.kv.rocksdb.RocksKv"] (t/testing "RocksDB" (f)))) (defn with-rocksdb-jnr [f] (binding [*kv-backend* "crux.kv.rocksdb.jnr.RocksJNRKv"] (t/testing "RocksJNRDB" (f)))) (defn with-lmdb [f] (binding [*kv-backend* "crux.kv.lmdb.LMDBKv"] (t/testing "LMDB" (f)))) (defn with-lmdb-jnr [f] (binding [*kv-backend* "crux.kv.lmdb.jnr.LMDBJNRKv"] (t/testing "LMDBJNR" (f)))) (defn with-each-kv-store-implementation [f] (doseq [with-kv-store-implementation [with-memdb with-rocksdb with-rocksdb-jnr with-lmdb with-lmdb-jnr]] (with-kv-store-implementation f))) (def ^:dynamic *kafka-bootstrap-servers*) (defn write-kafka-meta-properties [log-dir broker-id] (let [meta-properties (io/file log-dir "meta.properties")] (when-not (.exists meta-properties) (io/make-parents meta-properties) (with-open [out (io/output-stream meta-properties)] (doto (Properties.) (.setProperty "version" "0") (.setProperty "broker.id" (str broker-id)) (.store out "")))))) (def ^:dynamic ^AdminClient *admin-client*) (defn with-embedded-kafka-cluster [f] (let [zookeeper-data-dir (cio/create-tmpdir "zookeeper") zookeeper-port (cio/free-port) kafka-log-dir (doto (cio/create-tmpdir "kafka-log") (write-kafka-meta-properties ek/*broker-id*)) kafka-port (cio/free-port)] (try (with-open [embedded-kafka (ek/start-embedded-kafka #:crux.kafka.embedded{:zookeeper-data-dir (str zookeeper-data-dir) :zookeeper-port zookeeper-port :kafka-log-dir (str kafka-log-dir) :kafka-port kafka-port}) admin-client (k/create-admin-client {"bootstrap.servers" (get-in embedded-kafka [:options :bootstrap-servers])})] (binding [*admin-client* admin-client *kafka-bootstrap-servers* (get-in embedded-kafka [:options :bootstrap-servers])] (f))) (finally (cio/delete-dir kafka-log-dir) (cio/delete-dir zookeeper-data-dir))))) (def ^:dynamic ^KafkaProducer *producer*) (def ^:dynamic ^KafkaConsumer *consumer*) (def ^:dynamic *consumer-options* {}) (defn with-kafka-client [f & {:keys [consumer-options]}] (with-open [producer (k/create-producer {"bootstrap.servers" *kafka-bootstrap-servers*}) consumer (k/create-consumer (merge {"bootstrap.servers" *kafka-bootstrap-servers* "group.id" (str (UUID/randomUUID))} *consumer-options*))] (binding [*producer* producer *consumer* consumer] (f)))) (def ^:dynamic *api-url*) (def ^:dynamic ^ICruxAPI *api*) (def ^:dynamic ^ICruxAPI *cluster-node*) (defn with-cluster-node [f] (assert (bound? #'*kafka-bootstrap-servers*)) (assert (not (bound? #'*kv*))) (let [server-port (cio/free-port) db-dir (str (cio/create-tmpdir "kv-store")) test-id (UUID/randomUUID) tx-topic (str "tx-topic-" test-id) doc-topic (str "doc-topic-" test-id) options {:server-port server-port :db-dir db-dir :tx-topic tx-topic :doc-topic doc-topic :kv-backend *kv-backend* :bootstrap-servers *kafka-bootstrap-servers*}] (try (with-open [cluster-node (Crux/startClusterNode options) http-server (srv/start-http-server cluster-node options)] (binding [*cluster-node* cluster-node *api* cluster-node *api-url* (str "http://" ek/*host* ":" server-port)] (f))) (finally (cio/delete-dir db-dir))))) (defn with-standalone-system [f] (assert (not (bound? #'*kv*))) (let [db-dir (str (cio/create-tmpdir "kv-store")) options {:db-dir db-dir :kv-backend *kv-backend*}] (try (with-open [standalone-system (Crux/startStandaloneSystem options)] (binding [*api* standalone-system] (f))) (finally (cio/delete-dir db-dir))))) (defn with-standalone-system-using-event-log [f] (assert (not (bound? #'*kv*))) (let [db-dir (str (cio/create-tmpdir "kv-store")) event-log-dir (str (cio/create-tmpdir "event-log-dir")) options {:db-dir db-dir :event-log-dir event-log-dir :kv-backend *kv-backend*}] (try (with-open [standalone-system (Crux/startStandaloneSystem options)] (binding [*api* standalone-system] (f))) (finally (cio/delete-dir db-dir) (cio/delete-dir event-log-dir))))) (defn with-api-client [f] (assert (bound? #'*api-url*)) (with-open [api-client (Crux/newApiClient *api-url*)] (binding [*api* api-client] (f)))) (defn with-each-api-implementation [f] (t/testing "Local API ClusterNode" (with-cluster-node f)) (t/testing "Local API StandaloneSystem" (with-standalone-system f)) (t/testing "Local API StandaloneSystem using event log" (with-standalone-system-using-event-log f)) (t/testing "Remote API" (with-cluster-node #(with-api-client f)))) (defn with-silent-test-check [f] (binding [tcct/*report-completion* false] (f)))
true
(ns crux.fixtures (:require [clojure.test :as t] [clojure.test.check.clojure-test :as tcct] [clojure.java.io :as io] [crux.bootstrap :as b] [crux.codec :as c] [crux.db :as db] [crux.http-server :as srv] [crux.io :as cio] [crux.kafka.embedded :as ek] [crux.kafka :as k] [crux.kv :as kv] [crux.tx :as tx] [crux.index :as idx] [crux.lru :as lru]) (:import java.io.Closeable [java.util Properties UUID] org.apache.kafka.clients.admin.AdminClient org.apache.kafka.clients.producer.KafkaProducer org.apache.kafka.clients.consumer.KafkaConsumer [crux.api Crux ICruxAPI])) (defn random-person [] {:crux.db/id (UUID/randomUUID) :name (rand-nth ["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" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) :last-name (rand-nth ["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"]) :sex (rand-nth [:male :female]) :age (rand-int 100) :salary (rand-int 100000)}) (defn maps->tx-ops [maps ts] (vec (for [m maps] [:crux.tx/put (:crux.db/id m) m ts]))) (defn kv-tx-log ([kv] (tx/->KvTxLog kv (idx/->KvObjectStore kv))) ([kv object-store] (tx/->KvTxLog kv object-store))) (defn transact-entity-maps! ([kv entities] (transact-entity-maps! kv entities (cio/next-monotonic-date))) ([kv entities ts] (let [tx-log (kv-tx-log kv) tx-ops (maps->tx-ops entities ts)] @(db/submit-tx tx-log tx-ops) entities))) (defn entities->delete-tx-ops [entities ts] (vec (for [e entities] [:crux.tx/delete e ts]))) (defn delete-entities! ([kv entities] (delete-entities! kv entities (cio/next-monotonic-date))) ([kv entities ts] (let [tx-log (kv-tx-log kv) tx-ops (entities->delete-tx-ops entities ts)] @(db/submit-tx tx-log tx-ops) entities))) (defn transact-people! ([kv people-mixins] (transact-people! kv people-mixins (cio/next-monotonic-date))) ([kv people-mixins ts] (transact-entity-maps! kv (->> people-mixins (map merge (repeatedly random-person))) ts))) (def ^:dynamic *kv*) (def ^:dynamic *kv-backend* "crux.kv.rocksdb.RocksKv") (def ^:dynamic *check-and-store-index-version* true) (defn kv-object-store-w-cache [kv] (lru/->CachedObjectStore (lru/new-cache (:doc-cache-size b/default-options)) (b/start-object-store {:kv kv} b/default-options))) (defn kv-tx-log-w-cache [kv] (tx/->KvTxLog kv (kv-object-store-w-cache kv))) (defn without-kv-index-version [f] (binding [*check-and-store-index-version* false] (f))) (defn with-kv-store [f] (let [db-dir (cio/create-tmpdir "kv-store")] (try (binding [*kv* (b/start-kv-store {:db-dir (str db-dir) :kv-backend *kv-backend* :crux.index/check-and-store-index-version *check-and-store-index-version*})] (with-open [*kv* ^Closeable *kv*] (f))) (finally (cio/delete-dir db-dir))))) (defn with-memdb [f] (binding [*kv-backend* "crux.kv.memdb.MemKv"] (t/testing "MemDB" (f)))) (defn with-rocksdb [f] (binding [*kv-backend* "crux.kv.rocksdb.RocksKv"] (t/testing "RocksDB" (f)))) (defn with-rocksdb-jnr [f] (binding [*kv-backend* "crux.kv.rocksdb.jnr.RocksJNRKv"] (t/testing "RocksJNRDB" (f)))) (defn with-lmdb [f] (binding [*kv-backend* "crux.kv.lmdb.LMDBKv"] (t/testing "LMDB" (f)))) (defn with-lmdb-jnr [f] (binding [*kv-backend* "crux.kv.lmdb.jnr.LMDBJNRKv"] (t/testing "LMDBJNR" (f)))) (defn with-each-kv-store-implementation [f] (doseq [with-kv-store-implementation [with-memdb with-rocksdb with-rocksdb-jnr with-lmdb with-lmdb-jnr]] (with-kv-store-implementation f))) (def ^:dynamic *kafka-bootstrap-servers*) (defn write-kafka-meta-properties [log-dir broker-id] (let [meta-properties (io/file log-dir "meta.properties")] (when-not (.exists meta-properties) (io/make-parents meta-properties) (with-open [out (io/output-stream meta-properties)] (doto (Properties.) (.setProperty "version" "0") (.setProperty "broker.id" (str broker-id)) (.store out "")))))) (def ^:dynamic ^AdminClient *admin-client*) (defn with-embedded-kafka-cluster [f] (let [zookeeper-data-dir (cio/create-tmpdir "zookeeper") zookeeper-port (cio/free-port) kafka-log-dir (doto (cio/create-tmpdir "kafka-log") (write-kafka-meta-properties ek/*broker-id*)) kafka-port (cio/free-port)] (try (with-open [embedded-kafka (ek/start-embedded-kafka #:crux.kafka.embedded{:zookeeper-data-dir (str zookeeper-data-dir) :zookeeper-port zookeeper-port :kafka-log-dir (str kafka-log-dir) :kafka-port kafka-port}) admin-client (k/create-admin-client {"bootstrap.servers" (get-in embedded-kafka [:options :bootstrap-servers])})] (binding [*admin-client* admin-client *kafka-bootstrap-servers* (get-in embedded-kafka [:options :bootstrap-servers])] (f))) (finally (cio/delete-dir kafka-log-dir) (cio/delete-dir zookeeper-data-dir))))) (def ^:dynamic ^KafkaProducer *producer*) (def ^:dynamic ^KafkaConsumer *consumer*) (def ^:dynamic *consumer-options* {}) (defn with-kafka-client [f & {:keys [consumer-options]}] (with-open [producer (k/create-producer {"bootstrap.servers" *kafka-bootstrap-servers*}) consumer (k/create-consumer (merge {"bootstrap.servers" *kafka-bootstrap-servers* "group.id" (str (UUID/randomUUID))} *consumer-options*))] (binding [*producer* producer *consumer* consumer] (f)))) (def ^:dynamic *api-url*) (def ^:dynamic ^ICruxAPI *api*) (def ^:dynamic ^ICruxAPI *cluster-node*) (defn with-cluster-node [f] (assert (bound? #'*kafka-bootstrap-servers*)) (assert (not (bound? #'*kv*))) (let [server-port (cio/free-port) db-dir (str (cio/create-tmpdir "kv-store")) test-id (UUID/randomUUID) tx-topic (str "tx-topic-" test-id) doc-topic (str "doc-topic-" test-id) options {:server-port server-port :db-dir db-dir :tx-topic tx-topic :doc-topic doc-topic :kv-backend *kv-backend* :bootstrap-servers *kafka-bootstrap-servers*}] (try (with-open [cluster-node (Crux/startClusterNode options) http-server (srv/start-http-server cluster-node options)] (binding [*cluster-node* cluster-node *api* cluster-node *api-url* (str "http://" ek/*host* ":" server-port)] (f))) (finally (cio/delete-dir db-dir))))) (defn with-standalone-system [f] (assert (not (bound? #'*kv*))) (let [db-dir (str (cio/create-tmpdir "kv-store")) options {:db-dir db-dir :kv-backend *kv-backend*}] (try (with-open [standalone-system (Crux/startStandaloneSystem options)] (binding [*api* standalone-system] (f))) (finally (cio/delete-dir db-dir))))) (defn with-standalone-system-using-event-log [f] (assert (not (bound? #'*kv*))) (let [db-dir (str (cio/create-tmpdir "kv-store")) event-log-dir (str (cio/create-tmpdir "event-log-dir")) options {:db-dir db-dir :event-log-dir event-log-dir :kv-backend *kv-backend*}] (try (with-open [standalone-system (Crux/startStandaloneSystem options)] (binding [*api* standalone-system] (f))) (finally (cio/delete-dir db-dir) (cio/delete-dir event-log-dir))))) (defn with-api-client [f] (assert (bound? #'*api-url*)) (with-open [api-client (Crux/newApiClient *api-url*)] (binding [*api* api-client] (f)))) (defn with-each-api-implementation [f] (t/testing "Local API ClusterNode" (with-cluster-node f)) (t/testing "Local API StandaloneSystem" (with-standalone-system f)) (t/testing "Local API StandaloneSystem using event log" (with-standalone-system-using-event-log f)) (t/testing "Remote API" (with-cluster-node #(with-api-client f)))) (defn with-silent-test-check [f] (binding [tcct/*report-completion* false] (f)))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-11-09\"\n :doc \"Bootstrap aggrega", "end": 105, "score": 0.9998735189437866, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/taiga/test/bagging.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-11-09" :doc "Bootstrap aggregation (bagging) checks." } taiga.test.bagging (:require [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.classify.data.record :as record] [taiga.test.classify.data.defs :as defs])) ;; mvn -Dmaven.test.skip=true clean install ;; mvn -Dtest=taiga.test.bagging clojure:test ;;------------------------------------------------------------------------------ ;; TODO: make this a function so we can test with every data set. ;;------------------------------------------------------------------------------ (defn- freqs ^double [label data] (let [data-freqs (z/frequencies record/true-class data) frac (/ (double (z/get data-freqs 1.0)) (z/count data))] #_(println label (z/count data) "\n" frac) frac)) ;;------------------------------------------------------------------------------ (test/deftest bagging (z/reset-mersenne-twister-seeds) (let [options (defs/options (record/make-spikes-function 1.0) (* 1024 1024)) prng (z/mersenne-twister-generator) data (:data options) fd (freqs "data" data)] (dotimes [i 8] (let [bag (z/sample-with-replacement prng data) data-bag (z/intersection data bag) fb (freqs "bag" bag) fi (freqs "intersection" data-bag) coverage (float (/ (z/count data-bag) (z/count data)))] (test/is (== (z/count bag) (z/count data))) (test/is (< 0.631 coverage 0.633)) (test/is (< 0.988 (/ fb fd) 1.012)) (test/is (< 0.988 (/ fi fd) 1.012)))))) ;;------------------------------------------------------------------------------
6718
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-11-09" :doc "Bootstrap aggregation (bagging) checks." } taiga.test.bagging (:require [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.classify.data.record :as record] [taiga.test.classify.data.defs :as defs])) ;; mvn -Dmaven.test.skip=true clean install ;; mvn -Dtest=taiga.test.bagging clojure:test ;;------------------------------------------------------------------------------ ;; TODO: make this a function so we can test with every data set. ;;------------------------------------------------------------------------------ (defn- freqs ^double [label data] (let [data-freqs (z/frequencies record/true-class data) frac (/ (double (z/get data-freqs 1.0)) (z/count data))] #_(println label (z/count data) "\n" frac) frac)) ;;------------------------------------------------------------------------------ (test/deftest bagging (z/reset-mersenne-twister-seeds) (let [options (defs/options (record/make-spikes-function 1.0) (* 1024 1024)) prng (z/mersenne-twister-generator) data (:data options) fd (freqs "data" data)] (dotimes [i 8] (let [bag (z/sample-with-replacement prng data) data-bag (z/intersection data bag) fb (freqs "bag" bag) fi (freqs "intersection" data-bag) coverage (float (/ (z/count data-bag) (z/count data)))] (test/is (== (z/count bag) (z/count data))) (test/is (< 0.631 coverage 0.633)) (test/is (< 0.988 (/ fb fd) 1.012)) (test/is (< 0.988 (/ fi fd) 1.012)))))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-11-09" :doc "Bootstrap aggregation (bagging) checks." } taiga.test.bagging (:require [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.classify.data.record :as record] [taiga.test.classify.data.defs :as defs])) ;; mvn -Dmaven.test.skip=true clean install ;; mvn -Dtest=taiga.test.bagging clojure:test ;;------------------------------------------------------------------------------ ;; TODO: make this a function so we can test with every data set. ;;------------------------------------------------------------------------------ (defn- freqs ^double [label data] (let [data-freqs (z/frequencies record/true-class data) frac (/ (double (z/get data-freqs 1.0)) (z/count data))] #_(println label (z/count data) "\n" frac) frac)) ;;------------------------------------------------------------------------------ (test/deftest bagging (z/reset-mersenne-twister-seeds) (let [options (defs/options (record/make-spikes-function 1.0) (* 1024 1024)) prng (z/mersenne-twister-generator) data (:data options) fd (freqs "data" data)] (dotimes [i 8] (let [bag (z/sample-with-replacement prng data) data-bag (z/intersection data bag) fb (freqs "bag" bag) fi (freqs "intersection" data-bag) coverage (float (/ (z/count data-bag) (z/count data)))] (test/is (== (z/count bag) (z/count data))) (test/is (< 0.631 coverage 0.633)) (test/is (< 0.988 (/ fb fd) 1.012)) (test/is (< 0.988 (/ fi fd) 1.012)))))) ;;------------------------------------------------------------------------------
[ { "context": ";; Copyright (c) 2015 Parker Harris Emerson\n\n(ns capstone.query-interface\n (:use java-jdbc.s", "end": 43, "score": 0.9998455047607422, "start": 22, "tag": "NAME", "value": "Parker Harris Emerson" } ]
src/capstone/query_interface.clj
emersonp/capstone
3
;; Copyright (c) 2015 Parker Harris Emerson (ns capstone.query-interface (:use java-jdbc.sql) (:require [clojure.java.jdbc :as jdbc]) (:refer-clojure :exclude [find]) (:require [clojure.set :refer [union]]) (:require [honeysql.core :as sql] [honeysql.helpers :as sqlhelp])) (def ^:private pgdb { :subprotocol "postgresql" :subname "//localhost:5432/capstone_db" }) (def ^:private query (partial jdbc/query pgdb)) (defn find-sql [table {fields :select conditions :conditions :or {fields *}}] (select fields table (where conditions))) (defn find-by-attribute-sql ([table attribute value] (find-by-attribute-sql table attribute value {})) ([table attribute value options] (find-sql table (merge options {:conditions {attribute value}})))) (defn find-by-id-sql [table id & args] (apply find-by-attribute-sql (concat (list table :id id) args))) (defn find-all-column-sql [table column] (select column table)) (def find (comp query find-sql)) (def find-by-attribute (comp query find-by-attribute-sql)) (def find-by-id (comp first query find-by-id-sql)) (def find-all-column (comp query find-all-column-sql)) ;; ;; Database-specific wrapper functions ;; (def find-all-unique-column "Applies clojure set to find all distinct values within a column" ;; Likely inefficient, but unsure how to implement SQL DISTINCT in JSQL. (comp set find-all-column)) (defn find-average-passengers "Given a route-number, two stop-ids, and a trip-number, finds the average number of passengers on the train." [route-number stop1 stop2 trip-number train] (let [datadump (find :stopdata_03122014 {:select [:ESTIMATED_LOAD :LEAVE_TIME :ROUTE_NUMBER :LOCATION_ID :TRIP_NUMBER :DIRECTION] :conditions {:TRIP_NUMBER trip-number, :ROUTE_NUMBER route-number, :TRAIN train}}) time1 (:leave_time (first (filter #(= stop1 (:location_id %)) datadump))) time2 (:leave_time (first (filter #(= stop2 (:location_id %)) datadump))) start-time (if (and time1 time2) (min time1 time2) (or time1 time2)) end-time (if (and time1 time2) (min time1 time2) (or time1 time2)) filtered-data (filter #(>= end-time (get % :leave_time)) (filter #(<= start-time (get % :leave_time)) datadump)) ] (float (/ (reduce + (map :estimated_load filtered-data)) (count filtered-data))) )) (defn find-route-stops "Given a route-number, finds all stops that route stops at." [route-number] (map :location_id (set (find-by-attribute :stopdata_03122014 :ROUTE_NUMBER route-number {:select :LOCATION_ID})))) (defn shared-stops "Given two routes, finds all stops those routes share, and returns them as a set." [route1 route2] (clojure.set/intersection (set (find-route-stops route1)) (set (find-route-stops route2)))) (defn find-stop-routes "Given a stop-number, finds all routes that stop at it and returns them as set." [stop-number] (map :route_number (set (find-by-attribute :stopdata_03122014 :LOCATION_ID stop-number {:select :route_number})))) (defn shared-routes "Given two stops, finds all stops those routes share, and returns them as a set." [stop1 stop2] (clojure.set/intersection (set (find-stop-routes stop1)) (set (find-stop-routes stop2)))) (defn connecting-stops "Given two stops, returns all stops where they have connecting routes." ;; Test with stop-ids 4537 and 3538 [stop1 stop2] (reduce clojure.set/union (for [route1 (find-stop-routes stop1) route2 (find-stop-routes stop2)] (shared-stops route1 route2)))) (defn bus-arrival-departure-time-sql "Given a route number and a stop id, returns a set of all departure times and arrival times." [route-number location-id] (find-sql :stopdata_03122014 {:select [:LEAVE_TIME :ARRIVE_TIME] :conditions {:ROUTE_NUMBER route-number, :LOCATION_ID location-id}})) (def bus-event (comp query bus-arrival-departure-time-sql)) (defn departing-buses-window "Given a route number, a stop id, and a start time and end time (in int seconds after midnight), returns all departure times where departure times are between the start and end time." [route-number location-id start-window end-window] (filter #(< % end-window) (filter #(> % start-window) (map :leave_time (bus-event route-number location-id))))) (defn arriving-buses-window "Given a route number, a stop id, and a start time and end time (in int seconds after midnight), returns all arrival times where arrival times are between the start and end time." [route-number location-id start-window end-window] (filter #(< % end-window) (filter #(> % start-window) (map :arrive_time (bus-event route-number location-id))))) (defn connecting-routes "Given a start-stop, an end-stop, and a connecting-stop, returns all routes connecting the start-stop to the end-stop." ;; Test with stop-ids 4537 7476 3538 [start-stop connecting-stop end-stop] (list (shared-routes start-stop connecting-stop) (shared-routes connecting-stop end-stop))) (defn find-all-trips "Given a start-stop and end-stop, as well as a start-time and end-time, if there is a connecting route, will return all trips a passenger can take." [start-stop end-stop start-time end-time] (if (shared-routes start-stop end-stop) (for [route (shared-routes start-stop end-stop)] (assoc {} :route route :departure-times (departing-buses-window route start-stop start-time end-time) :then nil)))) (defn print-all-trips "Prints find-all-trips" [start-stop end-stop start-time end-time] (for [trip (find-all-trips start-stop end-stop start-time end-time)] (for [leave-time (:departure-times trip)] (do (str "Start at stop ID " start-stop ". Get on bus number " (:route trip) " at " leave-time ". Get off at stop ID " end-stop))))) (defn get-train-number "Given a stop-id, leave-time, and route, return a train." [stop-id leave-time route] (:train (first (find :stopdata_03122014 {:select [:TRAIN] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn get-direction "Given a stop-id, leave-time, and route, return a direction." [stop-id leave-time route] (:direction (first (find :stopdata_03122014 {:select [:DIRECTION] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn get-trip-number "Given a stop-id, leave-time, and route, return a trip number." [stop-id leave-time route] (:trip_number (first (find :stopdata_03122014 {:select [:TRIP_NUMBER] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn fakefunc [arg1 arg2 arg3 arg4 arg5] [arg1 arg2 arg3 arg4 arg5]) (defn plan-trip-based-passenger "Given a start-stop and end-stop, and a start-time and end-time, finds best route based on emptiness of bus." [start-stop end-stop start-time end-time] (let [minimum-pass (apply min (map #(apply min %) (for [route (find-all-trips start-stop end-stop start-time end-time)] (for [departure-times (:departure-times route)] (find-average-passengers (:route route) start-stop end-stop (get-trip-number start-stop departure-times (:route route)) (get-train-number start-stop departure-times (:route route)) ))) ))] (first (filter identity (distinct (apply union (map distinct (for [route (find-all-trips start-stop end-stop start-time end-time)] (for [departure-times (:departure-times route)] (if (= minimum-pass (find-average-passengers (:route route) start-stop end-stop (get-trip-number start-stop departure-times (:route route)) (get-train-number start-stop departure-times (:route route)) )) {:route-number (:route route), :start-stop start-stop, :end-stop end-stop, :leave-time departure-times})))))))))) (defn find-trip-stop-time "Given a route, a start-stop, an end-stop, and a departure-time (from start-stop), returns the arrival time of the bus at the end-stop." [route start-stop end-stop departure-time] (let [trip (find :stopdata_03122014 {:select [:TRIP_NUMBER] :conditions {:ROUTE_NUMBER route, :LOCATION_ID start-stop :LEAVE_TIME departure-time}})] (:arrive_time (first (find :stopdata_03122014 {:select [:ARRIVE_TIME] :conditions {:ROUTE_NUMBER route, :LOCATION_ID end-stop, :TRIP_NUMBER (:trip_number (first trip))}}))))) (defn find-route "Given two stops, return all possible routes. Note that this function brute-forces the pathfinding, only finding paths between stops with 0 or 1 transfers involved." [stop1 stop2] (let [routes (shared-routes stop1 stop2)] (if (= routes #{}) (prn "No shared routes.\n") (shared-routes stop1 stop2))))
9141
;; Copyright (c) 2015 <NAME> (ns capstone.query-interface (:use java-jdbc.sql) (:require [clojure.java.jdbc :as jdbc]) (:refer-clojure :exclude [find]) (:require [clojure.set :refer [union]]) (:require [honeysql.core :as sql] [honeysql.helpers :as sqlhelp])) (def ^:private pgdb { :subprotocol "postgresql" :subname "//localhost:5432/capstone_db" }) (def ^:private query (partial jdbc/query pgdb)) (defn find-sql [table {fields :select conditions :conditions :or {fields *}}] (select fields table (where conditions))) (defn find-by-attribute-sql ([table attribute value] (find-by-attribute-sql table attribute value {})) ([table attribute value options] (find-sql table (merge options {:conditions {attribute value}})))) (defn find-by-id-sql [table id & args] (apply find-by-attribute-sql (concat (list table :id id) args))) (defn find-all-column-sql [table column] (select column table)) (def find (comp query find-sql)) (def find-by-attribute (comp query find-by-attribute-sql)) (def find-by-id (comp first query find-by-id-sql)) (def find-all-column (comp query find-all-column-sql)) ;; ;; Database-specific wrapper functions ;; (def find-all-unique-column "Applies clojure set to find all distinct values within a column" ;; Likely inefficient, but unsure how to implement SQL DISTINCT in JSQL. (comp set find-all-column)) (defn find-average-passengers "Given a route-number, two stop-ids, and a trip-number, finds the average number of passengers on the train." [route-number stop1 stop2 trip-number train] (let [datadump (find :stopdata_03122014 {:select [:ESTIMATED_LOAD :LEAVE_TIME :ROUTE_NUMBER :LOCATION_ID :TRIP_NUMBER :DIRECTION] :conditions {:TRIP_NUMBER trip-number, :ROUTE_NUMBER route-number, :TRAIN train}}) time1 (:leave_time (first (filter #(= stop1 (:location_id %)) datadump))) time2 (:leave_time (first (filter #(= stop2 (:location_id %)) datadump))) start-time (if (and time1 time2) (min time1 time2) (or time1 time2)) end-time (if (and time1 time2) (min time1 time2) (or time1 time2)) filtered-data (filter #(>= end-time (get % :leave_time)) (filter #(<= start-time (get % :leave_time)) datadump)) ] (float (/ (reduce + (map :estimated_load filtered-data)) (count filtered-data))) )) (defn find-route-stops "Given a route-number, finds all stops that route stops at." [route-number] (map :location_id (set (find-by-attribute :stopdata_03122014 :ROUTE_NUMBER route-number {:select :LOCATION_ID})))) (defn shared-stops "Given two routes, finds all stops those routes share, and returns them as a set." [route1 route2] (clojure.set/intersection (set (find-route-stops route1)) (set (find-route-stops route2)))) (defn find-stop-routes "Given a stop-number, finds all routes that stop at it and returns them as set." [stop-number] (map :route_number (set (find-by-attribute :stopdata_03122014 :LOCATION_ID stop-number {:select :route_number})))) (defn shared-routes "Given two stops, finds all stops those routes share, and returns them as a set." [stop1 stop2] (clojure.set/intersection (set (find-stop-routes stop1)) (set (find-stop-routes stop2)))) (defn connecting-stops "Given two stops, returns all stops where they have connecting routes." ;; Test with stop-ids 4537 and 3538 [stop1 stop2] (reduce clojure.set/union (for [route1 (find-stop-routes stop1) route2 (find-stop-routes stop2)] (shared-stops route1 route2)))) (defn bus-arrival-departure-time-sql "Given a route number and a stop id, returns a set of all departure times and arrival times." [route-number location-id] (find-sql :stopdata_03122014 {:select [:LEAVE_TIME :ARRIVE_TIME] :conditions {:ROUTE_NUMBER route-number, :LOCATION_ID location-id}})) (def bus-event (comp query bus-arrival-departure-time-sql)) (defn departing-buses-window "Given a route number, a stop id, and a start time and end time (in int seconds after midnight), returns all departure times where departure times are between the start and end time." [route-number location-id start-window end-window] (filter #(< % end-window) (filter #(> % start-window) (map :leave_time (bus-event route-number location-id))))) (defn arriving-buses-window "Given a route number, a stop id, and a start time and end time (in int seconds after midnight), returns all arrival times where arrival times are between the start and end time." [route-number location-id start-window end-window] (filter #(< % end-window) (filter #(> % start-window) (map :arrive_time (bus-event route-number location-id))))) (defn connecting-routes "Given a start-stop, an end-stop, and a connecting-stop, returns all routes connecting the start-stop to the end-stop." ;; Test with stop-ids 4537 7476 3538 [start-stop connecting-stop end-stop] (list (shared-routes start-stop connecting-stop) (shared-routes connecting-stop end-stop))) (defn find-all-trips "Given a start-stop and end-stop, as well as a start-time and end-time, if there is a connecting route, will return all trips a passenger can take." [start-stop end-stop start-time end-time] (if (shared-routes start-stop end-stop) (for [route (shared-routes start-stop end-stop)] (assoc {} :route route :departure-times (departing-buses-window route start-stop start-time end-time) :then nil)))) (defn print-all-trips "Prints find-all-trips" [start-stop end-stop start-time end-time] (for [trip (find-all-trips start-stop end-stop start-time end-time)] (for [leave-time (:departure-times trip)] (do (str "Start at stop ID " start-stop ". Get on bus number " (:route trip) " at " leave-time ". Get off at stop ID " end-stop))))) (defn get-train-number "Given a stop-id, leave-time, and route, return a train." [stop-id leave-time route] (:train (first (find :stopdata_03122014 {:select [:TRAIN] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn get-direction "Given a stop-id, leave-time, and route, return a direction." [stop-id leave-time route] (:direction (first (find :stopdata_03122014 {:select [:DIRECTION] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn get-trip-number "Given a stop-id, leave-time, and route, return a trip number." [stop-id leave-time route] (:trip_number (first (find :stopdata_03122014 {:select [:TRIP_NUMBER] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn fakefunc [arg1 arg2 arg3 arg4 arg5] [arg1 arg2 arg3 arg4 arg5]) (defn plan-trip-based-passenger "Given a start-stop and end-stop, and a start-time and end-time, finds best route based on emptiness of bus." [start-stop end-stop start-time end-time] (let [minimum-pass (apply min (map #(apply min %) (for [route (find-all-trips start-stop end-stop start-time end-time)] (for [departure-times (:departure-times route)] (find-average-passengers (:route route) start-stop end-stop (get-trip-number start-stop departure-times (:route route)) (get-train-number start-stop departure-times (:route route)) ))) ))] (first (filter identity (distinct (apply union (map distinct (for [route (find-all-trips start-stop end-stop start-time end-time)] (for [departure-times (:departure-times route)] (if (= minimum-pass (find-average-passengers (:route route) start-stop end-stop (get-trip-number start-stop departure-times (:route route)) (get-train-number start-stop departure-times (:route route)) )) {:route-number (:route route), :start-stop start-stop, :end-stop end-stop, :leave-time departure-times})))))))))) (defn find-trip-stop-time "Given a route, a start-stop, an end-stop, and a departure-time (from start-stop), returns the arrival time of the bus at the end-stop." [route start-stop end-stop departure-time] (let [trip (find :stopdata_03122014 {:select [:TRIP_NUMBER] :conditions {:ROUTE_NUMBER route, :LOCATION_ID start-stop :LEAVE_TIME departure-time}})] (:arrive_time (first (find :stopdata_03122014 {:select [:ARRIVE_TIME] :conditions {:ROUTE_NUMBER route, :LOCATION_ID end-stop, :TRIP_NUMBER (:trip_number (first trip))}}))))) (defn find-route "Given two stops, return all possible routes. Note that this function brute-forces the pathfinding, only finding paths between stops with 0 or 1 transfers involved." [stop1 stop2] (let [routes (shared-routes stop1 stop2)] (if (= routes #{}) (prn "No shared routes.\n") (shared-routes stop1 stop2))))
true
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI (ns capstone.query-interface (:use java-jdbc.sql) (:require [clojure.java.jdbc :as jdbc]) (:refer-clojure :exclude [find]) (:require [clojure.set :refer [union]]) (:require [honeysql.core :as sql] [honeysql.helpers :as sqlhelp])) (def ^:private pgdb { :subprotocol "postgresql" :subname "//localhost:5432/capstone_db" }) (def ^:private query (partial jdbc/query pgdb)) (defn find-sql [table {fields :select conditions :conditions :or {fields *}}] (select fields table (where conditions))) (defn find-by-attribute-sql ([table attribute value] (find-by-attribute-sql table attribute value {})) ([table attribute value options] (find-sql table (merge options {:conditions {attribute value}})))) (defn find-by-id-sql [table id & args] (apply find-by-attribute-sql (concat (list table :id id) args))) (defn find-all-column-sql [table column] (select column table)) (def find (comp query find-sql)) (def find-by-attribute (comp query find-by-attribute-sql)) (def find-by-id (comp first query find-by-id-sql)) (def find-all-column (comp query find-all-column-sql)) ;; ;; Database-specific wrapper functions ;; (def find-all-unique-column "Applies clojure set to find all distinct values within a column" ;; Likely inefficient, but unsure how to implement SQL DISTINCT in JSQL. (comp set find-all-column)) (defn find-average-passengers "Given a route-number, two stop-ids, and a trip-number, finds the average number of passengers on the train." [route-number stop1 stop2 trip-number train] (let [datadump (find :stopdata_03122014 {:select [:ESTIMATED_LOAD :LEAVE_TIME :ROUTE_NUMBER :LOCATION_ID :TRIP_NUMBER :DIRECTION] :conditions {:TRIP_NUMBER trip-number, :ROUTE_NUMBER route-number, :TRAIN train}}) time1 (:leave_time (first (filter #(= stop1 (:location_id %)) datadump))) time2 (:leave_time (first (filter #(= stop2 (:location_id %)) datadump))) start-time (if (and time1 time2) (min time1 time2) (or time1 time2)) end-time (if (and time1 time2) (min time1 time2) (or time1 time2)) filtered-data (filter #(>= end-time (get % :leave_time)) (filter #(<= start-time (get % :leave_time)) datadump)) ] (float (/ (reduce + (map :estimated_load filtered-data)) (count filtered-data))) )) (defn find-route-stops "Given a route-number, finds all stops that route stops at." [route-number] (map :location_id (set (find-by-attribute :stopdata_03122014 :ROUTE_NUMBER route-number {:select :LOCATION_ID})))) (defn shared-stops "Given two routes, finds all stops those routes share, and returns them as a set." [route1 route2] (clojure.set/intersection (set (find-route-stops route1)) (set (find-route-stops route2)))) (defn find-stop-routes "Given a stop-number, finds all routes that stop at it and returns them as set." [stop-number] (map :route_number (set (find-by-attribute :stopdata_03122014 :LOCATION_ID stop-number {:select :route_number})))) (defn shared-routes "Given two stops, finds all stops those routes share, and returns them as a set." [stop1 stop2] (clojure.set/intersection (set (find-stop-routes stop1)) (set (find-stop-routes stop2)))) (defn connecting-stops "Given two stops, returns all stops where they have connecting routes." ;; Test with stop-ids 4537 and 3538 [stop1 stop2] (reduce clojure.set/union (for [route1 (find-stop-routes stop1) route2 (find-stop-routes stop2)] (shared-stops route1 route2)))) (defn bus-arrival-departure-time-sql "Given a route number and a stop id, returns a set of all departure times and arrival times." [route-number location-id] (find-sql :stopdata_03122014 {:select [:LEAVE_TIME :ARRIVE_TIME] :conditions {:ROUTE_NUMBER route-number, :LOCATION_ID location-id}})) (def bus-event (comp query bus-arrival-departure-time-sql)) (defn departing-buses-window "Given a route number, a stop id, and a start time and end time (in int seconds after midnight), returns all departure times where departure times are between the start and end time." [route-number location-id start-window end-window] (filter #(< % end-window) (filter #(> % start-window) (map :leave_time (bus-event route-number location-id))))) (defn arriving-buses-window "Given a route number, a stop id, and a start time and end time (in int seconds after midnight), returns all arrival times where arrival times are between the start and end time." [route-number location-id start-window end-window] (filter #(< % end-window) (filter #(> % start-window) (map :arrive_time (bus-event route-number location-id))))) (defn connecting-routes "Given a start-stop, an end-stop, and a connecting-stop, returns all routes connecting the start-stop to the end-stop." ;; Test with stop-ids 4537 7476 3538 [start-stop connecting-stop end-stop] (list (shared-routes start-stop connecting-stop) (shared-routes connecting-stop end-stop))) (defn find-all-trips "Given a start-stop and end-stop, as well as a start-time and end-time, if there is a connecting route, will return all trips a passenger can take." [start-stop end-stop start-time end-time] (if (shared-routes start-stop end-stop) (for [route (shared-routes start-stop end-stop)] (assoc {} :route route :departure-times (departing-buses-window route start-stop start-time end-time) :then nil)))) (defn print-all-trips "Prints find-all-trips" [start-stop end-stop start-time end-time] (for [trip (find-all-trips start-stop end-stop start-time end-time)] (for [leave-time (:departure-times trip)] (do (str "Start at stop ID " start-stop ". Get on bus number " (:route trip) " at " leave-time ". Get off at stop ID " end-stop))))) (defn get-train-number "Given a stop-id, leave-time, and route, return a train." [stop-id leave-time route] (:train (first (find :stopdata_03122014 {:select [:TRAIN] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn get-direction "Given a stop-id, leave-time, and route, return a direction." [stop-id leave-time route] (:direction (first (find :stopdata_03122014 {:select [:DIRECTION] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn get-trip-number "Given a stop-id, leave-time, and route, return a trip number." [stop-id leave-time route] (:trip_number (first (find :stopdata_03122014 {:select [:TRIP_NUMBER] :conditions {:ROUTE_NUMBER route :LOCATION_ID stop-id :LEAVE_TIME leave-time}})))) (defn fakefunc [arg1 arg2 arg3 arg4 arg5] [arg1 arg2 arg3 arg4 arg5]) (defn plan-trip-based-passenger "Given a start-stop and end-stop, and a start-time and end-time, finds best route based on emptiness of bus." [start-stop end-stop start-time end-time] (let [minimum-pass (apply min (map #(apply min %) (for [route (find-all-trips start-stop end-stop start-time end-time)] (for [departure-times (:departure-times route)] (find-average-passengers (:route route) start-stop end-stop (get-trip-number start-stop departure-times (:route route)) (get-train-number start-stop departure-times (:route route)) ))) ))] (first (filter identity (distinct (apply union (map distinct (for [route (find-all-trips start-stop end-stop start-time end-time)] (for [departure-times (:departure-times route)] (if (= minimum-pass (find-average-passengers (:route route) start-stop end-stop (get-trip-number start-stop departure-times (:route route)) (get-train-number start-stop departure-times (:route route)) )) {:route-number (:route route), :start-stop start-stop, :end-stop end-stop, :leave-time departure-times})))))))))) (defn find-trip-stop-time "Given a route, a start-stop, an end-stop, and a departure-time (from start-stop), returns the arrival time of the bus at the end-stop." [route start-stop end-stop departure-time] (let [trip (find :stopdata_03122014 {:select [:TRIP_NUMBER] :conditions {:ROUTE_NUMBER route, :LOCATION_ID start-stop :LEAVE_TIME departure-time}})] (:arrive_time (first (find :stopdata_03122014 {:select [:ARRIVE_TIME] :conditions {:ROUTE_NUMBER route, :LOCATION_ID end-stop, :TRIP_NUMBER (:trip_number (first trip))}}))))) (defn find-route "Given two stops, return all possible routes. Note that this function brute-forces the pathfinding, only finding paths between stops with 0 or 1 transfers involved." [stop1 stop2] (let [routes (shared-routes stop1 stop2)] (if (= routes #{}) (prn "No shared routes.\n") (shared-routes stop1 stop2))))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998140335083008, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
resources/public/cljs-out/dev/clojure/core/protocols.cljs
23trastos/REPLiCA
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 clojure.core.protocols) (defprotocol Datafiable :extend-via-metadata true (datafy [o] "return a representation of o as data (default identity)")) (extend-protocol Datafiable nil (datafy [_] nil) default (datafy [o] o)) (defprotocol Navigable :extend-via-metadata true (nav [coll k v] "return (possibly transformed) v in the context of coll and k (a key/index or nil), defaults to returning v.")) (extend-protocol Navigable default (nav [_ _ x] x))
37567
; 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 clojure.core.protocols) (defprotocol Datafiable :extend-via-metadata true (datafy [o] "return a representation of o as data (default identity)")) (extend-protocol Datafiable nil (datafy [_] nil) default (datafy [o] o)) (defprotocol Navigable :extend-via-metadata true (nav [coll k v] "return (possibly transformed) v in the context of coll and k (a key/index or nil), defaults to returning v.")) (extend-protocol Navigable default (nav [_ _ x] x))
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 clojure.core.protocols) (defprotocol Datafiable :extend-via-metadata true (datafy [o] "return a representation of o as data (default identity)")) (extend-protocol Datafiable nil (datafy [_] nil) default (datafy [o] o)) (defprotocol Navigable :extend-via-metadata true (nav [coll k v] "return (possibly transformed) v in the context of coll and k (a key/index or nil), defaults to returning v.")) (extend-protocol Navigable default (nav [_ _ x] x))
[ { "context": ";;;;;;;;;;;;;;;;;;;;;\n;; Functional Composition by Chris Ford (@ctford) ;;\n;; ThoughtWorks ", "end": 103, "score": 0.9998454451560974, "start": 93, "tag": "NAME", "value": "Chris Ford" }, { "context": ";;;;;;;;;;\n;; Functional Composition by Chris Ford (@ctford) ;;\n;; ThoughtWorks ", "end": 112, "score": 0.9997383952140808, "start": 104, "tag": "USERNAME", "value": "(@ctford" }, { "context": " ;;\n;; http://github.com/ctford/functional-composition ;;\n;; http://git", "end": 283, "score": 0.9994531273841858, "start": 277, "tag": "USERNAME", "value": "ctford" }, { "context": "nal-composition ;;\n;; http://github.com/ctford/leipzig ;;\n;; http://git", "end": 347, "score": 0.9993731379508972, "start": 341, "tag": "USERNAME", "value": "ctford" }, { "context": " ;;\n;; http://github.com/overtone/overtone ;;\n;;;;;;;;;;;;;;;", "end": 413, "score": 0.9964452981948853, "start": 405, "tag": "USERNAME", "value": "overtone" }, { "context": " (concat notes)))\n\n)\n\n; canone alla quarta, by johann sebastian bach\n(defn canone-alla-quarta [notes]\n (canon\n (co", "end": 7557, "score": 0.9991318583488464, "start": 7536, "tag": "NAME", "value": "johann sebastian bach" } ]
src/goldberg/variations/canone_alla_quarta.clj
ctford/functional-composition
97
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functional Composition by Chris Ford (@ctford) ;; ;; ThoughtWorks ;; ;; ;; ;; http://github.com/ctford/functional-composition ;; ;; http://github.com/ctford/leipzig ;; ;; http://github.com/overtone/overtone ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns goldberg.variations.canone-alla-quarta (:use [overtone.live :exclude [scale pitch midi->hz note sharp flat run fill]] [quil.core :only [smooth sketch ellipse frame-rate background width height stroke stroke-weight fill]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sine waves ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (definst tone [frequency 440] (sin-osc frequency)) (definst beep [frequency 440 duration 1] (let [envelope (line 1 0 duration :action FREE)] (* envelope (sin-osc frequency)))) (comment (tone 300) (beep 300) (stop) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Harmonics ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (definst bell [frequency 440 duration 10 h0 1 h1 0.6 h2 0.4 h3 0.25 h4 0.2 h5 0.15] (let [harmonic-series [ 1 2 3 4 5 6] ;[ 1 2 3 4.2 5.4 6.8] proportions [h0 h1 h2 h3 h4 h5] component (fn [harmonic proportion] (* 1/2 proportion (env-gen (perc 0.01 (* proportion duration))) (sin-osc (* harmonic frequency)))) whole (mix (map component harmonic-series proportions))] (detect-silence whole :action FREE) whole)) (comment (bell 300) (beep 300) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Psycho-acoustics ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (bell 600 10.0) (bell 500 10.0 0.0) (bell 400 10.0 0.0 0.0) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Equal temperament ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn midi->hz [midi] (* 8.1757989156 ; midi zero (java.lang.Math/pow 2 (/ midi 12)))) (comment (midi->hz 69) ) (defn ding [midi] (bell (midi->hz midi) 3)) (comment (ding 69) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Musical events ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn note [timing pitch] {:time timing :pitch pitch}) (defn where [k f notes] (->> notes (map #(update-in % [k] f)))) (defn from [offset] (partial + offset)) (defn play [notes] (let [scheduled-notes (->> notes (where :time (from (now))))] (doseq [{ms :time midi :pitch} scheduled-notes] (at ms (ding midi))) scheduled-notes)) (defn even-melody [pitches] (let [times (reductions + (repeat 1000/3)) notes (map note times pitches)] (play notes))) (comment (even-melody (range 70 81)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Scale ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defs [names values] `(do ~@(map (fn [name value] `(def ~name ~value)) names (eval values)))) (defn sum-n [series n] (reduce + (take n series))) (defn scale [intervals] (fn [degree] (if-not (neg? degree) (sum-n (cycle intervals) degree) ((comp - (scale (reverse intervals)) -) degree)))) (def major (scale [2 2 1 2 2 2 1])) (def C (from 60)) (defs [D E F G A B] (map (comp from C major) (rest (range)))) (defs [sharp flat] [inc dec]) ; alternative scales (def minor (scale [2 1 2 2 1 2 2])) (def blues (scale [3 2 1 1 3 2])) (def pentatonic (scale [3 2 2 3 2])) (def chromatic (scale [1])) (comment (even-melody (map (comp C sharp major) (concat (range 0 8) (reverse (range 0 7))))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Melody ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def row-row-row-your-boat (let [pitches [0 0 0 1 2 ; Row, row, row your boat, 2 1 2 3 4 ; Gently down the stream, 7 7 7 4 4 4 2 2 2 0 0 0 ; (take 4 (repeat "merrily")) 4 3 2 1 0] ; Life is but a dream! durations [1 1 2/3 1/3 1 2/3 1/3 2/3 1/3 2 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 2/3 1/3 2/3 1/3 2] times (reductions + 0 durations)] (map note times pitches))) (comment row-row-row-your-boat ) (defn bpm [beats] (fn [beat] (/ (* beat 60 1000) beats))) (comment ((bpm 120) 3) (->> row-row-row-your-boat (where :time (bpm 90)) (where :pitch (comp C major)) play) ) (defn run [[from & tos]] (if-let [to (first tos)] (let [up-or-down (if (<= from to) (range from to) (reverse (range (inc to) (inc from))))] (concat up-or-down (run tos))) [from])) (comment (even-melody (map (comp G major) (run [0 4 -1 1 0]) )) ) (defn accumulate [series] (map (partial sum-n series) (range (count series)))) (def repeats (partial mapcat #(apply repeat %))) (def runs (partial mapcat run)) (def melody (let [call [(repeats [[2 1/4] [1 1/2] [14 1/4] [1 3/2]]) (runs [[0 -1 3 0] [4] [1 8]])] response [(repeats [[10 1/4] [1 1/2] [2 1/4] [1 9/4]]) (runs [[7 -1 0] [0 -3]])] development [(repeats [[1 3/4] [12 1/4] [1 1/2] [1 1] [1 1/2] [12 1/4] [1 3]]) (runs [[4] [4] [2 -3] [-1 -2] [0] [3 5] [1] [1] [1 2] [-1 1 -1] [5 0]])] [durations pitches] (map concat call response development) times (map (from 1/2) (accumulate durations))] (map note times pitches))) (def bass (let [triples (partial mapcat #(repeat 3 %))] (->> (map note (accumulate (repeats [[21 1] [13 1/4]])) (concat (triples (runs [[-7 -10] [-12 -10]])) (runs [[5 0] [6 0]]))) (where :part (constantly :bass))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Canon ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn canon [f notes] (concat notes (f notes))) ; varieties of canon (defn simple [wait] (fn [notes] (->> notes (where :time (from wait))))) (defn interval [interval] (fn [notes] (->> notes (where :pitch (from interval))))) (def mirror (fn [notes] (->> notes (where :pitch -)))) (def crab (fn [notes] (->> notes (where :time -)))) (def table (comp mirror crab)) ; round (comment (->> row-row-row-your-boat (canon (simple 4)) (where :pitch (comp C major)) (where :time (bpm 90)) play) (defn canon [f notes] (->> notes f (where :part (constantly :follower)) (concat notes))) ) ; canone alla quarta, by johann sebastian bach (defn canone-alla-quarta [notes] (canon (comp (interval -3) mirror (simple 3)) notes)) (comment (->> melody canone-alla-quarta (concat bass) (where :pitch (comp G major)) (where :time (bpm 90)) play #_graph) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Graphing ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn graph [points] (let [highlow (fn [k] (let [values (map k points)] [(apply max values) (apply min values)])) [max-x min-x] (highlow :time) [max-y min-y] (highlow :pitch) adjust (fn [k high low points] (->> points (where k (from (- low))) (where k #(/ % (- high low))))) normalise (fn [points] (->> points (filter #(< (:time %) (now))) (adjust :time max-x min-x) (adjust :pitch max-y min-y)))] (sketch :title "Time vs pitch" :target :perm-frame :setup (fn [] (smooth) (frame-rate 20) (background 200)) :draw (fn [] (let [colours (fnil {:leader [190 90 90] :follower [10 10 80] :bass [70 130 70]} :leader)] (doseq [{x :time y :pitch voice :part} (normalise points)] (stroke-weight 5) (fill 255) (apply stroke (colours voice)) (ellipse (* (width) x) (- (* 2/3 (height)) (* 1/3 (height) y)) 10 10)))) :size [1024 768]) points))
31225
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functional Composition by <NAME> (@ctford) ;; ;; ThoughtWorks ;; ;; ;; ;; http://github.com/ctford/functional-composition ;; ;; http://github.com/ctford/leipzig ;; ;; http://github.com/overtone/overtone ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns goldberg.variations.canone-alla-quarta (:use [overtone.live :exclude [scale pitch midi->hz note sharp flat run fill]] [quil.core :only [smooth sketch ellipse frame-rate background width height stroke stroke-weight fill]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sine waves ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (definst tone [frequency 440] (sin-osc frequency)) (definst beep [frequency 440 duration 1] (let [envelope (line 1 0 duration :action FREE)] (* envelope (sin-osc frequency)))) (comment (tone 300) (beep 300) (stop) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Harmonics ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (definst bell [frequency 440 duration 10 h0 1 h1 0.6 h2 0.4 h3 0.25 h4 0.2 h5 0.15] (let [harmonic-series [ 1 2 3 4 5 6] ;[ 1 2 3 4.2 5.4 6.8] proportions [h0 h1 h2 h3 h4 h5] component (fn [harmonic proportion] (* 1/2 proportion (env-gen (perc 0.01 (* proportion duration))) (sin-osc (* harmonic frequency)))) whole (mix (map component harmonic-series proportions))] (detect-silence whole :action FREE) whole)) (comment (bell 300) (beep 300) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Psycho-acoustics ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (bell 600 10.0) (bell 500 10.0 0.0) (bell 400 10.0 0.0 0.0) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Equal temperament ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn midi->hz [midi] (* 8.1757989156 ; midi zero (java.lang.Math/pow 2 (/ midi 12)))) (comment (midi->hz 69) ) (defn ding [midi] (bell (midi->hz midi) 3)) (comment (ding 69) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Musical events ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn note [timing pitch] {:time timing :pitch pitch}) (defn where [k f notes] (->> notes (map #(update-in % [k] f)))) (defn from [offset] (partial + offset)) (defn play [notes] (let [scheduled-notes (->> notes (where :time (from (now))))] (doseq [{ms :time midi :pitch} scheduled-notes] (at ms (ding midi))) scheduled-notes)) (defn even-melody [pitches] (let [times (reductions + (repeat 1000/3)) notes (map note times pitches)] (play notes))) (comment (even-melody (range 70 81)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Scale ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defs [names values] `(do ~@(map (fn [name value] `(def ~name ~value)) names (eval values)))) (defn sum-n [series n] (reduce + (take n series))) (defn scale [intervals] (fn [degree] (if-not (neg? degree) (sum-n (cycle intervals) degree) ((comp - (scale (reverse intervals)) -) degree)))) (def major (scale [2 2 1 2 2 2 1])) (def C (from 60)) (defs [D E F G A B] (map (comp from C major) (rest (range)))) (defs [sharp flat] [inc dec]) ; alternative scales (def minor (scale [2 1 2 2 1 2 2])) (def blues (scale [3 2 1 1 3 2])) (def pentatonic (scale [3 2 2 3 2])) (def chromatic (scale [1])) (comment (even-melody (map (comp C sharp major) (concat (range 0 8) (reverse (range 0 7))))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Melody ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def row-row-row-your-boat (let [pitches [0 0 0 1 2 ; Row, row, row your boat, 2 1 2 3 4 ; Gently down the stream, 7 7 7 4 4 4 2 2 2 0 0 0 ; (take 4 (repeat "merrily")) 4 3 2 1 0] ; Life is but a dream! durations [1 1 2/3 1/3 1 2/3 1/3 2/3 1/3 2 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 2/3 1/3 2/3 1/3 2] times (reductions + 0 durations)] (map note times pitches))) (comment row-row-row-your-boat ) (defn bpm [beats] (fn [beat] (/ (* beat 60 1000) beats))) (comment ((bpm 120) 3) (->> row-row-row-your-boat (where :time (bpm 90)) (where :pitch (comp C major)) play) ) (defn run [[from & tos]] (if-let [to (first tos)] (let [up-or-down (if (<= from to) (range from to) (reverse (range (inc to) (inc from))))] (concat up-or-down (run tos))) [from])) (comment (even-melody (map (comp G major) (run [0 4 -1 1 0]) )) ) (defn accumulate [series] (map (partial sum-n series) (range (count series)))) (def repeats (partial mapcat #(apply repeat %))) (def runs (partial mapcat run)) (def melody (let [call [(repeats [[2 1/4] [1 1/2] [14 1/4] [1 3/2]]) (runs [[0 -1 3 0] [4] [1 8]])] response [(repeats [[10 1/4] [1 1/2] [2 1/4] [1 9/4]]) (runs [[7 -1 0] [0 -3]])] development [(repeats [[1 3/4] [12 1/4] [1 1/2] [1 1] [1 1/2] [12 1/4] [1 3]]) (runs [[4] [4] [2 -3] [-1 -2] [0] [3 5] [1] [1] [1 2] [-1 1 -1] [5 0]])] [durations pitches] (map concat call response development) times (map (from 1/2) (accumulate durations))] (map note times pitches))) (def bass (let [triples (partial mapcat #(repeat 3 %))] (->> (map note (accumulate (repeats [[21 1] [13 1/4]])) (concat (triples (runs [[-7 -10] [-12 -10]])) (runs [[5 0] [6 0]]))) (where :part (constantly :bass))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Canon ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn canon [f notes] (concat notes (f notes))) ; varieties of canon (defn simple [wait] (fn [notes] (->> notes (where :time (from wait))))) (defn interval [interval] (fn [notes] (->> notes (where :pitch (from interval))))) (def mirror (fn [notes] (->> notes (where :pitch -)))) (def crab (fn [notes] (->> notes (where :time -)))) (def table (comp mirror crab)) ; round (comment (->> row-row-row-your-boat (canon (simple 4)) (where :pitch (comp C major)) (where :time (bpm 90)) play) (defn canon [f notes] (->> notes f (where :part (constantly :follower)) (concat notes))) ) ; canone alla quarta, by <NAME> (defn canone-alla-quarta [notes] (canon (comp (interval -3) mirror (simple 3)) notes)) (comment (->> melody canone-alla-quarta (concat bass) (where :pitch (comp G major)) (where :time (bpm 90)) play #_graph) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Graphing ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn graph [points] (let [highlow (fn [k] (let [values (map k points)] [(apply max values) (apply min values)])) [max-x min-x] (highlow :time) [max-y min-y] (highlow :pitch) adjust (fn [k high low points] (->> points (where k (from (- low))) (where k #(/ % (- high low))))) normalise (fn [points] (->> points (filter #(< (:time %) (now))) (adjust :time max-x min-x) (adjust :pitch max-y min-y)))] (sketch :title "Time vs pitch" :target :perm-frame :setup (fn [] (smooth) (frame-rate 20) (background 200)) :draw (fn [] (let [colours (fnil {:leader [190 90 90] :follower [10 10 80] :bass [70 130 70]} :leader)] (doseq [{x :time y :pitch voice :part} (normalise points)] (stroke-weight 5) (fill 255) (apply stroke (colours voice)) (ellipse (* (width) x) (- (* 2/3 (height)) (* 1/3 (height) y)) 10 10)))) :size [1024 768]) points))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functional Composition by PI:NAME:<NAME>END_PI (@ctford) ;; ;; ThoughtWorks ;; ;; ;; ;; http://github.com/ctford/functional-composition ;; ;; http://github.com/ctford/leipzig ;; ;; http://github.com/overtone/overtone ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns goldberg.variations.canone-alla-quarta (:use [overtone.live :exclude [scale pitch midi->hz note sharp flat run fill]] [quil.core :only [smooth sketch ellipse frame-rate background width height stroke stroke-weight fill]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sine waves ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (definst tone [frequency 440] (sin-osc frequency)) (definst beep [frequency 440 duration 1] (let [envelope (line 1 0 duration :action FREE)] (* envelope (sin-osc frequency)))) (comment (tone 300) (beep 300) (stop) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Harmonics ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (definst bell [frequency 440 duration 10 h0 1 h1 0.6 h2 0.4 h3 0.25 h4 0.2 h5 0.15] (let [harmonic-series [ 1 2 3 4 5 6] ;[ 1 2 3 4.2 5.4 6.8] proportions [h0 h1 h2 h3 h4 h5] component (fn [harmonic proportion] (* 1/2 proportion (env-gen (perc 0.01 (* proportion duration))) (sin-osc (* harmonic frequency)))) whole (mix (map component harmonic-series proportions))] (detect-silence whole :action FREE) whole)) (comment (bell 300) (beep 300) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Psycho-acoustics ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (bell 600 10.0) (bell 500 10.0 0.0) (bell 400 10.0 0.0 0.0) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Equal temperament ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn midi->hz [midi] (* 8.1757989156 ; midi zero (java.lang.Math/pow 2 (/ midi 12)))) (comment (midi->hz 69) ) (defn ding [midi] (bell (midi->hz midi) 3)) (comment (ding 69) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Musical events ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn note [timing pitch] {:time timing :pitch pitch}) (defn where [k f notes] (->> notes (map #(update-in % [k] f)))) (defn from [offset] (partial + offset)) (defn play [notes] (let [scheduled-notes (->> notes (where :time (from (now))))] (doseq [{ms :time midi :pitch} scheduled-notes] (at ms (ding midi))) scheduled-notes)) (defn even-melody [pitches] (let [times (reductions + (repeat 1000/3)) notes (map note times pitches)] (play notes))) (comment (even-melody (range 70 81)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Scale ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defs [names values] `(do ~@(map (fn [name value] `(def ~name ~value)) names (eval values)))) (defn sum-n [series n] (reduce + (take n series))) (defn scale [intervals] (fn [degree] (if-not (neg? degree) (sum-n (cycle intervals) degree) ((comp - (scale (reverse intervals)) -) degree)))) (def major (scale [2 2 1 2 2 2 1])) (def C (from 60)) (defs [D E F G A B] (map (comp from C major) (rest (range)))) (defs [sharp flat] [inc dec]) ; alternative scales (def minor (scale [2 1 2 2 1 2 2])) (def blues (scale [3 2 1 1 3 2])) (def pentatonic (scale [3 2 2 3 2])) (def chromatic (scale [1])) (comment (even-melody (map (comp C sharp major) (concat (range 0 8) (reverse (range 0 7))))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Melody ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def row-row-row-your-boat (let [pitches [0 0 0 1 2 ; Row, row, row your boat, 2 1 2 3 4 ; Gently down the stream, 7 7 7 4 4 4 2 2 2 0 0 0 ; (take 4 (repeat "merrily")) 4 3 2 1 0] ; Life is but a dream! durations [1 1 2/3 1/3 1 2/3 1/3 2/3 1/3 2 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 1/3 2/3 1/3 2/3 1/3 2] times (reductions + 0 durations)] (map note times pitches))) (comment row-row-row-your-boat ) (defn bpm [beats] (fn [beat] (/ (* beat 60 1000) beats))) (comment ((bpm 120) 3) (->> row-row-row-your-boat (where :time (bpm 90)) (where :pitch (comp C major)) play) ) (defn run [[from & tos]] (if-let [to (first tos)] (let [up-or-down (if (<= from to) (range from to) (reverse (range (inc to) (inc from))))] (concat up-or-down (run tos))) [from])) (comment (even-melody (map (comp G major) (run [0 4 -1 1 0]) )) ) (defn accumulate [series] (map (partial sum-n series) (range (count series)))) (def repeats (partial mapcat #(apply repeat %))) (def runs (partial mapcat run)) (def melody (let [call [(repeats [[2 1/4] [1 1/2] [14 1/4] [1 3/2]]) (runs [[0 -1 3 0] [4] [1 8]])] response [(repeats [[10 1/4] [1 1/2] [2 1/4] [1 9/4]]) (runs [[7 -1 0] [0 -3]])] development [(repeats [[1 3/4] [12 1/4] [1 1/2] [1 1] [1 1/2] [12 1/4] [1 3]]) (runs [[4] [4] [2 -3] [-1 -2] [0] [3 5] [1] [1] [1 2] [-1 1 -1] [5 0]])] [durations pitches] (map concat call response development) times (map (from 1/2) (accumulate durations))] (map note times pitches))) (def bass (let [triples (partial mapcat #(repeat 3 %))] (->> (map note (accumulate (repeats [[21 1] [13 1/4]])) (concat (triples (runs [[-7 -10] [-12 -10]])) (runs [[5 0] [6 0]]))) (where :part (constantly :bass))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Canon ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn canon [f notes] (concat notes (f notes))) ; varieties of canon (defn simple [wait] (fn [notes] (->> notes (where :time (from wait))))) (defn interval [interval] (fn [notes] (->> notes (where :pitch (from interval))))) (def mirror (fn [notes] (->> notes (where :pitch -)))) (def crab (fn [notes] (->> notes (where :time -)))) (def table (comp mirror crab)) ; round (comment (->> row-row-row-your-boat (canon (simple 4)) (where :pitch (comp C major)) (where :time (bpm 90)) play) (defn canon [f notes] (->> notes f (where :part (constantly :follower)) (concat notes))) ) ; canone alla quarta, by PI:NAME:<NAME>END_PI (defn canone-alla-quarta [notes] (canon (comp (interval -3) mirror (simple 3)) notes)) (comment (->> melody canone-alla-quarta (concat bass) (where :pitch (comp G major)) (where :time (bpm 90)) play #_graph) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Graphing ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn graph [points] (let [highlow (fn [k] (let [values (map k points)] [(apply max values) (apply min values)])) [max-x min-x] (highlow :time) [max-y min-y] (highlow :pitch) adjust (fn [k high low points] (->> points (where k (from (- low))) (where k #(/ % (- high low))))) normalise (fn [points] (->> points (filter #(< (:time %) (now))) (adjust :time max-x min-x) (adjust :pitch max-y min-y)))] (sketch :title "Time vs pitch" :target :perm-frame :setup (fn [] (smooth) (frame-rate 20) (background 200)) :draw (fn [] (let [colours (fnil {:leader [190 90 90] :follower [10 10 80] :bass [70 130 70]} :leader)] (doseq [{x :time y :pitch voice :part} (normalise points)] (stroke-weight 5) (fill 255) (apply stroke (colours voice)) (ellipse (* (width) x) (- (* 2/3 (height)) (* 1/3 (height) y)) 10 10)))) :size [1024 768]) points))
[ { "context": " (b/button {:key \"ok-button\" :className \"btn-fill\" :kind :info\n ", "end": 9830, "score": 0.8245311975479126, "start": 9824, "tag": "KEY", "value": "button" }, { "context": " (b/button {:key \"cancel-button\" :className \"btn-fill\" :kind :danger\n ", "end": 10316, "score": 0.9361791014671326, "start": 10310, "tag": "KEY", "value": "button" }, { "context": "dress-name (:name address-data)\n dev {:name name\n :description description\n ", "end": 13796, "score": 0.9990930557250977, "start": 13792, "tag": "NAME", "value": "name" }, { "context": " (b/button {:key \"back-button\" :className \"btn-fill\" :kind :info\n ", "end": 17582, "score": 0.9398236274719238, "start": 17576, "tag": "KEY", "value": "button" }, { "context": " (b/button {:key \"ok-button\" :className \"btn-fill\" :kind :info\n ", "end": 17871, "score": 0.9376623630523682, "start": 17862, "tag": "KEY", "value": "ok-button" }, { "context": " (b/button {:key \"next-button\" :className \"btn-fill\" :kind :info\n ", "end": 18116, "score": 0.9878174066543579, "start": 18110, "tag": "KEY", "value": "button" }, { "context": " (b/button {:key \"cancel-button\" :className \"btn-fill\" :kind :danger\n ", "end": 18520, "score": 0.9958766102790833, "start": 18514, "tag": "KEY", "value": "button" } ]
src/main/org/edgexfoundry/ui/manager/ui/devices.cljs
jpwhitemn/edgex-ui-clojure
0
;;; Copyright (c) 2018 ;;; IoTech Ltd ;;; SPDX-License-Identifier: Apache-2.0 (ns org.edgexfoundry.ui.manager.ui.devices (:require [fulcro.client.primitives :as prim :refer [defui defsc]] [fulcro.i18n :refer [tr]] [fulcro.client.dom :as dom] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.client.data-fetch :as df :refer [load-field-action]] [fulcro.ui.bootstrap3 :as b] [fulcro.client.routing :as r] [fulcro.ui.forms :as f] [fulcro.util :refer [conform!]] [org.edgexfoundry.ui.manager.ui.routing :as routing] [org.edgexfoundry.ui.manager.api.mutations :as mu] [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]] [org.edgexfoundry.ui.manager.ui.labels :as lbl] [org.edgexfoundry.ui.manager.ui.common :as co] [org.edgexfoundry.ui.manager.ui.commands :as cmds] [org.edgexfoundry.ui.manager.ui.dialogs :as d] [clojure.set :as set] [clojure.string :as str])) (defn set-admin-mode-target-device* [state id] (let [device (get-in state [:device id]) new-mode (if (= (:adminState device) :LOCKED) :UNLOCKED :LOCKED) set-modal-state (fn [state attr val] (assoc-in state [:admin-status-modal :singleton attr] val))] (-> state (set-modal-state :device-id id) (set-modal-state :name (:name device)) (set-modal-state :mode new-mode)))) (defn assoc-options [state field opts default] (let [path (into co/new-device-ident [:fulcro.ui.forms/form :elements/by-name field])] (-> state (assoc-in (conj path :input/options) opts) (assoc-in (conj path :input/default-value) (:id default)) (assoc-in (conj co/new-device-ident field) (:id default))))) (defn set-unused-addressables* [state] (let [mk-id-set (fn [m] (into #{} (map #(-> % :addressable :id) (vals m)))) dsa-ids (mk-id-set (:device-service state)) sa-ids (mk-id-set (:schedule-event state)) addrs (vals (:addressable state)) a-ids (into #{} (map :id addrs)) unused-ids (set/difference a-ids dsa-ids sa-ids) selected-addr (filter #(contains? unused-ids (:id %)) addrs) label #(str (:protocol %) "://" (:address %) ":" (:port %) (:path %)) opts (mapv #(f/option (:id %) (label %)) selected-addr) default (-> selected-addr first)] (assoc-options state :addressable opts default))) (defn set-profiles* [state] (let [profiles (-> state :device-profile vals) opts (mapv #(f/option (:id %) (:name %)) profiles) default (-> profiles first)] (-> state (assoc-options :profile opts default)))) (defn set-services* [state] (let [services (-> state :device-service vals) opts (mapv #(f/option (:id %) (:name %)) services) default (-> services first)] (-> state (assoc-options :service opts default)))) (defn reset-add-device* [state] (-> state (assoc-in [:new-device :singleton :confirm?] false) (assoc-in (conj co/new-device-ident :name) "") (assoc-in (conj co/new-device-ident :description) "") (assoc-in (conj co/new-device-ident :labels) []))) (defmutation prepare-update-lock-mode [{:keys [id]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (set-admin-mode-target-device* id)))))) (defmutation prepare-add-device [noargs] (action [{:keys [state]}] (swap! state (fn [s] (-> s (set-unused-addressables*) (set-profiles*) (set-services*) (reset-add-device*)))))) (declare ProfileListEntry) (declare DeviceList) (defn show-admin-status-modal [comp id] (prim/transact! comp `[(prepare-update-lock-mode {:id ~id}) (r/set-route {:router :root/modal-router :target [:admin-status-modal :singleton]}) (b/show-modal {:id :admin-status-modal}) :modal-router])) (defn show-add-device-modal [comp] (prim/transact! comp `[(prepare-add-device {}) (r/set-route {:router :root/modal-router :target ~co/new-device-ident}) (b/show-modal {:id :add-device-modal}) :modal-router])) (defn add-new-device [comp form dev] (f/reset-from-entity! comp form) (prim/transact! comp `[(mu/add-device ~dev) (b/hide-modal {:id :add-device-modal})]) (df/load comp co/device-list-ident DeviceList)) (defn set-new-device-data* [state] (let [service-id (get-in state (conj co/new-device-ident :service)) service (-> state :device-service service-id) addr-id (get-in state (conj co/new-device-ident :addressable)) addr (-> state :addressable addr-id)] (-> state (assoc-in (conj co/new-device-ident :confirm?) true) (assoc-in (conj co/new-device-ident :service-data) service) (assoc-in (conj co/new-device-ident :address-data) addr)))) (defmutation prepare-confirm-add-device [noargs] (action [{:keys [state]}] (swap! state (fn [s] (-> s set-new-device-data*))))) (defn load-commands* [state device-id] (let [profile-id (get-in state [:device device-id :profile :id])] (-> state (assoc-in (conj co/command-list-ident :source-device) device-id) (assoc-in (conj co/command-list-ident :source-profile) [:device-profile profile-id])))) (defn add-value-descriptor* [state device-id] (let [profile-id (get-in state [:device device-id :profile :id]) device-resources (get-in state [:device-profile profile-id :deviceResources]) mk-vd (fn [dr] (let [name (:name dr) pv (get-in dr [:properties :value])] [name {:id name :type :value-descriptor :name name :defaultValue (-> pv :defaultValue) :descripiton (-> dr :description) :formatting "%s" :min (or (-> pv :minimum) "") :max (or (-> pv :maximum) "") :value-type (-> pv :type first) :uomLabel (-> dr :properties :units :defaultValue)}])) vds (into {} (mapv mk-vd device-resources))] (-> state (assoc :value-descriptor vds)))) (defn add-value-descriptor-refs* [state] (let [vds (-> state :value-descriptor vals) mkref (fn [v] [:value-descriptor (:id v)]) vd-refs (mapv #(vector :value-descriptor (:id %)) vds) add-refs (fn [s id] (assoc-in s [:command id :value-descriptors] vd-refs))] (reduce add-refs state (-> state :command keys)))) (defmutation add-value-descriptor-refs [nokeys] (action [{:keys [state]}] (swap! state (fn [s] (-> s add-value-descriptor-refs*))))) (defmutation load-commands [{:keys [id]}] (action [{:keys [state] :as env}] (df/load-action env :q/edgex-commands cmds/CommandListEntry {:target (conj co/command-list-ident :commands) :params {:id id} :post-mutation `add-value-descriptor-refs}) (swap! state (fn [s] (-> s (load-commands* id) (add-value-descriptor* id))))) (remote [env] (df/remote-load env))) (defn do-delete-device [this id] (prim/transact! this `[(mu/delete-device {:id ~id}) (t/reset-table-page {:id :show-devices})])) (defn show-device [this _ id] (routing/nav-to! this :info {:id id})) (defsc ServiceListEntry [this {:keys [id type name addressable]}] {:ident [:device-service :id] :query [:id :type :name :addressable]}) (defsc ScheduleEventListEntry [this {:keys [id type addressable]}] {:ident [:schedule-event :id] :query [:id :type :addressable]}) (defsc AddressableListEntry [this {:keys [id type name protocol address port path]}] {:ident [:addressable :id] :query [:id :type :name :protocol :address :port :path]}) (defsc ProfileListEntry [this {:keys [id type name manufacturer model description]}] {:ident [:device-profile :id] :query [:id :type :name :manufacturer :model :description]}) (defsc AdminStatusModal [this {:keys [device-id name mode modal modal/page]}] {:initial-state (fn [p] {:device-id :none :name "" :mode :LOCKED :modal (prim/get-initial-state b/Modal {:id :admin-status-modal :backdrop true}) :modal/page :admin-status-modal}) :ident (fn [] [:admin-status-modal :singleton]) :query [:device-id :name :mode :modal/page {:modal (prim/get-query b/Modal)}]} (let [mode-str (if (= mode :LOCKED) "Lock" "Unlock")] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Change Admin Status")) (b/ui-modal-body nil (dom/div #js {:className "swal2-icon swal2-warning" :style #js {:display "block"}} "!") (dom/p #js {:key "message" :className b/text-danger} (str mode-str " " name))) (b/ui-modal-footer nil (b/button {:key "ok-button" :className "btn-fill" :kind :info :onClick #(prim/transact! this `[(mu/update-lock-mode {:id ~device-id :mode ~mode}) (b/hide-modal {:id :admin-status-modal})])} "OK") (b/button {:key "cancel-button" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :admin-status-modal})])} "Cancel"))))) (defn device-general-table [id name description profile addressable labels] (let [labels-str (str/join ", " (map #(str "'" % "'" ) labels)) key-to-string #(subs (str %) 1)] (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Name" name) (t/row "Description" description) (if id (t/row "Id" (key-to-string id))) (t/row "Manufacturer" (:manufacturer profile)) (t/row "Model" (:model profile)) (t/row "Labels" labels-str) (dom/tr nil (dom/th #js {:rowSpan "5"} "Address") (dom/th nil "Name") (dom/td nil (:name addressable))) (t/subrow "Protocol" (:protocol addressable)) (t/subrow "Address" (:address addressable)) (t/subrow "Port" (:port addressable)) (t/subrow "Path" (:path addressable))))))) (defn device-service-table [service] (dom/div nil (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Service")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/subrow "Host" (-> service :addressable :address)) (t/subrow "Port" (-> service :addressable :port))))))) (defsc AddDeviceModal [this {:keys [confirm? name description labels profile address-data service-data profiles modal modal/page] :as props}] {:initial-state (fn [p] (merge (f/build-form this {:db/id 1}) {:confirm? false :modal (prim/get-initial-state b/Modal {:id :add-device-modal :backdrop true}) :modal/page :new-device})) :ident (fn [] co/new-device-ident) :query [:confirm? :address-data :service-data f/form-key :db/id :name :addressable :description :labels :profile :service :modal/page {:profiles (prim/get-query ProfileListEntry)} {:modal (prim/get-query b/Modal)}] :form-fields [(f/id-field :db/id) (f/text-input :name :placeholder "Name of the device" :validator `f/not-empty?) (f/dropdown-input :addressable [(f/option :none "No addressables available")] :default-value :none) (f/text-input :description :placeholder "Short description" :validator `f/not-empty?) (lbl/labels-input :labels :placeholder "Labels (one per line)") (f/dropdown-input :profile [(f/option :none "No profiles available")] :default-value :none) (f/dropdown-input :service [(f/option :none "No services available")] :default-value :none)]} (let [profile-name (-> (filter #(= profile (:id %)) profiles) first :name) service-name (:name service-data) address-name (:name address-data) dev {:name name :description description :labels labels :profile-name profile-name :service-name service-name :addressable-name address-name} valid? (f/valid? (f/validate-fields props)) profile-data (-> (filter #(= profile (:id %)) profiles) first)] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Add New Device")) (dom/div #js {:className "header"} "Add New Device") (b/ui-modal-body nil (dom/div #js {:className "card"} (if confirm? (dom/div #js {:className "container-fluid"} (dom/div #js {:className "row"} (dom/div #js {:className "col-md-12"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Device")) (device-general-table nil name description profile-data address-data labels) (device-service-table service-data)))) (dom/div #js {:className "content"} (co/field-with-label this props :name "Name" :className "form-control") (co/field-with-label this props :addressable "Addressable" :className "form-control") (co/field-with-label this props :description "Description" :className "form-control") (co/field-with-label this props :labels "Labels" :className "form-control") (co/field-with-label this props :profile "Profile" :className "form-control") (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (dom/tr nil (dom/th nil "Manufacturer") (dom/td nil (:manufacturer profile-data))) (dom/tr nil (dom/th nil "Model") (dom/td nil (:model profile-data))) (dom/tr nil (dom/th nil "Description") (dom/td nil (:description profile-data)))))) (co/field-with-label this props :service "Service" :className "form-control"))))) (b/ui-modal-footer nil (when confirm? (b/button {:key "back-button" :className "btn-fill" :kind :info :onClick #(m/toggle! this :confirm?)} "Back")) (if confirm? (b/button {:key "ok-button" :className "btn-fill" :kind :info :onClick #(add-new-device this props dev)} "OK") (b/button {:key "next-button" :className "btn-fill" :kind :info :onClick #(prim/transact! this `[(prepare-confirm-add-device {})]) :disabled (not valid?)} "Next")) (b/button {:key "cancel-button" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :add-device-modal})])} "Cancel"))))) (defsc DeviceInfo [this {:keys [id type name description profile labels adminState operatingState lastConnected lastReported addressable service]}] {:ident [:device :id] :query [:id :type :name :description :profile :labels :adminState :operatingState :lastConnected :lastReported :addressable :service]} (let [admin-str (if (= adminState :LOCKED) "Locked" "Unlocked") op-str (if (= operatingState :ENABLED) "Enabled" "Disabled") connected-str (co/conv-time lastConnected) reported-str (co/conv-time lastReported) serv-connected-str (co/conv-time (:lastConnected service)) serv-reported-str (co/conv-time (:lastReported service)) serv-admin-str (if (= (:adminState service) :LOCKED) "Locked" "Unlocked") serv-op-str (if (= (:operatingState service) :ENABLED) "Enabled" "Disabled")] (dom/div nil (dom/div #js {:className "card"} (dom/div #js {:className "fixed-table-toolbar"} (dom/div #js {:className "bars pull-right"} (b/button {:onClick #(routing/nav-to! this :main)} (dom/i #js {:className "glyphicon fa fa-caret-square-o-left"})))) (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Device")) (device-general-table id name description profile addressable labels)) (dom/div #js {:className "card"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Status")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Admin State" admin-str) (t/row "Operating State" op-str) (t/row "Last Connected" connected-str) (t/row "Last Reported" reported-str))))) (dom/div #js {:className "card"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Service")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Name" (:name service)) (t/row "Last Connected" serv-connected-str) (t/row "Last Reported" serv-reported-str) (t/row "Admin State" serv-admin-str) (t/row "Operating State" serv-op-str) (dom/tr nil (dom/th #js {:rowSpan "5"} "Address") (dom/th nil "Name") (dom/td nil (-> service :addressable :name))) (t/subrow "Protocol" (-> service :addressable :protocol)) (t/subrow "Address" (-> service :addressable :address)) (t/subrow "Port" (-> service :addressable :port)) (t/subrow "Path" (-> service :addressable :path))))))))) (defsc DeviceListEntry [this {:keys [id type name adminState operatingState lastConnected]} {:keys [onShow onCmds onDelete]}] {:ident [:device :id] :query [:id :type :name :adminState :operatingState :lastConnected]} (let [lastConnected-str (co/conv-time lastConnected) [op-icon op-icon-color] (if (= operatingState :ENABLED) ["fa fa-circle" "green"] ["fa fa-circle-o" "red"]) [lock-icon lock-action-icon lock-action-tip] (if (= adminState :LOCKED) ["fa fa-lock" "fa fa-unlock" "Unlock Device"] ["fa fa-unlock" "fa fa-lock" "Lock Device"])] (dom/tr nil (dom/td nil name) (dom/td #js {:className "text-center"} (dom/i #js {:className op-icon :style #js {:color op-icon-color} :aria-hidden "true"})) (dom/td #js {:className "text-center"} (dom/i #js {:className lock-icon :aria-hidden "true"})) (dom/td nil lastConnected-str) (dom/td #js {:className "td-actions text-right"} (dom/button #js {:type "button", :rel "tooltip", :title "View Device", :className "btn btn-info btn-simple btn-xs" :onClick #(onShow id)} (dom/i #js {:className "fa fa-info"})) (dom/button #js {:type "button", :rel "tooltip", :title lock-action-tip, :className "btn btn-success btn-simple btn-xs" :onClick #(show-admin-status-modal this id)} (dom/i #js {:className lock-action-icon})) (dom/button #js {:type "button", :rel "tooltip", :title "Control Device", :className "btn btn-danger btn-simple btn-xs" :onClick #(onCmds id)} (dom/i #js {:className "fa fa-dashboard"})) (dom/button #js {:type "button", :rel "tooltip", :title "Delete Device", :className "btn btn-danger btn-simple btn-xs" :onClick #(onDelete this type id)} (dom/i #js {:className "fa fa-times"})))))) (deftable DeviceList :show-devices :device [[:name "Name"] [:operatingState "Op Status"] [:adminState "Admin Status"] [:lastConnected "Last Seen"]] [{:onClick #(show-add-device-modal this) :icon "plus"} {:onClick #(df/refresh! this {:fallback `d/show-error}) :icon "refresh"}] :modals [{:modal d/DeleteModal :params {:modal-id :dd-modal} :callbacks {:onDelete do-delete-device}}] :actions [{:title :onShow :action-class :info :symbol "info" :onClick (fn [id] (routing/nav-to! this :info {:id id}))} {:title :onCmds :action-class :danger :symbol "times" :onClick (fn [id] (prim/transact! this `[(load-commands {:id ~id})]) (routing/nav-to! this :control))} {:title :onDelete :action-class :danger :symbol "times" :onClick (d/mk-show-modal :dd-modal)}] :row-symbol DeviceListEntry)
14796
;;; Copyright (c) 2018 ;;; IoTech Ltd ;;; SPDX-License-Identifier: Apache-2.0 (ns org.edgexfoundry.ui.manager.ui.devices (:require [fulcro.client.primitives :as prim :refer [defui defsc]] [fulcro.i18n :refer [tr]] [fulcro.client.dom :as dom] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.client.data-fetch :as df :refer [load-field-action]] [fulcro.ui.bootstrap3 :as b] [fulcro.client.routing :as r] [fulcro.ui.forms :as f] [fulcro.util :refer [conform!]] [org.edgexfoundry.ui.manager.ui.routing :as routing] [org.edgexfoundry.ui.manager.api.mutations :as mu] [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]] [org.edgexfoundry.ui.manager.ui.labels :as lbl] [org.edgexfoundry.ui.manager.ui.common :as co] [org.edgexfoundry.ui.manager.ui.commands :as cmds] [org.edgexfoundry.ui.manager.ui.dialogs :as d] [clojure.set :as set] [clojure.string :as str])) (defn set-admin-mode-target-device* [state id] (let [device (get-in state [:device id]) new-mode (if (= (:adminState device) :LOCKED) :UNLOCKED :LOCKED) set-modal-state (fn [state attr val] (assoc-in state [:admin-status-modal :singleton attr] val))] (-> state (set-modal-state :device-id id) (set-modal-state :name (:name device)) (set-modal-state :mode new-mode)))) (defn assoc-options [state field opts default] (let [path (into co/new-device-ident [:fulcro.ui.forms/form :elements/by-name field])] (-> state (assoc-in (conj path :input/options) opts) (assoc-in (conj path :input/default-value) (:id default)) (assoc-in (conj co/new-device-ident field) (:id default))))) (defn set-unused-addressables* [state] (let [mk-id-set (fn [m] (into #{} (map #(-> % :addressable :id) (vals m)))) dsa-ids (mk-id-set (:device-service state)) sa-ids (mk-id-set (:schedule-event state)) addrs (vals (:addressable state)) a-ids (into #{} (map :id addrs)) unused-ids (set/difference a-ids dsa-ids sa-ids) selected-addr (filter #(contains? unused-ids (:id %)) addrs) label #(str (:protocol %) "://" (:address %) ":" (:port %) (:path %)) opts (mapv #(f/option (:id %) (label %)) selected-addr) default (-> selected-addr first)] (assoc-options state :addressable opts default))) (defn set-profiles* [state] (let [profiles (-> state :device-profile vals) opts (mapv #(f/option (:id %) (:name %)) profiles) default (-> profiles first)] (-> state (assoc-options :profile opts default)))) (defn set-services* [state] (let [services (-> state :device-service vals) opts (mapv #(f/option (:id %) (:name %)) services) default (-> services first)] (-> state (assoc-options :service opts default)))) (defn reset-add-device* [state] (-> state (assoc-in [:new-device :singleton :confirm?] false) (assoc-in (conj co/new-device-ident :name) "") (assoc-in (conj co/new-device-ident :description) "") (assoc-in (conj co/new-device-ident :labels) []))) (defmutation prepare-update-lock-mode [{:keys [id]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (set-admin-mode-target-device* id)))))) (defmutation prepare-add-device [noargs] (action [{:keys [state]}] (swap! state (fn [s] (-> s (set-unused-addressables*) (set-profiles*) (set-services*) (reset-add-device*)))))) (declare ProfileListEntry) (declare DeviceList) (defn show-admin-status-modal [comp id] (prim/transact! comp `[(prepare-update-lock-mode {:id ~id}) (r/set-route {:router :root/modal-router :target [:admin-status-modal :singleton]}) (b/show-modal {:id :admin-status-modal}) :modal-router])) (defn show-add-device-modal [comp] (prim/transact! comp `[(prepare-add-device {}) (r/set-route {:router :root/modal-router :target ~co/new-device-ident}) (b/show-modal {:id :add-device-modal}) :modal-router])) (defn add-new-device [comp form dev] (f/reset-from-entity! comp form) (prim/transact! comp `[(mu/add-device ~dev) (b/hide-modal {:id :add-device-modal})]) (df/load comp co/device-list-ident DeviceList)) (defn set-new-device-data* [state] (let [service-id (get-in state (conj co/new-device-ident :service)) service (-> state :device-service service-id) addr-id (get-in state (conj co/new-device-ident :addressable)) addr (-> state :addressable addr-id)] (-> state (assoc-in (conj co/new-device-ident :confirm?) true) (assoc-in (conj co/new-device-ident :service-data) service) (assoc-in (conj co/new-device-ident :address-data) addr)))) (defmutation prepare-confirm-add-device [noargs] (action [{:keys [state]}] (swap! state (fn [s] (-> s set-new-device-data*))))) (defn load-commands* [state device-id] (let [profile-id (get-in state [:device device-id :profile :id])] (-> state (assoc-in (conj co/command-list-ident :source-device) device-id) (assoc-in (conj co/command-list-ident :source-profile) [:device-profile profile-id])))) (defn add-value-descriptor* [state device-id] (let [profile-id (get-in state [:device device-id :profile :id]) device-resources (get-in state [:device-profile profile-id :deviceResources]) mk-vd (fn [dr] (let [name (:name dr) pv (get-in dr [:properties :value])] [name {:id name :type :value-descriptor :name name :defaultValue (-> pv :defaultValue) :descripiton (-> dr :description) :formatting "%s" :min (or (-> pv :minimum) "") :max (or (-> pv :maximum) "") :value-type (-> pv :type first) :uomLabel (-> dr :properties :units :defaultValue)}])) vds (into {} (mapv mk-vd device-resources))] (-> state (assoc :value-descriptor vds)))) (defn add-value-descriptor-refs* [state] (let [vds (-> state :value-descriptor vals) mkref (fn [v] [:value-descriptor (:id v)]) vd-refs (mapv #(vector :value-descriptor (:id %)) vds) add-refs (fn [s id] (assoc-in s [:command id :value-descriptors] vd-refs))] (reduce add-refs state (-> state :command keys)))) (defmutation add-value-descriptor-refs [nokeys] (action [{:keys [state]}] (swap! state (fn [s] (-> s add-value-descriptor-refs*))))) (defmutation load-commands [{:keys [id]}] (action [{:keys [state] :as env}] (df/load-action env :q/edgex-commands cmds/CommandListEntry {:target (conj co/command-list-ident :commands) :params {:id id} :post-mutation `add-value-descriptor-refs}) (swap! state (fn [s] (-> s (load-commands* id) (add-value-descriptor* id))))) (remote [env] (df/remote-load env))) (defn do-delete-device [this id] (prim/transact! this `[(mu/delete-device {:id ~id}) (t/reset-table-page {:id :show-devices})])) (defn show-device [this _ id] (routing/nav-to! this :info {:id id})) (defsc ServiceListEntry [this {:keys [id type name addressable]}] {:ident [:device-service :id] :query [:id :type :name :addressable]}) (defsc ScheduleEventListEntry [this {:keys [id type addressable]}] {:ident [:schedule-event :id] :query [:id :type :addressable]}) (defsc AddressableListEntry [this {:keys [id type name protocol address port path]}] {:ident [:addressable :id] :query [:id :type :name :protocol :address :port :path]}) (defsc ProfileListEntry [this {:keys [id type name manufacturer model description]}] {:ident [:device-profile :id] :query [:id :type :name :manufacturer :model :description]}) (defsc AdminStatusModal [this {:keys [device-id name mode modal modal/page]}] {:initial-state (fn [p] {:device-id :none :name "" :mode :LOCKED :modal (prim/get-initial-state b/Modal {:id :admin-status-modal :backdrop true}) :modal/page :admin-status-modal}) :ident (fn [] [:admin-status-modal :singleton]) :query [:device-id :name :mode :modal/page {:modal (prim/get-query b/Modal)}]} (let [mode-str (if (= mode :LOCKED) "Lock" "Unlock")] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Change Admin Status")) (b/ui-modal-body nil (dom/div #js {:className "swal2-icon swal2-warning" :style #js {:display "block"}} "!") (dom/p #js {:key "message" :className b/text-danger} (str mode-str " " name))) (b/ui-modal-footer nil (b/button {:key "ok-<KEY>" :className "btn-fill" :kind :info :onClick #(prim/transact! this `[(mu/update-lock-mode {:id ~device-id :mode ~mode}) (b/hide-modal {:id :admin-status-modal})])} "OK") (b/button {:key "cancel-<KEY>" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :admin-status-modal})])} "Cancel"))))) (defn device-general-table [id name description profile addressable labels] (let [labels-str (str/join ", " (map #(str "'" % "'" ) labels)) key-to-string #(subs (str %) 1)] (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Name" name) (t/row "Description" description) (if id (t/row "Id" (key-to-string id))) (t/row "Manufacturer" (:manufacturer profile)) (t/row "Model" (:model profile)) (t/row "Labels" labels-str) (dom/tr nil (dom/th #js {:rowSpan "5"} "Address") (dom/th nil "Name") (dom/td nil (:name addressable))) (t/subrow "Protocol" (:protocol addressable)) (t/subrow "Address" (:address addressable)) (t/subrow "Port" (:port addressable)) (t/subrow "Path" (:path addressable))))))) (defn device-service-table [service] (dom/div nil (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Service")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/subrow "Host" (-> service :addressable :address)) (t/subrow "Port" (-> service :addressable :port))))))) (defsc AddDeviceModal [this {:keys [confirm? name description labels profile address-data service-data profiles modal modal/page] :as props}] {:initial-state (fn [p] (merge (f/build-form this {:db/id 1}) {:confirm? false :modal (prim/get-initial-state b/Modal {:id :add-device-modal :backdrop true}) :modal/page :new-device})) :ident (fn [] co/new-device-ident) :query [:confirm? :address-data :service-data f/form-key :db/id :name :addressable :description :labels :profile :service :modal/page {:profiles (prim/get-query ProfileListEntry)} {:modal (prim/get-query b/Modal)}] :form-fields [(f/id-field :db/id) (f/text-input :name :placeholder "Name of the device" :validator `f/not-empty?) (f/dropdown-input :addressable [(f/option :none "No addressables available")] :default-value :none) (f/text-input :description :placeholder "Short description" :validator `f/not-empty?) (lbl/labels-input :labels :placeholder "Labels (one per line)") (f/dropdown-input :profile [(f/option :none "No profiles available")] :default-value :none) (f/dropdown-input :service [(f/option :none "No services available")] :default-value :none)]} (let [profile-name (-> (filter #(= profile (:id %)) profiles) first :name) service-name (:name service-data) address-name (:name address-data) dev {:name <NAME> :description description :labels labels :profile-name profile-name :service-name service-name :addressable-name address-name} valid? (f/valid? (f/validate-fields props)) profile-data (-> (filter #(= profile (:id %)) profiles) first)] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Add New Device")) (dom/div #js {:className "header"} "Add New Device") (b/ui-modal-body nil (dom/div #js {:className "card"} (if confirm? (dom/div #js {:className "container-fluid"} (dom/div #js {:className "row"} (dom/div #js {:className "col-md-12"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Device")) (device-general-table nil name description profile-data address-data labels) (device-service-table service-data)))) (dom/div #js {:className "content"} (co/field-with-label this props :name "Name" :className "form-control") (co/field-with-label this props :addressable "Addressable" :className "form-control") (co/field-with-label this props :description "Description" :className "form-control") (co/field-with-label this props :labels "Labels" :className "form-control") (co/field-with-label this props :profile "Profile" :className "form-control") (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (dom/tr nil (dom/th nil "Manufacturer") (dom/td nil (:manufacturer profile-data))) (dom/tr nil (dom/th nil "Model") (dom/td nil (:model profile-data))) (dom/tr nil (dom/th nil "Description") (dom/td nil (:description profile-data)))))) (co/field-with-label this props :service "Service" :className "form-control"))))) (b/ui-modal-footer nil (when confirm? (b/button {:key "back-<KEY>" :className "btn-fill" :kind :info :onClick #(m/toggle! this :confirm?)} "Back")) (if confirm? (b/button {:key "<KEY>" :className "btn-fill" :kind :info :onClick #(add-new-device this props dev)} "OK") (b/button {:key "next-<KEY>" :className "btn-fill" :kind :info :onClick #(prim/transact! this `[(prepare-confirm-add-device {})]) :disabled (not valid?)} "Next")) (b/button {:key "cancel-<KEY>" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :add-device-modal})])} "Cancel"))))) (defsc DeviceInfo [this {:keys [id type name description profile labels adminState operatingState lastConnected lastReported addressable service]}] {:ident [:device :id] :query [:id :type :name :description :profile :labels :adminState :operatingState :lastConnected :lastReported :addressable :service]} (let [admin-str (if (= adminState :LOCKED) "Locked" "Unlocked") op-str (if (= operatingState :ENABLED) "Enabled" "Disabled") connected-str (co/conv-time lastConnected) reported-str (co/conv-time lastReported) serv-connected-str (co/conv-time (:lastConnected service)) serv-reported-str (co/conv-time (:lastReported service)) serv-admin-str (if (= (:adminState service) :LOCKED) "Locked" "Unlocked") serv-op-str (if (= (:operatingState service) :ENABLED) "Enabled" "Disabled")] (dom/div nil (dom/div #js {:className "card"} (dom/div #js {:className "fixed-table-toolbar"} (dom/div #js {:className "bars pull-right"} (b/button {:onClick #(routing/nav-to! this :main)} (dom/i #js {:className "glyphicon fa fa-caret-square-o-left"})))) (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Device")) (device-general-table id name description profile addressable labels)) (dom/div #js {:className "card"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Status")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Admin State" admin-str) (t/row "Operating State" op-str) (t/row "Last Connected" connected-str) (t/row "Last Reported" reported-str))))) (dom/div #js {:className "card"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Service")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Name" (:name service)) (t/row "Last Connected" serv-connected-str) (t/row "Last Reported" serv-reported-str) (t/row "Admin State" serv-admin-str) (t/row "Operating State" serv-op-str) (dom/tr nil (dom/th #js {:rowSpan "5"} "Address") (dom/th nil "Name") (dom/td nil (-> service :addressable :name))) (t/subrow "Protocol" (-> service :addressable :protocol)) (t/subrow "Address" (-> service :addressable :address)) (t/subrow "Port" (-> service :addressable :port)) (t/subrow "Path" (-> service :addressable :path))))))))) (defsc DeviceListEntry [this {:keys [id type name adminState operatingState lastConnected]} {:keys [onShow onCmds onDelete]}] {:ident [:device :id] :query [:id :type :name :adminState :operatingState :lastConnected]} (let [lastConnected-str (co/conv-time lastConnected) [op-icon op-icon-color] (if (= operatingState :ENABLED) ["fa fa-circle" "green"] ["fa fa-circle-o" "red"]) [lock-icon lock-action-icon lock-action-tip] (if (= adminState :LOCKED) ["fa fa-lock" "fa fa-unlock" "Unlock Device"] ["fa fa-unlock" "fa fa-lock" "Lock Device"])] (dom/tr nil (dom/td nil name) (dom/td #js {:className "text-center"} (dom/i #js {:className op-icon :style #js {:color op-icon-color} :aria-hidden "true"})) (dom/td #js {:className "text-center"} (dom/i #js {:className lock-icon :aria-hidden "true"})) (dom/td nil lastConnected-str) (dom/td #js {:className "td-actions text-right"} (dom/button #js {:type "button", :rel "tooltip", :title "View Device", :className "btn btn-info btn-simple btn-xs" :onClick #(onShow id)} (dom/i #js {:className "fa fa-info"})) (dom/button #js {:type "button", :rel "tooltip", :title lock-action-tip, :className "btn btn-success btn-simple btn-xs" :onClick #(show-admin-status-modal this id)} (dom/i #js {:className lock-action-icon})) (dom/button #js {:type "button", :rel "tooltip", :title "Control Device", :className "btn btn-danger btn-simple btn-xs" :onClick #(onCmds id)} (dom/i #js {:className "fa fa-dashboard"})) (dom/button #js {:type "button", :rel "tooltip", :title "Delete Device", :className "btn btn-danger btn-simple btn-xs" :onClick #(onDelete this type id)} (dom/i #js {:className "fa fa-times"})))))) (deftable DeviceList :show-devices :device [[:name "Name"] [:operatingState "Op Status"] [:adminState "Admin Status"] [:lastConnected "Last Seen"]] [{:onClick #(show-add-device-modal this) :icon "plus"} {:onClick #(df/refresh! this {:fallback `d/show-error}) :icon "refresh"}] :modals [{:modal d/DeleteModal :params {:modal-id :dd-modal} :callbacks {:onDelete do-delete-device}}] :actions [{:title :onShow :action-class :info :symbol "info" :onClick (fn [id] (routing/nav-to! this :info {:id id}))} {:title :onCmds :action-class :danger :symbol "times" :onClick (fn [id] (prim/transact! this `[(load-commands {:id ~id})]) (routing/nav-to! this :control))} {:title :onDelete :action-class :danger :symbol "times" :onClick (d/mk-show-modal :dd-modal)}] :row-symbol DeviceListEntry)
true
;;; Copyright (c) 2018 ;;; IoTech Ltd ;;; SPDX-License-Identifier: Apache-2.0 (ns org.edgexfoundry.ui.manager.ui.devices (:require [fulcro.client.primitives :as prim :refer [defui defsc]] [fulcro.i18n :refer [tr]] [fulcro.client.dom :as dom] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.client.data-fetch :as df :refer [load-field-action]] [fulcro.ui.bootstrap3 :as b] [fulcro.client.routing :as r] [fulcro.ui.forms :as f] [fulcro.util :refer [conform!]] [org.edgexfoundry.ui.manager.ui.routing :as routing] [org.edgexfoundry.ui.manager.api.mutations :as mu] [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]] [org.edgexfoundry.ui.manager.ui.labels :as lbl] [org.edgexfoundry.ui.manager.ui.common :as co] [org.edgexfoundry.ui.manager.ui.commands :as cmds] [org.edgexfoundry.ui.manager.ui.dialogs :as d] [clojure.set :as set] [clojure.string :as str])) (defn set-admin-mode-target-device* [state id] (let [device (get-in state [:device id]) new-mode (if (= (:adminState device) :LOCKED) :UNLOCKED :LOCKED) set-modal-state (fn [state attr val] (assoc-in state [:admin-status-modal :singleton attr] val))] (-> state (set-modal-state :device-id id) (set-modal-state :name (:name device)) (set-modal-state :mode new-mode)))) (defn assoc-options [state field opts default] (let [path (into co/new-device-ident [:fulcro.ui.forms/form :elements/by-name field])] (-> state (assoc-in (conj path :input/options) opts) (assoc-in (conj path :input/default-value) (:id default)) (assoc-in (conj co/new-device-ident field) (:id default))))) (defn set-unused-addressables* [state] (let [mk-id-set (fn [m] (into #{} (map #(-> % :addressable :id) (vals m)))) dsa-ids (mk-id-set (:device-service state)) sa-ids (mk-id-set (:schedule-event state)) addrs (vals (:addressable state)) a-ids (into #{} (map :id addrs)) unused-ids (set/difference a-ids dsa-ids sa-ids) selected-addr (filter #(contains? unused-ids (:id %)) addrs) label #(str (:protocol %) "://" (:address %) ":" (:port %) (:path %)) opts (mapv #(f/option (:id %) (label %)) selected-addr) default (-> selected-addr first)] (assoc-options state :addressable opts default))) (defn set-profiles* [state] (let [profiles (-> state :device-profile vals) opts (mapv #(f/option (:id %) (:name %)) profiles) default (-> profiles first)] (-> state (assoc-options :profile opts default)))) (defn set-services* [state] (let [services (-> state :device-service vals) opts (mapv #(f/option (:id %) (:name %)) services) default (-> services first)] (-> state (assoc-options :service opts default)))) (defn reset-add-device* [state] (-> state (assoc-in [:new-device :singleton :confirm?] false) (assoc-in (conj co/new-device-ident :name) "") (assoc-in (conj co/new-device-ident :description) "") (assoc-in (conj co/new-device-ident :labels) []))) (defmutation prepare-update-lock-mode [{:keys [id]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (set-admin-mode-target-device* id)))))) (defmutation prepare-add-device [noargs] (action [{:keys [state]}] (swap! state (fn [s] (-> s (set-unused-addressables*) (set-profiles*) (set-services*) (reset-add-device*)))))) (declare ProfileListEntry) (declare DeviceList) (defn show-admin-status-modal [comp id] (prim/transact! comp `[(prepare-update-lock-mode {:id ~id}) (r/set-route {:router :root/modal-router :target [:admin-status-modal :singleton]}) (b/show-modal {:id :admin-status-modal}) :modal-router])) (defn show-add-device-modal [comp] (prim/transact! comp `[(prepare-add-device {}) (r/set-route {:router :root/modal-router :target ~co/new-device-ident}) (b/show-modal {:id :add-device-modal}) :modal-router])) (defn add-new-device [comp form dev] (f/reset-from-entity! comp form) (prim/transact! comp `[(mu/add-device ~dev) (b/hide-modal {:id :add-device-modal})]) (df/load comp co/device-list-ident DeviceList)) (defn set-new-device-data* [state] (let [service-id (get-in state (conj co/new-device-ident :service)) service (-> state :device-service service-id) addr-id (get-in state (conj co/new-device-ident :addressable)) addr (-> state :addressable addr-id)] (-> state (assoc-in (conj co/new-device-ident :confirm?) true) (assoc-in (conj co/new-device-ident :service-data) service) (assoc-in (conj co/new-device-ident :address-data) addr)))) (defmutation prepare-confirm-add-device [noargs] (action [{:keys [state]}] (swap! state (fn [s] (-> s set-new-device-data*))))) (defn load-commands* [state device-id] (let [profile-id (get-in state [:device device-id :profile :id])] (-> state (assoc-in (conj co/command-list-ident :source-device) device-id) (assoc-in (conj co/command-list-ident :source-profile) [:device-profile profile-id])))) (defn add-value-descriptor* [state device-id] (let [profile-id (get-in state [:device device-id :profile :id]) device-resources (get-in state [:device-profile profile-id :deviceResources]) mk-vd (fn [dr] (let [name (:name dr) pv (get-in dr [:properties :value])] [name {:id name :type :value-descriptor :name name :defaultValue (-> pv :defaultValue) :descripiton (-> dr :description) :formatting "%s" :min (or (-> pv :minimum) "") :max (or (-> pv :maximum) "") :value-type (-> pv :type first) :uomLabel (-> dr :properties :units :defaultValue)}])) vds (into {} (mapv mk-vd device-resources))] (-> state (assoc :value-descriptor vds)))) (defn add-value-descriptor-refs* [state] (let [vds (-> state :value-descriptor vals) mkref (fn [v] [:value-descriptor (:id v)]) vd-refs (mapv #(vector :value-descriptor (:id %)) vds) add-refs (fn [s id] (assoc-in s [:command id :value-descriptors] vd-refs))] (reduce add-refs state (-> state :command keys)))) (defmutation add-value-descriptor-refs [nokeys] (action [{:keys [state]}] (swap! state (fn [s] (-> s add-value-descriptor-refs*))))) (defmutation load-commands [{:keys [id]}] (action [{:keys [state] :as env}] (df/load-action env :q/edgex-commands cmds/CommandListEntry {:target (conj co/command-list-ident :commands) :params {:id id} :post-mutation `add-value-descriptor-refs}) (swap! state (fn [s] (-> s (load-commands* id) (add-value-descriptor* id))))) (remote [env] (df/remote-load env))) (defn do-delete-device [this id] (prim/transact! this `[(mu/delete-device {:id ~id}) (t/reset-table-page {:id :show-devices})])) (defn show-device [this _ id] (routing/nav-to! this :info {:id id})) (defsc ServiceListEntry [this {:keys [id type name addressable]}] {:ident [:device-service :id] :query [:id :type :name :addressable]}) (defsc ScheduleEventListEntry [this {:keys [id type addressable]}] {:ident [:schedule-event :id] :query [:id :type :addressable]}) (defsc AddressableListEntry [this {:keys [id type name protocol address port path]}] {:ident [:addressable :id] :query [:id :type :name :protocol :address :port :path]}) (defsc ProfileListEntry [this {:keys [id type name manufacturer model description]}] {:ident [:device-profile :id] :query [:id :type :name :manufacturer :model :description]}) (defsc AdminStatusModal [this {:keys [device-id name mode modal modal/page]}] {:initial-state (fn [p] {:device-id :none :name "" :mode :LOCKED :modal (prim/get-initial-state b/Modal {:id :admin-status-modal :backdrop true}) :modal/page :admin-status-modal}) :ident (fn [] [:admin-status-modal :singleton]) :query [:device-id :name :mode :modal/page {:modal (prim/get-query b/Modal)}]} (let [mode-str (if (= mode :LOCKED) "Lock" "Unlock")] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Change Admin Status")) (b/ui-modal-body nil (dom/div #js {:className "swal2-icon swal2-warning" :style #js {:display "block"}} "!") (dom/p #js {:key "message" :className b/text-danger} (str mode-str " " name))) (b/ui-modal-footer nil (b/button {:key "ok-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info :onClick #(prim/transact! this `[(mu/update-lock-mode {:id ~device-id :mode ~mode}) (b/hide-modal {:id :admin-status-modal})])} "OK") (b/button {:key "cancel-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :admin-status-modal})])} "Cancel"))))) (defn device-general-table [id name description profile addressable labels] (let [labels-str (str/join ", " (map #(str "'" % "'" ) labels)) key-to-string #(subs (str %) 1)] (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Name" name) (t/row "Description" description) (if id (t/row "Id" (key-to-string id))) (t/row "Manufacturer" (:manufacturer profile)) (t/row "Model" (:model profile)) (t/row "Labels" labels-str) (dom/tr nil (dom/th #js {:rowSpan "5"} "Address") (dom/th nil "Name") (dom/td nil (:name addressable))) (t/subrow "Protocol" (:protocol addressable)) (t/subrow "Address" (:address addressable)) (t/subrow "Port" (:port addressable)) (t/subrow "Path" (:path addressable))))))) (defn device-service-table [service] (dom/div nil (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Service")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/subrow "Host" (-> service :addressable :address)) (t/subrow "Port" (-> service :addressable :port))))))) (defsc AddDeviceModal [this {:keys [confirm? name description labels profile address-data service-data profiles modal modal/page] :as props}] {:initial-state (fn [p] (merge (f/build-form this {:db/id 1}) {:confirm? false :modal (prim/get-initial-state b/Modal {:id :add-device-modal :backdrop true}) :modal/page :new-device})) :ident (fn [] co/new-device-ident) :query [:confirm? :address-data :service-data f/form-key :db/id :name :addressable :description :labels :profile :service :modal/page {:profiles (prim/get-query ProfileListEntry)} {:modal (prim/get-query b/Modal)}] :form-fields [(f/id-field :db/id) (f/text-input :name :placeholder "Name of the device" :validator `f/not-empty?) (f/dropdown-input :addressable [(f/option :none "No addressables available")] :default-value :none) (f/text-input :description :placeholder "Short description" :validator `f/not-empty?) (lbl/labels-input :labels :placeholder "Labels (one per line)") (f/dropdown-input :profile [(f/option :none "No profiles available")] :default-value :none) (f/dropdown-input :service [(f/option :none "No services available")] :default-value :none)]} (let [profile-name (-> (filter #(= profile (:id %)) profiles) first :name) service-name (:name service-data) address-name (:name address-data) dev {:name PI:NAME:<NAME>END_PI :description description :labels labels :profile-name profile-name :service-name service-name :addressable-name address-name} valid? (f/valid? (f/validate-fields props)) profile-data (-> (filter #(= profile (:id %)) profiles) first)] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Add New Device")) (dom/div #js {:className "header"} "Add New Device") (b/ui-modal-body nil (dom/div #js {:className "card"} (if confirm? (dom/div #js {:className "container-fluid"} (dom/div #js {:className "row"} (dom/div #js {:className "col-md-12"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Device")) (device-general-table nil name description profile-data address-data labels) (device-service-table service-data)))) (dom/div #js {:className "content"} (co/field-with-label this props :name "Name" :className "form-control") (co/field-with-label this props :addressable "Addressable" :className "form-control") (co/field-with-label this props :description "Description" :className "form-control") (co/field-with-label this props :labels "Labels" :className "form-control") (co/field-with-label this props :profile "Profile" :className "form-control") (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (dom/tr nil (dom/th nil "Manufacturer") (dom/td nil (:manufacturer profile-data))) (dom/tr nil (dom/th nil "Model") (dom/td nil (:model profile-data))) (dom/tr nil (dom/th nil "Description") (dom/td nil (:description profile-data)))))) (co/field-with-label this props :service "Service" :className "form-control"))))) (b/ui-modal-footer nil (when confirm? (b/button {:key "back-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info :onClick #(m/toggle! this :confirm?)} "Back")) (if confirm? (b/button {:key "PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info :onClick #(add-new-device this props dev)} "OK") (b/button {:key "next-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info :onClick #(prim/transact! this `[(prepare-confirm-add-device {})]) :disabled (not valid?)} "Next")) (b/button {:key "cancel-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :add-device-modal})])} "Cancel"))))) (defsc DeviceInfo [this {:keys [id type name description profile labels adminState operatingState lastConnected lastReported addressable service]}] {:ident [:device :id] :query [:id :type :name :description :profile :labels :adminState :operatingState :lastConnected :lastReported :addressable :service]} (let [admin-str (if (= adminState :LOCKED) "Locked" "Unlocked") op-str (if (= operatingState :ENABLED) "Enabled" "Disabled") connected-str (co/conv-time lastConnected) reported-str (co/conv-time lastReported) serv-connected-str (co/conv-time (:lastConnected service)) serv-reported-str (co/conv-time (:lastReported service)) serv-admin-str (if (= (:adminState service) :LOCKED) "Locked" "Unlocked") serv-op-str (if (= (:operatingState service) :ENABLED) "Enabled" "Disabled")] (dom/div nil (dom/div #js {:className "card"} (dom/div #js {:className "fixed-table-toolbar"} (dom/div #js {:className "bars pull-right"} (b/button {:onClick #(routing/nav-to! this :main)} (dom/i #js {:className "glyphicon fa fa-caret-square-o-left"})))) (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Device")) (device-general-table id name description profile addressable labels)) (dom/div #js {:className "card"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Status")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Admin State" admin-str) (t/row "Operating State" op-str) (t/row "Last Connected" connected-str) (t/row "Last Reported" reported-str))))) (dom/div #js {:className "card"} (dom/div #js {:className "header"} (dom/h4 #js {:className "title"} "Service")) (dom/div #js {:className "table-responsive"} (dom/table #js {:className "table table-bordered"} (dom/tbody nil (t/row "Name" (:name service)) (t/row "Last Connected" serv-connected-str) (t/row "Last Reported" serv-reported-str) (t/row "Admin State" serv-admin-str) (t/row "Operating State" serv-op-str) (dom/tr nil (dom/th #js {:rowSpan "5"} "Address") (dom/th nil "Name") (dom/td nil (-> service :addressable :name))) (t/subrow "Protocol" (-> service :addressable :protocol)) (t/subrow "Address" (-> service :addressable :address)) (t/subrow "Port" (-> service :addressable :port)) (t/subrow "Path" (-> service :addressable :path))))))))) (defsc DeviceListEntry [this {:keys [id type name adminState operatingState lastConnected]} {:keys [onShow onCmds onDelete]}] {:ident [:device :id] :query [:id :type :name :adminState :operatingState :lastConnected]} (let [lastConnected-str (co/conv-time lastConnected) [op-icon op-icon-color] (if (= operatingState :ENABLED) ["fa fa-circle" "green"] ["fa fa-circle-o" "red"]) [lock-icon lock-action-icon lock-action-tip] (if (= adminState :LOCKED) ["fa fa-lock" "fa fa-unlock" "Unlock Device"] ["fa fa-unlock" "fa fa-lock" "Lock Device"])] (dom/tr nil (dom/td nil name) (dom/td #js {:className "text-center"} (dom/i #js {:className op-icon :style #js {:color op-icon-color} :aria-hidden "true"})) (dom/td #js {:className "text-center"} (dom/i #js {:className lock-icon :aria-hidden "true"})) (dom/td nil lastConnected-str) (dom/td #js {:className "td-actions text-right"} (dom/button #js {:type "button", :rel "tooltip", :title "View Device", :className "btn btn-info btn-simple btn-xs" :onClick #(onShow id)} (dom/i #js {:className "fa fa-info"})) (dom/button #js {:type "button", :rel "tooltip", :title lock-action-tip, :className "btn btn-success btn-simple btn-xs" :onClick #(show-admin-status-modal this id)} (dom/i #js {:className lock-action-icon})) (dom/button #js {:type "button", :rel "tooltip", :title "Control Device", :className "btn btn-danger btn-simple btn-xs" :onClick #(onCmds id)} (dom/i #js {:className "fa fa-dashboard"})) (dom/button #js {:type "button", :rel "tooltip", :title "Delete Device", :className "btn btn-danger btn-simple btn-xs" :onClick #(onDelete this type id)} (dom/i #js {:className "fa fa-times"})))))) (deftable DeviceList :show-devices :device [[:name "Name"] [:operatingState "Op Status"] [:adminState "Admin Status"] [:lastConnected "Last Seen"]] [{:onClick #(show-add-device-modal this) :icon "plus"} {:onClick #(df/refresh! this {:fallback `d/show-error}) :icon "refresh"}] :modals [{:modal d/DeleteModal :params {:modal-id :dd-modal} :callbacks {:onDelete do-delete-device}}] :actions [{:title :onShow :action-class :info :symbol "info" :onClick (fn [id] (routing/nav-to! this :info {:id id}))} {:title :onCmds :action-class :danger :symbol "times" :onClick (fn [id] (prim/transact! this `[(load-commands {:id ~id})]) (routing/nav-to! this :control))} {:title :onDelete :action-class :danger :symbol "times" :onClick (d/mk-show-modal :dd-modal)}] :row-symbol DeviceListEntry)
[ { "context": "serverTimezone=UTC\")\n :user db-user\n :password db-password\n :sql \"database/ebdb.sql\"})\n\n(def ebdb-test-con", "end": 737, "score": 0.9986637234687805, "start": 726, "tag": "PASSWORD", "value": "db-password" }, { "context": "ne=UTC\")\n :user db-user\n :password db-password))\n\n;; THIS FIXTURE REQUIRES A LOCAL MySQL DATABAS", "end": 4098, "score": 0.9034304618835449, "start": 4087, "tag": "PASSWORD", "value": "db-password" } ]
test/dashboard/test/db_tools.clj
Purple-Services/dashboard-service
3
(ns dashboard.test.db-tools (:require [common.db :as db] [environ.core :refer [env]] [clojure.java.jdbc :refer [with-connection do-commands]] [clojure.test :refer [use-fixtures deftest is test-ns testing]])) (defn ebdb-config "Given a map of the form {:db-host <str> ; hostname of db :db-port <int> :db-name <str> :db-user <str> :db-password <str> } return a configuration" [{:keys [db-host db-port db-name db-user db-password]}] {:classname "com.mysql.jdbc.Driver" :subprotocol "mysql" :subname (str "//" db-host ":" db-port "/" db-name "?useLegacyDatetimeCode=false" "&serverTimezone=UTC") :user db-user :password db-password :sql "database/ebdb.sql"}) (def ebdb-test-config "Configuration map for connecting to the local dev database." (ebdb-config {:db-host (env :test-db-host) :db-port (env :test-db-port) :db-name (env :test-db-name) :db-user (env :test-db-user) :db-password (env :test-db-password)})) ;; if you want to use different pools, do a ;; (set-new-db-pool! ;; (ebdb-config {:db-host <host> ;; :db-port <db-port> ;; :db-name <db-name> ;; :db-user <db-user> ;; :db-password <db-passowrd})) ;; or ;; (set-new-db-pool! ebdb-test-config) ;; be sure to run it again after connecting to the remote dev ;; database so that you are sure to close the connection ;; ex: ;; (set-new-db-pool! remote-ebdb-dev-config) ;; ... run some code ;; (set-new-db-pool! ebdb-test-config) (def local-ebdb-dev-config "Configuration map for connecting to the local dev database." (ebdb-config {:db-host (env :test-db-host) :db-port (env :test-db-port) :db-name (env :local-dev-db-name) :db-user (env :test-db-user) :db-password (env :test-db-password)})) (def remote-ebdb-dev-config "Configuration map for connecting to the remote dev database" (ebdb-config {:db-host (env :remote-dev-db-host) :db-port (env :test-db-port) :db-name (env :remote-dev-db-name) :db-user (env :test-db-user) :db-password (env :remote-dev-db-password)})) (defn process-sql "Process a SQL file into statements that can be applied with do-commands" [filename] (let [sql-lines (-> (slurp filename) ; read in the sql file (clojure.string/replace #"--.*\n" "") ; ignore sql comments (clojure.string/split #";\n") ; sepereate into statements )] (->> sql-lines (map #(clojure.string/replace % #"\n" "")) (filter #(not (clojure.string/blank? %)))))) (defn create-tables-and-populate-database "Create tables and load test data for a datbase" [db-config] (let [ebdb-sql (process-sql (:sql db-config))] (with-connection db-config (apply do-commands ebdb-sql)))) (defn clear-test-database [] ;; clear out all of the changes made to the ebdb_test database (with-connection ebdb-test-config (apply do-commands '("DROP DATABASE IF EXISTS ebdb_test" "CREATE DATABASE IF NOT EXISTS ebdb_test")))) (defn clear-and-populate-test-database [] ;; start with a clean ebdb_test database (clear-test-database) ;; populate the tables (create-tables-and-populate-database ebdb-test-config)) (defn reset-db! [] (clear-and-populate-test-database)) (defn clear-and-populate-test-database-fixture [t] (clear-and-populate-test-database) (t)) (defn setup-ebdb-test-pool! [] (db/set-pooled-db! ebdb-test-config) (clear-and-populate-test-database)) (defn set-ebdb-pool-host! "Given db-uri in the form" [db-uri db-user db-password] (assoc ebdb-test-config :subname (str "//" db-uri "?useLegacyDatetimeCode=false" "&serverTimezone=UTC") :user db-user :password db-password)) ;; THIS FIXTURE REQUIRES A LOCAL MySQL DATABASE THAT HAS GIVEN PROPER ;; PERMISSIONS TO purplemaster FOR ebdb_test, OTHERWISE TESTS WILL FAIL! (defn database-fixture "Remove all test data from the database" [t] (clear-and-populate-test-database) ;; run the test (t) (clear-test-database)) (defn setup-ebdb-test-for-conn-fixture [t] (setup-ebdb-test-pool!) (t) (clear-test-database) ;; close out the db connection (.close (:datasource (db/conn)))) (defn set-new-db-pool! [config] ;; close out the current db connect (.close (:datasource (db/conn))) ;; open the new one (db/set-pooled-db! config))
1011
(ns dashboard.test.db-tools (:require [common.db :as db] [environ.core :refer [env]] [clojure.java.jdbc :refer [with-connection do-commands]] [clojure.test :refer [use-fixtures deftest is test-ns testing]])) (defn ebdb-config "Given a map of the form {:db-host <str> ; hostname of db :db-port <int> :db-name <str> :db-user <str> :db-password <str> } return a configuration" [{:keys [db-host db-port db-name db-user db-password]}] {:classname "com.mysql.jdbc.Driver" :subprotocol "mysql" :subname (str "//" db-host ":" db-port "/" db-name "?useLegacyDatetimeCode=false" "&serverTimezone=UTC") :user db-user :password <PASSWORD> :sql "database/ebdb.sql"}) (def ebdb-test-config "Configuration map for connecting to the local dev database." (ebdb-config {:db-host (env :test-db-host) :db-port (env :test-db-port) :db-name (env :test-db-name) :db-user (env :test-db-user) :db-password (env :test-db-password)})) ;; if you want to use different pools, do a ;; (set-new-db-pool! ;; (ebdb-config {:db-host <host> ;; :db-port <db-port> ;; :db-name <db-name> ;; :db-user <db-user> ;; :db-password <db-passowrd})) ;; or ;; (set-new-db-pool! ebdb-test-config) ;; be sure to run it again after connecting to the remote dev ;; database so that you are sure to close the connection ;; ex: ;; (set-new-db-pool! remote-ebdb-dev-config) ;; ... run some code ;; (set-new-db-pool! ebdb-test-config) (def local-ebdb-dev-config "Configuration map for connecting to the local dev database." (ebdb-config {:db-host (env :test-db-host) :db-port (env :test-db-port) :db-name (env :local-dev-db-name) :db-user (env :test-db-user) :db-password (env :test-db-password)})) (def remote-ebdb-dev-config "Configuration map for connecting to the remote dev database" (ebdb-config {:db-host (env :remote-dev-db-host) :db-port (env :test-db-port) :db-name (env :remote-dev-db-name) :db-user (env :test-db-user) :db-password (env :remote-dev-db-password)})) (defn process-sql "Process a SQL file into statements that can be applied with do-commands" [filename] (let [sql-lines (-> (slurp filename) ; read in the sql file (clojure.string/replace #"--.*\n" "") ; ignore sql comments (clojure.string/split #";\n") ; sepereate into statements )] (->> sql-lines (map #(clojure.string/replace % #"\n" "")) (filter #(not (clojure.string/blank? %)))))) (defn create-tables-and-populate-database "Create tables and load test data for a datbase" [db-config] (let [ebdb-sql (process-sql (:sql db-config))] (with-connection db-config (apply do-commands ebdb-sql)))) (defn clear-test-database [] ;; clear out all of the changes made to the ebdb_test database (with-connection ebdb-test-config (apply do-commands '("DROP DATABASE IF EXISTS ebdb_test" "CREATE DATABASE IF NOT EXISTS ebdb_test")))) (defn clear-and-populate-test-database [] ;; start with a clean ebdb_test database (clear-test-database) ;; populate the tables (create-tables-and-populate-database ebdb-test-config)) (defn reset-db! [] (clear-and-populate-test-database)) (defn clear-and-populate-test-database-fixture [t] (clear-and-populate-test-database) (t)) (defn setup-ebdb-test-pool! [] (db/set-pooled-db! ebdb-test-config) (clear-and-populate-test-database)) (defn set-ebdb-pool-host! "Given db-uri in the form" [db-uri db-user db-password] (assoc ebdb-test-config :subname (str "//" db-uri "?useLegacyDatetimeCode=false" "&serverTimezone=UTC") :user db-user :password <PASSWORD>)) ;; THIS FIXTURE REQUIRES A LOCAL MySQL DATABASE THAT HAS GIVEN PROPER ;; PERMISSIONS TO purplemaster FOR ebdb_test, OTHERWISE TESTS WILL FAIL! (defn database-fixture "Remove all test data from the database" [t] (clear-and-populate-test-database) ;; run the test (t) (clear-test-database)) (defn setup-ebdb-test-for-conn-fixture [t] (setup-ebdb-test-pool!) (t) (clear-test-database) ;; close out the db connection (.close (:datasource (db/conn)))) (defn set-new-db-pool! [config] ;; close out the current db connect (.close (:datasource (db/conn))) ;; open the new one (db/set-pooled-db! config))
true
(ns dashboard.test.db-tools (:require [common.db :as db] [environ.core :refer [env]] [clojure.java.jdbc :refer [with-connection do-commands]] [clojure.test :refer [use-fixtures deftest is test-ns testing]])) (defn ebdb-config "Given a map of the form {:db-host <str> ; hostname of db :db-port <int> :db-name <str> :db-user <str> :db-password <str> } return a configuration" [{:keys [db-host db-port db-name db-user db-password]}] {:classname "com.mysql.jdbc.Driver" :subprotocol "mysql" :subname (str "//" db-host ":" db-port "/" db-name "?useLegacyDatetimeCode=false" "&serverTimezone=UTC") :user db-user :password PI:PASSWORD:<PASSWORD>END_PI :sql "database/ebdb.sql"}) (def ebdb-test-config "Configuration map for connecting to the local dev database." (ebdb-config {:db-host (env :test-db-host) :db-port (env :test-db-port) :db-name (env :test-db-name) :db-user (env :test-db-user) :db-password (env :test-db-password)})) ;; if you want to use different pools, do a ;; (set-new-db-pool! ;; (ebdb-config {:db-host <host> ;; :db-port <db-port> ;; :db-name <db-name> ;; :db-user <db-user> ;; :db-password <db-passowrd})) ;; or ;; (set-new-db-pool! ebdb-test-config) ;; be sure to run it again after connecting to the remote dev ;; database so that you are sure to close the connection ;; ex: ;; (set-new-db-pool! remote-ebdb-dev-config) ;; ... run some code ;; (set-new-db-pool! ebdb-test-config) (def local-ebdb-dev-config "Configuration map for connecting to the local dev database." (ebdb-config {:db-host (env :test-db-host) :db-port (env :test-db-port) :db-name (env :local-dev-db-name) :db-user (env :test-db-user) :db-password (env :test-db-password)})) (def remote-ebdb-dev-config "Configuration map for connecting to the remote dev database" (ebdb-config {:db-host (env :remote-dev-db-host) :db-port (env :test-db-port) :db-name (env :remote-dev-db-name) :db-user (env :test-db-user) :db-password (env :remote-dev-db-password)})) (defn process-sql "Process a SQL file into statements that can be applied with do-commands" [filename] (let [sql-lines (-> (slurp filename) ; read in the sql file (clojure.string/replace #"--.*\n" "") ; ignore sql comments (clojure.string/split #";\n") ; sepereate into statements )] (->> sql-lines (map #(clojure.string/replace % #"\n" "")) (filter #(not (clojure.string/blank? %)))))) (defn create-tables-and-populate-database "Create tables and load test data for a datbase" [db-config] (let [ebdb-sql (process-sql (:sql db-config))] (with-connection db-config (apply do-commands ebdb-sql)))) (defn clear-test-database [] ;; clear out all of the changes made to the ebdb_test database (with-connection ebdb-test-config (apply do-commands '("DROP DATABASE IF EXISTS ebdb_test" "CREATE DATABASE IF NOT EXISTS ebdb_test")))) (defn clear-and-populate-test-database [] ;; start with a clean ebdb_test database (clear-test-database) ;; populate the tables (create-tables-and-populate-database ebdb-test-config)) (defn reset-db! [] (clear-and-populate-test-database)) (defn clear-and-populate-test-database-fixture [t] (clear-and-populate-test-database) (t)) (defn setup-ebdb-test-pool! [] (db/set-pooled-db! ebdb-test-config) (clear-and-populate-test-database)) (defn set-ebdb-pool-host! "Given db-uri in the form" [db-uri db-user db-password] (assoc ebdb-test-config :subname (str "//" db-uri "?useLegacyDatetimeCode=false" "&serverTimezone=UTC") :user db-user :password PI:PASSWORD:<PASSWORD>END_PI)) ;; THIS FIXTURE REQUIRES A LOCAL MySQL DATABASE THAT HAS GIVEN PROPER ;; PERMISSIONS TO purplemaster FOR ebdb_test, OTHERWISE TESTS WILL FAIL! (defn database-fixture "Remove all test data from the database" [t] (clear-and-populate-test-database) ;; run the test (t) (clear-test-database)) (defn setup-ebdb-test-for-conn-fixture [t] (setup-ebdb-test-pool!) (t) (clear-test-database) ;; close out the db connection (.close (:datasource (db/conn)))) (defn set-new-db-pool! [config] ;; close out the current db connect (.close (:datasource (db/conn))) ;; open the new one (db/set-pooled-db! config))
[ { "context": "type\" 2})\n (document/create-with-key {:name \"Bob\" :age 28} \"bob-key\" :people)\n (document/crea", "end": 1055, "score": 0.9996239542961121, "start": 1052, "tag": "NAME", "value": "Bob" }, { "context": " :people)\n (document/create-with-key {:name \"Peter\" :age 25} \"peter-key\" :people)\n ;; perform q", "end": 1130, "score": 0.9997100830078125, "start": 1125, "tag": "NAME", "value": "Peter" } ]
test/clarango/test/query.clj
Lepetere/clarango
25
(ns clarango.test.query (:require [clojure.test :refer :all] [clarango.core :as cla-core] [clarango.document :as document] [clarango.collection :as collection] [clarango.database :as database] [clarango.query :as query]) (:use clojure.pprint) (:use clarango.core)) ; Test data (lifted from the ArangoDB docs) (def func-name "myfunctions::temperature::celsiustofahrenheit") (def func-code "function (celsius) { return celsius * 1.8 + 32; }") (defn setup [] (cla-core/set-connection!) (database/create "QueryTestDB" [])) (defn teardown [] (database/delete "QueryTestDB")) (defn fixture [f] (setup) (f) (teardown)) (use-fixtures :each fixture) (defn to-map [data] (into {} (map (fn [[k v]] [(keyword k) v]) data))) (deftest graph-and-query-and-traversal-test (testing "perform query: find all people who are older than 24" (with-db "QueryTestDB" ;; create test data (collection/create :people {"type" 2}) (document/create-with-key {:name "Bob" :age 28} "bob-key" :people) (document/create-with-key {:name "Peter" :age 25} "peter-key" :people) ;; perform query tests (is (= false (get (query/validate "FOR p IN people FILTER p.age > 24 RETURN p") "error"))) (let [explain-result (query/explain "FOR p IN people FILTER p.age > 24 RETURN p")] (is (every? true? [(contains? explain-result "nodes") (contains? explain-result "rules") (contains? explain-result "collections") (contains? explain-result "variables")]))) (let [execute-result (query/execute "FOR p IN people FILTER p.age > 24 RETURN p")] (is (= false (get execute-result "hasMore"))) (is (= 2 (count (get execute-result "result")))))))) (deftest create-functions-test (testing "Creating non existing function (by name) returns 201" (let [result (to-map (query/new-function func-name func-code))] (is (:code result) 201))) (testing "Updating existing function (by name) returns 200" (let [result (to-map (query/new-function func-name func-code))] (is (:code result) 200))) ;; ArangoDB doesn't appear to have a function to clear down, ;;so we need to do it ourselves. (query/delete-function func-name)) (deftest get-functions-list (query/new-function func-name func-code) (testing "GET all functions returns a list" (let [result (query/get-functions)] (is (true? (seq? result))))) (testing "GET all functions returns function name as 'name'" (let [result (to-map (first (query/get-functions)))] (is (= func-name (:name result))))) (testing "GET all functions returns function code as 'code'" (let [result (to-map (first (query/get-functions)))] (is (= func-code (:code result))))) (query/delete-function func-name))
122285
(ns clarango.test.query (:require [clojure.test :refer :all] [clarango.core :as cla-core] [clarango.document :as document] [clarango.collection :as collection] [clarango.database :as database] [clarango.query :as query]) (:use clojure.pprint) (:use clarango.core)) ; Test data (lifted from the ArangoDB docs) (def func-name "myfunctions::temperature::celsiustofahrenheit") (def func-code "function (celsius) { return celsius * 1.8 + 32; }") (defn setup [] (cla-core/set-connection!) (database/create "QueryTestDB" [])) (defn teardown [] (database/delete "QueryTestDB")) (defn fixture [f] (setup) (f) (teardown)) (use-fixtures :each fixture) (defn to-map [data] (into {} (map (fn [[k v]] [(keyword k) v]) data))) (deftest graph-and-query-and-traversal-test (testing "perform query: find all people who are older than 24" (with-db "QueryTestDB" ;; create test data (collection/create :people {"type" 2}) (document/create-with-key {:name "<NAME>" :age 28} "bob-key" :people) (document/create-with-key {:name "<NAME>" :age 25} "peter-key" :people) ;; perform query tests (is (= false (get (query/validate "FOR p IN people FILTER p.age > 24 RETURN p") "error"))) (let [explain-result (query/explain "FOR p IN people FILTER p.age > 24 RETURN p")] (is (every? true? [(contains? explain-result "nodes") (contains? explain-result "rules") (contains? explain-result "collections") (contains? explain-result "variables")]))) (let [execute-result (query/execute "FOR p IN people FILTER p.age > 24 RETURN p")] (is (= false (get execute-result "hasMore"))) (is (= 2 (count (get execute-result "result")))))))) (deftest create-functions-test (testing "Creating non existing function (by name) returns 201" (let [result (to-map (query/new-function func-name func-code))] (is (:code result) 201))) (testing "Updating existing function (by name) returns 200" (let [result (to-map (query/new-function func-name func-code))] (is (:code result) 200))) ;; ArangoDB doesn't appear to have a function to clear down, ;;so we need to do it ourselves. (query/delete-function func-name)) (deftest get-functions-list (query/new-function func-name func-code) (testing "GET all functions returns a list" (let [result (query/get-functions)] (is (true? (seq? result))))) (testing "GET all functions returns function name as 'name'" (let [result (to-map (first (query/get-functions)))] (is (= func-name (:name result))))) (testing "GET all functions returns function code as 'code'" (let [result (to-map (first (query/get-functions)))] (is (= func-code (:code result))))) (query/delete-function func-name))
true
(ns clarango.test.query (:require [clojure.test :refer :all] [clarango.core :as cla-core] [clarango.document :as document] [clarango.collection :as collection] [clarango.database :as database] [clarango.query :as query]) (:use clojure.pprint) (:use clarango.core)) ; Test data (lifted from the ArangoDB docs) (def func-name "myfunctions::temperature::celsiustofahrenheit") (def func-code "function (celsius) { return celsius * 1.8 + 32; }") (defn setup [] (cla-core/set-connection!) (database/create "QueryTestDB" [])) (defn teardown [] (database/delete "QueryTestDB")) (defn fixture [f] (setup) (f) (teardown)) (use-fixtures :each fixture) (defn to-map [data] (into {} (map (fn [[k v]] [(keyword k) v]) data))) (deftest graph-and-query-and-traversal-test (testing "perform query: find all people who are older than 24" (with-db "QueryTestDB" ;; create test data (collection/create :people {"type" 2}) (document/create-with-key {:name "PI:NAME:<NAME>END_PI" :age 28} "bob-key" :people) (document/create-with-key {:name "PI:NAME:<NAME>END_PI" :age 25} "peter-key" :people) ;; perform query tests (is (= false (get (query/validate "FOR p IN people FILTER p.age > 24 RETURN p") "error"))) (let [explain-result (query/explain "FOR p IN people FILTER p.age > 24 RETURN p")] (is (every? true? [(contains? explain-result "nodes") (contains? explain-result "rules") (contains? explain-result "collections") (contains? explain-result "variables")]))) (let [execute-result (query/execute "FOR p IN people FILTER p.age > 24 RETURN p")] (is (= false (get execute-result "hasMore"))) (is (= 2 (count (get execute-result "result")))))))) (deftest create-functions-test (testing "Creating non existing function (by name) returns 201" (let [result (to-map (query/new-function func-name func-code))] (is (:code result) 201))) (testing "Updating existing function (by name) returns 200" (let [result (to-map (query/new-function func-name func-code))] (is (:code result) 200))) ;; ArangoDB doesn't appear to have a function to clear down, ;;so we need to do it ourselves. (query/delete-function func-name)) (deftest get-functions-list (query/new-function func-name func-code) (testing "GET all functions returns a list" (let [result (query/get-functions)] (is (true? (seq? result))))) (testing "GET all functions returns function name as 'name'" (let [result (to-map (first (query/get-functions)))] (is (= func-name (:name result))))) (testing "GET all functions returns function code as 'code'" (let [result (to-map (first (query/get-functions)))] (is (= func-code (:code result))))) (query/delete-function func-name))
[ { "context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998871684074402, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
test/territory_bro/infra/user_test.clj
3breadt/territory-bro
2
;; Copyright © 2015-2020 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns ^:slow territory-bro.infra.user-test (:require [clojure.java.jdbc :as jdbc] [clojure.test :refer :all] [territory-bro.infra.db :as db] [territory-bro.infra.user :as user] [territory-bro.test.fixtures :refer [db-fixture]] [territory-bro.test.testutil :refer [re-equals]]) (:import (java.util UUID) (territory_bro ValidationException))) (use-fixtures :once db-fixture) (defn subjects [users] (->> users (map :user/subject) (sort))) (deftest users-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [user-id (user/save-user! conn "user1" {:name "User 1"}) unrelated-user-id (user/save-user! conn "user2" {:name "User 2"}) unrelated-user (user/get-by-id conn unrelated-user-id)] (testing "create new user" (is user-id) (is (= {:user/id user-id :user/subject "user1" :user/attributes {:name "User 1"}} (user/get-by-id conn user-id)))) (testing "update existing user" (is (= user-id (user/save-user! conn "user1" {:name "new name"})) "should return same ID as before") (is (= {:user/id user-id :user/subject "user1" :user/attributes {:name "new name"}} (user/get-by-id conn user-id)) "should update attributes")) (testing "list users" (is (= ["user1" "user2"] (subjects (user/get-users conn))))) (testing "find users by IDs" (is (= ["user1"] (subjects (user/get-users conn {:ids [user-id]})))) (is (= ["user1" "user2"] (subjects (user/get-users conn {:ids [user-id unrelated-user-id]})))) (is (= [] (subjects (user/get-users conn {:ids []})))) (is (= [] (subjects (user/get-users conn {:ids nil}))))) (testing "find user by ID" (is (= user-id (:user/id (user/get-by-id conn user-id)))) (is (nil? (user/get-by-id conn (UUID/randomUUID))) "not found")) (testing "find users by subjects" (is (= ["user1"] (subjects (user/get-users conn {:subjects ["user1"]})))) (is (= ["user1" "user2"] (subjects (user/get-users conn {:subjects ["user1" "user2"]})))) (is (= [] (subjects (user/get-users conn {:subjects []})))) (is (= [] (subjects (user/get-users conn {:subjects nil}))))) (testing "find user by subject" (is (= user-id (:user/id (user/get-by-subject conn "user1")))) (is (nil? (user/get-by-subject conn "no-such-user")) "not found")) (testing "did not accidentally change unrelated users" (is (= unrelated-user (user/get-by-id conn unrelated-user-id))))))) (deftest check-user-exists-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [user-id (user/save-user! conn "user1" {:name "User 1"})] (testing "exists" (is (nil? (user/check-user-exists conn user-id)))) (testing "doesn't exist" (is (thrown-with-msg? ValidationException (re-equals "[[:no-such-user #uuid \"00000000-0000-0000-0000-000000000666\"]]") (user/check-user-exists conn (UUID. 0 0x666))))))))
112680
;; Copyright © 2015-2020 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns ^:slow territory-bro.infra.user-test (:require [clojure.java.jdbc :as jdbc] [clojure.test :refer :all] [territory-bro.infra.db :as db] [territory-bro.infra.user :as user] [territory-bro.test.fixtures :refer [db-fixture]] [territory-bro.test.testutil :refer [re-equals]]) (:import (java.util UUID) (territory_bro ValidationException))) (use-fixtures :once db-fixture) (defn subjects [users] (->> users (map :user/subject) (sort))) (deftest users-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [user-id (user/save-user! conn "user1" {:name "User 1"}) unrelated-user-id (user/save-user! conn "user2" {:name "User 2"}) unrelated-user (user/get-by-id conn unrelated-user-id)] (testing "create new user" (is user-id) (is (= {:user/id user-id :user/subject "user1" :user/attributes {:name "User 1"}} (user/get-by-id conn user-id)))) (testing "update existing user" (is (= user-id (user/save-user! conn "user1" {:name "new name"})) "should return same ID as before") (is (= {:user/id user-id :user/subject "user1" :user/attributes {:name "new name"}} (user/get-by-id conn user-id)) "should update attributes")) (testing "list users" (is (= ["user1" "user2"] (subjects (user/get-users conn))))) (testing "find users by IDs" (is (= ["user1"] (subjects (user/get-users conn {:ids [user-id]})))) (is (= ["user1" "user2"] (subjects (user/get-users conn {:ids [user-id unrelated-user-id]})))) (is (= [] (subjects (user/get-users conn {:ids []})))) (is (= [] (subjects (user/get-users conn {:ids nil}))))) (testing "find user by ID" (is (= user-id (:user/id (user/get-by-id conn user-id)))) (is (nil? (user/get-by-id conn (UUID/randomUUID))) "not found")) (testing "find users by subjects" (is (= ["user1"] (subjects (user/get-users conn {:subjects ["user1"]})))) (is (= ["user1" "user2"] (subjects (user/get-users conn {:subjects ["user1" "user2"]})))) (is (= [] (subjects (user/get-users conn {:subjects []})))) (is (= [] (subjects (user/get-users conn {:subjects nil}))))) (testing "find user by subject" (is (= user-id (:user/id (user/get-by-subject conn "user1")))) (is (nil? (user/get-by-subject conn "no-such-user")) "not found")) (testing "did not accidentally change unrelated users" (is (= unrelated-user (user/get-by-id conn unrelated-user-id))))))) (deftest check-user-exists-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [user-id (user/save-user! conn "user1" {:name "User 1"})] (testing "exists" (is (nil? (user/check-user-exists conn user-id)))) (testing "doesn't exist" (is (thrown-with-msg? ValidationException (re-equals "[[:no-such-user #uuid \"00000000-0000-0000-0000-000000000666\"]]") (user/check-user-exists conn (UUID. 0 0x666))))))))
true
;; Copyright © 2015-2020 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns ^:slow territory-bro.infra.user-test (:require [clojure.java.jdbc :as jdbc] [clojure.test :refer :all] [territory-bro.infra.db :as db] [territory-bro.infra.user :as user] [territory-bro.test.fixtures :refer [db-fixture]] [territory-bro.test.testutil :refer [re-equals]]) (:import (java.util UUID) (territory_bro ValidationException))) (use-fixtures :once db-fixture) (defn subjects [users] (->> users (map :user/subject) (sort))) (deftest users-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [user-id (user/save-user! conn "user1" {:name "User 1"}) unrelated-user-id (user/save-user! conn "user2" {:name "User 2"}) unrelated-user (user/get-by-id conn unrelated-user-id)] (testing "create new user" (is user-id) (is (= {:user/id user-id :user/subject "user1" :user/attributes {:name "User 1"}} (user/get-by-id conn user-id)))) (testing "update existing user" (is (= user-id (user/save-user! conn "user1" {:name "new name"})) "should return same ID as before") (is (= {:user/id user-id :user/subject "user1" :user/attributes {:name "new name"}} (user/get-by-id conn user-id)) "should update attributes")) (testing "list users" (is (= ["user1" "user2"] (subjects (user/get-users conn))))) (testing "find users by IDs" (is (= ["user1"] (subjects (user/get-users conn {:ids [user-id]})))) (is (= ["user1" "user2"] (subjects (user/get-users conn {:ids [user-id unrelated-user-id]})))) (is (= [] (subjects (user/get-users conn {:ids []})))) (is (= [] (subjects (user/get-users conn {:ids nil}))))) (testing "find user by ID" (is (= user-id (:user/id (user/get-by-id conn user-id)))) (is (nil? (user/get-by-id conn (UUID/randomUUID))) "not found")) (testing "find users by subjects" (is (= ["user1"] (subjects (user/get-users conn {:subjects ["user1"]})))) (is (= ["user1" "user2"] (subjects (user/get-users conn {:subjects ["user1" "user2"]})))) (is (= [] (subjects (user/get-users conn {:subjects []})))) (is (= [] (subjects (user/get-users conn {:subjects nil}))))) (testing "find user by subject" (is (= user-id (:user/id (user/get-by-subject conn "user1")))) (is (nil? (user/get-by-subject conn "no-such-user")) "not found")) (testing "did not accidentally change unrelated users" (is (= unrelated-user (user/get-by-id conn unrelated-user-id))))))) (deftest check-user-exists-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [user-id (user/save-user! conn "user1" {:name "User 1"})] (testing "exists" (is (nil? (user/check-user-exists conn user-id)))) (testing "doesn't exist" (is (thrown-with-msg? ValidationException (re-equals "[[:no-such-user #uuid \"00000000-0000-0000-0000-000000000666\"]]") (user/check-user-exists conn (UUID. 0 0x666))))))))
[ { "context": "(ns ^{:author \"Janos Erdos\"} erdos.sample\n (:require [erdos.sample.avl :a", "end": 26, "score": 0.9998729825019836, "start": 15, "tag": "NAME", "value": "Janos Erdos" } ]
src/erdos/sample.clj
erdos/erdos.sample
2
(ns ^{:author "Janos Erdos"} erdos.sample (:require [erdos.sample.avl :as avl])) (defn sample-seq "Given a map of [sample probability] pairs, returns a lazy seq of random samples." [kps] (assert (map? kps)) (assert (every? number? (vals kps))) (let [vkps (map float (vals kps)) sum (reduce + vkps) vs (for [v vkps] (/ v sum)) intervals (reductions + 0 vs) tree (apply sorted-map (interleave intervals (keys kps)))] (repeatedly #(val (first (.seqFrom ^clojure.lang.Sorted tree (rand) false)))))) (defn sample-tree "Given a map of [sample probability] pairs, returns an object that returns random sample when deref-ed. The returned object has support for fast conj, disj, count, assoc, dissoc, get, deref, count." [kps] (avl/sample-tree kps))
34919
(ns ^{:author "<NAME>"} erdos.sample (:require [erdos.sample.avl :as avl])) (defn sample-seq "Given a map of [sample probability] pairs, returns a lazy seq of random samples." [kps] (assert (map? kps)) (assert (every? number? (vals kps))) (let [vkps (map float (vals kps)) sum (reduce + vkps) vs (for [v vkps] (/ v sum)) intervals (reductions + 0 vs) tree (apply sorted-map (interleave intervals (keys kps)))] (repeatedly #(val (first (.seqFrom ^clojure.lang.Sorted tree (rand) false)))))) (defn sample-tree "Given a map of [sample probability] pairs, returns an object that returns random sample when deref-ed. The returned object has support for fast conj, disj, count, assoc, dissoc, get, deref, count." [kps] (avl/sample-tree kps))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} erdos.sample (:require [erdos.sample.avl :as avl])) (defn sample-seq "Given a map of [sample probability] pairs, returns a lazy seq of random samples." [kps] (assert (map? kps)) (assert (every? number? (vals kps))) (let [vkps (map float (vals kps)) sum (reduce + vkps) vs (for [v vkps] (/ v sum)) intervals (reductions + 0 vs) tree (apply sorted-map (interleave intervals (keys kps)))] (repeatedly #(val (first (.seqFrom ^clojure.lang.Sorted tree (rand) false)))))) (defn sample-tree "Given a map of [sample probability] pairs, returns an object that returns random sample when deref-ed. The returned object has support for fast conj, disj, count, assoc, dissoc, get, deref, count." [kps] (avl/sample-tree kps))
[ { "context": "omposition))\n\n; Example data\n(def cars\n [{:name \"Ferrari FF\"\n :horsepower 660\n :dollar-value 700000\n ", "end": 163, "score": 0.9992900490760803, "start": 153, "tag": "NAME", "value": "Ferrari FF" }, { "context": "ollar-value 700000\n :in-stock true}\n {:name \"Spyker C12 Zagato\"\n :horsepower 650\n :dollar-value 648000\n ", "end": 258, "score": 0.999840259552002, "start": 241, "tag": "NAME", "value": "Spyker C12 Zagato" }, { "context": "llar-value 648000\n :in-stock false}\n {:name \"Jaguar XKR-S\"\n :horsepower 550\n :dollar-value 132000\n ", "end": 349, "score": 0.9977506995201111, "start": 337, "tag": "NAME", "value": "Jaguar XKR-S" }, { "context": "llar-value 132000\n :in-stock false}\n {:name \"Audi R8\"\n :horsepower 525\n :dollar-value 114200\n ", "end": 435, "score": 0.9996638298034668, "start": 428, "tag": "NAME", "value": "Audi R8" }, { "context": "llar-value 114200\n :in-stock false}\n {:name \"Aston Martin One-77\"\n :horsepower 750\n :dollar-value 1850000", "end": 530, "score": 0.901211142539978, "start": 514, "tag": "NAME", "value": "Aston Martin One" }, { "context": "llar-value 1850000\n :in-stock true}\n {:name \"Pagani Huayra\"\n :horsepower 700\n :dollar-value 1300000\n ", "end": 625, "score": 0.9998883008956909, "start": 612, "tag": "NAME", "value": "Pagani Huayra" }, { "context": "\n(expect false (is-last-in-stock cars))\n\n(expect \"Ferrari FF\" (name-of-first-car cars))\n\n(expect 790700 (avera", "end": 804, "score": 0.89336097240448, "start": 794, "tag": "NAME", "value": "Ferrari FF" } ]
test/clojuring/mostly_adequate/ch5/composition_test.clj
ilmotta/clojuring
4
(ns clojuring.mostly-adequate.ch5.composition-test (:use expectations clojuring.mostly-adequate.ch5.composition)) ; Example data (def cars [{:name "Ferrari FF" :horsepower 660 :dollar-value 700000 :in-stock true} {:name "Spyker C12 Zagato" :horsepower 650 :dollar-value 648000 :in-stock false} {:name "Jaguar XKR-S" :horsepower 550 :dollar-value 132000 :in-stock false} {:name "Audi R8" :horsepower 525 :dollar-value 114200 :in-stock false} {:name "Aston Martin One-77" :horsepower 750 :dollar-value 1850000 :in-stock true} {:name "Pagani Huayra" :horsepower 700 :dollar-value 1300000 :in-stock false}]) (expect false (is-last-in-stock-original cars)) (expect false (is-last-in-stock cars)) (expect "Ferrari FF" (name-of-first-car cars)) (expect 790700 (average-dollar-value-original cars)) (expect 790700 (average-dollar-value cars)) (expect ["ferrari_ff"] (sanitize-names (take 1 cars))) (expect ["ferrari_ff"] (sanitize-names-2 (take 1 cars))) (expect ["ferrari_ff"] (sanitize-names-with-thread-last-macro (take 1 cars))) (expect "money-700000, money-1850000" (available-prices-original cars)) (expect "money-700000, money-1850000" (available-prices cars)) (expect "money-700000, money-1850000" (available-prices-with-thread cars))
111643
(ns clojuring.mostly-adequate.ch5.composition-test (:use expectations clojuring.mostly-adequate.ch5.composition)) ; Example data (def cars [{:name "<NAME>" :horsepower 660 :dollar-value 700000 :in-stock true} {:name "<NAME>" :horsepower 650 :dollar-value 648000 :in-stock false} {:name "<NAME>" :horsepower 550 :dollar-value 132000 :in-stock false} {:name "<NAME>" :horsepower 525 :dollar-value 114200 :in-stock false} {:name "<NAME>-77" :horsepower 750 :dollar-value 1850000 :in-stock true} {:name "<NAME>" :horsepower 700 :dollar-value 1300000 :in-stock false}]) (expect false (is-last-in-stock-original cars)) (expect false (is-last-in-stock cars)) (expect "<NAME>" (name-of-first-car cars)) (expect 790700 (average-dollar-value-original cars)) (expect 790700 (average-dollar-value cars)) (expect ["ferrari_ff"] (sanitize-names (take 1 cars))) (expect ["ferrari_ff"] (sanitize-names-2 (take 1 cars))) (expect ["ferrari_ff"] (sanitize-names-with-thread-last-macro (take 1 cars))) (expect "money-700000, money-1850000" (available-prices-original cars)) (expect "money-700000, money-1850000" (available-prices cars)) (expect "money-700000, money-1850000" (available-prices-with-thread cars))
true
(ns clojuring.mostly-adequate.ch5.composition-test (:use expectations clojuring.mostly-adequate.ch5.composition)) ; Example data (def cars [{:name "PI:NAME:<NAME>END_PI" :horsepower 660 :dollar-value 700000 :in-stock true} {:name "PI:NAME:<NAME>END_PI" :horsepower 650 :dollar-value 648000 :in-stock false} {:name "PI:NAME:<NAME>END_PI" :horsepower 550 :dollar-value 132000 :in-stock false} {:name "PI:NAME:<NAME>END_PI" :horsepower 525 :dollar-value 114200 :in-stock false} {:name "PI:NAME:<NAME>END_PI-77" :horsepower 750 :dollar-value 1850000 :in-stock true} {:name "PI:NAME:<NAME>END_PI" :horsepower 700 :dollar-value 1300000 :in-stock false}]) (expect false (is-last-in-stock-original cars)) (expect false (is-last-in-stock cars)) (expect "PI:NAME:<NAME>END_PI" (name-of-first-car cars)) (expect 790700 (average-dollar-value-original cars)) (expect 790700 (average-dollar-value cars)) (expect ["ferrari_ff"] (sanitize-names (take 1 cars))) (expect ["ferrari_ff"] (sanitize-names-2 (take 1 cars))) (expect ["ferrari_ff"] (sanitize-names-with-thread-last-macro (take 1 cars))) (expect "money-700000, money-1850000" (available-prices-original cars)) (expect "money-700000, money-1850000" (available-prices cars)) (expect "money-700000, money-1850000" (available-prices-with-thread cars))
[ { "context": "Column {:width 6}\n [ui/Embed {:id \"yYJ6laT_6M4\"\n :placeholder \"https://i", "end": 2311, "score": 0.6496841311454773, "start": 2307, "tag": "USERNAME", "value": "yYJ6" }, { "context": " {:width 6}\n [ui/Embed {:id \"yYJ6laT_6M4\"\n :placeholder \"https://img.", "end": 2314, "score": 0.5655603408813477, "start": 2313, "tag": "USERNAME", "value": "T" }, { "context": "[:a {:target \"_blank\"\n :key \"nuvlabox-engine-quickstart\"\n :href \"https://docs.nuvla.i", "end": 5602, "score": 0.9993689060211182, "start": 5576, "tag": "KEY", "value": "nuvlabox-engine-quickstart" }, { "context": "[:a {:target \"_blank\"\n :key \"video-nuvlabox-engine-quickstart\"\n :href \"https://docs.nuvla.i", "end": 9076, "score": 0.9991153478622437, "start": 9044, "tag": "KEY", "value": "video-nuvlabox-engine-quickstart" } ]
code/src/cljs/sixsq/nuvla/ui/welcome/views.cljs
nuvla/ui
8
(ns sixsq.nuvla.ui.welcome.views (:require [clojure.string :as str] [re-frame.core :refer [dispatch subscribe]] [sixsq.nuvla.ui.history.events :as history-events] [sixsq.nuvla.ui.i18n.subs :as i18n-subs] [sixsq.nuvla.ui.main.subs :as main-subs] [sixsq.nuvla.ui.panel :as panel] [sixsq.nuvla.ui.utils.semantic-ui :as ui])) (defn navigate-link [target-page text] [:a {:on-click #(dispatch [::history-events/navigate target-page]) :style {:cursor "pointer"}} text]) (defn step [number title & content] [ui/Step [ui/ListSA ^{:key title} [ui/ListItem (when-not (nil? number) [ui/Icon [ui/Label {:size :big, :circular true, :color "blue"} number]]) [ui/ListContent [ui/ListHeader title] [ui/ListDescription content]]]]]) (defmethod panel/render :welcome [path] (let [tr (subscribe [::i18n-subs/tr]) query-params (subscribe [::main-subs/nav-query-params]) {:keys [message, error]} @query-params] (when @query-params (when (or message error) (dispatch [:sixsq.nuvla.ui.main.events/set-message (if error :error :success) (or error message)])) (dispatch [::history-events/navigate (str (first path) "/")])) [:<> [ui/Grid {:stackable true :centered true :verticalAlign :middle :reversed :mobile :style {:margin-top "8px"}} [ui/GridColumn {:width 6} [ui/Header {:as "h1"} (@tr [:welcome-header])] [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-subheader])] [ui/HeaderSubheader {:as "h3"} (@tr [:welcome-subsubheader])] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :primary :button] :href "#add-nuvlabox"} (@tr [:welcome-create-nuvlabox])]] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :primary :button] :href "#launch-app"} (@tr [:welcome-launch-app])]] [ui/HeaderSubheader {:as "h3"} (@tr [:welcome-more-advanced])] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :button] :href "#video-at-the-edge"} (@tr [:welcome-process-video-at-edge])]]] [ui/GridColumn {:width 6} [ui/Embed {:id "yYJ6laT_6M4" :placeholder "https://img.youtube.com/vi/yYJ6laT_6M4/maxresdefault.jpg" :source "youtube"}]]] [ui/Divider] [ui/Header {:as "h2" :style {:text-align :center} :size :huge} (@tr [:welcome-resources])] [ui/HeaderSubheader {:as "h3" :style {:text-align :center}} (@tr [:welcome-resources-subheader])] [ui/CardGroup {:stackable true :centered true :columns 4} [ui/Card [ui/CardContent {:text-align :center} [ui/Header {:as :h2} (str/capitalize (@tr [:documentation]))] [ui/Icon {:name "book" :size "massive" :color "blue"}] [ui/Header {:as :h4} (@tr [:welcome-doc-subheader-pre]) " " [:a {:href "https://docs.nuvla.io"} (@tr [:here])] " " (@tr [:welcome-doc-subheader-post])]]] [ui/Card [ui/CardContent {:text-align :center} [ui/Header {:as :h2} (str/capitalize (@tr [:videos]))] [ui/Icon {:name "video" :size "massive" :color "blue"}] [ui/Header {:as :h4} (@tr [:welcome-video-subheader-pre]) " " [:a {:href "https://sixsq.com/media/videos.html"} (@tr [:video-channel])] " " (@tr [:welcome-video-subheader-post])]]]] [ui/Divider] [ui/Header {:as "h2" :style {:text-align :center} :size :huge} (@tr [:welcome-how-to-header])] [ui/HeaderSubheader {:as "h3" :style {:text-align :center :padding-bottom "20px"}} (@tr [:welcome-how-to-subheader])] [ui/Grid {:id :add-nuvlabox :centered true :stackable true :verticalAlign :middle} [ui/GridColumn {:width 6} [ui/Image {:floated "right" :src "/ui/images/welcome-nb.png" :fluid true}]] [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-how-to-nb-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-nb-subheader]) " " [:a {:href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine"} (@tr [:here])] "."] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-nb-1-header]) (@tr [:welcome-how-to-nb-1-subheader-pre]) " " [:a {:target "_blank" :key "nuvlabox-engine-requirements" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/requirements"} (@tr [:welcome-how-to-nb-1-subheader-mid])] " " (@tr [:welcome-how-to-nb-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-nb-2-header]) (@tr [:welcome-how-to-nb-2-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-nb-2-subheader-mid])} [navigate-link "edge" (@tr [:welcome-how-to-nb-2-subheader-mid])] " " (@tr [:welcome-how-to-nb-2-subheader-post]) ".") (step 3 (@tr [:welcome-how-to-nb-3-header]) (@tr [:welcome-how-to-nb-3-subheader-pre]) " " [:a {:target "_blank" :key "nuvlabox-engine-quickstart" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/quickstart"} (@tr [:documentation])] " " (@tr [:welcome-how-to-nb-3-subheader-post]) ".") (step 4 (@tr [:welcome-how-to-nb-4-header]) (@tr [:welcome-how-to-nb-4-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-nb-4-subheader-mid])} [navigate-link "edge" (@tr [:welcome-how-to-nb-4-subheader-mid])] ". " (@tr [:welcome-how-to-nb-4-subheader-post]) ".") (step 5 (@tr [:welcome-how-to-nb-5-header]) (@tr [:welcome-how-to-nb-5-subheader-pre]) ". " ^{:key (@tr [:show-me])} [:a {:href "#deploy-app"} (str/capitalize (@tr [:show-me]))] ".")]]] [ui/Divider] [ui/Grid {:id :launch-app :centered true :stackable true :verticalAlign :middle :reversed "mobile"} [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2", :id "deploy-app"} (@tr [:welcome-how-to-launch-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-launch-subheader]) " " [:a {:href "https://docs.nuvla.io/nuvla/launch-app"} (@tr [:here])] "."] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-launch-1-header-]) (@tr [:welcome-how-to-launch-1-subheader-pre]) " " ^{:key (@tr [:appstore])} [navigate-link "apps" (@tr [:appstore])] " " (@tr [:welcome-how-to-launch-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-launch-2-header]) (@tr [:welcome-how-to-launch-2-subheader-pre])) (step 3 (@tr [:welcome-how-to-launch-3-header]) (@tr [:welcome-how-to-launch-3-subheader-pre]) " ") (step 4 (@tr [:welcome-how-to-launch-4-header]) (@tr [:welcome-how-to-launch-4-subheader-pre]) " " ^{:key (@tr [:dashboard])} [navigate-link "dashboard" (@tr [:dashboard])] ", " (@tr [:welcome-how-to-launch-4-subheader-post]) ".")]] [ui/GridColumn {:width 6} [ui/Image {:floated "right" :src "/ui/images/welcome-appstore.png" :fluid true}]]] [ui/Divider] [ui/Grid {:id :video-at-the-edge :centered true :stackable true :verticalAlign :middle} [ui/GridColumn {:width 6} [ui/Embed {:id "BHzbEDzyfnQ" :placeholder "https://img.youtube.com/vi/BHzbEDzyfnQ/maxresdefault.jpg" :source "youtube"}]] [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-how-to-video-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-video-subheader])] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-video-1-header]) (@tr [:welcome-how-to-video-1-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-video-1-subheader-mid])} [:a {:target "_blank" :key "video-nuvlabox-engine-quickstart" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/quickstart"} (@tr [:welcome-how-to-video-1-subheader-mid])] " " (@tr [:welcome-how-to-video-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-video-2-header]) (@tr [:welcome-how-to-video-2-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-video-2-subheader-post])} [navigate-link "edge" (@tr [:welcome-how-to-video-2-subheader-post])] ".") (step 3 (@tr [:welcome-how-to-video-3-header]) (@tr [:welcome-how-to-video-3-subheader-pre]))]]]]))
39750
(ns sixsq.nuvla.ui.welcome.views (:require [clojure.string :as str] [re-frame.core :refer [dispatch subscribe]] [sixsq.nuvla.ui.history.events :as history-events] [sixsq.nuvla.ui.i18n.subs :as i18n-subs] [sixsq.nuvla.ui.main.subs :as main-subs] [sixsq.nuvla.ui.panel :as panel] [sixsq.nuvla.ui.utils.semantic-ui :as ui])) (defn navigate-link [target-page text] [:a {:on-click #(dispatch [::history-events/navigate target-page]) :style {:cursor "pointer"}} text]) (defn step [number title & content] [ui/Step [ui/ListSA ^{:key title} [ui/ListItem (when-not (nil? number) [ui/Icon [ui/Label {:size :big, :circular true, :color "blue"} number]]) [ui/ListContent [ui/ListHeader title] [ui/ListDescription content]]]]]) (defmethod panel/render :welcome [path] (let [tr (subscribe [::i18n-subs/tr]) query-params (subscribe [::main-subs/nav-query-params]) {:keys [message, error]} @query-params] (when @query-params (when (or message error) (dispatch [:sixsq.nuvla.ui.main.events/set-message (if error :error :success) (or error message)])) (dispatch [::history-events/navigate (str (first path) "/")])) [:<> [ui/Grid {:stackable true :centered true :verticalAlign :middle :reversed :mobile :style {:margin-top "8px"}} [ui/GridColumn {:width 6} [ui/Header {:as "h1"} (@tr [:welcome-header])] [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-subheader])] [ui/HeaderSubheader {:as "h3"} (@tr [:welcome-subsubheader])] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :primary :button] :href "#add-nuvlabox"} (@tr [:welcome-create-nuvlabox])]] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :primary :button] :href "#launch-app"} (@tr [:welcome-launch-app])]] [ui/HeaderSubheader {:as "h3"} (@tr [:welcome-more-advanced])] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :button] :href "#video-at-the-edge"} (@tr [:welcome-process-video-at-edge])]]] [ui/GridColumn {:width 6} [ui/Embed {:id "yYJ6laT_6M4" :placeholder "https://img.youtube.com/vi/yYJ6laT_6M4/maxresdefault.jpg" :source "youtube"}]]] [ui/Divider] [ui/Header {:as "h2" :style {:text-align :center} :size :huge} (@tr [:welcome-resources])] [ui/HeaderSubheader {:as "h3" :style {:text-align :center}} (@tr [:welcome-resources-subheader])] [ui/CardGroup {:stackable true :centered true :columns 4} [ui/Card [ui/CardContent {:text-align :center} [ui/Header {:as :h2} (str/capitalize (@tr [:documentation]))] [ui/Icon {:name "book" :size "massive" :color "blue"}] [ui/Header {:as :h4} (@tr [:welcome-doc-subheader-pre]) " " [:a {:href "https://docs.nuvla.io"} (@tr [:here])] " " (@tr [:welcome-doc-subheader-post])]]] [ui/Card [ui/CardContent {:text-align :center} [ui/Header {:as :h2} (str/capitalize (@tr [:videos]))] [ui/Icon {:name "video" :size "massive" :color "blue"}] [ui/Header {:as :h4} (@tr [:welcome-video-subheader-pre]) " " [:a {:href "https://sixsq.com/media/videos.html"} (@tr [:video-channel])] " " (@tr [:welcome-video-subheader-post])]]]] [ui/Divider] [ui/Header {:as "h2" :style {:text-align :center} :size :huge} (@tr [:welcome-how-to-header])] [ui/HeaderSubheader {:as "h3" :style {:text-align :center :padding-bottom "20px"}} (@tr [:welcome-how-to-subheader])] [ui/Grid {:id :add-nuvlabox :centered true :stackable true :verticalAlign :middle} [ui/GridColumn {:width 6} [ui/Image {:floated "right" :src "/ui/images/welcome-nb.png" :fluid true}]] [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-how-to-nb-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-nb-subheader]) " " [:a {:href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine"} (@tr [:here])] "."] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-nb-1-header]) (@tr [:welcome-how-to-nb-1-subheader-pre]) " " [:a {:target "_blank" :key "nuvlabox-engine-requirements" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/requirements"} (@tr [:welcome-how-to-nb-1-subheader-mid])] " " (@tr [:welcome-how-to-nb-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-nb-2-header]) (@tr [:welcome-how-to-nb-2-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-nb-2-subheader-mid])} [navigate-link "edge" (@tr [:welcome-how-to-nb-2-subheader-mid])] " " (@tr [:welcome-how-to-nb-2-subheader-post]) ".") (step 3 (@tr [:welcome-how-to-nb-3-header]) (@tr [:welcome-how-to-nb-3-subheader-pre]) " " [:a {:target "_blank" :key "<KEY>" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/quickstart"} (@tr [:documentation])] " " (@tr [:welcome-how-to-nb-3-subheader-post]) ".") (step 4 (@tr [:welcome-how-to-nb-4-header]) (@tr [:welcome-how-to-nb-4-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-nb-4-subheader-mid])} [navigate-link "edge" (@tr [:welcome-how-to-nb-4-subheader-mid])] ". " (@tr [:welcome-how-to-nb-4-subheader-post]) ".") (step 5 (@tr [:welcome-how-to-nb-5-header]) (@tr [:welcome-how-to-nb-5-subheader-pre]) ". " ^{:key (@tr [:show-me])} [:a {:href "#deploy-app"} (str/capitalize (@tr [:show-me]))] ".")]]] [ui/Divider] [ui/Grid {:id :launch-app :centered true :stackable true :verticalAlign :middle :reversed "mobile"} [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2", :id "deploy-app"} (@tr [:welcome-how-to-launch-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-launch-subheader]) " " [:a {:href "https://docs.nuvla.io/nuvla/launch-app"} (@tr [:here])] "."] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-launch-1-header-]) (@tr [:welcome-how-to-launch-1-subheader-pre]) " " ^{:key (@tr [:appstore])} [navigate-link "apps" (@tr [:appstore])] " " (@tr [:welcome-how-to-launch-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-launch-2-header]) (@tr [:welcome-how-to-launch-2-subheader-pre])) (step 3 (@tr [:welcome-how-to-launch-3-header]) (@tr [:welcome-how-to-launch-3-subheader-pre]) " ") (step 4 (@tr [:welcome-how-to-launch-4-header]) (@tr [:welcome-how-to-launch-4-subheader-pre]) " " ^{:key (@tr [:dashboard])} [navigate-link "dashboard" (@tr [:dashboard])] ", " (@tr [:welcome-how-to-launch-4-subheader-post]) ".")]] [ui/GridColumn {:width 6} [ui/Image {:floated "right" :src "/ui/images/welcome-appstore.png" :fluid true}]]] [ui/Divider] [ui/Grid {:id :video-at-the-edge :centered true :stackable true :verticalAlign :middle} [ui/GridColumn {:width 6} [ui/Embed {:id "BHzbEDzyfnQ" :placeholder "https://img.youtube.com/vi/BHzbEDzyfnQ/maxresdefault.jpg" :source "youtube"}]] [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-how-to-video-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-video-subheader])] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-video-1-header]) (@tr [:welcome-how-to-video-1-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-video-1-subheader-mid])} [:a {:target "_blank" :key "<KEY>" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/quickstart"} (@tr [:welcome-how-to-video-1-subheader-mid])] " " (@tr [:welcome-how-to-video-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-video-2-header]) (@tr [:welcome-how-to-video-2-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-video-2-subheader-post])} [navigate-link "edge" (@tr [:welcome-how-to-video-2-subheader-post])] ".") (step 3 (@tr [:welcome-how-to-video-3-header]) (@tr [:welcome-how-to-video-3-subheader-pre]))]]]]))
true
(ns sixsq.nuvla.ui.welcome.views (:require [clojure.string :as str] [re-frame.core :refer [dispatch subscribe]] [sixsq.nuvla.ui.history.events :as history-events] [sixsq.nuvla.ui.i18n.subs :as i18n-subs] [sixsq.nuvla.ui.main.subs :as main-subs] [sixsq.nuvla.ui.panel :as panel] [sixsq.nuvla.ui.utils.semantic-ui :as ui])) (defn navigate-link [target-page text] [:a {:on-click #(dispatch [::history-events/navigate target-page]) :style {:cursor "pointer"}} text]) (defn step [number title & content] [ui/Step [ui/ListSA ^{:key title} [ui/ListItem (when-not (nil? number) [ui/Icon [ui/Label {:size :big, :circular true, :color "blue"} number]]) [ui/ListContent [ui/ListHeader title] [ui/ListDescription content]]]]]) (defmethod panel/render :welcome [path] (let [tr (subscribe [::i18n-subs/tr]) query-params (subscribe [::main-subs/nav-query-params]) {:keys [message, error]} @query-params] (when @query-params (when (or message error) (dispatch [:sixsq.nuvla.ui.main.events/set-message (if error :error :success) (or error message)])) (dispatch [::history-events/navigate (str (first path) "/")])) [:<> [ui/Grid {:stackable true :centered true :verticalAlign :middle :reversed :mobile :style {:margin-top "8px"}} [ui/GridColumn {:width 6} [ui/Header {:as "h1"} (@tr [:welcome-header])] [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-subheader])] [ui/HeaderSubheader {:as "h3"} (@tr [:welcome-subsubheader])] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :primary :button] :href "#add-nuvlabox"} (@tr [:welcome-create-nuvlabox])]] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :primary :button] :href "#launch-app"} (@tr [:welcome-launch-app])]] [ui/HeaderSubheader {:as "h3"} (@tr [:welcome-more-advanced])] [:div {:style {:padding "10px 0"}} [:a {:class [:ui :button] :href "#video-at-the-edge"} (@tr [:welcome-process-video-at-edge])]]] [ui/GridColumn {:width 6} [ui/Embed {:id "yYJ6laT_6M4" :placeholder "https://img.youtube.com/vi/yYJ6laT_6M4/maxresdefault.jpg" :source "youtube"}]]] [ui/Divider] [ui/Header {:as "h2" :style {:text-align :center} :size :huge} (@tr [:welcome-resources])] [ui/HeaderSubheader {:as "h3" :style {:text-align :center}} (@tr [:welcome-resources-subheader])] [ui/CardGroup {:stackable true :centered true :columns 4} [ui/Card [ui/CardContent {:text-align :center} [ui/Header {:as :h2} (str/capitalize (@tr [:documentation]))] [ui/Icon {:name "book" :size "massive" :color "blue"}] [ui/Header {:as :h4} (@tr [:welcome-doc-subheader-pre]) " " [:a {:href "https://docs.nuvla.io"} (@tr [:here])] " " (@tr [:welcome-doc-subheader-post])]]] [ui/Card [ui/CardContent {:text-align :center} [ui/Header {:as :h2} (str/capitalize (@tr [:videos]))] [ui/Icon {:name "video" :size "massive" :color "blue"}] [ui/Header {:as :h4} (@tr [:welcome-video-subheader-pre]) " " [:a {:href "https://sixsq.com/media/videos.html"} (@tr [:video-channel])] " " (@tr [:welcome-video-subheader-post])]]]] [ui/Divider] [ui/Header {:as "h2" :style {:text-align :center} :size :huge} (@tr [:welcome-how-to-header])] [ui/HeaderSubheader {:as "h3" :style {:text-align :center :padding-bottom "20px"}} (@tr [:welcome-how-to-subheader])] [ui/Grid {:id :add-nuvlabox :centered true :stackable true :verticalAlign :middle} [ui/GridColumn {:width 6} [ui/Image {:floated "right" :src "/ui/images/welcome-nb.png" :fluid true}]] [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-how-to-nb-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-nb-subheader]) " " [:a {:href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine"} (@tr [:here])] "."] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-nb-1-header]) (@tr [:welcome-how-to-nb-1-subheader-pre]) " " [:a {:target "_blank" :key "nuvlabox-engine-requirements" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/requirements"} (@tr [:welcome-how-to-nb-1-subheader-mid])] " " (@tr [:welcome-how-to-nb-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-nb-2-header]) (@tr [:welcome-how-to-nb-2-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-nb-2-subheader-mid])} [navigate-link "edge" (@tr [:welcome-how-to-nb-2-subheader-mid])] " " (@tr [:welcome-how-to-nb-2-subheader-post]) ".") (step 3 (@tr [:welcome-how-to-nb-3-header]) (@tr [:welcome-how-to-nb-3-subheader-pre]) " " [:a {:target "_blank" :key "PI:KEY:<KEY>END_PI" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/quickstart"} (@tr [:documentation])] " " (@tr [:welcome-how-to-nb-3-subheader-post]) ".") (step 4 (@tr [:welcome-how-to-nb-4-header]) (@tr [:welcome-how-to-nb-4-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-nb-4-subheader-mid])} [navigate-link "edge" (@tr [:welcome-how-to-nb-4-subheader-mid])] ". " (@tr [:welcome-how-to-nb-4-subheader-post]) ".") (step 5 (@tr [:welcome-how-to-nb-5-header]) (@tr [:welcome-how-to-nb-5-subheader-pre]) ". " ^{:key (@tr [:show-me])} [:a {:href "#deploy-app"} (str/capitalize (@tr [:show-me]))] ".")]]] [ui/Divider] [ui/Grid {:id :launch-app :centered true :stackable true :verticalAlign :middle :reversed "mobile"} [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2", :id "deploy-app"} (@tr [:welcome-how-to-launch-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-launch-subheader]) " " [:a {:href "https://docs.nuvla.io/nuvla/launch-app"} (@tr [:here])] "."] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-launch-1-header-]) (@tr [:welcome-how-to-launch-1-subheader-pre]) " " ^{:key (@tr [:appstore])} [navigate-link "apps" (@tr [:appstore])] " " (@tr [:welcome-how-to-launch-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-launch-2-header]) (@tr [:welcome-how-to-launch-2-subheader-pre])) (step 3 (@tr [:welcome-how-to-launch-3-header]) (@tr [:welcome-how-to-launch-3-subheader-pre]) " ") (step 4 (@tr [:welcome-how-to-launch-4-header]) (@tr [:welcome-how-to-launch-4-subheader-pre]) " " ^{:key (@tr [:dashboard])} [navigate-link "dashboard" (@tr [:dashboard])] ", " (@tr [:welcome-how-to-launch-4-subheader-post]) ".")]] [ui/GridColumn {:width 6} [ui/Image {:floated "right" :src "/ui/images/welcome-appstore.png" :fluid true}]]] [ui/Divider] [ui/Grid {:id :video-at-the-edge :centered true :stackable true :verticalAlign :middle} [ui/GridColumn {:width 6} [ui/Embed {:id "BHzbEDzyfnQ" :placeholder "https://img.youtube.com/vi/BHzbEDzyfnQ/maxresdefault.jpg" :source "youtube"}]] [ui/GridColumn {:width 9} [ui/HeaderSubheader {:as "h2"} (@tr [:welcome-how-to-video-header])] [ui/HeaderSubheader {:as "h4"} (@tr [:welcome-how-to-video-subheader])] [ui/StepGroup {:vertical true} (step 1 (@tr [:welcome-how-to-video-1-header]) (@tr [:welcome-how-to-video-1-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-video-1-subheader-mid])} [:a {:target "_blank" :key "PI:KEY:<KEY>END_PI" :href "https://docs.nuvla.io/nuvlabox/nuvlabox-engine/quickstart"} (@tr [:welcome-how-to-video-1-subheader-mid])] " " (@tr [:welcome-how-to-video-1-subheader-post]) ".") (step 2 (@tr [:welcome-how-to-video-2-header]) (@tr [:welcome-how-to-video-2-subheader-pre]) " " ^{:key (@tr [:welcome-how-to-video-2-subheader-post])} [navigate-link "edge" (@tr [:welcome-how-to-video-2-subheader-post])] ".") (step 3 (@tr [:welcome-how-to-video-3-header]) (@tr [:welcome-how-to-video-3-subheader-pre]))]]]]))
[ { "context": " {:type :name-changed :data {:name \"jarvis\"}}\n {:type :sk", "end": 478, "score": 0.9960737824440002, "start": 472, "tag": "NAME", "value": "jarvis" }, { "context": "quence 2 :data {:type :name-changed :data {:name \"jarvis\"}}}\n {:stream-id \"7\" :sequence 3 :da", "end": 1057, "score": 0.9958935976028442, "start": 1051, "tag": "NAME", "value": "jarvis" }, { "context": " {:type :name-changed :data {:name \"jarvis\"}}\n {:type :sk", "end": 1765, "score": 0.9965587854385376, "start": 1759, "tag": "NAME", "value": "jarvis" }, { "context": " {:type :name-changed :data {:name \"jarvis\"}}\n {:type :sk", "end": 2311, "score": 0.9986354112625122, "start": 2305, "tag": "NAME", "value": "jarvis" }, { "context": "ser \"postgres\"\n :password \"postgres\"})\n\n(defn- reset-event-store [db-spec]\n (do\n ", "end": 2809, "score": 0.9995260238647461, "start": 2801, "tag": "PASSWORD", "value": "postgres" }, { "context": " {:type :name-changed :data {:name \"jarvis\"}}\n {:type :sk", "end": 3265, "score": 0.9980357885360718, "start": 3259, "tag": "NAME", "value": "jarvis" }, { "context": "uence 2 :event {:type :name-changed :data {:name \"jarvis\"}}}\n {:stream-id \"7\" :sequence 3 :ev", "end": 3824, "score": 0.9979678392410278, "start": 3818, "tag": "NAME", "value": "jarvis" }, { "context": " {:type :name-changed :data {:name \"jarvis\"}}\n {:type :", "end": 4577, "score": 0.9989359378814697, "start": 4571, "tag": "NAME", "value": "jarvis" }, { "context": " {:type :name-changed :data {:name \"jarvis\"}}\n {:type :", "end": 5163, "score": 0.9991605281829834, "start": 5157, "tag": "NAME", "value": "jarvis" } ]
data/test/clojure/dbb510a66bd6b83e94efadb5b802e6e73632e5feevent_store_test.clj
harshp8l/deep-learning-lang-detection
84
(ns jarvis.event-store-test (require [clojure.test :refer :all] [jarvis.event_store :refer :all]) (:import (jarvis.event MidAirCollision) (jarvis.event_store InMemory SqlStore))) (deftest in-memory-eventstore (testing "append and retrieve events" (let [store (-> (InMemory.) (append-events 7 0 [{:type :created} {:type :name-changed :data {:name "jarvis"}} {:type :skills-added :data #{:java}} {:type :skills-added :data #{:clojure :erlang}} {:type :skills-removed :data #{:java}}])) stream1 (stream-of store 7 {:max-sequence 1}) stream2 (stream-of store 7 {:min-sequence 2 :max-sequence 3})] ;(pprint store) (is (= [{:stream-id "7" :sequence 1 :data {:type :created}}] (:events stream1))) (is (= [{:stream-id "7" :sequence 2 :data {:type :name-changed :data {:name "jarvis"}}} {:stream-id "7" :sequence 3 :data {:type :skills-added :data #{:java}}}] (:events stream2))) (is (= 5 (:version stream1))) (is (= 5 (:version stream2))) (is (= "7" (:stream-id stream1))) (is (= "7" (:stream-id stream2))))) (testing "retrieve events of an unknown stream" (let [store (InMemory.) stream (stream-of store "7" {:max-sequence 1})] (is (nil? stream)))) (testing "retrieve empty events of an empty version range" (let [store (-> (InMemory.) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "jarvis"}} {:type :skills-added :data #{:java}}])) stream (stream-of store "7" {:min-sequence 7})] (is (not (nil? stream))) (is (= "7" (:stream-id stream))) (is (= 3 (:version stream))) (is (= [] (:events stream))))) (testing "mid-air-collision when expected-version is invalid" (let [store (-> (InMemory.) (append-events 7 0 [{:type :created} {:type :name-changed :data {:name "jarvis"}} {:type :skills-added :data #{:java}}]))] ;(pprint store) (is (thrown? MidAirCollision (append-events store 7 1 [{:type :skills-added :data #{:clojure :erlang}}])))))) (def db-spec {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//localhost:5432/jarvis-test" :user "postgres" :password "postgres"}) (defn- reset-event-store [db-spec] (do (drop-schema db-spec) (create-schema db-spec) (SqlStore. db-spec))) (deftest sql-eventstore (testing "append and retrieve events" (drop-schema db-spec) (create-schema db-spec) (let [store (-> (SqlStore. db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "jarvis"}} {:type :skills-added :data #{:java}} {:type :skills-added :data #{:clojure :erlang}} {:type :skills-removed :data #{:java}}])) stream1 (stream-of store 7 {:max-sequence 1}) stream2 (stream-of store 7 {:min-sequence 2 :max-sequence 3})] (is (= [{:stream-id "7" :sequence 1 :event {:type :created}}] (:events stream1))) (is (= [{:stream-id "7" :sequence 2 :event {:type :name-changed :data {:name "jarvis"}}} {:stream-id "7" :sequence 3 :event {:type :skills-added :data #{:java}}}] (:events stream2))) (is (= 5 (:version stream1))) (is (= 5 (:version stream2))) (is (= 7 (:stream-id stream1))) (is (= 7 (:stream-id stream2)))) (testing "retrieve events of an unknown stream" (let [store (reset-event-store db-spec) stream (stream-of store "7" {:max-version 1})] (is (nil? stream)))) (testing "retrieve empty events of an empty version range" (let [store (-> (reset-event-store db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "jarvis"}} {:type :skills-added :data #{:java}}])) stream (stream-of store "7" {:min-sequence 7})] (is (not (nil? stream))) (is (= "7" (:stream-id stream))) (is (= 3 (:version stream))) (is (= [] (:events stream))))) (testing "mid-air-collision when expected-version is invalid" (let [store (-> (reset-event-store db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "jarvis"}} {:type :skills-added :data #{:java}}]))] (is (thrown? MidAirCollision (append-events store "7" 1 [{:type :skills-added :data #{:clojure :erlang}}])))))))
87794
(ns jarvis.event-store-test (require [clojure.test :refer :all] [jarvis.event_store :refer :all]) (:import (jarvis.event MidAirCollision) (jarvis.event_store InMemory SqlStore))) (deftest in-memory-eventstore (testing "append and retrieve events" (let [store (-> (InMemory.) (append-events 7 0 [{:type :created} {:type :name-changed :data {:name "<NAME>"}} {:type :skills-added :data #{:java}} {:type :skills-added :data #{:clojure :erlang}} {:type :skills-removed :data #{:java}}])) stream1 (stream-of store 7 {:max-sequence 1}) stream2 (stream-of store 7 {:min-sequence 2 :max-sequence 3})] ;(pprint store) (is (= [{:stream-id "7" :sequence 1 :data {:type :created}}] (:events stream1))) (is (= [{:stream-id "7" :sequence 2 :data {:type :name-changed :data {:name "<NAME>"}}} {:stream-id "7" :sequence 3 :data {:type :skills-added :data #{:java}}}] (:events stream2))) (is (= 5 (:version stream1))) (is (= 5 (:version stream2))) (is (= "7" (:stream-id stream1))) (is (= "7" (:stream-id stream2))))) (testing "retrieve events of an unknown stream" (let [store (InMemory.) stream (stream-of store "7" {:max-sequence 1})] (is (nil? stream)))) (testing "retrieve empty events of an empty version range" (let [store (-> (InMemory.) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "<NAME>"}} {:type :skills-added :data #{:java}}])) stream (stream-of store "7" {:min-sequence 7})] (is (not (nil? stream))) (is (= "7" (:stream-id stream))) (is (= 3 (:version stream))) (is (= [] (:events stream))))) (testing "mid-air-collision when expected-version is invalid" (let [store (-> (InMemory.) (append-events 7 0 [{:type :created} {:type :name-changed :data {:name "<NAME>"}} {:type :skills-added :data #{:java}}]))] ;(pprint store) (is (thrown? MidAirCollision (append-events store 7 1 [{:type :skills-added :data #{:clojure :erlang}}])))))) (def db-spec {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//localhost:5432/jarvis-test" :user "postgres" :password "<PASSWORD>"}) (defn- reset-event-store [db-spec] (do (drop-schema db-spec) (create-schema db-spec) (SqlStore. db-spec))) (deftest sql-eventstore (testing "append and retrieve events" (drop-schema db-spec) (create-schema db-spec) (let [store (-> (SqlStore. db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "<NAME>"}} {:type :skills-added :data #{:java}} {:type :skills-added :data #{:clojure :erlang}} {:type :skills-removed :data #{:java}}])) stream1 (stream-of store 7 {:max-sequence 1}) stream2 (stream-of store 7 {:min-sequence 2 :max-sequence 3})] (is (= [{:stream-id "7" :sequence 1 :event {:type :created}}] (:events stream1))) (is (= [{:stream-id "7" :sequence 2 :event {:type :name-changed :data {:name "<NAME>"}}} {:stream-id "7" :sequence 3 :event {:type :skills-added :data #{:java}}}] (:events stream2))) (is (= 5 (:version stream1))) (is (= 5 (:version stream2))) (is (= 7 (:stream-id stream1))) (is (= 7 (:stream-id stream2)))) (testing "retrieve events of an unknown stream" (let [store (reset-event-store db-spec) stream (stream-of store "7" {:max-version 1})] (is (nil? stream)))) (testing "retrieve empty events of an empty version range" (let [store (-> (reset-event-store db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "<NAME>"}} {:type :skills-added :data #{:java}}])) stream (stream-of store "7" {:min-sequence 7})] (is (not (nil? stream))) (is (= "7" (:stream-id stream))) (is (= 3 (:version stream))) (is (= [] (:events stream))))) (testing "mid-air-collision when expected-version is invalid" (let [store (-> (reset-event-store db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "<NAME>"}} {:type :skills-added :data #{:java}}]))] (is (thrown? MidAirCollision (append-events store "7" 1 [{:type :skills-added :data #{:clojure :erlang}}])))))))
true
(ns jarvis.event-store-test (require [clojure.test :refer :all] [jarvis.event_store :refer :all]) (:import (jarvis.event MidAirCollision) (jarvis.event_store InMemory SqlStore))) (deftest in-memory-eventstore (testing "append and retrieve events" (let [store (-> (InMemory.) (append-events 7 0 [{:type :created} {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}} {:type :skills-added :data #{:java}} {:type :skills-added :data #{:clojure :erlang}} {:type :skills-removed :data #{:java}}])) stream1 (stream-of store 7 {:max-sequence 1}) stream2 (stream-of store 7 {:min-sequence 2 :max-sequence 3})] ;(pprint store) (is (= [{:stream-id "7" :sequence 1 :data {:type :created}}] (:events stream1))) (is (= [{:stream-id "7" :sequence 2 :data {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}}} {:stream-id "7" :sequence 3 :data {:type :skills-added :data #{:java}}}] (:events stream2))) (is (= 5 (:version stream1))) (is (= 5 (:version stream2))) (is (= "7" (:stream-id stream1))) (is (= "7" (:stream-id stream2))))) (testing "retrieve events of an unknown stream" (let [store (InMemory.) stream (stream-of store "7" {:max-sequence 1})] (is (nil? stream)))) (testing "retrieve empty events of an empty version range" (let [store (-> (InMemory.) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}} {:type :skills-added :data #{:java}}])) stream (stream-of store "7" {:min-sequence 7})] (is (not (nil? stream))) (is (= "7" (:stream-id stream))) (is (= 3 (:version stream))) (is (= [] (:events stream))))) (testing "mid-air-collision when expected-version is invalid" (let [store (-> (InMemory.) (append-events 7 0 [{:type :created} {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}} {:type :skills-added :data #{:java}}]))] ;(pprint store) (is (thrown? MidAirCollision (append-events store 7 1 [{:type :skills-added :data #{:clojure :erlang}}])))))) (def db-spec {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//localhost:5432/jarvis-test" :user "postgres" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (defn- reset-event-store [db-spec] (do (drop-schema db-spec) (create-schema db-spec) (SqlStore. db-spec))) (deftest sql-eventstore (testing "append and retrieve events" (drop-schema db-spec) (create-schema db-spec) (let [store (-> (SqlStore. db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}} {:type :skills-added :data #{:java}} {:type :skills-added :data #{:clojure :erlang}} {:type :skills-removed :data #{:java}}])) stream1 (stream-of store 7 {:max-sequence 1}) stream2 (stream-of store 7 {:min-sequence 2 :max-sequence 3})] (is (= [{:stream-id "7" :sequence 1 :event {:type :created}}] (:events stream1))) (is (= [{:stream-id "7" :sequence 2 :event {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}}} {:stream-id "7" :sequence 3 :event {:type :skills-added :data #{:java}}}] (:events stream2))) (is (= 5 (:version stream1))) (is (= 5 (:version stream2))) (is (= 7 (:stream-id stream1))) (is (= 7 (:stream-id stream2)))) (testing "retrieve events of an unknown stream" (let [store (reset-event-store db-spec) stream (stream-of store "7" {:max-version 1})] (is (nil? stream)))) (testing "retrieve empty events of an empty version range" (let [store (-> (reset-event-store db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}} {:type :skills-added :data #{:java}}])) stream (stream-of store "7" {:min-sequence 7})] (is (not (nil? stream))) (is (= "7" (:stream-id stream))) (is (= 3 (:version stream))) (is (= [] (:events stream))))) (testing "mid-air-collision when expected-version is invalid" (let [store (-> (reset-event-store db-spec) (append-events "7" 0 [{:type :created} {:type :name-changed :data {:name "PI:NAME:<NAME>END_PI"}} {:type :skills-added :data #{:java}}]))] (is (thrown? MidAirCollision (append-events store "7" 1 [{:type :skills-added :data #{:clojure :erlang}}])))))))
[ { "context": "maps are seq-able\n(def contact-info {:first-name \"Elvis\" :last-name \"Presley\" :address \"Graceland\" :city ", "end": 1026, "score": 0.9997361302375793, "start": 1021, "tag": "NAME", "value": "Elvis" }, { "context": "def contact-info {:first-name \"Elvis\" :last-name \"Presley\" :address \"Graceland\" :city \"Memphis\" :state \"TN\"", "end": 1047, "score": 0.9997323155403137, "start": 1040, "tag": "NAME", "value": "Presley" }, { "context": "ate \"TN\"})\n(assert (= (count (cons [:middle-name \"Aaron\"] contact-info)) 6))\n\n; Operations that return `S", "end": 1144, "score": 0.999475359916687, "start": 1139, "tag": "NAME", "value": "Aaron" }, { "context": "formation\n\n(def star-trek-characters (sorted-set \"Spock\" \"Kirk\" \"Worf\" \"Picard\" \"Riker\"))\n(assert (first ", "end": 2291, "score": 0.7385554313659668, "start": 2286, "tag": "NAME", "value": "Spock" }, { "context": "n\n\n(def star-trek-characters (sorted-set \"Spock\" \"Kirk\" \"Worf\" \"Picard\" \"Riker\"))\n(assert (first star-tr", "end": 2298, "score": 0.9758473634719849, "start": 2294, "tag": "NAME", "value": "Kirk" }, { "context": " star-trek-characters (sorted-set \"Spock\" \"Kirk\" \"Worf\" \"Picard\" \"Riker\"))\n(assert (first star-trek-char", "end": 2305, "score": 0.9903168082237244, "start": 2301, "tag": "NAME", "value": "Worf" }, { "context": "rek-characters (sorted-set \"Spock\" \"Kirk\" \"Worf\" \"Picard\" \"Riker\"))\n(assert (first star-trek-characters) \"", "end": 2314, "score": 0.9882470965385437, "start": 2308, "tag": "NAME", "value": "Picard" }, { "context": "cters (sorted-set \"Spock\" \"Kirk\" \"Worf\" \"Picard\" \"Riker\"))\n(assert (first star-trek-characters) \"Spock\")\n", "end": 2322, "score": 0.959089994430542, "start": 2317, "tag": "NAME", "value": "Riker" } ]
clojure/sequences/sequences.clj
miroadamy/language-matrix
15
; A list, set, map are sequences and can be operated on ; by a common set of sequence functions. Keep in mind that all ; sequence functions will return an `ISeq`, a java representation ; of a `Seq` (sequence) pronounced 'Seek'. `Seq` looks much like a list ; on the console but it is indeed an implementation of a `Seq` ; ; first obtains the first element (assert (= (first '(1 2 3 4 5)) 1)) ; rest obtains the collection minus the first element ; the seq function will return a `seq` of any sequence. (assert (= (rest #{1 2 3 4 5}) '(4 3 2 5))) ; cons will append an element depending on the collections (assert (= (cons 3 '(4 5 6 7)) '(3 4 5 6 7))) ; `seq` will return nil if the collection is empty (assert (= (seq '()) nil)) ; `next` is the equivalent of (seq(rest aseq)) (assert (= (count (next #{1 2 3 4 5})) 4)) ; vectors are seq-able (assert (= (cons 3 [4 5 6 7]) '(3 4 5 6 7))) (assert (= (rest [3 4 5 6]) '(4 5 6))) (assert (= (first [5 6 7 9]) 5)) ; maps are seq-able (def contact-info {:first-name "Elvis" :last-name "Presley" :address "Graceland" :city "Memphis" :state "TN"}) (assert (= (count (cons [:middle-name "Aaron"] contact-info)) 6)) ; Operations that return `Seq` are different ; depending on the collection being operated on. ; In the end though, they are `Seq` ; An operation on a list returns a clojure.lang.PersistentList (assert (= (. (class (rest '(1 2 3 4))) getName) "clojure.lang.PersistentList")) ; An operation on a vector returns a clojure.lang.PersistentVector$ChunkedSeq (assert (= (. (class (rest [1 2 3 4])) getName) "clojure.lang.PersistentVector$ChunkedSeq")) ; An operation on a set returns a clojure.lang.APersistentMap$KeySeq (assert (= (. (class (rest #{1 2 3 4})) getName) "clojure.lang.APersistentMap$KeySeq")) ; An operation on a map returns a clojure.lang.Aclojure.lang.PersistentHashMap (assert (= (. (class (rest contact-info)) getName) "clojure.lang.PersistentHashMap$NodeSeq")) ; Many of these operations wouldn't make sense based on implementation like hash maps and sets ; since the order cannot be determined at runtime. You can however use collections like sorted set ; and sorted map see sorted_sets/sortedsets.clj and sorted_maps/sortedmaps.clj for more information (def star-trek-characters (sorted-set "Spock" "Kirk" "Worf" "Picard" "Riker")) (assert (first star-trek-characters) "Spock") (def band-hometowns (sorted-map :depeche-mode "basildon" :the-cure "crawley" :talking-heads "providence")) (assert (first band-hometowns) [:depeche-mode "basildon"])
96341
; A list, set, map are sequences and can be operated on ; by a common set of sequence functions. Keep in mind that all ; sequence functions will return an `ISeq`, a java representation ; of a `Seq` (sequence) pronounced 'Seek'. `Seq` looks much like a list ; on the console but it is indeed an implementation of a `Seq` ; ; first obtains the first element (assert (= (first '(1 2 3 4 5)) 1)) ; rest obtains the collection minus the first element ; the seq function will return a `seq` of any sequence. (assert (= (rest #{1 2 3 4 5}) '(4 3 2 5))) ; cons will append an element depending on the collections (assert (= (cons 3 '(4 5 6 7)) '(3 4 5 6 7))) ; `seq` will return nil if the collection is empty (assert (= (seq '()) nil)) ; `next` is the equivalent of (seq(rest aseq)) (assert (= (count (next #{1 2 3 4 5})) 4)) ; vectors are seq-able (assert (= (cons 3 [4 5 6 7]) '(3 4 5 6 7))) (assert (= (rest [3 4 5 6]) '(4 5 6))) (assert (= (first [5 6 7 9]) 5)) ; maps are seq-able (def contact-info {:first-name "<NAME>" :last-name "<NAME>" :address "Graceland" :city "Memphis" :state "TN"}) (assert (= (count (cons [:middle-name "<NAME>"] contact-info)) 6)) ; Operations that return `Seq` are different ; depending on the collection being operated on. ; In the end though, they are `Seq` ; An operation on a list returns a clojure.lang.PersistentList (assert (= (. (class (rest '(1 2 3 4))) getName) "clojure.lang.PersistentList")) ; An operation on a vector returns a clojure.lang.PersistentVector$ChunkedSeq (assert (= (. (class (rest [1 2 3 4])) getName) "clojure.lang.PersistentVector$ChunkedSeq")) ; An operation on a set returns a clojure.lang.APersistentMap$KeySeq (assert (= (. (class (rest #{1 2 3 4})) getName) "clojure.lang.APersistentMap$KeySeq")) ; An operation on a map returns a clojure.lang.Aclojure.lang.PersistentHashMap (assert (= (. (class (rest contact-info)) getName) "clojure.lang.PersistentHashMap$NodeSeq")) ; Many of these operations wouldn't make sense based on implementation like hash maps and sets ; since the order cannot be determined at runtime. You can however use collections like sorted set ; and sorted map see sorted_sets/sortedsets.clj and sorted_maps/sortedmaps.clj for more information (def star-trek-characters (sorted-set "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>")) (assert (first star-trek-characters) "Spock") (def band-hometowns (sorted-map :depeche-mode "basildon" :the-cure "crawley" :talking-heads "providence")) (assert (first band-hometowns) [:depeche-mode "basildon"])
true
; A list, set, map are sequences and can be operated on ; by a common set of sequence functions. Keep in mind that all ; sequence functions will return an `ISeq`, a java representation ; of a `Seq` (sequence) pronounced 'Seek'. `Seq` looks much like a list ; on the console but it is indeed an implementation of a `Seq` ; ; first obtains the first element (assert (= (first '(1 2 3 4 5)) 1)) ; rest obtains the collection minus the first element ; the seq function will return a `seq` of any sequence. (assert (= (rest #{1 2 3 4 5}) '(4 3 2 5))) ; cons will append an element depending on the collections (assert (= (cons 3 '(4 5 6 7)) '(3 4 5 6 7))) ; `seq` will return nil if the collection is empty (assert (= (seq '()) nil)) ; `next` is the equivalent of (seq(rest aseq)) (assert (= (count (next #{1 2 3 4 5})) 4)) ; vectors are seq-able (assert (= (cons 3 [4 5 6 7]) '(3 4 5 6 7))) (assert (= (rest [3 4 5 6]) '(4 5 6))) (assert (= (first [5 6 7 9]) 5)) ; maps are seq-able (def contact-info {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :address "Graceland" :city "Memphis" :state "TN"}) (assert (= (count (cons [:middle-name "PI:NAME:<NAME>END_PI"] contact-info)) 6)) ; Operations that return `Seq` are different ; depending on the collection being operated on. ; In the end though, they are `Seq` ; An operation on a list returns a clojure.lang.PersistentList (assert (= (. (class (rest '(1 2 3 4))) getName) "clojure.lang.PersistentList")) ; An operation on a vector returns a clojure.lang.PersistentVector$ChunkedSeq (assert (= (. (class (rest [1 2 3 4])) getName) "clojure.lang.PersistentVector$ChunkedSeq")) ; An operation on a set returns a clojure.lang.APersistentMap$KeySeq (assert (= (. (class (rest #{1 2 3 4})) getName) "clojure.lang.APersistentMap$KeySeq")) ; An operation on a map returns a clojure.lang.Aclojure.lang.PersistentHashMap (assert (= (. (class (rest contact-info)) getName) "clojure.lang.PersistentHashMap$NodeSeq")) ; Many of these operations wouldn't make sense based on implementation like hash maps and sets ; since the order cannot be determined at runtime. You can however use collections like sorted set ; and sorted map see sorted_sets/sortedsets.clj and sorted_maps/sortedmaps.clj for more information (def star-trek-characters (sorted-set "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")) (assert (first star-trek-characters) "Spock") (def band-hometowns (sorted-map :depeche-mode "basildon" :the-cure "crawley" :talking-heads "providence")) (assert (first band-hometowns) [:depeche-mode "basildon"])
[ { "context": ";; The MIT License\n;; \n;; Copyright (c) 2011 John Svazic\n;; \n;; Permission is hereby granted, free of char", "end": 56, "score": 0.999848484992981, "start": 45, "tag": "NAME", "value": "John Svazic" } ]
clojure/test/net/auxesia/test/chromosome.clj
Srivani-Y/Hello-wolrld
159
;; The MIT License ;; ;; Copyright (c) 2011 John Svazic ;; ;; 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 ;; 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 net.auxesia.test.chromosome (:use [net.auxesia.chromosome :as chromosome] :reload) (:use [clojure.test]) (:use [clojure.set])) (deftest test-fitness (testing "fitness function" (testing "Perfect fitness" (is (= 0 (:fitness (chromosome/generate "Hello, world!"))))) (testing "Random genes" (is (= 399 (:fitness (chromosome/generate "H5p&J;!l<X\\7l")))) (is (= 297 (:fitness (chromosome/generate "Vc;fx#QRP8V\\$")))) (is (= 415 (:fitness (chromosome/generate "t\\O`E_Jx$n=NF"))))))) (deftest test-generate (testing "generate function" (loop [c (chromosome/generate) idx (int 0)] (if (== idx 1000) true (do (is (>= (:fitness c) 0)) (is (== (count chromosome/*target-gene*) (count (:gene c)))) (let [gene (:gene c)] (loop [g-idx (int 0)] (if (== g-idx (count gene)) true (if (and (>= (int (get gene g-idx)) 32) (<= (int (get gene g-idx)) 121)) (recur (inc g-idx)) (is (false "Invalid character found!")))))) (recur (chromosome/generate) (inc idx))))))) (deftest test-mutate (testing "mutate function" (loop [c (chromosome/generate) idx (int 0)] (if (== idx 1000) true (let [mutated (chromosome/mutate c) set1 (apply sorted-set (:gene c)) set2 (apply sorted-set (:gene mutated))] (do (testing "Gene size for mutated chromosome" (is (== (count (:gene c)) (count (:gene mutated))))) (testing "Difference count for mutated gene" (is (<= (count (clojure.set/difference set1 set2)) 1))) (recur (chromosome/generate) (inc idx)))))))) (defn- find-pivot "Helper method used to find a pivot point between two strings." [s1 s2] (let [size (count s1)] (loop [idx (int 0)] (cond (== size idx) nil (not= (get s1 idx) (get s2 idx)) idx :default (recur (inc idx)))))) (deftest test-mate (testing "The mate function" (let [c1 (chromosome/generate) c2 (chromosome/generate) children (chromosome/mate c1 c2) pivot (find-pivot (:gene c1) (:gene (first children)))] (do (testing "Size of returned sequence from the mate function" (is (== 2 (count children)))) (testing "Size of the gene from the first child" (is (== (count chromosome/*target-gene*) (count (:gene (first children)))))) (testing "Size of the gene from the second child" (is (== (count chromosome/*target-gene*) (count (:gene (last children)))))) (testing "Mating results from the first child" (loop [g-idx 0] ; Check the first child (when (< g-idx (count (:gene c1))) (if (< g-idx pivot) (is (= (get (:gene c1) g-idx) (get (:gene (first children)) g-idx))) (is (= (get (:gene c2) g-idx) (get (:gene (first children)) g-idx)))) (recur (inc g-idx))))) (testing "Mating results from the second child" (loop [g-idx 0] ; Check the second child (when (< g-idx (count (:gene c2))) (if (< g-idx pivot) (is (= (get (:gene c2) g-idx) (get (:gene (second children)) g-idx))) (is (= (get (:gene c1) g-idx) (get (:gene (second children)) g-idx)))) (recur (inc g-idx)))))))))
10511
;; The MIT License ;; ;; Copyright (c) 2011 <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 ;; 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 net.auxesia.test.chromosome (:use [net.auxesia.chromosome :as chromosome] :reload) (:use [clojure.test]) (:use [clojure.set])) (deftest test-fitness (testing "fitness function" (testing "Perfect fitness" (is (= 0 (:fitness (chromosome/generate "Hello, world!"))))) (testing "Random genes" (is (= 399 (:fitness (chromosome/generate "H5p&J;!l<X\\7l")))) (is (= 297 (:fitness (chromosome/generate "Vc;fx#QRP8V\\$")))) (is (= 415 (:fitness (chromosome/generate "t\\O`E_Jx$n=NF"))))))) (deftest test-generate (testing "generate function" (loop [c (chromosome/generate) idx (int 0)] (if (== idx 1000) true (do (is (>= (:fitness c) 0)) (is (== (count chromosome/*target-gene*) (count (:gene c)))) (let [gene (:gene c)] (loop [g-idx (int 0)] (if (== g-idx (count gene)) true (if (and (>= (int (get gene g-idx)) 32) (<= (int (get gene g-idx)) 121)) (recur (inc g-idx)) (is (false "Invalid character found!")))))) (recur (chromosome/generate) (inc idx))))))) (deftest test-mutate (testing "mutate function" (loop [c (chromosome/generate) idx (int 0)] (if (== idx 1000) true (let [mutated (chromosome/mutate c) set1 (apply sorted-set (:gene c)) set2 (apply sorted-set (:gene mutated))] (do (testing "Gene size for mutated chromosome" (is (== (count (:gene c)) (count (:gene mutated))))) (testing "Difference count for mutated gene" (is (<= (count (clojure.set/difference set1 set2)) 1))) (recur (chromosome/generate) (inc idx)))))))) (defn- find-pivot "Helper method used to find a pivot point between two strings." [s1 s2] (let [size (count s1)] (loop [idx (int 0)] (cond (== size idx) nil (not= (get s1 idx) (get s2 idx)) idx :default (recur (inc idx)))))) (deftest test-mate (testing "The mate function" (let [c1 (chromosome/generate) c2 (chromosome/generate) children (chromosome/mate c1 c2) pivot (find-pivot (:gene c1) (:gene (first children)))] (do (testing "Size of returned sequence from the mate function" (is (== 2 (count children)))) (testing "Size of the gene from the first child" (is (== (count chromosome/*target-gene*) (count (:gene (first children)))))) (testing "Size of the gene from the second child" (is (== (count chromosome/*target-gene*) (count (:gene (last children)))))) (testing "Mating results from the first child" (loop [g-idx 0] ; Check the first child (when (< g-idx (count (:gene c1))) (if (< g-idx pivot) (is (= (get (:gene c1) g-idx) (get (:gene (first children)) g-idx))) (is (= (get (:gene c2) g-idx) (get (:gene (first children)) g-idx)))) (recur (inc g-idx))))) (testing "Mating results from the second child" (loop [g-idx 0] ; Check the second child (when (< g-idx (count (:gene c2))) (if (< g-idx pivot) (is (= (get (:gene c2) g-idx) (get (:gene (second children)) g-idx))) (is (= (get (:gene c1) g-idx) (get (:gene (second children)) g-idx)))) (recur (inc g-idx)))))))))
true
;; The MIT License ;; ;; Copyright (c) 2011 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 ;; 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 net.auxesia.test.chromosome (:use [net.auxesia.chromosome :as chromosome] :reload) (:use [clojure.test]) (:use [clojure.set])) (deftest test-fitness (testing "fitness function" (testing "Perfect fitness" (is (= 0 (:fitness (chromosome/generate "Hello, world!"))))) (testing "Random genes" (is (= 399 (:fitness (chromosome/generate "H5p&J;!l<X\\7l")))) (is (= 297 (:fitness (chromosome/generate "Vc;fx#QRP8V\\$")))) (is (= 415 (:fitness (chromosome/generate "t\\O`E_Jx$n=NF"))))))) (deftest test-generate (testing "generate function" (loop [c (chromosome/generate) idx (int 0)] (if (== idx 1000) true (do (is (>= (:fitness c) 0)) (is (== (count chromosome/*target-gene*) (count (:gene c)))) (let [gene (:gene c)] (loop [g-idx (int 0)] (if (== g-idx (count gene)) true (if (and (>= (int (get gene g-idx)) 32) (<= (int (get gene g-idx)) 121)) (recur (inc g-idx)) (is (false "Invalid character found!")))))) (recur (chromosome/generate) (inc idx))))))) (deftest test-mutate (testing "mutate function" (loop [c (chromosome/generate) idx (int 0)] (if (== idx 1000) true (let [mutated (chromosome/mutate c) set1 (apply sorted-set (:gene c)) set2 (apply sorted-set (:gene mutated))] (do (testing "Gene size for mutated chromosome" (is (== (count (:gene c)) (count (:gene mutated))))) (testing "Difference count for mutated gene" (is (<= (count (clojure.set/difference set1 set2)) 1))) (recur (chromosome/generate) (inc idx)))))))) (defn- find-pivot "Helper method used to find a pivot point between two strings." [s1 s2] (let [size (count s1)] (loop [idx (int 0)] (cond (== size idx) nil (not= (get s1 idx) (get s2 idx)) idx :default (recur (inc idx)))))) (deftest test-mate (testing "The mate function" (let [c1 (chromosome/generate) c2 (chromosome/generate) children (chromosome/mate c1 c2) pivot (find-pivot (:gene c1) (:gene (first children)))] (do (testing "Size of returned sequence from the mate function" (is (== 2 (count children)))) (testing "Size of the gene from the first child" (is (== (count chromosome/*target-gene*) (count (:gene (first children)))))) (testing "Size of the gene from the second child" (is (== (count chromosome/*target-gene*) (count (:gene (last children)))))) (testing "Mating results from the first child" (loop [g-idx 0] ; Check the first child (when (< g-idx (count (:gene c1))) (if (< g-idx pivot) (is (= (get (:gene c1) g-idx) (get (:gene (first children)) g-idx))) (is (= (get (:gene c2) g-idx) (get (:gene (first children)) g-idx)))) (recur (inc g-idx))))) (testing "Mating results from the second child" (loop [g-idx 0] ; Check the second child (when (< g-idx (count (:gene c2))) (if (< g-idx pivot) (is (= (get (:gene c2) g-idx) (get (:gene (second children)) g-idx))) (is (= (get (:gene c1) g-idx) (get (:gene (second children)) g-idx)))) (recur (inc g-idx)))))))))
[ { "context": "(ns vismod-reframe.db)\n\n(def default-db\n {:name \"Ryan\"\n :open-main-menu false \n :active-solver :mul", "end": 54, "score": 0.6950135231018066, "start": 50, "tag": "NAME", "value": "Ryan" } ]
src/cljs/vismod_reframe/db.cljs
rozifus/vismod-reframe
0
(ns vismod-reframe.db) (def default-db {:name "Ryan" :open-main-menu false :active-solver :multorder })
105863
(ns vismod-reframe.db) (def default-db {:name "<NAME>" :open-main-menu false :active-solver :multorder })
true
(ns vismod-reframe.db) (def default-db {:name "PI:NAME:<NAME>END_PI" :open-main-menu false :active-solver :multorder })
[ { "context": "(ns tollbooth.core)\n\n; Joe Einertson\n; CSci 4651 Spring 2012 - Problem Set 8\n; http://", "end": 36, "score": 0.9998583793640137, "start": 23, "tag": "NAME", "value": "Joe Einertson" }, { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 252, "score": 0.9998553991317749, "start": 241, "tag": "NAME", "value": "Rich Hickey" } ]
src/tollbooth/core.clj
royaldark/clojure-tollbooth
0
(ns tollbooth.core) ; Joe Einertson ; CSci 4651 Spring 2012 - Problem Set 8 ; http://cda.morris.umn.edu/~elenam/4651spring2012/psets/ps8.html ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; car sim ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Common Public License 1.0 (http://opensource.org/licenses/cpl.php) ; which can be found in the file CPL.TXT 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. ;number of toll lanes (def lanes 50) ;length of each lane (def lane-length 45) ;pixels per world cell (def scale 10) ;toll wait lower bound (in ms) (def lower-wait 500) ;toll wait upper bound (in ms) (def upper-wait 1000) (def dir-delta {:south [0 1] :southwest [-1 1] :southeast [1 1]}) (def animation-sleep-ms 100) (def car-sleep-ms 80) (def running true) (defstruct cell :booth :car) ;world is a 2d vector of refs to cells (def world (apply vector (map (fn [_] (apply vector (map (fn [_] (ref (struct cell false false))) (range lane-length)))) (range lanes)))) (defn place [[x y]] (-> world (nth x) (nth y))) (defstruct car :dir) (defn create-car "create an car in the specified lane, returning an car agent on the location" [x] (sync nil (let [loc [x 0] p (place loc) a (struct car :south)] (alter p assoc :car a) (agent loc)))) (defn rand-in-bounds "returns a random integer between upper and lower bounds (inclusive)" [lower upper] (+ (rand-int (inc (- upper lower))) lower)) (defn despawn-car "waits a random amount of time and despawns a car" [a loc] (let [wait-time (rand-in-bounds lower-wait upper-wait) p (place loc)] (. Thread (sleep wait-time)) (sync nil (alter p assoc :car false)))) (defn setup-booths "places toll booths" [] (sync nil (doall (for [i (range lanes)] (let [p (place [i (dec lane-length)])] (alter p assoc :booth true)))))) (defn delta-loc "returns the location one step in the given dir. Note the world is a torus" [[x y] dir] (let [[dx dy] (dir-delta dir)] [(mod (+ x dx) lanes) (mod (+ y dy) lane-length)])) ;;;;;;;;;;;;;;;;;;;;;;;;;; car agent functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;a car agent tracks the location of an car, and controls the behavior of ;the car at that location (defn move "moves the car a certain direction. Must be called in a transaction that has verified the way is clear" [loc dir] (let [oldp (place loc) car (:car @oldp) newloc (delta-loc loc dir) p (place newloc)] ;move the car (alter p assoc :car car) (alter oldp assoc :car false) newloc)) (defn behave "the main function for the car agent" [loc] (let [p (place loc) car (:car @p) ahead (place (delta-loc loc :south)) ahead-left (place (delta-loc loc :southeast)) ahead-right (place (delta-loc loc :southwest))] (. Thread (sleep car-sleep-ms)) (dosync (when (and running (not (:booth @ahead))) (send-off *agent* #'behave)) (cond (:booth @ahead) (send-off *agent* #'despawn-car loc) (not (:car @ahead)) (move loc :south) (not (:car @ahead-left)) (move loc :southeast) (not (:car @ahead-right)) (move loc :southwest) :else ; (:car @ahead) loc)))) (defn spawn-loop "sleeps a random amount of time, then spawns a car" [x] (while running (let [wait-time (rand-in-bounds lower-wait upper-wait)] (. Thread (sleep wait-time)) (send-off (create-car x) #'behave)))) (defn start-spawners "creates one car spawner per lane and spins it off into its own thread, which then begins execution" [] (doall (for [i (range lanes)] (.start (Thread. #(spawn-loop i)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; UI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (import '(java.awt Color Graphics Dimension) '(java.awt.image BufferedImage) '(javax.swing JPanel JFrame)) (defn fill-cell [#^Graphics g x y c] (doto g (.setColor c) (.fillRect (* x scale) (* y scale) scale scale))) (defn render-car [car #^Graphics g x y] (let [black (. (new Color 0 0 0 255) (getRGB)) gray (. (new Color 100 100 100 255) (getRGB)) red (. (new Color 255 0 0 255) (getRGB)) [hx hy tx ty] [2 4 2 0]] (doto g (.setColor (new Color 0 0 0 255)) (.fillRect (* scale (+ 0.25 x)) (* scale (+ 0.125 y)) (* 0.5 scale) (* 0.75 scale))))) (defn render-place [g p x y] (when (:booth p) (fill-cell g x y (new Color 255 0 0 255))) (when (:car p) (render-car (:car p) g x y))) (defn render [g] (let [v (dosync (apply vector (for [x (range lanes) y (range lane-length)] @(place [x y])))) img (new BufferedImage (* scale lanes) (* scale lane-length) (. BufferedImage TYPE_INT_ARGB)) bg (. img (getGraphics))] (doto bg (.setColor (. Color white)) (.fillRect 0 0 (. img (getWidth)) (. img (getHeight)))) (dorun (for [x (range lanes) y (range lane-length)] (let [zzz (v (+ (* x lane-length) y))] (render-place bg zzz x y) ))) (doto bg (.setColor (. Color blue))) (. g (drawImage img 0 0 nil)) (. bg (dispose)))) (def panel (doto (proxy [JPanel] [] (paint [g] (render g))) (.setPreferredSize (new Dimension (* scale lanes) (* scale lane-length))))) (def frame (doto (new JFrame "Toll Booth Simulation") (.add panel) .pack .show)) (def animator (agent nil)) (defn animation [x] (when running (send-off *agent* #'animation)) (. panel (repaint)) (. Thread (sleep animation-sleep-ms)) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; use ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn -main [& args] (setup-booths) (send-off animator animation) (start-spawners))
117457
(ns tollbooth.core) ; <NAME> ; CSci 4651 Spring 2012 - Problem Set 8 ; http://cda.morris.umn.edu/~elenam/4651spring2012/psets/ps8.html ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; car sim ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Common Public License 1.0 (http://opensource.org/licenses/cpl.php) ; which can be found in the file CPL.TXT 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. ;number of toll lanes (def lanes 50) ;length of each lane (def lane-length 45) ;pixels per world cell (def scale 10) ;toll wait lower bound (in ms) (def lower-wait 500) ;toll wait upper bound (in ms) (def upper-wait 1000) (def dir-delta {:south [0 1] :southwest [-1 1] :southeast [1 1]}) (def animation-sleep-ms 100) (def car-sleep-ms 80) (def running true) (defstruct cell :booth :car) ;world is a 2d vector of refs to cells (def world (apply vector (map (fn [_] (apply vector (map (fn [_] (ref (struct cell false false))) (range lane-length)))) (range lanes)))) (defn place [[x y]] (-> world (nth x) (nth y))) (defstruct car :dir) (defn create-car "create an car in the specified lane, returning an car agent on the location" [x] (sync nil (let [loc [x 0] p (place loc) a (struct car :south)] (alter p assoc :car a) (agent loc)))) (defn rand-in-bounds "returns a random integer between upper and lower bounds (inclusive)" [lower upper] (+ (rand-int (inc (- upper lower))) lower)) (defn despawn-car "waits a random amount of time and despawns a car" [a loc] (let [wait-time (rand-in-bounds lower-wait upper-wait) p (place loc)] (. Thread (sleep wait-time)) (sync nil (alter p assoc :car false)))) (defn setup-booths "places toll booths" [] (sync nil (doall (for [i (range lanes)] (let [p (place [i (dec lane-length)])] (alter p assoc :booth true)))))) (defn delta-loc "returns the location one step in the given dir. Note the world is a torus" [[x y] dir] (let [[dx dy] (dir-delta dir)] [(mod (+ x dx) lanes) (mod (+ y dy) lane-length)])) ;;;;;;;;;;;;;;;;;;;;;;;;;; car agent functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;a car agent tracks the location of an car, and controls the behavior of ;the car at that location (defn move "moves the car a certain direction. Must be called in a transaction that has verified the way is clear" [loc dir] (let [oldp (place loc) car (:car @oldp) newloc (delta-loc loc dir) p (place newloc)] ;move the car (alter p assoc :car car) (alter oldp assoc :car false) newloc)) (defn behave "the main function for the car agent" [loc] (let [p (place loc) car (:car @p) ahead (place (delta-loc loc :south)) ahead-left (place (delta-loc loc :southeast)) ahead-right (place (delta-loc loc :southwest))] (. Thread (sleep car-sleep-ms)) (dosync (when (and running (not (:booth @ahead))) (send-off *agent* #'behave)) (cond (:booth @ahead) (send-off *agent* #'despawn-car loc) (not (:car @ahead)) (move loc :south) (not (:car @ahead-left)) (move loc :southeast) (not (:car @ahead-right)) (move loc :southwest) :else ; (:car @ahead) loc)))) (defn spawn-loop "sleeps a random amount of time, then spawns a car" [x] (while running (let [wait-time (rand-in-bounds lower-wait upper-wait)] (. Thread (sleep wait-time)) (send-off (create-car x) #'behave)))) (defn start-spawners "creates one car spawner per lane and spins it off into its own thread, which then begins execution" [] (doall (for [i (range lanes)] (.start (Thread. #(spawn-loop i)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; UI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (import '(java.awt Color Graphics Dimension) '(java.awt.image BufferedImage) '(javax.swing JPanel JFrame)) (defn fill-cell [#^Graphics g x y c] (doto g (.setColor c) (.fillRect (* x scale) (* y scale) scale scale))) (defn render-car [car #^Graphics g x y] (let [black (. (new Color 0 0 0 255) (getRGB)) gray (. (new Color 100 100 100 255) (getRGB)) red (. (new Color 255 0 0 255) (getRGB)) [hx hy tx ty] [2 4 2 0]] (doto g (.setColor (new Color 0 0 0 255)) (.fillRect (* scale (+ 0.25 x)) (* scale (+ 0.125 y)) (* 0.5 scale) (* 0.75 scale))))) (defn render-place [g p x y] (when (:booth p) (fill-cell g x y (new Color 255 0 0 255))) (when (:car p) (render-car (:car p) g x y))) (defn render [g] (let [v (dosync (apply vector (for [x (range lanes) y (range lane-length)] @(place [x y])))) img (new BufferedImage (* scale lanes) (* scale lane-length) (. BufferedImage TYPE_INT_ARGB)) bg (. img (getGraphics))] (doto bg (.setColor (. Color white)) (.fillRect 0 0 (. img (getWidth)) (. img (getHeight)))) (dorun (for [x (range lanes) y (range lane-length)] (let [zzz (v (+ (* x lane-length) y))] (render-place bg zzz x y) ))) (doto bg (.setColor (. Color blue))) (. g (drawImage img 0 0 nil)) (. bg (dispose)))) (def panel (doto (proxy [JPanel] [] (paint [g] (render g))) (.setPreferredSize (new Dimension (* scale lanes) (* scale lane-length))))) (def frame (doto (new JFrame "Toll Booth Simulation") (.add panel) .pack .show)) (def animator (agent nil)) (defn animation [x] (when running (send-off *agent* #'animation)) (. panel (repaint)) (. Thread (sleep animation-sleep-ms)) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; use ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn -main [& args] (setup-booths) (send-off animator animation) (start-spawners))
true
(ns tollbooth.core) ; PI:NAME:<NAME>END_PI ; CSci 4651 Spring 2012 - Problem Set 8 ; http://cda.morris.umn.edu/~elenam/4651spring2012/psets/ps8.html ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; car sim ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Common Public License 1.0 (http://opensource.org/licenses/cpl.php) ; which can be found in the file CPL.TXT 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. ;number of toll lanes (def lanes 50) ;length of each lane (def lane-length 45) ;pixels per world cell (def scale 10) ;toll wait lower bound (in ms) (def lower-wait 500) ;toll wait upper bound (in ms) (def upper-wait 1000) (def dir-delta {:south [0 1] :southwest [-1 1] :southeast [1 1]}) (def animation-sleep-ms 100) (def car-sleep-ms 80) (def running true) (defstruct cell :booth :car) ;world is a 2d vector of refs to cells (def world (apply vector (map (fn [_] (apply vector (map (fn [_] (ref (struct cell false false))) (range lane-length)))) (range lanes)))) (defn place [[x y]] (-> world (nth x) (nth y))) (defstruct car :dir) (defn create-car "create an car in the specified lane, returning an car agent on the location" [x] (sync nil (let [loc [x 0] p (place loc) a (struct car :south)] (alter p assoc :car a) (agent loc)))) (defn rand-in-bounds "returns a random integer between upper and lower bounds (inclusive)" [lower upper] (+ (rand-int (inc (- upper lower))) lower)) (defn despawn-car "waits a random amount of time and despawns a car" [a loc] (let [wait-time (rand-in-bounds lower-wait upper-wait) p (place loc)] (. Thread (sleep wait-time)) (sync nil (alter p assoc :car false)))) (defn setup-booths "places toll booths" [] (sync nil (doall (for [i (range lanes)] (let [p (place [i (dec lane-length)])] (alter p assoc :booth true)))))) (defn delta-loc "returns the location one step in the given dir. Note the world is a torus" [[x y] dir] (let [[dx dy] (dir-delta dir)] [(mod (+ x dx) lanes) (mod (+ y dy) lane-length)])) ;;;;;;;;;;;;;;;;;;;;;;;;;; car agent functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;a car agent tracks the location of an car, and controls the behavior of ;the car at that location (defn move "moves the car a certain direction. Must be called in a transaction that has verified the way is clear" [loc dir] (let [oldp (place loc) car (:car @oldp) newloc (delta-loc loc dir) p (place newloc)] ;move the car (alter p assoc :car car) (alter oldp assoc :car false) newloc)) (defn behave "the main function for the car agent" [loc] (let [p (place loc) car (:car @p) ahead (place (delta-loc loc :south)) ahead-left (place (delta-loc loc :southeast)) ahead-right (place (delta-loc loc :southwest))] (. Thread (sleep car-sleep-ms)) (dosync (when (and running (not (:booth @ahead))) (send-off *agent* #'behave)) (cond (:booth @ahead) (send-off *agent* #'despawn-car loc) (not (:car @ahead)) (move loc :south) (not (:car @ahead-left)) (move loc :southeast) (not (:car @ahead-right)) (move loc :southwest) :else ; (:car @ahead) loc)))) (defn spawn-loop "sleeps a random amount of time, then spawns a car" [x] (while running (let [wait-time (rand-in-bounds lower-wait upper-wait)] (. Thread (sleep wait-time)) (send-off (create-car x) #'behave)))) (defn start-spawners "creates one car spawner per lane and spins it off into its own thread, which then begins execution" [] (doall (for [i (range lanes)] (.start (Thread. #(spawn-loop i)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; UI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (import '(java.awt Color Graphics Dimension) '(java.awt.image BufferedImage) '(javax.swing JPanel JFrame)) (defn fill-cell [#^Graphics g x y c] (doto g (.setColor c) (.fillRect (* x scale) (* y scale) scale scale))) (defn render-car [car #^Graphics g x y] (let [black (. (new Color 0 0 0 255) (getRGB)) gray (. (new Color 100 100 100 255) (getRGB)) red (. (new Color 255 0 0 255) (getRGB)) [hx hy tx ty] [2 4 2 0]] (doto g (.setColor (new Color 0 0 0 255)) (.fillRect (* scale (+ 0.25 x)) (* scale (+ 0.125 y)) (* 0.5 scale) (* 0.75 scale))))) (defn render-place [g p x y] (when (:booth p) (fill-cell g x y (new Color 255 0 0 255))) (when (:car p) (render-car (:car p) g x y))) (defn render [g] (let [v (dosync (apply vector (for [x (range lanes) y (range lane-length)] @(place [x y])))) img (new BufferedImage (* scale lanes) (* scale lane-length) (. BufferedImage TYPE_INT_ARGB)) bg (. img (getGraphics))] (doto bg (.setColor (. Color white)) (.fillRect 0 0 (. img (getWidth)) (. img (getHeight)))) (dorun (for [x (range lanes) y (range lane-length)] (let [zzz (v (+ (* x lane-length) y))] (render-place bg zzz x y) ))) (doto bg (.setColor (. Color blue))) (. g (drawImage img 0 0 nil)) (. bg (dispose)))) (def panel (doto (proxy [JPanel] [] (paint [g] (render g))) (.setPreferredSize (new Dimension (* scale lanes) (* scale lane-length))))) (def frame (doto (new JFrame "Toll Booth Simulation") (.add panel) .pack .show)) (def animator (agent nil)) (defn animation [x] (when running (send-off *agent* #'animation)) (. panel (repaint)) (. Thread (sleep animation-sleep-ms)) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; use ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn -main [& args] (setup-booths) (send-off animator animation) (start-spawners))
[ { "context": "\n(def opts\n {:values {:email \"foobar\" :password \"p@sswOad\"}\n :errors {:email \"please input your email add", "end": 587, "score": 0.999417245388031, "start": 579, "tag": "PASSWORD", "value": "p@sswOad" }, { "context": " {:type :password :name :password :placeholer \"Password\"}]]\n [:button.btn.btn-primary {:type :submit}", "end": 1213, "score": 0.9658990502357483, "start": 1205, "tag": "PASSWORD", "value": "Password" } ]
examples/cljs/src-cljs/example/core.cljs
ayato-p/kuuga
23
(ns example.core (:require [kuuga.ultimate :as ultimate :include-macros true] [rum.core :as rum])) (defn invalid-feedback [opts tagopts] (let [err-msg (get-in opts [:errors (:name tagopts)])] [:div.invalid-feedback err-msg])) (defn update-input-opts [opts tagopts] (let [{:keys [values errors]} opts tname (:name tagopts)] (-> tagopts (assoc :class (if (contains? errors tname) "is-invalid" "is-valid")) (cond-> (some? (get values tname)) (assoc :value (get values tname)))))) (def opts {:values {:email "foobar" :password "p@sswOad"} :errors {:email "please input your email address"}}) (rum/defc macro-form [opts] [:div [:h1 "Transformed form"] (ultimate/transform opts [:form {:method :post} [:div.form-group [:label {:for "input-email"} "Email address"] [:input#input-email.form-control {:type :email :name :email :placeholer "Enter email"}] [:small.form-text.text-muted "We'll never share your email with anyone else."]] [:div.form-group [:label {:for "input-password"} "Password"] [:input#input-password.form-control {:type :password :name :password :placeholer "Password"}]] [:button.btn.btn-primary {:type :submit} "Submit"]])]) (defn main [] (let [elm (js/document.querySelector "div.container")] (rum/mount (macro-form opts) elm))) (main)
38931
(ns example.core (:require [kuuga.ultimate :as ultimate :include-macros true] [rum.core :as rum])) (defn invalid-feedback [opts tagopts] (let [err-msg (get-in opts [:errors (:name tagopts)])] [:div.invalid-feedback err-msg])) (defn update-input-opts [opts tagopts] (let [{:keys [values errors]} opts tname (:name tagopts)] (-> tagopts (assoc :class (if (contains? errors tname) "is-invalid" "is-valid")) (cond-> (some? (get values tname)) (assoc :value (get values tname)))))) (def opts {:values {:email "foobar" :password "<PASSWORD>"} :errors {:email "please input your email address"}}) (rum/defc macro-form [opts] [:div [:h1 "Transformed form"] (ultimate/transform opts [:form {:method :post} [:div.form-group [:label {:for "input-email"} "Email address"] [:input#input-email.form-control {:type :email :name :email :placeholer "Enter email"}] [:small.form-text.text-muted "We'll never share your email with anyone else."]] [:div.form-group [:label {:for "input-password"} "Password"] [:input#input-password.form-control {:type :password :name :password :placeholer "<PASSWORD>"}]] [:button.btn.btn-primary {:type :submit} "Submit"]])]) (defn main [] (let [elm (js/document.querySelector "div.container")] (rum/mount (macro-form opts) elm))) (main)
true
(ns example.core (:require [kuuga.ultimate :as ultimate :include-macros true] [rum.core :as rum])) (defn invalid-feedback [opts tagopts] (let [err-msg (get-in opts [:errors (:name tagopts)])] [:div.invalid-feedback err-msg])) (defn update-input-opts [opts tagopts] (let [{:keys [values errors]} opts tname (:name tagopts)] (-> tagopts (assoc :class (if (contains? errors tname) "is-invalid" "is-valid")) (cond-> (some? (get values tname)) (assoc :value (get values tname)))))) (def opts {:values {:email "foobar" :password "PI:PASSWORD:<PASSWORD>END_PI"} :errors {:email "please input your email address"}}) (rum/defc macro-form [opts] [:div [:h1 "Transformed form"] (ultimate/transform opts [:form {:method :post} [:div.form-group [:label {:for "input-email"} "Email address"] [:input#input-email.form-control {:type :email :name :email :placeholer "Enter email"}] [:small.form-text.text-muted "We'll never share your email with anyone else."]] [:div.form-group [:label {:for "input-password"} "Password"] [:input#input-password.form-control {:type :password :name :password :placeholer "PI:PASSWORD:<PASSWORD>END_PI"}]] [:button.btn.btn-primary {:type :submit} "Submit"]])]) (defn main [] (let [elm (js/document.querySelector "div.container")] (rum/mount (macro-form opts) elm))) (main)
[ { "context": " (fn [_] {:host \"smtp@example.com\"\n :", "end": 1815, "score": 0.9998413324356079, "start": 1799, "tag": "EMAIL", "value": "smtp@example.com" }, { "context": " :user \"admin\"\n :", "end": 1991, "score": 0.9819973707199097, "start": 1986, "tag": "USERNAME", "value": "admin" }, { "context": " :pass \"password\"})\n\n ;; WARNING: This is a fragi", "end": 2055, "score": 0.9993875026702881, "start": 2047, "tag": "PASSWORD", "value": "password" }, { "context": " [\"one\", \"two\"]\n plaintext-password \"Plaintext-password-1\"\n jane-email \"jane@example.o", "end": 2610, "score": 0.999446451663971, "start": 2590, "tag": "PASSWORD", "value": "Plaintext-password-1" }, { "context": "ext-password-1\"\n jane-email \"jane@example.org\"\n\n href-create {:description ", "end": 2662, "score": 0.9999077320098877, "start": 2646, "tag": "EMAIL", "value": "jane@example.org" }, { "context": " :password plaintext-password\n :", "end": 2925, "score": 0.9864916801452637, "start": 2907, "tag": "PASSWORD", "value": "plaintext-password" }, { "context": " :username jane-email\n :pas", "end": 4438, "score": 0.9997066259384155, "start": 4428, "tag": "USERNAME", "value": "jane-email" }, { "context": " :password plaintext-password}}]\n\n ;; create user\n ;; user should", "end": 4512, "score": 0.9990403652191162, "start": 4494, "tag": "PASSWORD", "value": "plaintext-password" }, { "context": " (fn [_] {:host \"smtp@example.com\"\n :", "end": 19385, "score": 0.9952314496040344, "start": 19369, "tag": "EMAIL", "value": "smtp@example.com" }, { "context": " :user \"admin\"\n :", "end": 19561, "score": 0.9970354437828064, "start": 19556, "tag": "USERNAME", "value": "admin" }, { "context": " :pass \"password\"})\n\n ;; WARNING: This is a fragi", "end": 19625, "score": 0.9993934631347656, "start": 19617, "tag": "PASSWORD", "value": "password" }, { "context": " [\"one\", \"two\"]\n plaintext-password \"Plaintext-password-1\"\n tarzan-email \"tarzan@example", "end": 20180, "score": 0.9994635581970215, "start": 20160, "tag": "PASSWORD", "value": "Plaintext-password-1" }, { "context": "ext-password-1\"\n tarzan-email \"tarzan@example.org\"\n\n href-create {:description ", "end": 20234, "score": 0.9999227523803711, "start": 20216, "tag": "EMAIL", "value": "tarzan@example.org" }, { "context": " :password plaintext-password\n :", "end": 20497, "score": 0.9981510043144226, "start": 20479, "tag": "PASSWORD", "value": "plaintext-password" }, { "context": " :username tarzan-email\n :pas", "end": 22015, "score": 0.999616801738739, "start": 22003, "tag": "USERNAME", "value": "tarzan-email" }, { "context": " :password plaintext-password}}\n secret (atom nil)\n ", "end": 22089, "score": 0.9991741180419922, "start": 22071, "tag": "PASSWORD", "value": "plaintext-password" } ]
code/test/sixsq/nuvla/server/resources/user_email_password_2fa_lifecycle_test.clj
nuvla/server
0
(ns sixsq.nuvla.server.resources.user-email-password-2fa-lifecycle-test (:require [clojure.data.json :as json] [clojure.string :as str] [clojure.test :refer [deftest is use-fixtures]] [one-time.core :as ot] [peridot.core :refer [content-type header request session]] [postal.core :as postal] [ring.util.codec :as codec] [sixsq.nuvla.server.app.params :as p] [sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]] [sixsq.nuvla.server.resources.email.sending :as email-sending] [sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu] [sixsq.nuvla.server.resources.session :as session] [sixsq.nuvla.server.resources.session-template :as st] [sixsq.nuvla.server.resources.two-factor-auth.utils :as auth-2fa] [sixsq.nuvla.server.resources.user :as user] [sixsq.nuvla.server.resources.user-template :as user-tpl] [sixsq.nuvla.server.resources.user-template-email-password :as email-password] [sixsq.nuvla.server.util.metadata-test-utils :as mdtu])) (use-fixtures :once ltu/with-test-server-fixture) (def base-uri (str p/service-context user/resource-type)) (deftest check-metadata (mdtu/check-metadata-exists (str user-tpl/resource-type "-" email-password/resource-url))) (deftest lifecycle-email (let [email-body (atom nil) session (-> (ltu/ring-app) session (content-type "application/json")) session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] (with-redefs [email-sending/extract-smtp-cfg (fn [_] {:host "smtp@example.com" :port 465 :ssl true :user "admin" :pass "password"}) ;; WARNING: This is a fragile Regex matching to recover callback URL. postal/send-message (fn [_ {:keys [body]}] (reset! email-body body) {:code 0, :error :SUCCESS, :message "OK"})] (let [href (str user-tpl/resource-type "/" email-password/registration-method) description-attr "description" tags-attr ["one", "two"] plaintext-password "Plaintext-password-1" jane-email "jane@example.org" href-create {:description description-attr :tags tags-attr :template {:href href :password plaintext-password :email jane-email}} resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (ltu/body-resource-id resp) user-url (str p/service-context user-id) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) enable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-present :enable-2fa) (ltu/is-operation-absent :disable-2fa) (ltu/get-op-url :enable-2fa)) validation-link (->> @email-body second :content (re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*") second) session-base-url (str p/service-context session/resource-type) valid-session-create {:template {:href (str st/resource-type "/password") :username jane-email :password plaintext-password}}] ;; create user ;; user should provide method (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {})) (ltu/body->edn) (ltu/message-matches "resource does not satisfy defined schema") (ltu/is-status 400)) ;; user should have a validated email (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-email})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches "User should have a validated email.")) ;; check validation of resource (is (not (nil? validation-link))) (-> session-admin (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200)) (is (re-matches #"^email.*successfully validated$" (-> session-anon (request validation-link) (ltu/body->edn) (ltu/is-status 200) (ltu/body) :message))) ;; user is able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) (let [location (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-email})) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to enable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa nil)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)) ;; user should not be able to remove :auth-method by edit (-> session-created-user (request (str user-url "?select=id,auth-method-2fa") :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)))) ;; create session should now return callback to validate token (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; session is created when token is valid (let [session-url (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201) (ltu/location-url))] (-> session-admin (request session-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :user user-id) (ltu/is-key-value :identifier jane-email)) ;; after a successful execution of callback, callback is no more executable (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409) (ltu/message-matches "cannot re-execute callback"))))) ;; create session will not be possible after 3 faillures, even with right token at 4th try (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ;; user should be able to execute callback 3 times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; 4th try with right token will fail (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409)))) ;; user should be able to disable 2fa (let [disable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-absent :enable-2fa) (ltu/is-operation-present :disable-2fa) (ltu/get-op-url :disable-2fa)) location (-> session-created-user (request disable-2fa-url) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to disable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data "none") (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set to none (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa "none")) ;; user is re-able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) )) ) ))) (deftest lifecycle-totp (let [email-body (atom nil) session (-> (ltu/ring-app) session (content-type "application/json")) session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] (with-redefs [email-sending/extract-smtp-cfg (fn [_] {:host "smtp@example.com" :port 465 :ssl true :user "admin" :pass "password"}) ;; WARNING: This is a fragile Regex matching to recover callback URL. postal/send-message (fn [_ {:keys [body]}] (reset! email-body body) {:code 0, :error :SUCCESS, :message "OK"})] (let [href (str user-tpl/resource-type "/" email-password/registration-method) description-attr "description" tags-attr ["one", "two"] plaintext-password "Plaintext-password-1" tarzan-email "tarzan@example.org" href-create {:description description-attr :tags tags-attr :template {:href href :password plaintext-password :email tarzan-email}} resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (ltu/body-resource-id resp) user-url (str p/service-context user-id) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) enable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-present :enable-2fa) (ltu/is-operation-absent :disable-2fa) (ltu/get-op-url :enable-2fa)) validation-link (->> @email-body second :content (re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*") second) session-base-url (str p/service-context session/resource-type) valid-session-create {:template {:href (str st/resource-type "/password") :username tarzan-email :password plaintext-password}} secret (atom nil) get-totp (comp str ot/get-totp-token)] ;; create user ;; user should provide method (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {})) (ltu/body->edn) (ltu/message-matches "resource does not satisfy defined schema") (ltu/is-status 400)) (is (re-matches #"^email.*successfully validated$" (-> session-anon (request validation-link) (ltu/body->edn) (ltu/is-status 200) (ltu/body) :message))) ;; user is able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) (let [enable-resp (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-totp})) (ltu/body->edn) (ltu/is-status 200) (ltu/body)) location (:location enable-resp)] (reset! secret (:secret enable-resp)) ;; user should not be able to enable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa nil)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp) (ltu/is-key-value (comp not str/blank?) :credential-totp true)) ;; user should not be able to remove :auth-method by edit (-> session-created-user (request (str user-url "?select=id,auth-method-2fa,credential-totp") :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp) (ltu/is-key-value (comp not str/blank?) :credential-totp true)))) ;; create session should now return callback to validate token (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (get-totp @secret)] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; session is created when token is valid (let [session-url (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201) (ltu/location-url))] (-> session-admin (request session-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :user user-id) (ltu/is-key-value :identifier tarzan-email)) ;; after a successful execution of callback, callback is no more executable (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409) (ltu/message-matches "cannot re-execute callback"))))) ;; create session will not be possible after 3 faillures, even with right token at 4th try (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ;; user should be able to execute callback 3 times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; 4th try with right token will fail (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 409)))) ;; user should be able to disable 2fa (let [disable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-absent :enable-2fa) (ltu/is-operation-present :disable-2fa) (ltu/get-op-url :disable-2fa)) location (-> session-created-user (request disable-2fa-url) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to disable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data "none")) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set to none (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa "none")) ;; user is re-able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) )) ) )))
37137
(ns sixsq.nuvla.server.resources.user-email-password-2fa-lifecycle-test (:require [clojure.data.json :as json] [clojure.string :as str] [clojure.test :refer [deftest is use-fixtures]] [one-time.core :as ot] [peridot.core :refer [content-type header request session]] [postal.core :as postal] [ring.util.codec :as codec] [sixsq.nuvla.server.app.params :as p] [sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]] [sixsq.nuvla.server.resources.email.sending :as email-sending] [sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu] [sixsq.nuvla.server.resources.session :as session] [sixsq.nuvla.server.resources.session-template :as st] [sixsq.nuvla.server.resources.two-factor-auth.utils :as auth-2fa] [sixsq.nuvla.server.resources.user :as user] [sixsq.nuvla.server.resources.user-template :as user-tpl] [sixsq.nuvla.server.resources.user-template-email-password :as email-password] [sixsq.nuvla.server.util.metadata-test-utils :as mdtu])) (use-fixtures :once ltu/with-test-server-fixture) (def base-uri (str p/service-context user/resource-type)) (deftest check-metadata (mdtu/check-metadata-exists (str user-tpl/resource-type "-" email-password/resource-url))) (deftest lifecycle-email (let [email-body (atom nil) session (-> (ltu/ring-app) session (content-type "application/json")) session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] (with-redefs [email-sending/extract-smtp-cfg (fn [_] {:host "<EMAIL>" :port 465 :ssl true :user "admin" :pass "<PASSWORD>"}) ;; WARNING: This is a fragile Regex matching to recover callback URL. postal/send-message (fn [_ {:keys [body]}] (reset! email-body body) {:code 0, :error :SUCCESS, :message "OK"})] (let [href (str user-tpl/resource-type "/" email-password/registration-method) description-attr "description" tags-attr ["one", "two"] plaintext-password "<PASSWORD>" jane-email "<EMAIL>" href-create {:description description-attr :tags tags-attr :template {:href href :password <PASSWORD> :email jane-email}} resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (ltu/body-resource-id resp) user-url (str p/service-context user-id) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) enable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-present :enable-2fa) (ltu/is-operation-absent :disable-2fa) (ltu/get-op-url :enable-2fa)) validation-link (->> @email-body second :content (re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*") second) session-base-url (str p/service-context session/resource-type) valid-session-create {:template {:href (str st/resource-type "/password") :username jane-email :password <PASSWORD>}}] ;; create user ;; user should provide method (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {})) (ltu/body->edn) (ltu/message-matches "resource does not satisfy defined schema") (ltu/is-status 400)) ;; user should have a validated email (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-email})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches "User should have a validated email.")) ;; check validation of resource (is (not (nil? validation-link))) (-> session-admin (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200)) (is (re-matches #"^email.*successfully validated$" (-> session-anon (request validation-link) (ltu/body->edn) (ltu/is-status 200) (ltu/body) :message))) ;; user is able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) (let [location (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-email})) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to enable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa nil)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)) ;; user should not be able to remove :auth-method by edit (-> session-created-user (request (str user-url "?select=id,auth-method-2fa") :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)))) ;; create session should now return callback to validate token (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; session is created when token is valid (let [session-url (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201) (ltu/location-url))] (-> session-admin (request session-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :user user-id) (ltu/is-key-value :identifier jane-email)) ;; after a successful execution of callback, callback is no more executable (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409) (ltu/message-matches "cannot re-execute callback"))))) ;; create session will not be possible after 3 faillures, even with right token at 4th try (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ;; user should be able to execute callback 3 times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; 4th try with right token will fail (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409)))) ;; user should be able to disable 2fa (let [disable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-absent :enable-2fa) (ltu/is-operation-present :disable-2fa) (ltu/get-op-url :disable-2fa)) location (-> session-created-user (request disable-2fa-url) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to disable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data "none") (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set to none (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa "none")) ;; user is re-able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) )) ) ))) (deftest lifecycle-totp (let [email-body (atom nil) session (-> (ltu/ring-app) session (content-type "application/json")) session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] (with-redefs [email-sending/extract-smtp-cfg (fn [_] {:host "<EMAIL>" :port 465 :ssl true :user "admin" :pass "<PASSWORD>"}) ;; WARNING: This is a fragile Regex matching to recover callback URL. postal/send-message (fn [_ {:keys [body]}] (reset! email-body body) {:code 0, :error :SUCCESS, :message "OK"})] (let [href (str user-tpl/resource-type "/" email-password/registration-method) description-attr "description" tags-attr ["one", "two"] plaintext-password "<PASSWORD>" tarzan-email "<EMAIL>" href-create {:description description-attr :tags tags-attr :template {:href href :password <PASSWORD> :email tarzan-email}} resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (ltu/body-resource-id resp) user-url (str p/service-context user-id) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) enable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-present :enable-2fa) (ltu/is-operation-absent :disable-2fa) (ltu/get-op-url :enable-2fa)) validation-link (->> @email-body second :content (re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*") second) session-base-url (str p/service-context session/resource-type) valid-session-create {:template {:href (str st/resource-type "/password") :username tarzan-email :password <PASSWORD>}} secret (atom nil) get-totp (comp str ot/get-totp-token)] ;; create user ;; user should provide method (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {})) (ltu/body->edn) (ltu/message-matches "resource does not satisfy defined schema") (ltu/is-status 400)) (is (re-matches #"^email.*successfully validated$" (-> session-anon (request validation-link) (ltu/body->edn) (ltu/is-status 200) (ltu/body) :message))) ;; user is able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) (let [enable-resp (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-totp})) (ltu/body->edn) (ltu/is-status 200) (ltu/body)) location (:location enable-resp)] (reset! secret (:secret enable-resp)) ;; user should not be able to enable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa nil)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp) (ltu/is-key-value (comp not str/blank?) :credential-totp true)) ;; user should not be able to remove :auth-method by edit (-> session-created-user (request (str user-url "?select=id,auth-method-2fa,credential-totp") :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp) (ltu/is-key-value (comp not str/blank?) :credential-totp true)))) ;; create session should now return callback to validate token (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (get-totp @secret)] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; session is created when token is valid (let [session-url (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201) (ltu/location-url))] (-> session-admin (request session-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :user user-id) (ltu/is-key-value :identifier tarzan-email)) ;; after a successful execution of callback, callback is no more executable (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409) (ltu/message-matches "cannot re-execute callback"))))) ;; create session will not be possible after 3 faillures, even with right token at 4th try (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ;; user should be able to execute callback 3 times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; 4th try with right token will fail (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 409)))) ;; user should be able to disable 2fa (let [disable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-absent :enable-2fa) (ltu/is-operation-present :disable-2fa) (ltu/get-op-url :disable-2fa)) location (-> session-created-user (request disable-2fa-url) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to disable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data "none")) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set to none (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa "none")) ;; user is re-able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) )) ) )))
true
(ns sixsq.nuvla.server.resources.user-email-password-2fa-lifecycle-test (:require [clojure.data.json :as json] [clojure.string :as str] [clojure.test :refer [deftest is use-fixtures]] [one-time.core :as ot] [peridot.core :refer [content-type header request session]] [postal.core :as postal] [ring.util.codec :as codec] [sixsq.nuvla.server.app.params :as p] [sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]] [sixsq.nuvla.server.resources.email.sending :as email-sending] [sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu] [sixsq.nuvla.server.resources.session :as session] [sixsq.nuvla.server.resources.session-template :as st] [sixsq.nuvla.server.resources.two-factor-auth.utils :as auth-2fa] [sixsq.nuvla.server.resources.user :as user] [sixsq.nuvla.server.resources.user-template :as user-tpl] [sixsq.nuvla.server.resources.user-template-email-password :as email-password] [sixsq.nuvla.server.util.metadata-test-utils :as mdtu])) (use-fixtures :once ltu/with-test-server-fixture) (def base-uri (str p/service-context user/resource-type)) (deftest check-metadata (mdtu/check-metadata-exists (str user-tpl/resource-type "-" email-password/resource-url))) (deftest lifecycle-email (let [email-body (atom nil) session (-> (ltu/ring-app) session (content-type "application/json")) session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] (with-redefs [email-sending/extract-smtp-cfg (fn [_] {:host "PI:EMAIL:<EMAIL>END_PI" :port 465 :ssl true :user "admin" :pass "PI:PASSWORD:<PASSWORD>END_PI"}) ;; WARNING: This is a fragile Regex matching to recover callback URL. postal/send-message (fn [_ {:keys [body]}] (reset! email-body body) {:code 0, :error :SUCCESS, :message "OK"})] (let [href (str user-tpl/resource-type "/" email-password/registration-method) description-attr "description" tags-attr ["one", "two"] plaintext-password "PI:PASSWORD:<PASSWORD>END_PI" jane-email "PI:EMAIL:<EMAIL>END_PI" href-create {:description description-attr :tags tags-attr :template {:href href :password PI:PASSWORD:<PASSWORD>END_PI :email jane-email}} resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (ltu/body-resource-id resp) user-url (str p/service-context user-id) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) enable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-present :enable-2fa) (ltu/is-operation-absent :disable-2fa) (ltu/get-op-url :enable-2fa)) validation-link (->> @email-body second :content (re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*") second) session-base-url (str p/service-context session/resource-type) valid-session-create {:template {:href (str st/resource-type "/password") :username jane-email :password PI:PASSWORD:<PASSWORD>END_PI}}] ;; create user ;; user should provide method (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {})) (ltu/body->edn) (ltu/message-matches "resource does not satisfy defined schema") (ltu/is-status 400)) ;; user should have a validated email (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-email})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches "User should have a validated email.")) ;; check validation of resource (is (not (nil? validation-link))) (-> session-admin (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200)) (is (re-matches #"^email.*successfully validated$" (-> session-anon (request validation-link) (ltu/body->edn) (ltu/is-status 200) (ltu/body) :message))) ;; user is able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) (let [location (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-email})) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to enable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa nil)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)) ;; user should not be able to remove :auth-method by edit (-> session-created-user (request (str user-url "?select=id,auth-method-2fa") :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)))) ;; create session should now return callback to validate token (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; session is created when token is valid (let [session-url (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201) (ltu/location-url))] (-> session-admin (request session-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :user user-id) (ltu/is-key-value :identifier jane-email)) ;; after a successful execution of callback, callback is no more executable (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409) (ltu/message-matches "cannot re-execute callback"))))) ;; create session will not be possible after 3 faillures, even with right token at 4th try (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-email) (ltu/is-key-value :token :data user-token)) ;; user should be able to execute callback 3 times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; 4th try with right token will fail (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409)))) ;; user should be able to disable 2fa (let [disable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-absent :enable-2fa) (ltu/is-operation-present :disable-2fa) (ltu/get-op-url :disable-2fa)) location (-> session-created-user (request disable-2fa-url) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to disable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-email)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (->> @email-body second :content (re-find #"\d+"))] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data "none") (ltu/is-key-value :token :data user-token)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set to none (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa "none")) ;; user is re-able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) )) ) ))) (deftest lifecycle-totp (let [email-body (atom nil) session (-> (ltu/ring-app) session (content-type "application/json")) session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] (with-redefs [email-sending/extract-smtp-cfg (fn [_] {:host "PI:EMAIL:<EMAIL>END_PI" :port 465 :ssl true :user "admin" :pass "PI:PASSWORD:<PASSWORD>END_PI"}) ;; WARNING: This is a fragile Regex matching to recover callback URL. postal/send-message (fn [_ {:keys [body]}] (reset! email-body body) {:code 0, :error :SUCCESS, :message "OK"})] (let [href (str user-tpl/resource-type "/" email-password/registration-method) description-attr "description" tags-attr ["one", "two"] plaintext-password "PI:PASSWORD:<PASSWORD>END_PI" tarzan-email "PI:EMAIL:<EMAIL>END_PI" href-create {:description description-attr :tags tags-attr :template {:href href :password PI:PASSWORD:<PASSWORD>END_PI :email tarzan-email}} resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (ltu/body-resource-id resp) user-url (str p/service-context user-id) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) enable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-present :enable-2fa) (ltu/is-operation-absent :disable-2fa) (ltu/get-op-url :enable-2fa)) validation-link (->> @email-body second :content (re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*") second) session-base-url (str p/service-context session/resource-type) valid-session-create {:template {:href (str st/resource-type "/password") :username tarzan-email :password PI:PASSWORD:<PASSWORD>END_PI}} secret (atom nil) get-totp (comp str ot/get-totp-token)] ;; create user ;; user should provide method (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {})) (ltu/body->edn) (ltu/message-matches "resource does not satisfy defined schema") (ltu/is-status 400)) (is (re-matches #"^email.*successfully validated$" (-> session-anon (request validation-link) (ltu/body->edn) (ltu/is-status 200) (ltu/body) :message))) ;; user is able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) (let [enable-resp (-> session-created-user (request enable-2fa-url :request-method :post :body (json/write-str {:method auth-2fa/method-totp})) (ltu/body->edn) (ltu/is-status 200) (ltu/body)) location (:location enable-resp)] (reset! secret (:secret enable-resp)) ;; user should not be able to enable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa nil)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp) (ltu/is-key-value (comp not str/blank?) :credential-totp true)) ;; user should not be able to remove :auth-method by edit (-> session-created-user (request (str user-url "?select=id,auth-method-2fa,credential-totp") :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp) (ltu/is-key-value (comp not str/blank?) :credential-totp true)))) ;; create session should now return callback to validate token (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute") user-token (get-totp @secret)] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; session is created when token is valid (let [session-url (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201) (ltu/location-url))] (-> session-admin (request session-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :user user-id) (ltu/is-key-value :identifier tarzan-email)) ;; after a successful execution of callback, callback is no more executable (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token user-token})) (ltu/body->edn) (ltu/is-status 409) (ltu/message-matches "cannot re-execute callback"))))) ;; create session will not be possible after 3 faillures, even with right token at 4th try (let [location (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data auth-2fa/method-totp)) ;; user should be able to execute callback 3 times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) ;; 4th try with right token will fail (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 409)))) ;; user should be able to disable 2fa (let [disable-2fa-url (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-operation-absent :enable-2fa) (ltu/is-operation-present :disable-2fa) (ltu/get-op-url :disable-2fa)) location (-> session-created-user (request disable-2fa-url) (ltu/body->edn) (ltu/is-status 200) (ltu/location))] ;; user should not be able to disable 2FA until callback get successfully activated (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa auth-2fa/method-totp)) (is (re-matches #"http.*\/api\/callback\/.*\/execute" location)) (let [callback-url (->> location codec/url-decode (re-matches #"http.*(\/api.*)\/execute") second) callback-exec-url (str callback-url "/execute")] (-> session-admin (request callback-url) (ltu/body->edn) (ltu/is-status 200) (ltu/is-key-value :method :data "none")) ; user should not be able to see callback data (-> session-created-user (request callback-url) (ltu/body->edn) (ltu/is-status 403)) ;; user should be able to execute callback multiple times (-> session-created-user (request callback-exec-url :request-method :put :body (json/write-str {})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token "wrong"})) (ltu/body->edn) (ltu/is-status 400) (ltu/message-matches auth-2fa/msg-wrong-2fa-token)) (-> session-anon (request callback-exec-url :request-method :put :body (json/write-str {:token (get-totp @secret)})) (ltu/body->edn) (ltu/is-status 200)) ;; user 2FA method should be set to none (-> session-created-user (request user-url) (ltu/body->edn) (ltu/is-key-value :auth-method-2fa "none")) ;; user is re-able to get session without 2FA (-> session-anon (request session-base-url :request-method :post :body (json/write-str valid-session-create)) (ltu/body->edn) (ltu/is-set-cookie) (ltu/is-status 201)) )) ) )))
[ { "context": "]}]\n (let [geometry {:href \"https://github.com/reagent-project/reagent/tree/master/examples/geometry\"}\n j", "end": 1000, "score": 0.8746428489685059, "start": 987, "tag": "USERNAME", "value": "agent-project" }, { "context": "metry\"}\n jonase {:href \"https://github.com/jonase\"}]\n [:div.reagent-demo\n [:h1 [link {:href ", "end": 1089, "score": 0.9959125518798828, "start": 1083, "tag": "USERNAME", "value": "jonase" }, { "context": " with Reagent, written\n by \" [:a jonase \"Jonas Enlund\"] \". It also shows how you can\n use Reag", "end": 5037, "score": 0.9998638033866882, "start": 5025, "tag": "NAME", "value": "Jonas Enlund" } ]
demo/reagentdemo/news/anyargs.cljs
nberger/reagent
0
(ns reagentdemo.news.anyargs (:require [reagent.core :as r] [reagent.debug :refer-macros [dbg println]] [reagentdemo.syntax :as s] [sitetools.core :as tools :refer [link]] [reagentdemo.common :as common :refer [demo-component]] [geometry.core :as geometry])) (def url "/news/any-arguments.html") (def title "All arguments allowed") (def ns-src (s/syntaxed "(ns example (:require [reagent.core :as r]))")) (defn hello-component [name] [:p "Hello, " name "!"]) (defn say-hello [] [hello-component "world"]) (defn geometry-example [] [geometry/main {:width "100%" :height 500}]) (defn my-div [] (let [this (r/current-component)] (into [:div.custom (r/props this)] (r/children this)))) (defn call-my-div [] [:div [my-div "Some text."] [my-div {:style {:font-weight 'bold}} [:p "Some other text in bold."]]]) (defn main [{:keys [summary]}] (let [geometry {:href "https://github.com/reagent-project/reagent/tree/master/examples/geometry"} jonase {:href "https://github.com/jonase"}] [:div.reagent-demo [:h1 [link {:href url} title]] [:div.demo-text [:h2 "If it looks like a function…"] [:p "Calling a component in Reagent looks a lot like a function call. Now it also " [:em "works"] " like one."] [:p "Before 0.4.0, component functions were always called with three arguments: a map of attributes, a vector of ”children”, and the current React component."] [:p "This was confusing, and an unnecessary limitation, so now component functions get exactly the same arguments you pass to them."] (if summary [link {:href url :class 'news-read-more} "Read more"] [:div.demo-text [:p "In other words, you can now do this:"] [demo-component {:comp say-hello :src (s/src-of [:hello-component :say-hello])}] [:p "In the above example, it wouldn’t make any difference at all if " [:code "hello-component"] " had been called as a function, i.e with parentheses instead of brackets (except for performance, since components are cached between renders if the arguments to them don’t change)."] [:p "But there is one drawback: component function no longer receives the ”current component” as a parameter. Instead you’ll have to use " [:code "reagent.core/current-component"] " in order to get that. Beware that " [:code "current-component"] " is only valid in component functions, and must be called outside of e.g event handlers and " [:code "for"] " expressions, so it’s safest to always put the call at the top, as in " [:code "my-div"] " here:"] [demo-component {:comp call-my-div :src [:pre ns-src (s/src-of [:my-div :call-my-div])]}] [:p [:em "Note: "] [:code "r/props"] " and " [:code "r/children"] " correspond to React’s " [:code "this.props"] " and " [:code "this.props.children"] ", respectively. They may be convenient to use when wrapping native React components, since they follow the same conventions when interpreting the arguments given."] [:h2 "Other news in 0.4.0"] [:ul [:li "React has been updated to version 0.9.0."] [:li "You can now use any object that satisfies " [:code "ifn?"] " as a component function, and not just plain functions. That includes functions defined with " [:code "deftype"] ", " [:code "defrecord"] ", etc, as well as collections like maps."] [:li [:code "reagent.core/set-state"] " and " [:code "reagent.core/replace-state"] " are now implemented using an " [:code "reagent.core/atom"] ", and are consequently async."] [:li "Keys associated with items in a seq (e.g ”dynamic children” in React parlance) can now be specified with meta-data, as well as with a " [:code ":key"] " item in the first parameter as before. In other words, these two forms are now equivalent: " [:code "^{:key foo} [:li bar]"] " and " [:code "[:li {:key foo} bar]"] "."] [:li "Performance has been improved even further. For example, there is now practically no overhead for tracking derefs in components that don’t use " [:code "atom"] "s. Allocations and memory use have also been reduced."] [:li "Intro and examples have been tweaked a little to take advantage of the new calling conventions."]] [:h2 "New svg example"] [:p "There is also a new, elegant and simple " [:a geometry "example"] " of using svg with Reagent, written by " [:a jonase "Jonas Enlund"] ". It also shows how you can use Reagent’s new calling convensions, and looks like this:"] [demo-component {:comp geometry-example}]])]])) (tools/register-page url [#'main] title)
70402
(ns reagentdemo.news.anyargs (:require [reagent.core :as r] [reagent.debug :refer-macros [dbg println]] [reagentdemo.syntax :as s] [sitetools.core :as tools :refer [link]] [reagentdemo.common :as common :refer [demo-component]] [geometry.core :as geometry])) (def url "/news/any-arguments.html") (def title "All arguments allowed") (def ns-src (s/syntaxed "(ns example (:require [reagent.core :as r]))")) (defn hello-component [name] [:p "Hello, " name "!"]) (defn say-hello [] [hello-component "world"]) (defn geometry-example [] [geometry/main {:width "100%" :height 500}]) (defn my-div [] (let [this (r/current-component)] (into [:div.custom (r/props this)] (r/children this)))) (defn call-my-div [] [:div [my-div "Some text."] [my-div {:style {:font-weight 'bold}} [:p "Some other text in bold."]]]) (defn main [{:keys [summary]}] (let [geometry {:href "https://github.com/reagent-project/reagent/tree/master/examples/geometry"} jonase {:href "https://github.com/jonase"}] [:div.reagent-demo [:h1 [link {:href url} title]] [:div.demo-text [:h2 "If it looks like a function…"] [:p "Calling a component in Reagent looks a lot like a function call. Now it also " [:em "works"] " like one."] [:p "Before 0.4.0, component functions were always called with three arguments: a map of attributes, a vector of ”children”, and the current React component."] [:p "This was confusing, and an unnecessary limitation, so now component functions get exactly the same arguments you pass to them."] (if summary [link {:href url :class 'news-read-more} "Read more"] [:div.demo-text [:p "In other words, you can now do this:"] [demo-component {:comp say-hello :src (s/src-of [:hello-component :say-hello])}] [:p "In the above example, it wouldn’t make any difference at all if " [:code "hello-component"] " had been called as a function, i.e with parentheses instead of brackets (except for performance, since components are cached between renders if the arguments to them don’t change)."] [:p "But there is one drawback: component function no longer receives the ”current component” as a parameter. Instead you’ll have to use " [:code "reagent.core/current-component"] " in order to get that. Beware that " [:code "current-component"] " is only valid in component functions, and must be called outside of e.g event handlers and " [:code "for"] " expressions, so it’s safest to always put the call at the top, as in " [:code "my-div"] " here:"] [demo-component {:comp call-my-div :src [:pre ns-src (s/src-of [:my-div :call-my-div])]}] [:p [:em "Note: "] [:code "r/props"] " and " [:code "r/children"] " correspond to React’s " [:code "this.props"] " and " [:code "this.props.children"] ", respectively. They may be convenient to use when wrapping native React components, since they follow the same conventions when interpreting the arguments given."] [:h2 "Other news in 0.4.0"] [:ul [:li "React has been updated to version 0.9.0."] [:li "You can now use any object that satisfies " [:code "ifn?"] " as a component function, and not just plain functions. That includes functions defined with " [:code "deftype"] ", " [:code "defrecord"] ", etc, as well as collections like maps."] [:li [:code "reagent.core/set-state"] " and " [:code "reagent.core/replace-state"] " are now implemented using an " [:code "reagent.core/atom"] ", and are consequently async."] [:li "Keys associated with items in a seq (e.g ”dynamic children” in React parlance) can now be specified with meta-data, as well as with a " [:code ":key"] " item in the first parameter as before. In other words, these two forms are now equivalent: " [:code "^{:key foo} [:li bar]"] " and " [:code "[:li {:key foo} bar]"] "."] [:li "Performance has been improved even further. For example, there is now practically no overhead for tracking derefs in components that don’t use " [:code "atom"] "s. Allocations and memory use have also been reduced."] [:li "Intro and examples have been tweaked a little to take advantage of the new calling conventions."]] [:h2 "New svg example"] [:p "There is also a new, elegant and simple " [:a geometry "example"] " of using svg with Reagent, written by " [:a jonase "<NAME>"] ". It also shows how you can use Reagent’s new calling convensions, and looks like this:"] [demo-component {:comp geometry-example}]])]])) (tools/register-page url [#'main] title)
true
(ns reagentdemo.news.anyargs (:require [reagent.core :as r] [reagent.debug :refer-macros [dbg println]] [reagentdemo.syntax :as s] [sitetools.core :as tools :refer [link]] [reagentdemo.common :as common :refer [demo-component]] [geometry.core :as geometry])) (def url "/news/any-arguments.html") (def title "All arguments allowed") (def ns-src (s/syntaxed "(ns example (:require [reagent.core :as r]))")) (defn hello-component [name] [:p "Hello, " name "!"]) (defn say-hello [] [hello-component "world"]) (defn geometry-example [] [geometry/main {:width "100%" :height 500}]) (defn my-div [] (let [this (r/current-component)] (into [:div.custom (r/props this)] (r/children this)))) (defn call-my-div [] [:div [my-div "Some text."] [my-div {:style {:font-weight 'bold}} [:p "Some other text in bold."]]]) (defn main [{:keys [summary]}] (let [geometry {:href "https://github.com/reagent-project/reagent/tree/master/examples/geometry"} jonase {:href "https://github.com/jonase"}] [:div.reagent-demo [:h1 [link {:href url} title]] [:div.demo-text [:h2 "If it looks like a function…"] [:p "Calling a component in Reagent looks a lot like a function call. Now it also " [:em "works"] " like one."] [:p "Before 0.4.0, component functions were always called with three arguments: a map of attributes, a vector of ”children”, and the current React component."] [:p "This was confusing, and an unnecessary limitation, so now component functions get exactly the same arguments you pass to them."] (if summary [link {:href url :class 'news-read-more} "Read more"] [:div.demo-text [:p "In other words, you can now do this:"] [demo-component {:comp say-hello :src (s/src-of [:hello-component :say-hello])}] [:p "In the above example, it wouldn’t make any difference at all if " [:code "hello-component"] " had been called as a function, i.e with parentheses instead of brackets (except for performance, since components are cached between renders if the arguments to them don’t change)."] [:p "But there is one drawback: component function no longer receives the ”current component” as a parameter. Instead you’ll have to use " [:code "reagent.core/current-component"] " in order to get that. Beware that " [:code "current-component"] " is only valid in component functions, and must be called outside of e.g event handlers and " [:code "for"] " expressions, so it’s safest to always put the call at the top, as in " [:code "my-div"] " here:"] [demo-component {:comp call-my-div :src [:pre ns-src (s/src-of [:my-div :call-my-div])]}] [:p [:em "Note: "] [:code "r/props"] " and " [:code "r/children"] " correspond to React’s " [:code "this.props"] " and " [:code "this.props.children"] ", respectively. They may be convenient to use when wrapping native React components, since they follow the same conventions when interpreting the arguments given."] [:h2 "Other news in 0.4.0"] [:ul [:li "React has been updated to version 0.9.0."] [:li "You can now use any object that satisfies " [:code "ifn?"] " as a component function, and not just plain functions. That includes functions defined with " [:code "deftype"] ", " [:code "defrecord"] ", etc, as well as collections like maps."] [:li [:code "reagent.core/set-state"] " and " [:code "reagent.core/replace-state"] " are now implemented using an " [:code "reagent.core/atom"] ", and are consequently async."] [:li "Keys associated with items in a seq (e.g ”dynamic children” in React parlance) can now be specified with meta-data, as well as with a " [:code ":key"] " item in the first parameter as before. In other words, these two forms are now equivalent: " [:code "^{:key foo} [:li bar]"] " and " [:code "[:li {:key foo} bar]"] "."] [:li "Performance has been improved even further. For example, there is now practically no overhead for tracking derefs in components that don’t use " [:code "atom"] "s. Allocations and memory use have also been reduced."] [:li "Intro and examples have been tweaked a little to take advantage of the new calling conventions."]] [:h2 "New svg example"] [:p "There is also a new, elegant and simple " [:a geometry "example"] " of using svg with Reagent, written by " [:a jonase "PI:NAME:<NAME>END_PI"] ". It also shows how you can use Reagent’s new calling convensions, and looks like this:"] [demo-component {:comp geometry-example}]])]])) (tools/register-page url [#'main] title)
[ { "context": ";\n; Copyright 2018 Peter Monks\n; SPDX-License-Identifier: Apache-2.0\n;\n; License", "end": 30, "score": 0.9996762871742249, "start": 19, "tag": "NAME", "value": "Peter Monks" } ]
test/clj_symphony/test.clj
pmonks/clj-symphony
4
; ; Copyright 2018 Peter Monks ; SPDX-License-Identifier: Apache-2.0 ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns clj-symphony.test (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.test :refer :all])) ; This is a placeholder for now that simply confirms that the right matrix of JVM and Clojure versions is being used by Travis CI (println "\n☔️ Running tests on Clojure" (clojure-version) "/ JVM" (System/getProperty "java.version") (str "(" (System/getProperty "java.vm.name") " v" (System/getProperty "java.vm.version") ")"))
63543
; ; Copyright 2018 <NAME> ; SPDX-License-Identifier: Apache-2.0 ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns clj-symphony.test (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.test :refer :all])) ; This is a placeholder for now that simply confirms that the right matrix of JVM and Clojure versions is being used by Travis CI (println "\n☔️ Running tests on Clojure" (clojure-version) "/ JVM" (System/getProperty "java.version") (str "(" (System/getProperty "java.vm.name") " v" (System/getProperty "java.vm.version") ")"))
true
; ; Copyright 2018 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: Apache-2.0 ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns clj-symphony.test (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.test :refer :all])) ; This is a placeholder for now that simply confirms that the right matrix of JVM and Clojure versions is being used by Travis CI (println "\n☔️ Running tests on Clojure" (clojure-version) "/ JVM" (System/getProperty "java.version") (str "(" (System/getProperty "java.vm.name") " v" (System/getProperty "java.vm.version") ")"))
[ { "context": "\"]\n :LastName \"Smith\"}]}\n {:ShortName \"LPDAAC\"\n ", "end": 2134, "score": 0.9997661113739014, "start": 2129, "tag": "NAME", "value": "Smith" }, { "context": "\"]\n :LastName \"Smith\"}]}]})\n\n(def data-centers-umm-with-home-page-url\n", "end": 2335, "score": 0.999759316444397, "start": 2330, "tag": "NAME", "value": "Smith" }, { "context": " :Value \"nsidc@nsidc.org\"}]}}\n {:ShortName \"ShortName\"\n ", "end": 3662, "score": 0.9998946785926819, "start": 3647, "tag": "EMAIL", "value": "nsidc@nsidc.org" }, { "context": "\"]\n :LastName \"Smith\"}]\n :ContactInformation {:Relate", "end": 4019, "score": 0.9996514320373535, "start": 4014, "tag": "NAME", "value": "Smith" }, { "context": "1 {:token (e/login (s/context) \"user1\") :user-id \"user2\"}\n bulk-update-options2 {:token (e/login (", "end": 9085, "score": 0.7211852073669434, "start": 9080, "tag": "USERNAME", "value": "user2" }, { "context": "\"user1\")}\n bulk-update-options3 {:user-id \"user2\"}\n bulk-update-body {:concept-ids [\"all\"]\n", "end": 9201, "score": 0.813957691192627, "start": 9196, "tag": "USERNAME", "value": "user2" }, { "context": " :Value \"nsidc@nsidc.org\"}]}}\n {:ShortName \"New ShortNam", "end": 33834, "score": 0.9828774929046631, "start": 33819, "tag": "EMAIL", "value": "nsidc@nsidc.org" }, { "context": " :Value \"nsidc@nsidc.org\"}]}}\n {:ShortName \"New ShortNam", "end": 37000, "score": 0.9999213814735413, "start": 36985, "tag": "EMAIL", "value": "nsidc@nsidc.org" } ]
system-int-test/test/cmr/system_int_test/ingest/bulk_update/bulk_update_test.clj
indiejames/Common-Metadata-Repository
0
(ns cmr.system-int-test.ingest.bulk-update.bulk-update-test "CMR bulk update. Test the actual update " (:require [cheshire.core :as json] [clojure.test :refer :all] [clojure.java.io :as io] [cmr.common-app.test.side-api :as side] [cmr.common.time-keeper :as time-keeper] [cmr.common.util :as util :refer [are3]] [cmr.ingest.config :as ingest-config] [cmr.message-queue.test.queue-broker-side-api :as qb-side-api] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.data2.core :as data2-core] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.data2.umm-spec-common :as data-umm-cmn] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2"}) (search/freeze-resume-time-fixture)])) (def collection-formats "Formats to test bulk update" [:dif :dif10 :echo10 :iso19115 :iso-smap :umm-json]) (def science-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}]}) (def find-and-replace-multiple-science-keywords-umm "Used to test the case when update-value contains a list of science keywords." {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"}]}) (def data-centers-umm {:DataCenters [{:ShortName "NSID" ;; intentional misspelling for tests :LongName "National Snow and Ice Data Center" :Roles ["ARCHIVER"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "Smith"}]} {:ShortName "LPDAAC" :Roles ["PROCESSOR"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "Smith"}]}]}) (def data-centers-umm-with-home-page-url "Defines data center with home page url." {:DataCenters [{:ShortName "ShortName" :LongName "Hydrogeophysics Group, Aarhus University " :Roles ["ARCHIVER", "DISTRIBUTOR"] :Uuid "ef941ad9-1662-400d-a24a-c300a72c1531" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://nsidc.org/daac/index.html"} {:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "nsidc@nsidc.org"}]}} {:ShortName "ShortName" :LongName "Hydrogeophysics Group, Aarhus University " :Roles ["ARCHIVER"]} {:ShortName "ShortName" :Roles ["PROCESSOR"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "Smith"}] :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://nsidc.org/daac/index.html"}]}}]}) (def find-update-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}]}) (def find-replace-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}]}) (def platforms-instruments-umm {:Platforms [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper"}]}]}) (def large-status-message-umm {:RelatedUrls [{:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}} {:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}} {:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}}]}) (defn- generate-concept-id [index provider] (format "C120000000%s-%s" index provider)) (defn- ingest-collection-in-each-format "Ingest a collection in each format and return a list of concept-ids" ([attribs] (ingest-collection-in-each-format attribs collection-formats)) ([attribs formats] (doall (for [x (range (count formats)) :let [format (nth formats x) collection (data-umm-c/collection-concept (data-umm-c/collection x attribs) format)]] (:concept-id (ingest/ingest-concept (assoc collection :concept-id (generate-concept-id x "PROV1")))))))) (defn- ingest-collection-in-umm-json-format "Ingest a collection in UMM Json format and return a list of one concept-id. This is used to test the CMR-4517, on complete removal of platforms/instruments. Since it's only testing the bulk update part after the ingest, which format to use for ingest is irrelevant. So it's easier to just test with one format of ingest." [attribs] (let [collection (data-umm-c/collection-concept (data-umm-c/collection 1 attribs) :umm-json)] [(:concept-id (ingest/ingest-concept (assoc collection :concept-id (generate-concept-id 1 "PROV1"))))])) (deftest bulk-update-science-keywords ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) bulk-update-options1 {:token (e/login (s/context) "user1") :user-id "user2"} bulk-update-options2 {:token (e/login (s/context) "user1")} bulk-update-options3 {:user-id "user2"} bulk-update-body {:concept-ids ["all"] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}} ;; CMR-4570 tests that no duplicate science keywords are created. duplicate-body {:concept-ids ["ALL" ] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"}}] ;; Initiate bulk update that shouldn't add any duplicates. (let [response (ingest/bulk-update-collections "PROV1" duplicate-body) _ (index/wait-until-indexed) {:keys [task-id]} response ;; I am surprised to find out that the task-id returned in the response is a string ;; Here I am just blindly patch this test to work with a string. next-task-id (+ 1 (Integer/parseInt task-id)) collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response))) (side/eval-form `(ingest-config/set-bulk-update-enabled! false)) ;; Kick off bulk update when bulk update is disabled is not allowed (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 400 (:status response))) (is (= ["Bulk update is disabled."] (:errors response)))) (let [collection-response (ingest/bulk-update-task-status "PROV1" next-task-id)] (is (= 404 (:status collection-response))) (is (= [(format "Bulk update task with task id [%s] could not be found for provider id [PROV1]." next-task-id)] (:errors collection-response)))) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= 200 (:status collection-response)))) (let [collection-response (ingest/bulk-update-task-status "PROV2" task-id)] (is (= 404 (:status collection-response))) (is (= [(format "Bulk update task with task id [%s] could not be found for provider id [PROV2]." task-id)] (:errors collection-response)))) (side/eval-form `(ingest-config/set-bulk-update-enabled! true))) ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options1)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 3 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 3 "user2") (is (= "2017-01-01T00:00:00Z" (:revision-date (:meta concept)))) (some #(= {:Date "2017-01-01T00:00:00Z" :Type "UPDATE"} %) (:MetadataDates (:umm concept))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:VariableLevel1 "HEAVY METALS CONCENTRATION" :Category "EARTH SCIENCE" :Term "ENVIRONMENTAL IMPACTS" :Topic "HUMAN DIMENSIONS"}] (:ScienceKeywords (:umm concept)))))) (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options2)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 4 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 4 "user1"))) (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options3)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 5 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 5 "user2"))))) (deftest bulk-update-add-to-existing-multiple-science-keywords ;; This test is the same as the previous bulk-update-science-keywords test except ;; that it shows that update-value could be an array of objects. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"}]} ;; CMR-4570 tests that no duplicate science keywords are created. duplicate-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Initiate bulk update that shouldn't add any duplicates. (ingest/bulk-update-collections "PROV1" duplicate-body) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest bulk-update-clear-all-and-replace-with-multiple-science-keywords ;; This test shows that update-value could be an array of objects when doing CLEAR_ALL_AND_REPLACE. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "CLEAR_ALL_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest bulk-update-find-and-replace-with-multiple-science-keywords ;; This test shows that update-value could be an array of objects when doing FIND_AND_REPLACE. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format find-and-replace-multiple-science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :find-value {:Topic "OCEANS"} :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest data-center-bulk-update (let [concept-ids (ingest-collection-in-each-format data-centers-umm) _ (index/wait-until-indexed)] (testing "Data center find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "DATA_CENTERS" :find-value {:ShortName "NSID"} :update-value {:ShortName "NSIDC" :Roles ["ORIGINATOR"]}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "NSIDC" :Roles ["ORIGINATOR"]} {:ShortName "LPDAAC" :Roles ["PROCESSOR"]}] (map #(select-keys % [:Roles :ShortName]) (:DataCenters (:umm concept)))))))))) (deftest nil-instrument-long-name-bulk-update (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "nil instrument long name find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"} :update-value {:ShortName "LVIS" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first) platforms (get-in concept [:umm :Platforms])]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]}] platforms))))))) (deftest instrument-bulk-update-find-and-replace (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "instrument find and replace" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"} :update-value [{:ShortName "LVIS"}]} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first) platforms (get-in concept [:umm :Platforms])]] (is (= 2 (:revision-id (:meta concept)))) ;; Make sure find and replace won't add an empty Instruments to the first platform which ;; doesn't contain any instruments. (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]}] platforms))))))) (deftest nil-platform-long-name-bulk-update (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "nil platform long name find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "PLATFORMS" :find-value {:ShortName "a340-600-1"} :update-value {:ShortName "SMAP" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "SMAP" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper"}]}] (:Platforms (:umm concept))))))))) (deftest data-center-home-page-url-removal (let [concept-ids (ingest-collection-in-umm-json-format data-centers-umm-with-home-page-url) _ (index/wait-until-indexed)] (testing "Data center find and update home page url - removal case." (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE_HOME_PAGE_URL" :update-field "DATA_CENTERS" :find-value {:ShortName "ShortName"} :update-value {:ShortName "New ShortName" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "New ShortName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "nsidc@nsidc.org"}]}} {:ShortName "New ShortName"} {:ShortName "New ShortName" :ContactInformation {}}] (map #(select-keys % [:ShortName :LongName :ContactInformation]) (:DataCenters (:umm concept)))))))))) (deftest data-center-home-page-url-update (let [concept-ids (ingest-collection-in-umm-json-format data-centers-umm-with-home-page-url) _ (index/wait-until-indexed)] (testing "Data center find and update home page url - update case." (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE_HOME_PAGE_URL" :update-field "DATA_CENTERS" :find-value {:ShortName "ShortName"} :update-value {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"} {:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "nsidc@nsidc.org"}]}} {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}} {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}}] (map #(select-keys % [:ShortName :LongName :ContactInformation]) (:DataCenters (:umm concept)))))))))) (deftest bulk-update-replace-test (let [concept-ids (ingest-collection-in-each-format find-replace-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-replace-with-identical-update-value-test (let [concept-ids (ingest-collection-in-each-format find-replace-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :find-value {:VariableLevel1 "CARBON MONOXIDE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-remove-all-instruments-test (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REMOVE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-status (first (:collection-statuses collection-response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "UPDATED" (:status collection-status))) (is (= "Collection was updated successfully, but translating the collection to UMM-C had the following issues: [:MetadataDates] latest UPDATE date value: [2017-01-01T00:00:00.000Z] should be in the past." (:status-message collection-status)))) ;; Check that each concept was updated. (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft"} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft"}] (:Platforms (:umm concept))))))) (deftest bulk-update-update-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE", :Topic "ATMOSPHERE", :Term "AIR QUALITY", :VariableLevel1 "EMISSIONS"} {:Category "EARTH SCIENCE", :Topic "ATMOSPHERE", :Term "AIR QUALITY", :VariableLevel1 "EMISSIONS", :VariableLevel2 "CLOUD LIQUID WATER/ICE"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-update-with-identical-update-value-test (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "OCEANS"} :update-value {:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-update-not-found-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} original-concepts (doseq [concept-id concept-ids] (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)) task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body)) _ (index/wait-until-indexed) new-concepts (doseq [concept-id concept-ids] (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first))] (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-statuses (for [concept-id concept-ids] {:concept-id concept-id :status "SKIPPED" :status-message (str "Collection with concept-id [" concept-id "] is not updated because no find-value found.")})] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Task completed with 6 SKIPPED out of 6 total collection update(s)." (:status-message collection-response))) (is (= collection-statuses (:collection-statuses collection-response)))) ;; Check that each concept was not updated. ;; revision-id not changed, format not changed, it's identical to the original-concepts. (is (= new-concepts original-concepts)))) (deftest bulk-update-update-all-tombstone-test (let [coll1 (data2-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1"})) coll2 (data2-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E2" :ShortName "S2"})) _ (index/wait-until-indexed) bulk-update-body1 {:concept-ids ["ALL"] :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} bulk-update-body2 {:concept-ids [(:concept-id coll1) (:concept-id coll2)] :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}}] ;; perform bulk update, verify that both collections are skipped because find-value is not found. (testing "all the non-deleted collections are included in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Task completed with 2 SKIPPED out of 2 total collection update(s)." (:status-message collection-response))))) ;; delete the collection (is (= 200 (:status (ingest/delete-concept (data2-core/umm-c-collection->concept coll1 :echo10))))) (index/wait-until-indexed) ;; perform another bulk update, verify that the deleted collection is not included when getting all ;; collections from the provider. (testing "Deleted collection is excluded in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "Task completed with 1 SKIPPED out of 1 total collection update(s)." (:status-message collection-response))))) ;; perform a bulk update with the deleted collection's concept-id and a non-deleted collection's concept-id ;; The deleted one should fail the update. (testing "Deleted collection is failed in update concept-id case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body2) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response)) collection-statuses (:collection-statuses collection-response)] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Collection with concept-id [C1200000009-PROV1] is deleted. Can not be updated." (get (first collection-statuses) :status-message))) (is (= "Task completed with 1 FAILED and 1 SKIPPED out of 2 total collection update(s)." (:status-message collection-response))))) ;; delete the second collection (is (= 200 (:status (ingest/delete-concept (data2-core/umm-c-collection->concept coll2 :echo10))))) (index/wait-until-indexed) ;; perform another bulk update, verify that the deleted collections are not included when getting all ;; collections from the provider. (testing "All collections are deleted in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed)] (is (= ["There are no collections that have not been deleted for provider [PROV1]."] (:errors response))))))) (deftest bulk-update-default-name-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= (:task-id response) (get collection-response :name))) (is (= "COMPLETE" (:task-status collection-response)))))) (deftest bulk-update-unique-name-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :name "unique" :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} response (ingest/bulk-update-collections "PROV1" bulk-update-body) response2 (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) (is (= 422 (:status response2))) (is (= ["Error creating bulk update task: Bulk update name needs to be unique within the provider."] (:errors response2))))) (deftest bulk-update-xml-to-umm-failure-test (let [coll-metadata (slurp (io/resource "dif-samples/cmr-4455-collection.xml")) concept (ingest/ingest-concept (ingest/concept :collection "PROV1" "foo" :dif coll-metadata)) _ (index/wait-until-indexed) bulk-update-body {:concept-ids [(:concept-id concept)] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response))))))) (deftest bulk-update-large-status-message-test (let [concept-ids (ingest-collection-in-umm-json-format large-status-message-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-status (first (:collection-statuses collection-response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "UPDATED" (:status collection-status))) (is (< 255 (count (:status-message collection-status)))))))
63069
(ns cmr.system-int-test.ingest.bulk-update.bulk-update-test "CMR bulk update. Test the actual update " (:require [cheshire.core :as json] [clojure.test :refer :all] [clojure.java.io :as io] [cmr.common-app.test.side-api :as side] [cmr.common.time-keeper :as time-keeper] [cmr.common.util :as util :refer [are3]] [cmr.ingest.config :as ingest-config] [cmr.message-queue.test.queue-broker-side-api :as qb-side-api] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.data2.core :as data2-core] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.data2.umm-spec-common :as data-umm-cmn] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2"}) (search/freeze-resume-time-fixture)])) (def collection-formats "Formats to test bulk update" [:dif :dif10 :echo10 :iso19115 :iso-smap :umm-json]) (def science-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}]}) (def find-and-replace-multiple-science-keywords-umm "Used to test the case when update-value contains a list of science keywords." {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"}]}) (def data-centers-umm {:DataCenters [{:ShortName "NSID" ;; intentional misspelling for tests :LongName "National Snow and Ice Data Center" :Roles ["ARCHIVER"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "<NAME>"}]} {:ShortName "LPDAAC" :Roles ["PROCESSOR"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "<NAME>"}]}]}) (def data-centers-umm-with-home-page-url "Defines data center with home page url." {:DataCenters [{:ShortName "ShortName" :LongName "Hydrogeophysics Group, Aarhus University " :Roles ["ARCHIVER", "DISTRIBUTOR"] :Uuid "ef941ad9-1662-400d-a24a-c300a72c1531" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://nsidc.org/daac/index.html"} {:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "<EMAIL>"}]}} {:ShortName "ShortName" :LongName "Hydrogeophysics Group, Aarhus University " :Roles ["ARCHIVER"]} {:ShortName "ShortName" :Roles ["PROCESSOR"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "<NAME>"}] :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://nsidc.org/daac/index.html"}]}}]}) (def find-update-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}]}) (def find-replace-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}]}) (def platforms-instruments-umm {:Platforms [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper"}]}]}) (def large-status-message-umm {:RelatedUrls [{:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}} {:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}} {:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}}]}) (defn- generate-concept-id [index provider] (format "C120000000%s-%s" index provider)) (defn- ingest-collection-in-each-format "Ingest a collection in each format and return a list of concept-ids" ([attribs] (ingest-collection-in-each-format attribs collection-formats)) ([attribs formats] (doall (for [x (range (count formats)) :let [format (nth formats x) collection (data-umm-c/collection-concept (data-umm-c/collection x attribs) format)]] (:concept-id (ingest/ingest-concept (assoc collection :concept-id (generate-concept-id x "PROV1")))))))) (defn- ingest-collection-in-umm-json-format "Ingest a collection in UMM Json format and return a list of one concept-id. This is used to test the CMR-4517, on complete removal of platforms/instruments. Since it's only testing the bulk update part after the ingest, which format to use for ingest is irrelevant. So it's easier to just test with one format of ingest." [attribs] (let [collection (data-umm-c/collection-concept (data-umm-c/collection 1 attribs) :umm-json)] [(:concept-id (ingest/ingest-concept (assoc collection :concept-id (generate-concept-id 1 "PROV1"))))])) (deftest bulk-update-science-keywords ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) bulk-update-options1 {:token (e/login (s/context) "user1") :user-id "user2"} bulk-update-options2 {:token (e/login (s/context) "user1")} bulk-update-options3 {:user-id "user2"} bulk-update-body {:concept-ids ["all"] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}} ;; CMR-4570 tests that no duplicate science keywords are created. duplicate-body {:concept-ids ["ALL" ] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"}}] ;; Initiate bulk update that shouldn't add any duplicates. (let [response (ingest/bulk-update-collections "PROV1" duplicate-body) _ (index/wait-until-indexed) {:keys [task-id]} response ;; I am surprised to find out that the task-id returned in the response is a string ;; Here I am just blindly patch this test to work with a string. next-task-id (+ 1 (Integer/parseInt task-id)) collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response))) (side/eval-form `(ingest-config/set-bulk-update-enabled! false)) ;; Kick off bulk update when bulk update is disabled is not allowed (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 400 (:status response))) (is (= ["Bulk update is disabled."] (:errors response)))) (let [collection-response (ingest/bulk-update-task-status "PROV1" next-task-id)] (is (= 404 (:status collection-response))) (is (= [(format "Bulk update task with task id [%s] could not be found for provider id [PROV1]." next-task-id)] (:errors collection-response)))) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= 200 (:status collection-response)))) (let [collection-response (ingest/bulk-update-task-status "PROV2" task-id)] (is (= 404 (:status collection-response))) (is (= [(format "Bulk update task with task id [%s] could not be found for provider id [PROV2]." task-id)] (:errors collection-response)))) (side/eval-form `(ingest-config/set-bulk-update-enabled! true))) ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options1)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 3 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 3 "user2") (is (= "2017-01-01T00:00:00Z" (:revision-date (:meta concept)))) (some #(= {:Date "2017-01-01T00:00:00Z" :Type "UPDATE"} %) (:MetadataDates (:umm concept))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:VariableLevel1 "HEAVY METALS CONCENTRATION" :Category "EARTH SCIENCE" :Term "ENVIRONMENTAL IMPACTS" :Topic "HUMAN DIMENSIONS"}] (:ScienceKeywords (:umm concept)))))) (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options2)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 4 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 4 "user1"))) (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options3)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 5 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 5 "user2"))))) (deftest bulk-update-add-to-existing-multiple-science-keywords ;; This test is the same as the previous bulk-update-science-keywords test except ;; that it shows that update-value could be an array of objects. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"}]} ;; CMR-4570 tests that no duplicate science keywords are created. duplicate-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Initiate bulk update that shouldn't add any duplicates. (ingest/bulk-update-collections "PROV1" duplicate-body) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest bulk-update-clear-all-and-replace-with-multiple-science-keywords ;; This test shows that update-value could be an array of objects when doing CLEAR_ALL_AND_REPLACE. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "CLEAR_ALL_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest bulk-update-find-and-replace-with-multiple-science-keywords ;; This test shows that update-value could be an array of objects when doing FIND_AND_REPLACE. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format find-and-replace-multiple-science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :find-value {:Topic "OCEANS"} :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest data-center-bulk-update (let [concept-ids (ingest-collection-in-each-format data-centers-umm) _ (index/wait-until-indexed)] (testing "Data center find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "DATA_CENTERS" :find-value {:ShortName "NSID"} :update-value {:ShortName "NSIDC" :Roles ["ORIGINATOR"]}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "NSIDC" :Roles ["ORIGINATOR"]} {:ShortName "LPDAAC" :Roles ["PROCESSOR"]}] (map #(select-keys % [:Roles :ShortName]) (:DataCenters (:umm concept)))))))))) (deftest nil-instrument-long-name-bulk-update (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "nil instrument long name find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"} :update-value {:ShortName "LVIS" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first) platforms (get-in concept [:umm :Platforms])]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]}] platforms))))))) (deftest instrument-bulk-update-find-and-replace (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "instrument find and replace" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"} :update-value [{:ShortName "LVIS"}]} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first) platforms (get-in concept [:umm :Platforms])]] (is (= 2 (:revision-id (:meta concept)))) ;; Make sure find and replace won't add an empty Instruments to the first platform which ;; doesn't contain any instruments. (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]}] platforms))))))) (deftest nil-platform-long-name-bulk-update (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "nil platform long name find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "PLATFORMS" :find-value {:ShortName "a340-600-1"} :update-value {:ShortName "SMAP" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "SMAP" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper"}]}] (:Platforms (:umm concept))))))))) (deftest data-center-home-page-url-removal (let [concept-ids (ingest-collection-in-umm-json-format data-centers-umm-with-home-page-url) _ (index/wait-until-indexed)] (testing "Data center find and update home page url - removal case." (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE_HOME_PAGE_URL" :update-field "DATA_CENTERS" :find-value {:ShortName "ShortName"} :update-value {:ShortName "New ShortName" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "New ShortName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "<EMAIL>"}]}} {:ShortName "New ShortName"} {:ShortName "New ShortName" :ContactInformation {}}] (map #(select-keys % [:ShortName :LongName :ContactInformation]) (:DataCenters (:umm concept)))))))))) (deftest data-center-home-page-url-update (let [concept-ids (ingest-collection-in-umm-json-format data-centers-umm-with-home-page-url) _ (index/wait-until-indexed)] (testing "Data center find and update home page url - update case." (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE_HOME_PAGE_URL" :update-field "DATA_CENTERS" :find-value {:ShortName "ShortName"} :update-value {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"} {:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "<EMAIL>"}]}} {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}} {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}}] (map #(select-keys % [:ShortName :LongName :ContactInformation]) (:DataCenters (:umm concept)))))))))) (deftest bulk-update-replace-test (let [concept-ids (ingest-collection-in-each-format find-replace-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-replace-with-identical-update-value-test (let [concept-ids (ingest-collection-in-each-format find-replace-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :find-value {:VariableLevel1 "CARBON MONOXIDE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-remove-all-instruments-test (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REMOVE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-status (first (:collection-statuses collection-response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "UPDATED" (:status collection-status))) (is (= "Collection was updated successfully, but translating the collection to UMM-C had the following issues: [:MetadataDates] latest UPDATE date value: [2017-01-01T00:00:00.000Z] should be in the past." (:status-message collection-status)))) ;; Check that each concept was updated. (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft"} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft"}] (:Platforms (:umm concept))))))) (deftest bulk-update-update-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE", :Topic "ATMOSPHERE", :Term "AIR QUALITY", :VariableLevel1 "EMISSIONS"} {:Category "EARTH SCIENCE", :Topic "ATMOSPHERE", :Term "AIR QUALITY", :VariableLevel1 "EMISSIONS", :VariableLevel2 "CLOUD LIQUID WATER/ICE"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-update-with-identical-update-value-test (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "OCEANS"} :update-value {:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-update-not-found-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} original-concepts (doseq [concept-id concept-ids] (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)) task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body)) _ (index/wait-until-indexed) new-concepts (doseq [concept-id concept-ids] (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first))] (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-statuses (for [concept-id concept-ids] {:concept-id concept-id :status "SKIPPED" :status-message (str "Collection with concept-id [" concept-id "] is not updated because no find-value found.")})] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Task completed with 6 SKIPPED out of 6 total collection update(s)." (:status-message collection-response))) (is (= collection-statuses (:collection-statuses collection-response)))) ;; Check that each concept was not updated. ;; revision-id not changed, format not changed, it's identical to the original-concepts. (is (= new-concepts original-concepts)))) (deftest bulk-update-update-all-tombstone-test (let [coll1 (data2-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1"})) coll2 (data2-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E2" :ShortName "S2"})) _ (index/wait-until-indexed) bulk-update-body1 {:concept-ids ["ALL"] :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} bulk-update-body2 {:concept-ids [(:concept-id coll1) (:concept-id coll2)] :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}}] ;; perform bulk update, verify that both collections are skipped because find-value is not found. (testing "all the non-deleted collections are included in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Task completed with 2 SKIPPED out of 2 total collection update(s)." (:status-message collection-response))))) ;; delete the collection (is (= 200 (:status (ingest/delete-concept (data2-core/umm-c-collection->concept coll1 :echo10))))) (index/wait-until-indexed) ;; perform another bulk update, verify that the deleted collection is not included when getting all ;; collections from the provider. (testing "Deleted collection is excluded in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "Task completed with 1 SKIPPED out of 1 total collection update(s)." (:status-message collection-response))))) ;; perform a bulk update with the deleted collection's concept-id and a non-deleted collection's concept-id ;; The deleted one should fail the update. (testing "Deleted collection is failed in update concept-id case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body2) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response)) collection-statuses (:collection-statuses collection-response)] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Collection with concept-id [C1200000009-PROV1] is deleted. Can not be updated." (get (first collection-statuses) :status-message))) (is (= "Task completed with 1 FAILED and 1 SKIPPED out of 2 total collection update(s)." (:status-message collection-response))))) ;; delete the second collection (is (= 200 (:status (ingest/delete-concept (data2-core/umm-c-collection->concept coll2 :echo10))))) (index/wait-until-indexed) ;; perform another bulk update, verify that the deleted collections are not included when getting all ;; collections from the provider. (testing "All collections are deleted in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed)] (is (= ["There are no collections that have not been deleted for provider [PROV1]."] (:errors response))))))) (deftest bulk-update-default-name-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= (:task-id response) (get collection-response :name))) (is (= "COMPLETE" (:task-status collection-response)))))) (deftest bulk-update-unique-name-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :name "unique" :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} response (ingest/bulk-update-collections "PROV1" bulk-update-body) response2 (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) (is (= 422 (:status response2))) (is (= ["Error creating bulk update task: Bulk update name needs to be unique within the provider."] (:errors response2))))) (deftest bulk-update-xml-to-umm-failure-test (let [coll-metadata (slurp (io/resource "dif-samples/cmr-4455-collection.xml")) concept (ingest/ingest-concept (ingest/concept :collection "PROV1" "foo" :dif coll-metadata)) _ (index/wait-until-indexed) bulk-update-body {:concept-ids [(:concept-id concept)] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response))))))) (deftest bulk-update-large-status-message-test (let [concept-ids (ingest-collection-in-umm-json-format large-status-message-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-status (first (:collection-statuses collection-response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "UPDATED" (:status collection-status))) (is (< 255 (count (:status-message collection-status)))))))
true
(ns cmr.system-int-test.ingest.bulk-update.bulk-update-test "CMR bulk update. Test the actual update " (:require [cheshire.core :as json] [clojure.test :refer :all] [clojure.java.io :as io] [cmr.common-app.test.side-api :as side] [cmr.common.time-keeper :as time-keeper] [cmr.common.util :as util :refer [are3]] [cmr.ingest.config :as ingest-config] [cmr.message-queue.test.queue-broker-side-api :as qb-side-api] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.data2.core :as data2-core] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.data2.umm-spec-common :as data-umm-cmn] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2"}) (search/freeze-resume-time-fixture)])) (def collection-formats "Formats to test bulk update" [:dif :dif10 :echo10 :iso19115 :iso-smap :umm-json]) (def science-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}]}) (def find-and-replace-multiple-science-keywords-umm "Used to test the case when update-value contains a list of science keywords." {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"}]}) (def data-centers-umm {:DataCenters [{:ShortName "NSID" ;; intentional misspelling for tests :LongName "National Snow and Ice Data Center" :Roles ["ARCHIVER"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "PI:NAME:<NAME>END_PI"}]} {:ShortName "LPDAAC" :Roles ["PROCESSOR"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "PI:NAME:<NAME>END_PI"}]}]}) (def data-centers-umm-with-home-page-url "Defines data center with home page url." {:DataCenters [{:ShortName "ShortName" :LongName "Hydrogeophysics Group, Aarhus University " :Roles ["ARCHIVER", "DISTRIBUTOR"] :Uuid "ef941ad9-1662-400d-a24a-c300a72c1531" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://nsidc.org/daac/index.html"} {:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "PI:EMAIL:<EMAIL>END_PI"}]}} {:ShortName "ShortName" :LongName "Hydrogeophysics Group, Aarhus University " :Roles ["ARCHIVER"]} {:ShortName "ShortName" :Roles ["PROCESSOR"] :ContactPersons [{:Roles ["Data Center Contact"] :LastName "PI:NAME:<NAME>END_PI"}] :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://nsidc.org/daac/index.html"}]}}]}) (def find-update-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}]}) (def find-replace-keywords-umm {:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}]}) (def platforms-instruments-umm {:Platforms [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper"}]}]}) (def large-status-message-umm {:RelatedUrls [{:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}} {:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}} {:Description "Related url description" :URL "www.foobarbazquxquux.com" :URLContentType "DistributionURL" :Type "GET DATA" :Subtype "Earthdata Search" :GetData {:Format "ascii" :Size 10.0 :Unit "MB" :Fees "fees"}}]}) (defn- generate-concept-id [index provider] (format "C120000000%s-%s" index provider)) (defn- ingest-collection-in-each-format "Ingest a collection in each format and return a list of concept-ids" ([attribs] (ingest-collection-in-each-format attribs collection-formats)) ([attribs formats] (doall (for [x (range (count formats)) :let [format (nth formats x) collection (data-umm-c/collection-concept (data-umm-c/collection x attribs) format)]] (:concept-id (ingest/ingest-concept (assoc collection :concept-id (generate-concept-id x "PROV1")))))))) (defn- ingest-collection-in-umm-json-format "Ingest a collection in UMM Json format and return a list of one concept-id. This is used to test the CMR-4517, on complete removal of platforms/instruments. Since it's only testing the bulk update part after the ingest, which format to use for ingest is irrelevant. So it's easier to just test with one format of ingest." [attribs] (let [collection (data-umm-c/collection-concept (data-umm-c/collection 1 attribs) :umm-json)] [(:concept-id (ingest/ingest-concept (assoc collection :concept-id (generate-concept-id 1 "PROV1"))))])) (deftest bulk-update-science-keywords ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) bulk-update-options1 {:token (e/login (s/context) "user1") :user-id "user2"} bulk-update-options2 {:token (e/login (s/context) "user1")} bulk-update-options3 {:user-id "user2"} bulk-update-body {:concept-ids ["all"] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}} ;; CMR-4570 tests that no duplicate science keywords are created. duplicate-body {:concept-ids ["ALL" ] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"}}] ;; Initiate bulk update that shouldn't add any duplicates. (let [response (ingest/bulk-update-collections "PROV1" duplicate-body) _ (index/wait-until-indexed) {:keys [task-id]} response ;; I am surprised to find out that the task-id returned in the response is a string ;; Here I am just blindly patch this test to work with a string. next-task-id (+ 1 (Integer/parseInt task-id)) collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response))) (side/eval-form `(ingest-config/set-bulk-update-enabled! false)) ;; Kick off bulk update when bulk update is disabled is not allowed (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 400 (:status response))) (is (= ["Bulk update is disabled."] (:errors response)))) (let [collection-response (ingest/bulk-update-task-status "PROV1" next-task-id)] (is (= 404 (:status collection-response))) (is (= [(format "Bulk update task with task id [%s] could not be found for provider id [PROV1]." next-task-id)] (:errors collection-response)))) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= 200 (:status collection-response)))) (let [collection-response (ingest/bulk-update-task-status "PROV2" task-id)] (is (= 404 (:status collection-response))) (is (= [(format "Bulk update task with task id [%s] could not be found for provider id [PROV2]." task-id)] (:errors collection-response)))) (side/eval-form `(ingest-config/set-bulk-update-enabled! true))) ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options1)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 3 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 3 "user2") (is (= "2017-01-01T00:00:00Z" (:revision-date (:meta concept)))) (some #(= {:Date "2017-01-01T00:00:00Z" :Type "UPDATE"} %) (:MetadataDates (:umm concept))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:VariableLevel1 "HEAVY METALS CONCENTRATION" :Category "EARTH SCIENCE" :Term "ENVIRONMENTAL IMPACTS" :Topic "HUMAN DIMENSIONS"}] (:ScienceKeywords (:umm concept)))))) (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options2)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 4 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 4 "user1"))) (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body bulk-update-options3)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 5 (:revision-id (:meta concept)))) (ingest/assert-user-id concept-id 5 "user2"))))) (deftest bulk-update-add-to-existing-multiple-science-keywords ;; This test is the same as the previous bulk-update-science-keywords test except ;; that it shows that update-value could be an array of objects. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"}]} ;; CMR-4570 tests that no duplicate science keywords are created. duplicate-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Initiate bulk update that shouldn't add any duplicates. (ingest/bulk-update-collections "PROV1" duplicate-body) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:Category "EARTH SCIENCE" :Term "MARINE SEDIMENTS" :Topic "OCEANS"} {:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest bulk-update-clear-all-and-replace-with-multiple-science-keywords ;; This test shows that update-value could be an array of objects when doing CLEAR_ALL_AND_REPLACE. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "CLEAR_ALL_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest bulk-update-find-and-replace-with-multiple-science-keywords ;; This test shows that update-value could be an array of objects when doing FIND_AND_REPLACE. ;; Ingest a collection in each format with science keywords to update (let [concept-ids (ingest-collection-in-each-format find-and-replace-multiple-science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :find-value {:Topic "OCEANS"} :update-field "SCIENCE_KEYWORDS" :update-value [{:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"} {:Category "EARTH SCIENCE2" :Topic "HUMAN DIMENSIONS2" :Term "ENVIRONMENTAL IMPACTS2" :VariableLevel1 "HEAVY METALS CONCENTRATION2"} {:Category "EARTH SCIENCE1" :Topic "HUMAN DIMENSIONS1" :Term "ENVIRONMENTAL IMPACTS1" :VariableLevel1 "HEAVY METALS CONCENTRATION1"}]}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= (:ScienceKeywords (:umm concept)) [{:VariableLevel1 "HEAVY METALS CONCENTRATION1" :Category "EARTH SCIENCE1" :Term "ENVIRONMENTAL IMPACTS1" :Topic "HUMAN DIMENSIONS1"} {:VariableLevel1 "HEAVY METALS CONCENTRATION2" :Category "EARTH SCIENCE2" :Term "ENVIRONMENTAL IMPACTS2" :Topic "HUMAN DIMENSIONS2"}])))))) (deftest data-center-bulk-update (let [concept-ids (ingest-collection-in-each-format data-centers-umm) _ (index/wait-until-indexed)] (testing "Data center find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "DATA_CENTERS" :find-value {:ShortName "NSID"} :update-value {:ShortName "NSIDC" :Roles ["ORIGINATOR"]}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "NSIDC" :Roles ["ORIGINATOR"]} {:ShortName "LPDAAC" :Roles ["PROCESSOR"]}] (map #(select-keys % [:Roles :ShortName]) (:DataCenters (:umm concept)))))))))) (deftest nil-instrument-long-name-bulk-update (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "nil instrument long name find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"} :update-value {:ShortName "LVIS" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first) platforms (get-in concept [:umm :Platforms])]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]}] platforms))))))) (deftest instrument-bulk-update-find-and-replace (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "instrument find and replace" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"} :update-value [{:ShortName "LVIS"}]} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first) platforms (get-in concept [:umm :Platforms])]] (is (= 2 (:revision-id (:meta concept)))) ;; Make sure find and replace won't add an empty Instruments to the first platform which ;; doesn't contain any instruments. (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "LVIS"}]}] platforms))))))) (deftest nil-platform-long-name-bulk-update (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed)] (testing "nil platform long name find and update" (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "PLATFORMS" :find-value {:ShortName "a340-600-1"} :update-value {:ShortName "SMAP" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "SMAP" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper" :Technique "testing" :NumberOfInstruments 0 :OperationalModes ["mode1" "mode2"]}]} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft" :Instruments [{:ShortName "atm" :LongName "airborne topographic mapper"}]}] (:Platforms (:umm concept))))))))) (deftest data-center-home-page-url-removal (let [concept-ids (ingest-collection-in-umm-json-format data-centers-umm-with-home-page-url) _ (index/wait-until-indexed)] (testing "Data center find and update home page url - removal case." (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE_HOME_PAGE_URL" :update-field "DATA_CENTERS" :find-value {:ShortName "ShortName"} :update-value {:ShortName "New ShortName" :LongName nil}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "New ShortName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "PI:EMAIL:<EMAIL>END_PI"}]}} {:ShortName "New ShortName"} {:ShortName "New ShortName" :ContactInformation {}}] (map #(select-keys % [:ShortName :LongName :ContactInformation]) (:DataCenters (:umm concept)))))))))) (deftest data-center-home-page-url-update (let [concept-ids (ingest-collection-in-umm-json-format data-centers-umm-with-home-page-url) _ (index/wait-until-indexed)] (testing "Data center find and update home page url - update case." (let [bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE_HOME_PAGE_URL" :update-field "DATA_CENTERS" :find-value {:ShortName "ShortName"} :update-value {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"} {:URLContentType "DataCenterURL" :Type "PROJECT HOME PAGE" :URL "http://nsidc.org/daac/index.html"}] :ContactMechanisms [{:Type "Telephone" :Value "1 303 492 6199 x"} {:Type "Fax" :Value "1 303 492 2468 x"} {:Type "Email" :Value "PI:EMAIL:<EMAIL>END_PI"}]}} {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}} {:ShortName "New ShortName" :LongName "New LongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL" :Type "HOME PAGE" :URL "http://test.org/daac/index.html"}]}}] (map #(select-keys % [:ShortName :LongName :ContactInformation]) (:DataCenters (:umm concept)))))))))) (deftest bulk-update-replace-test (let [concept-ids (ingest-collection-in-each-format find-replace-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-replace-with-identical-update-value-test (let [concept-ids (ingest-collection-in-each-format find-replace-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REPLACE" :update-field "SCIENCE_KEYWORDS" :find-value {:VariableLevel1 "CARBON MONOXIDE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "CARBON MONOXIDE"} {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "CLOUDS" :VariableLevel1 "CLOUD MICROPHYSICS" :VariableLevel2 "CLOUD LIQUID WATER/ICE"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-remove-all-instruments-test (let [concept-ids (ingest-collection-in-umm-json-format platforms-instruments-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_REMOVE" :update-field "INSTRUMENTS" :find-value {:ShortName "atm"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-status (first (:collection-statuses collection-response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "UPDATED" (:status collection-status))) (is (= "Collection was updated successfully, but translating the collection to UMM-C had the following issues: [:MetadataDates] latest UPDATE date value: [2017-01-01T00:00:00.000Z] should be in the past." (:status-message collection-status)))) ;; Check that each concept was updated. (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= [{:ShortName "a340-600-1" :LongName "airbus a340-600-1" :Type "Aircraft"} {:ShortName "a340-600-2" :LongName "airbus a340-600" :Type "Aircraft"} {:ShortName "a340-600-3" :LongName "airbus a340-600" :Type "Aircraft"}] (:Platforms (:umm concept))))))) (deftest bulk-update-update-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE", :Topic "ATMOSPHERE", :Term "AIR QUALITY", :VariableLevel1 "EMISSIONS"} {:Category "EARTH SCIENCE", :Topic "ATMOSPHERE", :Term "AIR QUALITY", :VariableLevel1 "EMISSIONS", :VariableLevel2 "CLOUD LIQUID WATER/ICE"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-update-with-identical-update-value-test (let [concept-ids (ingest-collection-in-each-format science-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "OCEANS"} :update-value {:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id)] (is (= "COMPLETE" (:task-status collection-response)))) ;; Check that each concept was updated (doseq [concept-id concept-ids :let [concept (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)]] (is (= 2 (:revision-id (:meta concept)))) (is (= "application/vnd.nasa.cmr.umm+json" (:format (:meta concept)))) (is (= [{:Category "EARTH SCIENCE" :Topic "OCEANS" :Term "MARINE SEDIMENTS"}] (:ScienceKeywords (:umm concept))))))) (deftest bulk-update-update-not-found-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} original-concepts (doseq [concept-id concept-ids] (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first)) task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body)) _ (index/wait-until-indexed) new-concepts (doseq [concept-id concept-ids] (-> (search/find-concepts-umm-json :collection {:concept-id concept-id}) :results :items first))] (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-statuses (for [concept-id concept-ids] {:concept-id concept-id :status "SKIPPED" :status-message (str "Collection with concept-id [" concept-id "] is not updated because no find-value found.")})] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Task completed with 6 SKIPPED out of 6 total collection update(s)." (:status-message collection-response))) (is (= collection-statuses (:collection-statuses collection-response)))) ;; Check that each concept was not updated. ;; revision-id not changed, format not changed, it's identical to the original-concepts. (is (= new-concepts original-concepts)))) (deftest bulk-update-update-all-tombstone-test (let [coll1 (data2-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1"})) coll2 (data2-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E2" :ShortName "S2"})) _ (index/wait-until-indexed) bulk-update-body1 {:concept-ids ["ALL"] :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} bulk-update-body2 {:concept-ids [(:concept-id coll1) (:concept-id coll2)] :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" ;; Note: find-value is case-sensitive. :find-value {:Topic "aTmoSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}}] ;; perform bulk update, verify that both collections are skipped because find-value is not found. (testing "all the non-deleted collections are included in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Task completed with 2 SKIPPED out of 2 total collection update(s)." (:status-message collection-response))))) ;; delete the collection (is (= 200 (:status (ingest/delete-concept (data2-core/umm-c-collection->concept coll1 :echo10))))) (index/wait-until-indexed) ;; perform another bulk update, verify that the deleted collection is not included when getting all ;; collections from the provider. (testing "Deleted collection is excluded in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "Task completed with 1 SKIPPED out of 1 total collection update(s)." (:status-message collection-response))))) ;; perform a bulk update with the deleted collection's concept-id and a non-deleted collection's concept-id ;; The deleted one should fail the update. (testing "Deleted collection is failed in update concept-id case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body2) _ (index/wait-until-indexed) collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response)) collection-statuses (:collection-statuses collection-response)] (is (= "COMPLETE" (:task-status collection-response))) (is (= "Collection with concept-id [C1200000009-PROV1] is deleted. Can not be updated." (get (first collection-statuses) :status-message))) (is (= "Task completed with 1 FAILED and 1 SKIPPED out of 2 total collection update(s)." (:status-message collection-response))))) ;; delete the second collection (is (= 200 (:status (ingest/delete-concept (data2-core/umm-c-collection->concept coll2 :echo10))))) (index/wait-until-indexed) ;; perform another bulk update, verify that the deleted collections are not included when getting all ;; collections from the provider. (testing "All collections are deleted in update all case." (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body1) _ (index/wait-until-indexed)] (is (= ["There are no collections that have not been deleted for provider [PROV1]."] (:errors response))))))) (deftest bulk-update-default-name-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= (:task-id response) (get collection-response :name))) (is (= "COMPLETE" (:task-status collection-response)))))) (deftest bulk-update-unique-name-test (let [concept-ids (ingest-collection-in-each-format find-update-keywords-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :name "unique" :update-type "FIND_AND_UPDATE" :update-field "SCIENCE_KEYWORDS" :find-value {:Topic "ATMOSPHERE"} :update-value {:Category "EARTH SCIENCE" :Topic "ATMOSPHERE" :Term "AIR QUALITY" :VariableLevel1 "EMISSIONS"}} response (ingest/bulk-update-collections "PROV1" bulk-update-body) response2 (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) (is (= 422 (:status response2))) (is (= ["Error creating bulk update task: Bulk update name needs to be unique within the provider."] (:errors response2))))) (deftest bulk-update-xml-to-umm-failure-test (let [coll-metadata (slurp (io/resource "dif-samples/cmr-4455-collection.xml")) concept (ingest/ingest-concept (ingest/concept :collection "PROV1" "foo" :dif coll-metadata)) _ (index/wait-until-indexed) bulk-update-body {:concept-ids [(:concept-id concept)] :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}}] ;; Kick off bulk update (let [response (ingest/bulk-update-collections "PROV1" bulk-update-body)] (is (= 200 (:status response))) ;; Wait for queueing/indexing to catch up (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" (:task-id response))] (is (= "COMPLETE" (:task-status collection-response))))))) (deftest bulk-update-large-status-message-test (let [concept-ids (ingest-collection-in-umm-json-format large-status-message-umm) _ (index/wait-until-indexed) bulk-update-body {:concept-ids concept-ids :update-type "ADD_TO_EXISTING" :update-field "SCIENCE_KEYWORDS" :update-value {:Category "EARTH SCIENCE" :Topic "HUMAN DIMENSIONS" :Term "ENVIRONMENTAL IMPACTS" :VariableLevel1 "HEAVY METALS CONCENTRATION"}} task-id (:task-id (ingest/bulk-update-collections "PROV1" bulk-update-body))] (index/wait-until-indexed) (let [collection-response (ingest/bulk-update-task-status "PROV1" task-id) collection-status (first (:collection-statuses collection-response))] (is (= "COMPLETE" (:task-status collection-response))) (is (= "UPDATED" (:status collection-status))) (is (< 255 (count (:status-message collection-status)))))))
[ { "context": "edis-conn (redis-core/create {:host host :password password})\n data (redis-core/wcar redis-conn (redis", "end": 297, "score": 0.774488627910614, "start": 289, "tag": "PASSWORD", "value": "password" } ]
kafka-clj/src/kafka_clj/apputils/cmd_work_queue.clj
gerritjvv/kafka-fast
152
(ns kafka-clj.apputils.cmd-work-queue (:require [kafka-clj.redis.protocol :as redis-api] [kafka-clj.redis.core :as redis-core])) (defn read-redis-queue [[host from limit & {:strs [password] :or {password nil}}]] (let [redis-conn (redis-core/create {:host host :password password}) data (redis-core/wcar redis-conn (redis-api/-lrange redis-conn "etl-kafka-work-queue" from limit))] (doseq [item data] (prn item))))
114926
(ns kafka-clj.apputils.cmd-work-queue (:require [kafka-clj.redis.protocol :as redis-api] [kafka-clj.redis.core :as redis-core])) (defn read-redis-queue [[host from limit & {:strs [password] :or {password nil}}]] (let [redis-conn (redis-core/create {:host host :password <PASSWORD>}) data (redis-core/wcar redis-conn (redis-api/-lrange redis-conn "etl-kafka-work-queue" from limit))] (doseq [item data] (prn item))))
true
(ns kafka-clj.apputils.cmd-work-queue (:require [kafka-clj.redis.protocol :as redis-api] [kafka-clj.redis.core :as redis-core])) (defn read-redis-queue [[host from limit & {:strs [password] :or {password nil}}]] (let [redis-conn (redis-core/create {:host host :password PI:PASSWORD:<PASSWORD>END_PI}) data (redis-core/wcar redis-conn (redis-api/-lrange redis-conn "etl-kafka-work-queue" from limit))] (doseq [item data] (prn item))))
[ { "context": "(:clj (vec (sort (su/get-port-names)))\n ; TODO(Richo): Implement this!\n :cljs []))\n\n(defonce ^:pri", "end": 252, "score": 0.9954589605331421, "start": 247, "tag": "NAME", "value": "Richo" } ]
middleware/server/src/middleware/device/ports/scanner.cljc
GIRA/UziScript
15
(ns middleware.device.ports.scanner (:require [clojure.core.async :refer [chan <! >! go-loop timeout alts! close!]] #?(:clj [serial.util :as su]))) (defn- get-available-ports [] #?(:clj (vec (sort (su/get-port-names))) ; TODO(Richo): Implement this! :cljs [])) (defonce ^:private cancel-token (atom nil)) (def available-ports (atom [])) (defn stop! [] (when-let [token @cancel-token] (close! token))) (defn start! [] (let [[old _] (reset-vals! cancel-token (let [token (chan)] (go-loop [] (let [previous @available-ports current (get-available-ports)] (when (not= previous current) (reset! available-ports current))) (let [[_ ch] (alts! [token (timeout 1000)] :priority true)] (when-not (= ch token) (recur)))) token))] (when old (close! old))))
61957
(ns middleware.device.ports.scanner (:require [clojure.core.async :refer [chan <! >! go-loop timeout alts! close!]] #?(:clj [serial.util :as su]))) (defn- get-available-ports [] #?(:clj (vec (sort (su/get-port-names))) ; TODO(<NAME>): Implement this! :cljs [])) (defonce ^:private cancel-token (atom nil)) (def available-ports (atom [])) (defn stop! [] (when-let [token @cancel-token] (close! token))) (defn start! [] (let [[old _] (reset-vals! cancel-token (let [token (chan)] (go-loop [] (let [previous @available-ports current (get-available-ports)] (when (not= previous current) (reset! available-ports current))) (let [[_ ch] (alts! [token (timeout 1000)] :priority true)] (when-not (= ch token) (recur)))) token))] (when old (close! old))))
true
(ns middleware.device.ports.scanner (:require [clojure.core.async :refer [chan <! >! go-loop timeout alts! close!]] #?(:clj [serial.util :as su]))) (defn- get-available-ports [] #?(:clj (vec (sort (su/get-port-names))) ; TODO(PI:NAME:<NAME>END_PI): Implement this! :cljs [])) (defonce ^:private cancel-token (atom nil)) (def available-ports (atom [])) (defn stop! [] (when-let [token @cancel-token] (close! token))) (defn start! [] (let [[old _] (reset-vals! cancel-token (let [token (chan)] (go-loop [] (let [previous @available-ports current (get-available-ports)] (when (not= previous current) (reset! available-ports current))) (let [[_ ch] (alts! [token (timeout 1000)] :priority true)] (when-not (= ch token) (recur)))) token))] (when old (close! old))))
[ { "context": "me}\n {:name \"toucan\"\n :database-type \"OB", "end": 1008, "score": 0.9861062169075012, "start": 1002, "tag": "NAME", "value": "toucan" }, { "context": "}}}\n {:name \"buyer\"\n :database-type \"OB", "end": 2267, "score": 0.5380285978317261, "start": 2262, "tag": "NAME", "value": "buyer" }, { "context": " :display_name \"Name\"\n :database_type", "end": 7032, "score": 0.552257776260376, "start": 7028, "tag": "NAME", "value": "Name" } ]
c#-metabase/test/metabase/test/mock/toucanery.clj
hanakhry/Crime_Admin
0
(ns metabase.test.mock.toucanery "A document style database mocked for testing. This is a dynamic schema db with `:nested-fields`. Most notably meant to serve as a representation of a Mongo database." (:require [medley.core :as m] [metabase.driver :as driver] [metabase.test.mock.util :as mock-util])) (def toucanery-tables {"transactions" {:name "transactions" :schema nil :fields #{{:name "id" :pk? true :database-type "SERIAL" :base-type :type/Integer} {:name "ts" :database-type "BIGINT" :base-type :type/BigInteger :effective-type :type/DateTime :coercion-strategy :Coercion/UNIXMilliSeconds->DateTime} {:name "toucan" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "name" :database-type "VARCHAR" :base-type :type/Text} {:name "details" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "age" :database-type "INT" :base-type :type/Integer} {:name "weight" :database-type "DECIMAL" :semantic-type :type/Category :base-type :type/Decimal}}}}} {:name "buyer" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "name" :database-type "VARCHAR" :base-type :type/Text} {:name "cc" :database-type "VARCHAR" :base-type :type/Text}}}}} "employees" {:name "employees" :schema nil :fields #{{:name "id" :database-type "SERIAL" :base-type :type/Integer} {:name "name" :database-type "VARCHAR" :base-type :type/Text}}}}) (driver/register! ::toucanery, :abstract? true) (defmethod driver/describe-database ::toucanery [_ {:keys [exclude-tables]}] (let [tables (for [table (vals toucanery-tables) :when (not (contains? exclude-tables (:name table)))] (select-keys table [:schema :name]))] {:tables (set tables)})) (defn- add-db-position [field position] (-> field (assoc :database-position position) (m/update-existing :nested-fields (partial (comp set map) #(add-db-position % position))))) (defmethod driver/describe-table ::toucanery [_ _ table] (-> (get toucanery-tables (:name table)) (update :fields (partial (comp set map-indexed) (fn [idx field] (add-db-position field idx)))))) (defmethod driver/table-rows-seq ::toucanery [_ _ table] (when (= (:name table) "_metabase_metadata") [{:keypath "movies.filming.description", :value "If the movie is currently being filmed."} {:keypath "movies.description", :value "A cinematic adventure."}])) (defmethod driver/supports? [::toucanery :nested-fields] [_ _] true) (defmethod driver/mbql->native ::toucanery [_ query] query) (defmethod driver/execute-reducible-query ::toucanery [_ query _ respond] (mock-util/mock-execute-reducible-query query respond)) (def toucanery-tables-and-fields [(merge mock-util/table-defaults {:name "employees" :fields [(merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "id" :display_name "ID" :database_type "SERIAL" :base_type :type/Integer :semantic_type :type/PK})] :display_name "Employees"}) (merge mock-util/table-defaults {:name "transactions" :fields [(merge mock-util/field-defaults {:name "ts" :display_name "Ts" :database_type "BIGINT" :base_type :type/BigInteger :effective_type :type/DateTime :coercion_strategy :Coercion/UNIXMilliSeconds->DateTime}) (merge mock-util/field-defaults {:name "id" :display_name "ID" :database_type "SERIAL" :base_type :type/Integer}) (merge mock-util/field-defaults {:name "buyer" :display_name "Buyer" :database_type "OBJECT" :base_type :type/Dictionary}) (merge mock-util/field-defaults {:name "cc" :display_name "Cc" :database_type "VARCHAR" :base_type :type/Text :parent_id true}) (merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :parent_id true :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "age" :display_name "Age" :database_type "INT" :base_type :type/Integer :parent_id true}) (merge mock-util/field-defaults {:name "details" :display_name "Details" :database_type "OBJECT" :base_type :type/Dictionary :parent_id true}) (merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :parent_id true :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "toucan" :display_name "Toucan" :database_type "OBJECT" :base_type :type/Dictionary}) (merge mock-util/field-defaults {:name "weight" :display_name "Weight" :database_type "DECIMAL" :base_type :type/Decimal :parent_id true :semantic_type :type/Category})] :display_name "Transactions"})])
18877
(ns metabase.test.mock.toucanery "A document style database mocked for testing. This is a dynamic schema db with `:nested-fields`. Most notably meant to serve as a representation of a Mongo database." (:require [medley.core :as m] [metabase.driver :as driver] [metabase.test.mock.util :as mock-util])) (def toucanery-tables {"transactions" {:name "transactions" :schema nil :fields #{{:name "id" :pk? true :database-type "SERIAL" :base-type :type/Integer} {:name "ts" :database-type "BIGINT" :base-type :type/BigInteger :effective-type :type/DateTime :coercion-strategy :Coercion/UNIXMilliSeconds->DateTime} {:name "<NAME>" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "name" :database-type "VARCHAR" :base-type :type/Text} {:name "details" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "age" :database-type "INT" :base-type :type/Integer} {:name "weight" :database-type "DECIMAL" :semantic-type :type/Category :base-type :type/Decimal}}}}} {:name "<NAME>" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "name" :database-type "VARCHAR" :base-type :type/Text} {:name "cc" :database-type "VARCHAR" :base-type :type/Text}}}}} "employees" {:name "employees" :schema nil :fields #{{:name "id" :database-type "SERIAL" :base-type :type/Integer} {:name "name" :database-type "VARCHAR" :base-type :type/Text}}}}) (driver/register! ::toucanery, :abstract? true) (defmethod driver/describe-database ::toucanery [_ {:keys [exclude-tables]}] (let [tables (for [table (vals toucanery-tables) :when (not (contains? exclude-tables (:name table)))] (select-keys table [:schema :name]))] {:tables (set tables)})) (defn- add-db-position [field position] (-> field (assoc :database-position position) (m/update-existing :nested-fields (partial (comp set map) #(add-db-position % position))))) (defmethod driver/describe-table ::toucanery [_ _ table] (-> (get toucanery-tables (:name table)) (update :fields (partial (comp set map-indexed) (fn [idx field] (add-db-position field idx)))))) (defmethod driver/table-rows-seq ::toucanery [_ _ table] (when (= (:name table) "_metabase_metadata") [{:keypath "movies.filming.description", :value "If the movie is currently being filmed."} {:keypath "movies.description", :value "A cinematic adventure."}])) (defmethod driver/supports? [::toucanery :nested-fields] [_ _] true) (defmethod driver/mbql->native ::toucanery [_ query] query) (defmethod driver/execute-reducible-query ::toucanery [_ query _ respond] (mock-util/mock-execute-reducible-query query respond)) (def toucanery-tables-and-fields [(merge mock-util/table-defaults {:name "employees" :fields [(merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "id" :display_name "ID" :database_type "SERIAL" :base_type :type/Integer :semantic_type :type/PK})] :display_name "Employees"}) (merge mock-util/table-defaults {:name "transactions" :fields [(merge mock-util/field-defaults {:name "ts" :display_name "Ts" :database_type "BIGINT" :base_type :type/BigInteger :effective_type :type/DateTime :coercion_strategy :Coercion/UNIXMilliSeconds->DateTime}) (merge mock-util/field-defaults {:name "id" :display_name "ID" :database_type "SERIAL" :base_type :type/Integer}) (merge mock-util/field-defaults {:name "buyer" :display_name "Buyer" :database_type "OBJECT" :base_type :type/Dictionary}) (merge mock-util/field-defaults {:name "cc" :display_name "Cc" :database_type "VARCHAR" :base_type :type/Text :parent_id true}) (merge mock-util/field-defaults {:name "name" :display_name "<NAME>" :database_type "VARCHAR" :base_type :type/Text :parent_id true :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "age" :display_name "Age" :database_type "INT" :base_type :type/Integer :parent_id true}) (merge mock-util/field-defaults {:name "details" :display_name "Details" :database_type "OBJECT" :base_type :type/Dictionary :parent_id true}) (merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :parent_id true :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "toucan" :display_name "Toucan" :database_type "OBJECT" :base_type :type/Dictionary}) (merge mock-util/field-defaults {:name "weight" :display_name "Weight" :database_type "DECIMAL" :base_type :type/Decimal :parent_id true :semantic_type :type/Category})] :display_name "Transactions"})])
true
(ns metabase.test.mock.toucanery "A document style database mocked for testing. This is a dynamic schema db with `:nested-fields`. Most notably meant to serve as a representation of a Mongo database." (:require [medley.core :as m] [metabase.driver :as driver] [metabase.test.mock.util :as mock-util])) (def toucanery-tables {"transactions" {:name "transactions" :schema nil :fields #{{:name "id" :pk? true :database-type "SERIAL" :base-type :type/Integer} {:name "ts" :database-type "BIGINT" :base-type :type/BigInteger :effective-type :type/DateTime :coercion-strategy :Coercion/UNIXMilliSeconds->DateTime} {:name "PI:NAME:<NAME>END_PI" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "name" :database-type "VARCHAR" :base-type :type/Text} {:name "details" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "age" :database-type "INT" :base-type :type/Integer} {:name "weight" :database-type "DECIMAL" :semantic-type :type/Category :base-type :type/Decimal}}}}} {:name "PI:NAME:<NAME>END_PI" :database-type "OBJECT" :base-type :type/Dictionary :nested-fields #{{:name "name" :database-type "VARCHAR" :base-type :type/Text} {:name "cc" :database-type "VARCHAR" :base-type :type/Text}}}}} "employees" {:name "employees" :schema nil :fields #{{:name "id" :database-type "SERIAL" :base-type :type/Integer} {:name "name" :database-type "VARCHAR" :base-type :type/Text}}}}) (driver/register! ::toucanery, :abstract? true) (defmethod driver/describe-database ::toucanery [_ {:keys [exclude-tables]}] (let [tables (for [table (vals toucanery-tables) :when (not (contains? exclude-tables (:name table)))] (select-keys table [:schema :name]))] {:tables (set tables)})) (defn- add-db-position [field position] (-> field (assoc :database-position position) (m/update-existing :nested-fields (partial (comp set map) #(add-db-position % position))))) (defmethod driver/describe-table ::toucanery [_ _ table] (-> (get toucanery-tables (:name table)) (update :fields (partial (comp set map-indexed) (fn [idx field] (add-db-position field idx)))))) (defmethod driver/table-rows-seq ::toucanery [_ _ table] (when (= (:name table) "_metabase_metadata") [{:keypath "movies.filming.description", :value "If the movie is currently being filmed."} {:keypath "movies.description", :value "A cinematic adventure."}])) (defmethod driver/supports? [::toucanery :nested-fields] [_ _] true) (defmethod driver/mbql->native ::toucanery [_ query] query) (defmethod driver/execute-reducible-query ::toucanery [_ query _ respond] (mock-util/mock-execute-reducible-query query respond)) (def toucanery-tables-and-fields [(merge mock-util/table-defaults {:name "employees" :fields [(merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "id" :display_name "ID" :database_type "SERIAL" :base_type :type/Integer :semantic_type :type/PK})] :display_name "Employees"}) (merge mock-util/table-defaults {:name "transactions" :fields [(merge mock-util/field-defaults {:name "ts" :display_name "Ts" :database_type "BIGINT" :base_type :type/BigInteger :effective_type :type/DateTime :coercion_strategy :Coercion/UNIXMilliSeconds->DateTime}) (merge mock-util/field-defaults {:name "id" :display_name "ID" :database_type "SERIAL" :base_type :type/Integer}) (merge mock-util/field-defaults {:name "buyer" :display_name "Buyer" :database_type "OBJECT" :base_type :type/Dictionary}) (merge mock-util/field-defaults {:name "cc" :display_name "Cc" :database_type "VARCHAR" :base_type :type/Text :parent_id true}) (merge mock-util/field-defaults {:name "name" :display_name "PI:NAME:<NAME>END_PI" :database_type "VARCHAR" :base_type :type/Text :parent_id true :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "age" :display_name "Age" :database_type "INT" :base_type :type/Integer :parent_id true}) (merge mock-util/field-defaults {:name "details" :display_name "Details" :database_type "OBJECT" :base_type :type/Dictionary :parent_id true}) (merge mock-util/field-defaults {:name "name" :display_name "Name" :database_type "VARCHAR" :base_type :type/Text :parent_id true :semantic_type :type/Name}) (merge mock-util/field-defaults {:name "toucan" :display_name "Toucan" :database_type "OBJECT" :base_type :type/Dictionary}) (merge mock-util/field-defaults {:name "weight" :display_name "Weight" :database_type "DECIMAL" :base_type :type/Decimal :parent_id true :semantic_type :type/Category})] :display_name "Transactions"})])
[ { "context": "ethods\n(let [private-patient (->PrivatePatient 1 \"Victor\" \"123456\")\n plan-patient (->HealthInsuranceP", "end": 1199, "score": 0.9995940923690796, "start": 1193, "tag": "NAME", "value": "Victor" }, { "context": ")\n plan-patient (->HealthInsurancePatient 2 \"Fred\" \"987654\" [:x-ray :ultrasound])]\n\n (println\n ", "end": 1263, "score": 0.9995588660240173, "start": 1259, "tag": "NAME", "value": "Fred" } ]
hospital_patient/src/hospital_patient/class4.clj
vgeorgo/courses-alura-clojure
0
(ns hospital-patient.class4 (:use clojure.pprint)) ; Defining records (classes) (defrecord HealthInsurancePatient [id name document plan]) (defrecord PrivatePatient [id name document]) ; Returns anything that will be used to identify what method should be used. ; Not a good practice to return different types (like :keys and class) (defn type-of-authorization [request] (let [patient (:patient request) situation (:situation request) urgent? (= :urgent situation)] (if urgent? :authorized (class patient)))) ; Defines a method that will have multiple implementations depending the result of the function ; 'type-of-authorization' (defmulti sign-authorization? type-of-authorization) ; Defining the methods based on the possible returns of 'type-of-authorization' (defmethod sign-authorization? :authorized [_] false) (defmethod sign-authorization? PrivatePatient [request] (>= (:value request 0) 50)) (defmethod sign-authorization? HealthInsurancePatient [request] (let [plan (:plan (:patient request)) procedure (:procedure request)] (not (some #(= % procedure) plan)))) ; Test methods (let [private-patient (->PrivatePatient 1 "Victor" "123456") plan-patient (->HealthInsurancePatient 2 "Fred" "987654" [:x-ray :ultrasound])] (println "Private patient normal sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :normal})) (println "Private patient normal sign 40? " (sign-authorization? {:patient private-patient, :value 40, :procedure :blood-sample})) (println "Private patient urgent sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :urgent})) (println "Plan patient normal sign x-ray? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :x-ray :situation :normal})) (println "Plan patient normal sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :normal})) (println "Plan patient urgent sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :urgent})))
49472
(ns hospital-patient.class4 (:use clojure.pprint)) ; Defining records (classes) (defrecord HealthInsurancePatient [id name document plan]) (defrecord PrivatePatient [id name document]) ; Returns anything that will be used to identify what method should be used. ; Not a good practice to return different types (like :keys and class) (defn type-of-authorization [request] (let [patient (:patient request) situation (:situation request) urgent? (= :urgent situation)] (if urgent? :authorized (class patient)))) ; Defines a method that will have multiple implementations depending the result of the function ; 'type-of-authorization' (defmulti sign-authorization? type-of-authorization) ; Defining the methods based on the possible returns of 'type-of-authorization' (defmethod sign-authorization? :authorized [_] false) (defmethod sign-authorization? PrivatePatient [request] (>= (:value request 0) 50)) (defmethod sign-authorization? HealthInsurancePatient [request] (let [plan (:plan (:patient request)) procedure (:procedure request)] (not (some #(= % procedure) plan)))) ; Test methods (let [private-patient (->PrivatePatient 1 "<NAME>" "123456") plan-patient (->HealthInsurancePatient 2 "<NAME>" "987654" [:x-ray :ultrasound])] (println "Private patient normal sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :normal})) (println "Private patient normal sign 40? " (sign-authorization? {:patient private-patient, :value 40, :procedure :blood-sample})) (println "Private patient urgent sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :urgent})) (println "Plan patient normal sign x-ray? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :x-ray :situation :normal})) (println "Plan patient normal sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :normal})) (println "Plan patient urgent sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :urgent})))
true
(ns hospital-patient.class4 (:use clojure.pprint)) ; Defining records (classes) (defrecord HealthInsurancePatient [id name document plan]) (defrecord PrivatePatient [id name document]) ; Returns anything that will be used to identify what method should be used. ; Not a good practice to return different types (like :keys and class) (defn type-of-authorization [request] (let [patient (:patient request) situation (:situation request) urgent? (= :urgent situation)] (if urgent? :authorized (class patient)))) ; Defines a method that will have multiple implementations depending the result of the function ; 'type-of-authorization' (defmulti sign-authorization? type-of-authorization) ; Defining the methods based on the possible returns of 'type-of-authorization' (defmethod sign-authorization? :authorized [_] false) (defmethod sign-authorization? PrivatePatient [request] (>= (:value request 0) 50)) (defmethod sign-authorization? HealthInsurancePatient [request] (let [plan (:plan (:patient request)) procedure (:procedure request)] (not (some #(= % procedure) plan)))) ; Test methods (let [private-patient (->PrivatePatient 1 "PI:NAME:<NAME>END_PI" "123456") plan-patient (->HealthInsurancePatient 2 "PI:NAME:<NAME>END_PI" "987654" [:x-ray :ultrasound])] (println "Private patient normal sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :normal})) (println "Private patient normal sign 40? " (sign-authorization? {:patient private-patient, :value 40, :procedure :blood-sample})) (println "Private patient urgent sign 500? " (sign-authorization? {:patient private-patient, :value 500, :procedure :blood-sample :situation :urgent})) (println "Plan patient normal sign x-ray? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :x-ray :situation :normal})) (println "Plan patient normal sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :normal})) (println "Plan patient urgent sign weird-exam? " (sign-authorization? {:patient plan-patient, :value 500, :procedure :weird-exam :situation :urgent})))
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.9706907868385315, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-rx/src/test/clojure/pigpen/rx/extensions_test.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.rx.extensions-test (:use clojure.test pigpen.rx.extensions) (:require [rx.lang.clojure.core :as rx] [rx.lang.clojure.blocking :as rx-block]) (:import [rx Observable Observer Subscriber Subscription] [rx.observables BlockingObservable])) (deftest test-multicast ;; TODO relax the timing here. Sometimes this will show a false negative (let [results (vec (repeatedly 7 #(atom []))) track (fn [a] (fn [n] (swap! (results a) conj n))) values (atom []) data (rx/observable* (fn [^Subscriber o] (let [cancel (atom false)] (.add o (reify Subscription (unsubscribe [this] (swap! cancel (constantly true))))) (future (doseq [i (take-while (fn [_] (not @cancel)) (range))] (.onNext o i) (swap! values #(conj % i)) (Thread/sleep 3)))))) mo (multicast data) ;; create two children o1 (mo) o2 (mo) ;; first subscription on o1, don't start _ (rx/subscribe (rx/take 1 o1) (track 0)) _ (Thread/sleep 10) ;; second subscription on o1, don't start _ (rx/subscribe (rx/take 2 o1) (track 1)) _ (Thread/sleep 10) ;; first subscription on o2, start _ (rx/subscribe (rx/take 3 o2) (track 2)) ;; it should finish by now _ (Thread/sleep 10) ;; subscribe to o2 again _ (rx/subscribe (rx/take 4 o2) (track 3)) ;; create a third child & subscribe o3 (mo) _ (rx/subscribe (rx/take 4 o3) (track 4)) ;; subscribe to o1, start over _ (rx/subscribe (rx/take 4 o1) (track 5)) ;; wait until halfway done _ (Thread/sleep 5) ;; add another child o4 (mo) _ (rx/subscribe (rx/take 4 o4) (track 6)) _ (Thread/sleep 50)] (is (= [0 1 2 0 1 2 3 4 5] @values)) (is (= (map deref results) [[0] [0 1] [0 1 2] [0 1 2 3] [0 1 2 3] [0 1 2 3] [2 3 4 5]])))) (deftest test-multicast-crossover (let [d0 (rx/seq->o [1 2 3]) d1 (rx/seq->o [4 5 6]) m0 (multicast d0) m1 (multicast d1) j0 (rx/merge (m0) (m1)) j1 (rx/merge (m0) (m1)) s0 (rx/merge j0 j1) v0 (rx-block/into [] s0)] (is (= (sort v0) [1 1 2 2 3 3 4 4 5 5 6 6]))))
22219
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.rx.extensions-test (:use clojure.test pigpen.rx.extensions) (:require [rx.lang.clojure.core :as rx] [rx.lang.clojure.blocking :as rx-block]) (:import [rx Observable Observer Subscriber Subscription] [rx.observables BlockingObservable])) (deftest test-multicast ;; TODO relax the timing here. Sometimes this will show a false negative (let [results (vec (repeatedly 7 #(atom []))) track (fn [a] (fn [n] (swap! (results a) conj n))) values (atom []) data (rx/observable* (fn [^Subscriber o] (let [cancel (atom false)] (.add o (reify Subscription (unsubscribe [this] (swap! cancel (constantly true))))) (future (doseq [i (take-while (fn [_] (not @cancel)) (range))] (.onNext o i) (swap! values #(conj % i)) (Thread/sleep 3)))))) mo (multicast data) ;; create two children o1 (mo) o2 (mo) ;; first subscription on o1, don't start _ (rx/subscribe (rx/take 1 o1) (track 0)) _ (Thread/sleep 10) ;; second subscription on o1, don't start _ (rx/subscribe (rx/take 2 o1) (track 1)) _ (Thread/sleep 10) ;; first subscription on o2, start _ (rx/subscribe (rx/take 3 o2) (track 2)) ;; it should finish by now _ (Thread/sleep 10) ;; subscribe to o2 again _ (rx/subscribe (rx/take 4 o2) (track 3)) ;; create a third child & subscribe o3 (mo) _ (rx/subscribe (rx/take 4 o3) (track 4)) ;; subscribe to o1, start over _ (rx/subscribe (rx/take 4 o1) (track 5)) ;; wait until halfway done _ (Thread/sleep 5) ;; add another child o4 (mo) _ (rx/subscribe (rx/take 4 o4) (track 6)) _ (Thread/sleep 50)] (is (= [0 1 2 0 1 2 3 4 5] @values)) (is (= (map deref results) [[0] [0 1] [0 1 2] [0 1 2 3] [0 1 2 3] [0 1 2 3] [2 3 4 5]])))) (deftest test-multicast-crossover (let [d0 (rx/seq->o [1 2 3]) d1 (rx/seq->o [4 5 6]) m0 (multicast d0) m1 (multicast d1) j0 (rx/merge (m0) (m1)) j1 (rx/merge (m0) (m1)) s0 (rx/merge j0 j1) v0 (rx-block/into [] s0)] (is (= (sort v0) [1 1 2 2 3 3 4 4 5 5 6 6]))))
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.rx.extensions-test (:use clojure.test pigpen.rx.extensions) (:require [rx.lang.clojure.core :as rx] [rx.lang.clojure.blocking :as rx-block]) (:import [rx Observable Observer Subscriber Subscription] [rx.observables BlockingObservable])) (deftest test-multicast ;; TODO relax the timing here. Sometimes this will show a false negative (let [results (vec (repeatedly 7 #(atom []))) track (fn [a] (fn [n] (swap! (results a) conj n))) values (atom []) data (rx/observable* (fn [^Subscriber o] (let [cancel (atom false)] (.add o (reify Subscription (unsubscribe [this] (swap! cancel (constantly true))))) (future (doseq [i (take-while (fn [_] (not @cancel)) (range))] (.onNext o i) (swap! values #(conj % i)) (Thread/sleep 3)))))) mo (multicast data) ;; create two children o1 (mo) o2 (mo) ;; first subscription on o1, don't start _ (rx/subscribe (rx/take 1 o1) (track 0)) _ (Thread/sleep 10) ;; second subscription on o1, don't start _ (rx/subscribe (rx/take 2 o1) (track 1)) _ (Thread/sleep 10) ;; first subscription on o2, start _ (rx/subscribe (rx/take 3 o2) (track 2)) ;; it should finish by now _ (Thread/sleep 10) ;; subscribe to o2 again _ (rx/subscribe (rx/take 4 o2) (track 3)) ;; create a third child & subscribe o3 (mo) _ (rx/subscribe (rx/take 4 o3) (track 4)) ;; subscribe to o1, start over _ (rx/subscribe (rx/take 4 o1) (track 5)) ;; wait until halfway done _ (Thread/sleep 5) ;; add another child o4 (mo) _ (rx/subscribe (rx/take 4 o4) (track 6)) _ (Thread/sleep 50)] (is (= [0 1 2 0 1 2 3 4 5] @values)) (is (= (map deref results) [[0] [0 1] [0 1 2] [0 1 2 3] [0 1 2 3] [0 1 2 3] [2 3 4 5]])))) (deftest test-multicast-crossover (let [d0 (rx/seq->o [1 2 3]) d1 (rx/seq->o [4 5 6]) m0 (multicast d0) m1 (multicast d1) j0 (rx/merge (m0) (m1)) j1 (rx/merge (m0) (m1)) s0 (rx/merge j0 j1) v0 (rx-block/into [] s0)] (is (= (sort v0) [1 1 2 2 3 3 4 4 5 5 6 6]))))
[ { "context": ";;; Copyright 2013 Mitchell Kember. Subject to the MIT License.\n;;; 2010 Canadian Co", "end": 34, "score": 0.9998852610588074, "start": 19, "tag": "NAME", "value": "Mitchell Kember" } ]
src/ccc/y2010/s2.clj
mk12/ccc
0
;;; Copyright 2013 Mitchell Kember. Subject to the MIT License. ;;; 2010 Canadian Computing Competition: Senior Division ;;; Problem S2: Huffman Encoding (ns ccc.y2010.s2) ;;; A "binary sequence" is a string containing only ASCII 0 and 1. ;;; A "code" is a binary sequence that represents a value. ;;; A "value" is a char or a string. ;;; A "Huffman map" is a map from codes to values. (defn decode-bit "Decodes a single bit using huff-map and [buf msg] where buf is a collection of bits that have not yet been decoded and msg is the decoded message so far." [huff-map [buf msg] bit] (let [new-buf (conj buf bit)] (if-let [value (huff-map (apply str new-buf))] [[] (conj msg value)] [new-buf msg]))) (defn main "Decodes bin-seq (a binary sequence) using huff-map (a Huffman map)." [huff-map bin-seq] (let [decode (partial decode-bit huff-map)] (->> (reduce decode [[] []] bin-seq) second (apply str))))
54876
;;; Copyright 2013 <NAME>. Subject to the MIT License. ;;; 2010 Canadian Computing Competition: Senior Division ;;; Problem S2: Huffman Encoding (ns ccc.y2010.s2) ;;; A "binary sequence" is a string containing only ASCII 0 and 1. ;;; A "code" is a binary sequence that represents a value. ;;; A "value" is a char or a string. ;;; A "Huffman map" is a map from codes to values. (defn decode-bit "Decodes a single bit using huff-map and [buf msg] where buf is a collection of bits that have not yet been decoded and msg is the decoded message so far." [huff-map [buf msg] bit] (let [new-buf (conj buf bit)] (if-let [value (huff-map (apply str new-buf))] [[] (conj msg value)] [new-buf msg]))) (defn main "Decodes bin-seq (a binary sequence) using huff-map (a Huffman map)." [huff-map bin-seq] (let [decode (partial decode-bit huff-map)] (->> (reduce decode [[] []] bin-seq) second (apply str))))
true
;;; Copyright 2013 PI:NAME:<NAME>END_PI. Subject to the MIT License. ;;; 2010 Canadian Computing Competition: Senior Division ;;; Problem S2: Huffman Encoding (ns ccc.y2010.s2) ;;; A "binary sequence" is a string containing only ASCII 0 and 1. ;;; A "code" is a binary sequence that represents a value. ;;; A "value" is a char or a string. ;;; A "Huffman map" is a map from codes to values. (defn decode-bit "Decodes a single bit using huff-map and [buf msg] where buf is a collection of bits that have not yet been decoded and msg is the decoded message so far." [huff-map [buf msg] bit] (let [new-buf (conj buf bit)] (if-let [value (huff-map (apply str new-buf))] [[] (conj msg value)] [new-buf msg]))) (defn main "Decodes bin-seq (a binary sequence) using huff-map (a Huffman map)." [huff-map bin-seq] (let [decode (partial decode-bit huff-map)] (->> (reduce decode [[] []] bin-seq) second (apply str))))
[ { "context": "QLException)))\n\n;; Inspired by https://github.com/Shyp/go-dberror/blob/master/error_test.go\n\n(use-fixtur", "end": 331, "score": 0.9995995759963989, "start": 327, "tag": "USERNAME", "value": "Shyp" }, { "context": "7e99-d616-4d8c-9c02-cbd13bceac60\"))\n(def email-1 \"test@example.com\")\n(def email-2 \"test2@example.com\")\n\n(deftest not", "end": 602, "score": 0.9999256134033203, "start": 586, "tag": "EMAIL", "value": "test@example.com" }, { "context": "))\n(def email-1 \"test@example.com\")\n(def email-2 \"test2@example.com\")\n\n(deftest not-null-violation\n (testing \"one co", "end": 636, "score": 0.9999244809150696, "start": 619, "tag": "EMAIL", "value": "test2@example.com" }, { "context": "ow contains (3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, test@example.com, -1, active, null).\"\n :postgresql/", "end": 2395, "score": 0.9993506669998169, "start": 2379, "tag": "EMAIL", "value": "test@example.com" }, { "context": " :postgresql.error/detail \"Key (id)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7) already exists.\"\n :postgresql/s", "end": 5415, "score": 0.8282673358917236, "start": 5379, "tag": "KEY", "value": "3c7d2b4a-3fc8-4782-a518-4ce9efef51e7" }, { "context": " :postgresql.error/detail \"Key (str_1, str_2)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, test@example.com) already exists.\"\n ", "end": 6263, "score": 0.989075779914856, "start": 6227, "tag": "KEY", "value": "3c7d2b4a-3fc8-4782-a518-4ce9efef51e7" }, { "context": "r_1, str_2)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, test@example.com) already exists.\"\n :postgresql/s", "end": 6281, "score": 0.9997791051864624, "start": 6265, "tag": "EMAIL", "value": "test@example.com" }, { "context": " :postgresql.error/detail \"Key (email)=(test@example.com) already exists.\"\n :postgresql/sql", "end": 7197, "score": 0.9998823404312134, "start": 7181, "tag": "EMAIL", "value": "test@example.com" }, { "context": " :postgresql.error/detail \"Key (account_id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is not pre", "end": 7899, "score": 0.8241270780563354, "start": 7896, "tag": "KEY", "value": "id)" }, { "context": " :postgresql.error/detail \"Key (account_id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is not present in table \\\"accounts\\\".\"\n ", "end": 7938, "score": 0.9809319376945496, "start": 7901, "tag": "KEY", "value": "91f47e99-d616-4d8c-9c02-cbd13bceac60)" }, { "context": " :postgresql.error/detail \"Key (id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is still ref", "end": 9069, "score": 0.8292988538742065, "start": 9069, "tag": "KEY", "value": "" }, { "context": " :postgresql.error/detail \"Key (id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is still referenced from t", "end": 9085, "score": 0.9758927226066589, "start": 9071, "tag": "KEY", "value": "91f47e99-d616-" } ]
test/com/verybigthings/pgerrors/core_test.clj
VeryBigThings/pgerrors
1
(ns com.verybigthings.pgerrors.core-test (:require [clojure.test :refer :all] [com.verybigthings.pgerrors.test-helpers :as th] [next.jdbc :as jdbc] [com.verybigthings.pgerrors.core :refer [extract-data]]) (:import (org.postgresql.util PSQLException))) ;; Inspired by https://github.com/Shyp/go-dberror/blob/master/error_test.go (use-fixtures :once th/reset-db-fixture) (def uuid-1 (java.util.UUID/fromString "3c7d2b4a-3fc8-4782-a518-4ce9efef51e7")) (def uuid-2 (java.util.UUID/fromString "91f47e99-d616-4d8c-9c02-cbd13bceac60")) (def email-1 "test@example.com") (def email-2 "test2@example.com") (deftest not-null-violation (testing "one column" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id) VALUES(?)" nil]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Null value in column \"id\" violates not-null constraint" :postgresql.error/detail "Failing row contains (null, null, null, active, null)." :postgresql/sql-state "23502" :postgresql/error :not-null-violation, :postgresql/columns ["id"]} (extract-data e))))))) (testing "two columns" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO two_not_null (str_1, str_2) VALUES(?, ?)" nil nil]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Null value in column \"str_1\" violates not-null constraint" :postgresql.error/detail "Failing row contains (null, null)." :postgresql/sql-state "23502" :postgresql/error :not-null-violation, :postgresql/columns ["str_1"]} (extract-data e)))))))) (deftest default-constraint (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, -1)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "New row for relation \"accounts\" violates check constraint \"accounts_balance_check\"" :postgresql.error/detail "Failing row contains (3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, test@example.com, -1, active, null)." :postgresql/sql-state "23514" :postgresql/error :check-violation :postgresql/constraint "accounts_balance_check" :postgresql/relation "accounts"} (extract-data e))))))) (deftest invalid-uuid (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id) VALUES('foo')"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input syntax for type uuid: \"foo\"" :postgresql/sql-state "22P02" :postgresql/type "uuid" :postgresql/value "foo" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest invalid-json (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (data) VALUES('')"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input syntax for type json" :postgresql.error/detail "The input string ended unexpectedly." :postgresql/sql-state "22P02" :postgresql/type "json" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest invalid-enum (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance, status) VALUES(?, ?, 1, 'blah')" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input value for enum account_status: \"blah\"" :postgresql/sql-state "22P02" :postgresql/type "enum" :postgresql.type/enum "account_status" :postgresql/value "blah" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest too-large-int (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 40000)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Smallint out of range" :postgresql/sql-state "22003" :postgresql/error :numeric-value-out-of-range} (extract-data e))))))) (deftest unique-constraint (testing "one column" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"accounts_pkey\"" :postgresql.error/detail "Key (id)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7) already exists." :postgresql/sql-state "23505" :postgresql/columns ["id"] :postgresql/constraint "accounts_pkey" :postgresql/error :unique-violation} (extract-data e))))))) (testing "two columns" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO two_col_uniqueness (str_1, str_2) VALUES(?, ?)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO two_col_uniqueness (str_1, str_2) VALUES(?, ?)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"two_col_uniqueness_str_1_str_2\"" :postgresql.error/detail "Key (str_1, str_2)=(3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, test@example.com) already exists." :postgresql/sql-state "23505" :postgresql/columns ["str_1" "str_2"] :postgresql/constraint "two_col_uniqueness_str_1_str_2" :postgresql/error :unique-violation} (extract-data e)))))))) (deftest unique-failure-on-update (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-2 email-2]) (jdbc/execute! t ["UPDATE accounts SET email = ? WHERE id = ?" email-1 uuid-2]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"accounts_email_key\"" :postgresql.error/detail "Key (email)=(test@example.com) already exists." :postgresql/sql-state "23505" :postgresql/columns ["email"] :postgresql/constraint "accounts_email_key" :postgresql/error :unique-violation} (extract-data e))))))) (deftest foreign-key-failure (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO payments (id, account_id) VALUES(?, ?)" uuid-1 uuid-2]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Insert or update on table \"payments\" violates foreign key constraint \"payments_account_id_fkey\"" :postgresql.error/detail "Key (account_id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is not present in table \"accounts\"." :postgresql/sql-state "23503" :postgresql/columns ["account_id"] :postgresql/constraint "payments_account_id_fkey" :postgresql/error :foreign-key-violation :postgresql/relation "payments" :postgresql.relation/foreign "accounts" } (extract-data e))))))) (deftest foreign-key-parent-delete (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-2 email-2]) (jdbc/execute! t ["INSERT INTO payments (id, account_id) VALUES(?, ?)" uuid-1 uuid-2]) (jdbc/execute! t ["DELETE FROM accounts"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Update or delete on table \"accounts\" violates foreign key constraint \"payments_account_id_fkey\" on table \"payments\"" :postgresql.error/detail "Key (id)=(91f47e99-d616-4d8c-9c02-cbd13bceac60) is still referenced from table \"payments\"." :postgresql/sql-state "23503" :postgresql/columns ["id"] :postgresql/constraint "payments_account_id_fkey" :postgresql/error :foreign-key-violation :postgresql/relation "accounts" :postgresql.relation/foreign "payments"} (extract-data e)))))))
8459
(ns com.verybigthings.pgerrors.core-test (:require [clojure.test :refer :all] [com.verybigthings.pgerrors.test-helpers :as th] [next.jdbc :as jdbc] [com.verybigthings.pgerrors.core :refer [extract-data]]) (:import (org.postgresql.util PSQLException))) ;; Inspired by https://github.com/Shyp/go-dberror/blob/master/error_test.go (use-fixtures :once th/reset-db-fixture) (def uuid-1 (java.util.UUID/fromString "3c7d2b4a-3fc8-4782-a518-4ce9efef51e7")) (def uuid-2 (java.util.UUID/fromString "91f47e99-d616-4d8c-9c02-cbd13bceac60")) (def email-1 "<EMAIL>") (def email-2 "<EMAIL>") (deftest not-null-violation (testing "one column" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id) VALUES(?)" nil]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Null value in column \"id\" violates not-null constraint" :postgresql.error/detail "Failing row contains (null, null, null, active, null)." :postgresql/sql-state "23502" :postgresql/error :not-null-violation, :postgresql/columns ["id"]} (extract-data e))))))) (testing "two columns" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO two_not_null (str_1, str_2) VALUES(?, ?)" nil nil]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Null value in column \"str_1\" violates not-null constraint" :postgresql.error/detail "Failing row contains (null, null)." :postgresql/sql-state "23502" :postgresql/error :not-null-violation, :postgresql/columns ["str_1"]} (extract-data e)))))))) (deftest default-constraint (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, -1)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "New row for relation \"accounts\" violates check constraint \"accounts_balance_check\"" :postgresql.error/detail "Failing row contains (3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, <EMAIL>, -1, active, null)." :postgresql/sql-state "23514" :postgresql/error :check-violation :postgresql/constraint "accounts_balance_check" :postgresql/relation "accounts"} (extract-data e))))))) (deftest invalid-uuid (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id) VALUES('foo')"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input syntax for type uuid: \"foo\"" :postgresql/sql-state "22P02" :postgresql/type "uuid" :postgresql/value "foo" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest invalid-json (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (data) VALUES('')"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input syntax for type json" :postgresql.error/detail "The input string ended unexpectedly." :postgresql/sql-state "22P02" :postgresql/type "json" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest invalid-enum (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance, status) VALUES(?, ?, 1, 'blah')" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input value for enum account_status: \"blah\"" :postgresql/sql-state "22P02" :postgresql/type "enum" :postgresql.type/enum "account_status" :postgresql/value "blah" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest too-large-int (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 40000)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Smallint out of range" :postgresql/sql-state "22003" :postgresql/error :numeric-value-out-of-range} (extract-data e))))))) (deftest unique-constraint (testing "one column" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"accounts_pkey\"" :postgresql.error/detail "Key (id)=(<KEY>) already exists." :postgresql/sql-state "23505" :postgresql/columns ["id"] :postgresql/constraint "accounts_pkey" :postgresql/error :unique-violation} (extract-data e))))))) (testing "two columns" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO two_col_uniqueness (str_1, str_2) VALUES(?, ?)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO two_col_uniqueness (str_1, str_2) VALUES(?, ?)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"two_col_uniqueness_str_1_str_2\"" :postgresql.error/detail "Key (str_1, str_2)=(<KEY>, <EMAIL>) already exists." :postgresql/sql-state "23505" :postgresql/columns ["str_1" "str_2"] :postgresql/constraint "two_col_uniqueness_str_1_str_2" :postgresql/error :unique-violation} (extract-data e)))))))) (deftest unique-failure-on-update (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-2 email-2]) (jdbc/execute! t ["UPDATE accounts SET email = ? WHERE id = ?" email-1 uuid-2]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"accounts_email_key\"" :postgresql.error/detail "Key (email)=(<EMAIL>) already exists." :postgresql/sql-state "23505" :postgresql/columns ["email"] :postgresql/constraint "accounts_email_key" :postgresql/error :unique-violation} (extract-data e))))))) (deftest foreign-key-failure (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO payments (id, account_id) VALUES(?, ?)" uuid-1 uuid-2]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Insert or update on table \"payments\" violates foreign key constraint \"payments_account_id_fkey\"" :postgresql.error/detail "Key (account_<KEY>=(<KEY> is not present in table \"accounts\"." :postgresql/sql-state "23503" :postgresql/columns ["account_id"] :postgresql/constraint "payments_account_id_fkey" :postgresql/error :foreign-key-violation :postgresql/relation "payments" :postgresql.relation/foreign "accounts" } (extract-data e))))))) (deftest foreign-key-parent-delete (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-2 email-2]) (jdbc/execute! t ["INSERT INTO payments (id, account_id) VALUES(?, ?)" uuid-1 uuid-2]) (jdbc/execute! t ["DELETE FROM accounts"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Update or delete on table \"accounts\" violates foreign key constraint \"payments_account_id_fkey\" on table \"payments\"" :postgresql.error/detail "Key (id)<KEY>=(<KEY>4d8c-9c02-cbd13bceac60) is still referenced from table \"payments\"." :postgresql/sql-state "23503" :postgresql/columns ["id"] :postgresql/constraint "payments_account_id_fkey" :postgresql/error :foreign-key-violation :postgresql/relation "accounts" :postgresql.relation/foreign "payments"} (extract-data e)))))))
true
(ns com.verybigthings.pgerrors.core-test (:require [clojure.test :refer :all] [com.verybigthings.pgerrors.test-helpers :as th] [next.jdbc :as jdbc] [com.verybigthings.pgerrors.core :refer [extract-data]]) (:import (org.postgresql.util PSQLException))) ;; Inspired by https://github.com/Shyp/go-dberror/blob/master/error_test.go (use-fixtures :once th/reset-db-fixture) (def uuid-1 (java.util.UUID/fromString "3c7d2b4a-3fc8-4782-a518-4ce9efef51e7")) (def uuid-2 (java.util.UUID/fromString "91f47e99-d616-4d8c-9c02-cbd13bceac60")) (def email-1 "PI:EMAIL:<EMAIL>END_PI") (def email-2 "PI:EMAIL:<EMAIL>END_PI") (deftest not-null-violation (testing "one column" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id) VALUES(?)" nil]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Null value in column \"id\" violates not-null constraint" :postgresql.error/detail "Failing row contains (null, null, null, active, null)." :postgresql/sql-state "23502" :postgresql/error :not-null-violation, :postgresql/columns ["id"]} (extract-data e))))))) (testing "two columns" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO two_not_null (str_1, str_2) VALUES(?, ?)" nil nil]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Null value in column \"str_1\" violates not-null constraint" :postgresql.error/detail "Failing row contains (null, null)." :postgresql/sql-state "23502" :postgresql/error :not-null-violation, :postgresql/columns ["str_1"]} (extract-data e)))))))) (deftest default-constraint (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, -1)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "New row for relation \"accounts\" violates check constraint \"accounts_balance_check\"" :postgresql.error/detail "Failing row contains (3c7d2b4a-3fc8-4782-a518-4ce9efef51e7, PI:EMAIL:<EMAIL>END_PI, -1, active, null)." :postgresql/sql-state "23514" :postgresql/error :check-violation :postgresql/constraint "accounts_balance_check" :postgresql/relation "accounts"} (extract-data e))))))) (deftest invalid-uuid (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id) VALUES('foo')"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input syntax for type uuid: \"foo\"" :postgresql/sql-state "22P02" :postgresql/type "uuid" :postgresql/value "foo" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest invalid-json (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (data) VALUES('')"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input syntax for type json" :postgresql.error/detail "The input string ended unexpectedly." :postgresql/sql-state "22P02" :postgresql/type "json" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest invalid-enum (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance, status) VALUES(?, ?, 1, 'blah')" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Invalid input value for enum account_status: \"blah\"" :postgresql/sql-state "22P02" :postgresql/type "enum" :postgresql.type/enum "account_status" :postgresql/value "blah" :postgresql/error :invalid-text-representation} (extract-data e))))))) (deftest too-large-int (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 40000)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Smallint out of range" :postgresql/sql-state "22003" :postgresql/error :numeric-value-out-of-range} (extract-data e))))))) (deftest unique-constraint (testing "one column" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"accounts_pkey\"" :postgresql.error/detail "Key (id)=(PI:KEY:<KEY>END_PI) already exists." :postgresql/sql-state "23505" :postgresql/columns ["id"] :postgresql/constraint "accounts_pkey" :postgresql/error :unique-violation} (extract-data e))))))) (testing "two columns" (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO two_col_uniqueness (str_1, str_2) VALUES(?, ?)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO two_col_uniqueness (str_1, str_2) VALUES(?, ?)" uuid-1 email-1]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"two_col_uniqueness_str_1_str_2\"" :postgresql.error/detail "Key (str_1, str_2)=(PI:KEY:<KEY>END_PI, PI:EMAIL:<EMAIL>END_PI) already exists." :postgresql/sql-state "23505" :postgresql/columns ["str_1" "str_2"] :postgresql/constraint "two_col_uniqueness_str_1_str_2" :postgresql/error :unique-violation} (extract-data e)))))))) (deftest unique-failure-on-update (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-2 email-2]) (jdbc/execute! t ["UPDATE accounts SET email = ? WHERE id = ?" email-1 uuid-2]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Duplicate key value violates unique constraint \"accounts_email_key\"" :postgresql.error/detail "Key (email)=(PI:EMAIL:<EMAIL>END_PI) already exists." :postgresql/sql-state "23505" :postgresql/columns ["email"] :postgresql/constraint "accounts_email_key" :postgresql/error :unique-violation} (extract-data e))))))) (deftest foreign-key-failure (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO payments (id, account_id) VALUES(?, ?)" uuid-1 uuid-2]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Insert or update on table \"payments\" violates foreign key constraint \"payments_account_id_fkey\"" :postgresql.error/detail "Key (account_PI:KEY:<KEY>END_PI=(PI:KEY:<KEY>END_PI is not present in table \"accounts\"." :postgresql/sql-state "23503" :postgresql/columns ["account_id"] :postgresql/constraint "payments_account_id_fkey" :postgresql/error :foreign-key-violation :postgresql/relation "payments" :postgresql.relation/foreign "accounts" } (extract-data e))))))) (deftest foreign-key-parent-delete (jdbc/with-transaction [t th/db-uri {:rollback-only true}] (try (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-1 email-1]) (jdbc/execute! t ["INSERT INTO accounts (id, email, balance) VALUES(?, ?, 1)" uuid-2 email-2]) (jdbc/execute! t ["INSERT INTO payments (id, account_id) VALUES(?, ?)" uuid-1 uuid-2]) (jdbc/execute! t ["DELETE FROM accounts"]) (is false) (catch PSQLException e (is (= {:postgresql.error/message "Update or delete on table \"accounts\" violates foreign key constraint \"payments_account_id_fkey\" on table \"payments\"" :postgresql.error/detail "Key (id)PI:KEY:<KEY>END_PI=(PI:KEY:<KEY>END_PI4d8c-9c02-cbd13bceac60) is still referenced from table \"payments\"." :postgresql/sql-state "23503" :postgresql/columns ["id"] :postgresql/constraint "payments_account_id_fkey" :postgresql/error :foreign-key-violation :postgresql/relation "accounts" :postgresql.relation/foreign "payments"} (extract-data e)))))))
[ { "context": ".github.protojure/core\"\n :url \"http://github.com/protojure/lib\"\n :license {:name \"Apache License 2.0\"\n ", "end": 151, "score": 0.9990233778953552, "start": 142, "tag": "USERNAME", "value": "protojure" }, { "context": "0\"\n :year 2022\n :key \"apache-2.0\"}\n :plugins [[lein-cljfmt \"0.8.0\"]\n ", "end": 309, "score": 0.5437384843826294, "start": 307, "tag": "KEY", "value": "2." } ]
modules/io/project.clj
gitslim/lib
0
(defproject io.github.protojure/io "2.0.7-SNAPSHOT" :description "IO library to support io.github.protojure/core" :url "http://github.com/protojure/lib" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2022 :key "apache-2.0"} :plugins [[lein-cljfmt "0.8.0"] [lein-kibit "0.1.8"] [lein-bikeshed "0.5.2"] [lein-set-version "0.4.1"] [lein-parent "0.3.8"]] :parent-project {:path "../../project.clj" :inherit [:managed-dependencies :javac-options]} :dependencies [[org.clojure/clojure] [org.clojure/core.async]] :java-source-paths ["src"])
41221
(defproject io.github.protojure/io "2.0.7-SNAPSHOT" :description "IO library to support io.github.protojure/core" :url "http://github.com/protojure/lib" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2022 :key "apache-<KEY>0"} :plugins [[lein-cljfmt "0.8.0"] [lein-kibit "0.1.8"] [lein-bikeshed "0.5.2"] [lein-set-version "0.4.1"] [lein-parent "0.3.8"]] :parent-project {:path "../../project.clj" :inherit [:managed-dependencies :javac-options]} :dependencies [[org.clojure/clojure] [org.clojure/core.async]] :java-source-paths ["src"])
true
(defproject io.github.protojure/io "2.0.7-SNAPSHOT" :description "IO library to support io.github.protojure/core" :url "http://github.com/protojure/lib" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2022 :key "apache-PI:KEY:<KEY>END_PI0"} :plugins [[lein-cljfmt "0.8.0"] [lein-kibit "0.1.8"] [lein-bikeshed "0.5.2"] [lein-set-version "0.4.1"] [lein-parent "0.3.8"]] :parent-project {:path "../../project.clj" :inherit [:managed-dependencies :javac-options]} :dependencies [[org.clojure/clojure] [org.clojure/core.async]] :java-source-paths ["src"])
[ { "context": "il (encrypt-email email)\n hashed-password (hash-password password)\n uid (uuid)\n existing-use", "end": 1537, "score": 0.7119931578636169, "start": 1524, "tag": "PASSWORD", "value": "hash-password" }, { "context": " (insert-user db {:email encrypted-email :password hashed-password :uid uid})\n {:uid uid}))))\n\n(defn validate", "end": 1746, "score": 0.9825021624565125, "start": 1731, "tag": "PASSWORD", "value": "hashed-password" } ]
src/authtest/auth.clj
dspearson/authtest
0
(ns authtest.auth (:require [caesium.magicnonce.secretbox :as msb] [caesium.crypto.box :as box] [caesium.byte-bufs :as bb] [caesium.crypto.pwhash :as pwhash] [buddy.core.codecs :as codecs] [clojure.java.io :as io] [authtest.db :refer :all]) (:gen-class)) (def keyfile (io/file (or (System/getenv "AUTHTEST_KEY") (str (System/getProperty "user.home") "/.authtest.key")))) (defn uuid [] (.toString (java.util.UUID/randomUUID))) (defn generate-admin-key [] (if (.exists keyfile) false (let [keypair (box/keypair!) public (codecs/bytes->hex (bb/->bytes (:public keypair))) secret (codecs/bytes->hex (bb/->bytes (:secret keypair)))] (spit keyfile public) {:public public :secret secret}))) (defn delete-admin-key [] (if (.exists keyfile) (io/delete-file keyfile))) (defn get-admin-public-key [] (if-not (.exists keyfile) (throw (RuntimeException. "Key does not exist.")) (codecs/hex->bytes (slurp keyfile)))) (defn encrypt-email [email] (let [email-bytes (.getBytes email "UTF-8") public-key (get-admin-public-key) encrypted-email (msb/secretbox-det email-bytes public-key)] encrypted-email)) (defn hash-password [password] (pwhash/pwhash-str password pwhash/opslimit-sensitive pwhash/memlimit-sensitive)) (defn generate-user [email password] (let [encrypted-email (encrypt-email email) hashed-password (hash-password password) uid (uuid) existing-user (get-user db {:email encrypted-email})] (if existing-user false (do (insert-user db {:email encrypted-email :password hashed-password :uid uid}) {:uid uid})))) (defn validate-user ; not constant-time [email password] (let [encrypted-email (encrypt-email email) existing-user (get-user db {:email encrypted-email})] (if-not existing-user false (and (= 0 (pwhash/pwhash-str-verify (:password existing-user) password)) {:uid (:uid existing-user)})))) (defn change-password [uid old-password new-password] (let [existing-user (get-user-by-uid db {:uid uid})] (if-not existing-user false (if (= 0 (pwhash/pwhash-str-verify (:password existing-user) old-password)) (let [hashed-password (hash-password new-password)] (and (update-password db {:uid uid :password hashed-password})) true) false))))
100606
(ns authtest.auth (:require [caesium.magicnonce.secretbox :as msb] [caesium.crypto.box :as box] [caesium.byte-bufs :as bb] [caesium.crypto.pwhash :as pwhash] [buddy.core.codecs :as codecs] [clojure.java.io :as io] [authtest.db :refer :all]) (:gen-class)) (def keyfile (io/file (or (System/getenv "AUTHTEST_KEY") (str (System/getProperty "user.home") "/.authtest.key")))) (defn uuid [] (.toString (java.util.UUID/randomUUID))) (defn generate-admin-key [] (if (.exists keyfile) false (let [keypair (box/keypair!) public (codecs/bytes->hex (bb/->bytes (:public keypair))) secret (codecs/bytes->hex (bb/->bytes (:secret keypair)))] (spit keyfile public) {:public public :secret secret}))) (defn delete-admin-key [] (if (.exists keyfile) (io/delete-file keyfile))) (defn get-admin-public-key [] (if-not (.exists keyfile) (throw (RuntimeException. "Key does not exist.")) (codecs/hex->bytes (slurp keyfile)))) (defn encrypt-email [email] (let [email-bytes (.getBytes email "UTF-8") public-key (get-admin-public-key) encrypted-email (msb/secretbox-det email-bytes public-key)] encrypted-email)) (defn hash-password [password] (pwhash/pwhash-str password pwhash/opslimit-sensitive pwhash/memlimit-sensitive)) (defn generate-user [email password] (let [encrypted-email (encrypt-email email) hashed-password (<PASSWORD> password) uid (uuid) existing-user (get-user db {:email encrypted-email})] (if existing-user false (do (insert-user db {:email encrypted-email :password <PASSWORD> :uid uid}) {:uid uid})))) (defn validate-user ; not constant-time [email password] (let [encrypted-email (encrypt-email email) existing-user (get-user db {:email encrypted-email})] (if-not existing-user false (and (= 0 (pwhash/pwhash-str-verify (:password existing-user) password)) {:uid (:uid existing-user)})))) (defn change-password [uid old-password new-password] (let [existing-user (get-user-by-uid db {:uid uid})] (if-not existing-user false (if (= 0 (pwhash/pwhash-str-verify (:password existing-user) old-password)) (let [hashed-password (hash-password new-password)] (and (update-password db {:uid uid :password hashed-password})) true) false))))
true
(ns authtest.auth (:require [caesium.magicnonce.secretbox :as msb] [caesium.crypto.box :as box] [caesium.byte-bufs :as bb] [caesium.crypto.pwhash :as pwhash] [buddy.core.codecs :as codecs] [clojure.java.io :as io] [authtest.db :refer :all]) (:gen-class)) (def keyfile (io/file (or (System/getenv "AUTHTEST_KEY") (str (System/getProperty "user.home") "/.authtest.key")))) (defn uuid [] (.toString (java.util.UUID/randomUUID))) (defn generate-admin-key [] (if (.exists keyfile) false (let [keypair (box/keypair!) public (codecs/bytes->hex (bb/->bytes (:public keypair))) secret (codecs/bytes->hex (bb/->bytes (:secret keypair)))] (spit keyfile public) {:public public :secret secret}))) (defn delete-admin-key [] (if (.exists keyfile) (io/delete-file keyfile))) (defn get-admin-public-key [] (if-not (.exists keyfile) (throw (RuntimeException. "Key does not exist.")) (codecs/hex->bytes (slurp keyfile)))) (defn encrypt-email [email] (let [email-bytes (.getBytes email "UTF-8") public-key (get-admin-public-key) encrypted-email (msb/secretbox-det email-bytes public-key)] encrypted-email)) (defn hash-password [password] (pwhash/pwhash-str password pwhash/opslimit-sensitive pwhash/memlimit-sensitive)) (defn generate-user [email password] (let [encrypted-email (encrypt-email email) hashed-password (PI:PASSWORD:<PASSWORD>END_PI password) uid (uuid) existing-user (get-user db {:email encrypted-email})] (if existing-user false (do (insert-user db {:email encrypted-email :password PI:PASSWORD:<PASSWORD>END_PI :uid uid}) {:uid uid})))) (defn validate-user ; not constant-time [email password] (let [encrypted-email (encrypt-email email) existing-user (get-user db {:email encrypted-email})] (if-not existing-user false (and (= 0 (pwhash/pwhash-str-verify (:password existing-user) password)) {:uid (:uid existing-user)})))) (defn change-password [uid old-password new-password] (let [existing-user (get-user-by-uid db {:uid uid})] (if-not existing-user false (if (= 0 (pwhash/pwhash-str-verify (:password existing-user) old-password)) (let [hashed-password (hash-password new-password)] (and (update-password db {:uid uid :password hashed-password})) true) false))))
[ { "context": " key to use here?\n (hidden-field {:key 0xdeadbeef} \"_method\" method-str)])\n (concat body)\n ", "end": 5626, "score": 0.9074881672859192, "start": 5617, "tag": "KEY", "value": "xdeadbeef" } ]
resources/public/main.out/sablono/core.cljs
drewverlee/garlic
0
(ns sablono.core (:require-macros [sablono.core :refer [defelem gen-input-fields]]) (:require [clojure.string :refer [upper-case]] [goog.string :as gstring] [sablono.normalize :as normalize] [sablono.util :refer [as-str to-uri]] [sablono.interpreter :as interpreter] [goog.dom :as dom])) (defn wrap-attrs "Add an optional attribute argument to a function that returns a element vector." [func] (fn [& args] (if (map? (first args)) (let [[tag & body] (apply func (rest args))] (if (map? (first body)) (into [tag (merge (first body) (first args))] (rest body)) (into [tag (first args)] body))) (apply func args)))) (defn- update-arglists [arglists] (for [args arglists] (vec (cons 'attr-map? args)))) (defn include-css "Include a list of external stylesheet files." [& styles] (for [style styles] [:link {:type "text/css", :href (as-str style), :rel "stylesheet"}])) (defn include-js "Include the JavaScript library at `src`." [src] (dom/appendChild (.-body (dom/getDocument)) (dom/createDom "script" #js {:src src}))) (defn include-react "Include Facebook's React JavaScript library." [] (include-js "http://fb.me/react-0.12.2.js")) (defelem link-to "Wraps some content in a HTML hyperlink with the supplied URL." [url & content] [:a {:href (as-str url)} content]) (defelem mail-to "Wraps some content in a HTML hyperlink with the supplied e-mail address. If no content provided use the e-mail address as content." [e-mail & [content]] [:a {:href (str "mailto:" e-mail)} (or content e-mail)]) (defelem unordered-list "Wrap a collection in an unordered list." [coll] [:ul (for [x coll] [:li x])]) (defelem ordered-list "Wrap a collection in an ordered list." [coll] [:ol (for [x coll] [:li x])]) (defelem image "Create an image element." ([src] [:img {:src (as-str src)}]) ([src alt] [:img {:src (as-str src), :alt alt}])) (def ^:dynamic *group* []) (defn- make-name "Create a field name from the supplied argument the current field group." [name] (reduce #(str %1 "[" %2 "]") (conj *group* (as-str name)))) (defn- make-id "Create a field id from the supplied argument and current field group." [name] (reduce #(str %1 "-" %2) (conj *group* (as-str name)))) (defn- input-field* "Creates a new <input> element." ([type name] [:input {:type type :name (make-name name) :id (make-id name)}]) ([type name value] [:input {:type type :name (make-name name) :id (make-id name) :value (or value js/undefined)}])) (gen-input-fields) (def file-upload file-field) (defelem check-box "Creates a check box." ([name] [:input {:type "checkbox" :name (make-name name) :id (make-id name)}]) ([name checked?] [:input {:type "checkbox" :name (make-name name) :id (make-id name) :checked checked?}]) ([name checked? value] [:input {:type "checkbox" :name (make-name name) :id (make-id name) :value value :checked checked?}])) (defelem radio-button "Creates a radio button." ([group] [:input {:type "radio" :name (make-name group) :id (make-id (as-str group))}]) ([group checked?] [:input {:type "radio" :name (make-name group) :id (make-id (as-str group)) :checked checked?}]) ([group checked? value] [:input {:type "radio" :name (make-name group) :id (make-id (str (as-str group) "-" (as-str value))) :value value :checked checked?}])) (defn- hash-key [x] (gstring/hashCode (pr-str x))) (defelem select-options "Creates a seq of option tags from a collection." [coll] (for [x coll] (if (sequential? x) (let [[text val disabled?] x disabled? (boolean disabled?)] (if (sequential? val) [:optgroup {:key (hash-key text) :label text} (select-options val)] [:option {:disabled disabled? :key (hash-key val) :value val} text])) [:option {:key (hash-key x) :value x} x]))) (defelem drop-down "Creates a drop-down box using the <select> tag." ([name options] (drop-down name options nil)) ([name options selected] [:select {:name (make-name name) :id (make-id name)} (select-options options selected)])) (defelem text-area "Creates a text area element." ([name] [:textarea {:name (make-name name) :id (make-id name)}]) ([name value] [:textarea {:name (make-name name) :id (make-id name) :value (or value js/undefined)}])) (defelem label "Creates a label for an input field with the supplied name." [name text] [:label {:htmlFor (make-id name)} text]) (defelem submit-button "Creates a submit button." [text] [:input {:type "submit" :value text}]) (defelem reset-button "Creates a form reset button." [text] [:input {:type "reset" :value text}]) (defelem form-to "Create a form that points to a particular method and route. e.g. (form-to [:put \"/post\"] ...)" [[method action] & body] (let [method-str (upper-case (name method)) action-uri (to-uri action)] (-> (if (contains? #{:get :post} method) [:form {:method method-str, :action action-uri}] [:form {:method "POST", :action action-uri} ;; TODO: What key to use here? (hidden-field {:key 0xdeadbeef} "_method" method-str)]) (concat body) (vec))))
116360
(ns sablono.core (:require-macros [sablono.core :refer [defelem gen-input-fields]]) (:require [clojure.string :refer [upper-case]] [goog.string :as gstring] [sablono.normalize :as normalize] [sablono.util :refer [as-str to-uri]] [sablono.interpreter :as interpreter] [goog.dom :as dom])) (defn wrap-attrs "Add an optional attribute argument to a function that returns a element vector." [func] (fn [& args] (if (map? (first args)) (let [[tag & body] (apply func (rest args))] (if (map? (first body)) (into [tag (merge (first body) (first args))] (rest body)) (into [tag (first args)] body))) (apply func args)))) (defn- update-arglists [arglists] (for [args arglists] (vec (cons 'attr-map? args)))) (defn include-css "Include a list of external stylesheet files." [& styles] (for [style styles] [:link {:type "text/css", :href (as-str style), :rel "stylesheet"}])) (defn include-js "Include the JavaScript library at `src`." [src] (dom/appendChild (.-body (dom/getDocument)) (dom/createDom "script" #js {:src src}))) (defn include-react "Include Facebook's React JavaScript library." [] (include-js "http://fb.me/react-0.12.2.js")) (defelem link-to "Wraps some content in a HTML hyperlink with the supplied URL." [url & content] [:a {:href (as-str url)} content]) (defelem mail-to "Wraps some content in a HTML hyperlink with the supplied e-mail address. If no content provided use the e-mail address as content." [e-mail & [content]] [:a {:href (str "mailto:" e-mail)} (or content e-mail)]) (defelem unordered-list "Wrap a collection in an unordered list." [coll] [:ul (for [x coll] [:li x])]) (defelem ordered-list "Wrap a collection in an ordered list." [coll] [:ol (for [x coll] [:li x])]) (defelem image "Create an image element." ([src] [:img {:src (as-str src)}]) ([src alt] [:img {:src (as-str src), :alt alt}])) (def ^:dynamic *group* []) (defn- make-name "Create a field name from the supplied argument the current field group." [name] (reduce #(str %1 "[" %2 "]") (conj *group* (as-str name)))) (defn- make-id "Create a field id from the supplied argument and current field group." [name] (reduce #(str %1 "-" %2) (conj *group* (as-str name)))) (defn- input-field* "Creates a new <input> element." ([type name] [:input {:type type :name (make-name name) :id (make-id name)}]) ([type name value] [:input {:type type :name (make-name name) :id (make-id name) :value (or value js/undefined)}])) (gen-input-fields) (def file-upload file-field) (defelem check-box "Creates a check box." ([name] [:input {:type "checkbox" :name (make-name name) :id (make-id name)}]) ([name checked?] [:input {:type "checkbox" :name (make-name name) :id (make-id name) :checked checked?}]) ([name checked? value] [:input {:type "checkbox" :name (make-name name) :id (make-id name) :value value :checked checked?}])) (defelem radio-button "Creates a radio button." ([group] [:input {:type "radio" :name (make-name group) :id (make-id (as-str group))}]) ([group checked?] [:input {:type "radio" :name (make-name group) :id (make-id (as-str group)) :checked checked?}]) ([group checked? value] [:input {:type "radio" :name (make-name group) :id (make-id (str (as-str group) "-" (as-str value))) :value value :checked checked?}])) (defn- hash-key [x] (gstring/hashCode (pr-str x))) (defelem select-options "Creates a seq of option tags from a collection." [coll] (for [x coll] (if (sequential? x) (let [[text val disabled?] x disabled? (boolean disabled?)] (if (sequential? val) [:optgroup {:key (hash-key text) :label text} (select-options val)] [:option {:disabled disabled? :key (hash-key val) :value val} text])) [:option {:key (hash-key x) :value x} x]))) (defelem drop-down "Creates a drop-down box using the <select> tag." ([name options] (drop-down name options nil)) ([name options selected] [:select {:name (make-name name) :id (make-id name)} (select-options options selected)])) (defelem text-area "Creates a text area element." ([name] [:textarea {:name (make-name name) :id (make-id name)}]) ([name value] [:textarea {:name (make-name name) :id (make-id name) :value (or value js/undefined)}])) (defelem label "Creates a label for an input field with the supplied name." [name text] [:label {:htmlFor (make-id name)} text]) (defelem submit-button "Creates a submit button." [text] [:input {:type "submit" :value text}]) (defelem reset-button "Creates a form reset button." [text] [:input {:type "reset" :value text}]) (defelem form-to "Create a form that points to a particular method and route. e.g. (form-to [:put \"/post\"] ...)" [[method action] & body] (let [method-str (upper-case (name method)) action-uri (to-uri action)] (-> (if (contains? #{:get :post} method) [:form {:method method-str, :action action-uri}] [:form {:method "POST", :action action-uri} ;; TODO: What key to use here? (hidden-field {:key 0<KEY>} "_method" method-str)]) (concat body) (vec))))
true
(ns sablono.core (:require-macros [sablono.core :refer [defelem gen-input-fields]]) (:require [clojure.string :refer [upper-case]] [goog.string :as gstring] [sablono.normalize :as normalize] [sablono.util :refer [as-str to-uri]] [sablono.interpreter :as interpreter] [goog.dom :as dom])) (defn wrap-attrs "Add an optional attribute argument to a function that returns a element vector." [func] (fn [& args] (if (map? (first args)) (let [[tag & body] (apply func (rest args))] (if (map? (first body)) (into [tag (merge (first body) (first args))] (rest body)) (into [tag (first args)] body))) (apply func args)))) (defn- update-arglists [arglists] (for [args arglists] (vec (cons 'attr-map? args)))) (defn include-css "Include a list of external stylesheet files." [& styles] (for [style styles] [:link {:type "text/css", :href (as-str style), :rel "stylesheet"}])) (defn include-js "Include the JavaScript library at `src`." [src] (dom/appendChild (.-body (dom/getDocument)) (dom/createDom "script" #js {:src src}))) (defn include-react "Include Facebook's React JavaScript library." [] (include-js "http://fb.me/react-0.12.2.js")) (defelem link-to "Wraps some content in a HTML hyperlink with the supplied URL." [url & content] [:a {:href (as-str url)} content]) (defelem mail-to "Wraps some content in a HTML hyperlink with the supplied e-mail address. If no content provided use the e-mail address as content." [e-mail & [content]] [:a {:href (str "mailto:" e-mail)} (or content e-mail)]) (defelem unordered-list "Wrap a collection in an unordered list." [coll] [:ul (for [x coll] [:li x])]) (defelem ordered-list "Wrap a collection in an ordered list." [coll] [:ol (for [x coll] [:li x])]) (defelem image "Create an image element." ([src] [:img {:src (as-str src)}]) ([src alt] [:img {:src (as-str src), :alt alt}])) (def ^:dynamic *group* []) (defn- make-name "Create a field name from the supplied argument the current field group." [name] (reduce #(str %1 "[" %2 "]") (conj *group* (as-str name)))) (defn- make-id "Create a field id from the supplied argument and current field group." [name] (reduce #(str %1 "-" %2) (conj *group* (as-str name)))) (defn- input-field* "Creates a new <input> element." ([type name] [:input {:type type :name (make-name name) :id (make-id name)}]) ([type name value] [:input {:type type :name (make-name name) :id (make-id name) :value (or value js/undefined)}])) (gen-input-fields) (def file-upload file-field) (defelem check-box "Creates a check box." ([name] [:input {:type "checkbox" :name (make-name name) :id (make-id name)}]) ([name checked?] [:input {:type "checkbox" :name (make-name name) :id (make-id name) :checked checked?}]) ([name checked? value] [:input {:type "checkbox" :name (make-name name) :id (make-id name) :value value :checked checked?}])) (defelem radio-button "Creates a radio button." ([group] [:input {:type "radio" :name (make-name group) :id (make-id (as-str group))}]) ([group checked?] [:input {:type "radio" :name (make-name group) :id (make-id (as-str group)) :checked checked?}]) ([group checked? value] [:input {:type "radio" :name (make-name group) :id (make-id (str (as-str group) "-" (as-str value))) :value value :checked checked?}])) (defn- hash-key [x] (gstring/hashCode (pr-str x))) (defelem select-options "Creates a seq of option tags from a collection." [coll] (for [x coll] (if (sequential? x) (let [[text val disabled?] x disabled? (boolean disabled?)] (if (sequential? val) [:optgroup {:key (hash-key text) :label text} (select-options val)] [:option {:disabled disabled? :key (hash-key val) :value val} text])) [:option {:key (hash-key x) :value x} x]))) (defelem drop-down "Creates a drop-down box using the <select> tag." ([name options] (drop-down name options nil)) ([name options selected] [:select {:name (make-name name) :id (make-id name)} (select-options options selected)])) (defelem text-area "Creates a text area element." ([name] [:textarea {:name (make-name name) :id (make-id name)}]) ([name value] [:textarea {:name (make-name name) :id (make-id name) :value (or value js/undefined)}])) (defelem label "Creates a label for an input field with the supplied name." [name text] [:label {:htmlFor (make-id name)} text]) (defelem submit-button "Creates a submit button." [text] [:input {:type "submit" :value text}]) (defelem reset-button "Creates a form reset button." [text] [:input {:type "reset" :value text}]) (defelem form-to "Create a form that points to a particular method and route. e.g. (form-to [:put \"/post\"] ...)" [[method action] & body] (let [method-str (upper-case (name method)) action-uri (to-uri action)] (-> (if (contains? #{:get :post} method) [:form {:method method-str, :action action-uri}] [:form {:method "POST", :action action-uri} ;; TODO: What key to use here? (hidden-field {:key 0PI:KEY:<KEY>END_PI} "_method" method-str)]) (concat body) (vec))))
[ { "context": "dexing-collections\n (is (match? {1 {:id 1 :name \"Foo\"}, 2 {:id 2 :name \"Bar\"}}\n (coll/ind", "end": 862, "score": 0.6642709970474243, "start": 859, "tag": "NAME", "value": "Foo" }, { "context": "}\n (coll/index-by :id [{:id 1 :name \"Foo\"} {:id 2 :name \"Bar\"}]))))\n", "end": 940, "score": 0.8108406066894531, "start": 937, "tag": "NAME", "value": "Foo" } ]
test/paprika/collection_test.cljc
mauricioszabo/paprika
8
(ns paprika.collection-test (:require [clojure.test :refer [deftest testing is]] [paprika.collection :as coll] [matcher-combinators.test])) (def some-map {:a 10 :b 20}) (deftest functions-for-maps (testing "maps keys and values" (is (match? {"a" "10" "b" "20"} (coll/map-kv #(vector (name %1) (str %2)) some-map)))) (testing "maps keys" (is (match? {"a" 10 "b" 20} (coll/map-keys name some-map)))) (testing "maps values" (is (match? {:a "10" :b "20"} (coll/map-values str some-map))))) (deftest update-if-not-nil (is (match? {} (coll/update-in-when {} [:foo :bar] (constantly nil)))) (is (match? {:foo {:baz 10}} (coll/update-in-when {} [:foo :baz] (constantly 10))))) (deftest indexing-collections (is (match? {1 {:id 1 :name "Foo"}, 2 {:id 2 :name "Bar"}} (coll/index-by :id [{:id 1 :name "Foo"} {:id 2 :name "Bar"}]))))
71178
(ns paprika.collection-test (:require [clojure.test :refer [deftest testing is]] [paprika.collection :as coll] [matcher-combinators.test])) (def some-map {:a 10 :b 20}) (deftest functions-for-maps (testing "maps keys and values" (is (match? {"a" "10" "b" "20"} (coll/map-kv #(vector (name %1) (str %2)) some-map)))) (testing "maps keys" (is (match? {"a" 10 "b" 20} (coll/map-keys name some-map)))) (testing "maps values" (is (match? {:a "10" :b "20"} (coll/map-values str some-map))))) (deftest update-if-not-nil (is (match? {} (coll/update-in-when {} [:foo :bar] (constantly nil)))) (is (match? {:foo {:baz 10}} (coll/update-in-when {} [:foo :baz] (constantly 10))))) (deftest indexing-collections (is (match? {1 {:id 1 :name "<NAME>"}, 2 {:id 2 :name "Bar"}} (coll/index-by :id [{:id 1 :name "<NAME>"} {:id 2 :name "Bar"}]))))
true
(ns paprika.collection-test (:require [clojure.test :refer [deftest testing is]] [paprika.collection :as coll] [matcher-combinators.test])) (def some-map {:a 10 :b 20}) (deftest functions-for-maps (testing "maps keys and values" (is (match? {"a" "10" "b" "20"} (coll/map-kv #(vector (name %1) (str %2)) some-map)))) (testing "maps keys" (is (match? {"a" 10 "b" 20} (coll/map-keys name some-map)))) (testing "maps values" (is (match? {:a "10" :b "20"} (coll/map-values str some-map))))) (deftest update-if-not-nil (is (match? {} (coll/update-in-when {} [:foo :bar] (constantly nil)))) (is (match? {:foo {:baz 10}} (coll/update-in-when {} [:foo :baz] (constantly 10))))) (deftest indexing-collections (is (match? {1 {:id 1 :name "PI:NAME:<NAME>END_PI"}, 2 {:id 2 :name "Bar"}} (coll/index-by :id [{:id 1 :name "PI:NAME:<NAME>END_PI"} {:id 2 :name "Bar"}]))))
[ { "context": " under the License.\n;;\n;; Copyright (c) 2013-2016, Kenneth Leung. All rights reserved.\n\n(ns ^{:doc \"Various boot-c", "end": 599, "score": 0.9998642802238464, "start": 586, "tag": "NAME", "value": "Kenneth Leung" }, { "context": "^{:doc \"Various boot-clj helpers.\"\n :author \"Kenneth Leung\" }\n\n czlab.pariah.boot\n\n (:require [boot.task.b", "end": 690, "score": 0.9998699426651001, "start": 677, "tag": "NAME", "value": "Kenneth Leung" } ]
attic/boot.clj
llnek/jasal
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 (c) 2013-2016, Kenneth Leung. All rights reserved. (ns ^{:doc "Various boot-clj helpers." :author "Kenneth Leung" } czlab.pariah.boot (:require [boot.task.built-in :refer [install pom aot uber target]] [boot.core :as bc] [cemerick.pomegranate :as pom] [flatland.ordered.map :as fom] [flatland.ordered.set :as fos] [clojure.data.json :as js] [clojure.java.io :as io] [clojure.string :as cs] [czlab.pariah.antlib :as a]) (:import [clojure.lang APersistentMap APersistentVector] [java.util Stack] [java.io File] [java.util.regex Pattern])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;pull in flatland stuff to force things compiled (def ^:private dummy-1 (fom/ordered-map)) (def ^:private dummy-2 (fos/ordered-set)) ;;default local vars (defonce ^:private l-vars (atom {})) ;;user vars (defonce ^:private u-vars (atom {})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private spit* "Slurp utf-8" [f c] `(spit ~f ~c :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private slurp* "Spit utf-8" [f] `(slurp ~f :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private lsfs "List files" [a & args] `(.listFiles (io/file ~a ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private ficp "File's canonical path name" [a & args] `(.getCanonicalPath (io/file ~a ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn se! "Set a local var" [k v] (swap! l-vars assoc k v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn localVars "Get the local vars" ^APersistentMap [] @l-vars) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn replaceFile! "Replace content of a file" [file work] {:pre [(fn? work)]} (spit* file (-> (slurp* file) (work)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- gpaths "Recurse and look for folders containing files with this extension" [top out ^String ext] (doseq [^File f (lsfs top) :let [p (.getParentFile f) n (.getName f)]] (cond (.isDirectory f) (gpaths f out ext) (.endsWith n ext) (when-not (contains? @out p) (swap! out conj p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- grepFolderPaths "Recurse a folder, picking out sub-folders which contain files with the given extension" [root ^String ext] (let [rlen (-> (ficp root) (.length )) out (atom []) bin (atom #{})] (gpaths root bin ext) (doseq [k @bin :let [kp (ficp k)]] (swap! out conj (.substring kp (inc rlen)))) @out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn fp! "Constructs a file path" [& args] (clojure.string/join "/" args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- glocal "Get the value for this local var" [k] (let [v (@l-vars k)] (if (fn? v) (v k) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn ge "Get the value for this local var" ([k] (ge k false)) ([k local?] (let [rc (if local? (glocal k) (if-some [v (@u-vars k)] (if (fn? v) (v k) v) (glocal k)))] ;;sometimes we really want nothing to be returned (if (not= :nichts rc) (or rc (bc/get-env k)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private minitask "Wraps it like an ant task" [func & forms] `(do (println (str ~func ":")) ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro artifactID "Get the name of this artifact" [] `(name (ge :project))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro idAndVer "Id and version" [] `(str (artifactID) "-" (ge :version))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- listCljNsps "Generate a list of clojure namespaces based on scanning for .clj files recursively" ^APersistentVector [root & paths] (let [base #(cs/replace (.getName ^File %) #"\.[^\.]+$" "") dot #(cs/replace % "/" ".") ffs #(let [^File f %] (and (.isFile f) (.endsWith (.getName f) ".clj")))] (sort (reduce (fn [memo path] (let [nsp (dot path)] (concat memo (map #(str nsp "." (base %)) (filter ffs (lsfs root path)))))) [] paths)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn clrBuild "Clean build folders" [] (minitask "clean/build" (a/cleanDir (io/file (ge :bootBuildDir))) (a/cleanDir (io/file (ge :libDir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn preBuild "Prepare build folders" [] (minitask "pre/build" (doseq [s (ge :mdirs)] (.mkdirs (io/file s))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileJava "Compile java files and copy resources to output dir" [] (let [ex (ge :exclude-java)] (a/runTarget* "compile/src/java" (a/antJavac (ge :javac-opts) [[:compilerarg (ge :compiler-args)] [:include "**/*.java"] [:exclude ex] [:classpath (ge :cpath)]]) (a/antCopy {:todir (ge :jczDir)} [[:fileset {:dir (fp! (ge :srcDir) "java") :excludes "**/*.java"}] [:fileset {:dir (fp! (ge :srcDir) "resources")}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileClj "Compile clojure files and copy resources to output dir" [] (let [root (io/file (ge :srcDir) "clojure") ps (grepFolderPaths root ".clj") ex (ge :exclude-clj) out (atom '())] ;;figure out all files(namespaces) (doseq [p ps] (swap! out concat (partition-all 24 (listCljNsps root p)))) ;;compile each namespace (minitask "compile/src/clojure" (doseq [p @out :let [p (filter #(let [^String s1 %1] (cond (string? ex) (not (.matches s1 ^String ex)) (instance? Pattern ex) (nil? (re-matches ex s1)) :else true)) p)] :when (> (count p) 0)] (a/runTasks* (a/antJava (ge :cljc-opts) (concat [[:argvalues p]] (ge :cjnested))))) (a/runTasks* (a/antCopy {:todir (ge :cczDir)} [[:fileset {:dir root :excludes "**/*.clj"}]]))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- jarFiles "Create the jar file" [] (let [d {:excludes "**/log4j.*,**/log4j2.*,**/logback.*"} j [:fileset (merge {:dir (ge :jczDir)} d)] c [:fileset (merge {:dir (ge :cczDir)} d)]] (a/runTarget* "jar/files" (a/antJar {:destFile (fp! (ge :distDir) (str (idAndVer) ".jar"))} [j c])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- preTest "Prepare for test" [] (minitask "pre/test" (.mkdirs (io/file (ge :buildTestDir))) (.mkdirs (io/file (ge :reportTestDir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileJavaTest "Compile java test files" [] (a/runTarget* "compile/test/java" (a/antJavac (merge (ge :javac-opts) {:srcdir (fp! (ge :tstDir) "java") :destdir (ge :buildTestDir)}) [[:include "**/*.java"] [:classpath (ge :tpath)] [:compilerarg (ge :compiler-args)]]) (a/antCopy {:todir (ge :buildTestDir)} [[:fileset {:dir (fp! (ge :tstDir) "java") :excludes "**/*.java"}]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileCljTest "Compile clojure test files" [] (let [root (io/file (ge :tstDir) "clojure") ps (grepFolderPaths root ".clj") out (atom '())] (doseq [p ps] (swap! out concat (partition-all 24 (listCljNsps root p)))) (minitask "compile/test/clojure" (doseq [p @out] (a/runTasks* (a/antJava (ge :cljc-opts) [[:sysprops (assoc (ge :cljc-sys-props) :clojure.compile.path (ge :buildTestDir))] [:classpath (ge :tjpath)] [:argvalues p]]))) (a/runTasks* (a/antCopy {:todir (ge :buildTestDir)} [[:fileset {:dir root :excludes "**/*.clj"}]]))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- runCljTest "Execute clojure test cases" [] (a/runTarget* "run/test/clojure" (a/antJunit {:logFailedTests true :showOutput false :printsummary true :fork true :haltonfailure true} [[:classpath (ge :tjpath)] [:formatter {:type "plain" :useFile false}] [:test {:name (ge :test-runner) :todir (ge :reportTestDir)} [[:formatter {:type "xml"}]]]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- runJavaTest "Execute java test cases" [] (a/runTarget* "run/test/java" (a/antJunit {:logFailedTests true :showOutput false :printsummary true :fork true :haltonfailure true} [[:classpath (ge :tpath)] [:formatter {:type "plain" :useFile false}] [:batchtest {:todir (ge :reportTestDir)} [[:fileset {:dir (ge :buildTestDir)} [[:include "**/JUnit.*"]]] [:formatter {:type "xml"}]]]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- buildJavaTest "Build for java tests" [] (a/cleanDir (io/file (ge :buildTestDir))) (preTest) (compileJavaTest)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- buildCljTest "Build for clojure tests" [] (buildJavaTest) (compileCljTest)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runCmd "Run an external command" {:no-doc true} [cmd workDir args] (a/runTarget* (str "cmd:" cmd) (a/antExec {:executable cmd :dir workDir :spawn false} [[:argvalues (or args [])]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn genDocs "Generate api docs" [] (let [rootDir (fp! (ge :packDir) "docs") srcDir (ge :srcDir)] (a/cleanDir rootDir) (a/runTarget* "pack/docs" (a/antJavadoc {:destdir (fp! rootDir "java") :access "protected" :author true :nodeprecated false :nodeprecatedlist false :noindex false :nonavbar false :notree false :source (ge :java-ver) :splitindex true :use true :version true} [[:fileset {:dir (fp! srcDir "java") :includes "**/*.java"}] [:classpath (ge :cpath)]]) (a/antJava {:classname "czlab.pariah.codox" :fork true :failonerror true} [[:argvalues [(ge :basedir) (fp! srcDir "clojure") (fp! rootDir "clojure")]] [:classpath (ge :cjpath) ]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootEnvVars! "Basic vars" [] (se! :warnonref :clojure.compile.warn-on-reflection) (se! :homedir (System/getProperty "user.home")) (se! :basedir (System/getProperty "user.dir")) (se! :java-ver "1.8") (se! :deps-path "lib") (se! :warn-reflection true) (se! :pmode "dev") (se! :bld "out") (se! :cout "z") (se! :jcz "j") (se! :ccz "c") (se! :web "w") (se! :bootBuildDir #(let [_ %] (fp! (ge :basedir) (ge :bld)))) (se! :jczDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :jcz)))) (se! :cczDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :ccz)))) (se! :webDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :web)))) (se! :distDir #(let [_ %] (fp! (ge :bootBuildDir) "d"))) (se! :qaDir #(let [_ %] (fp! (ge :bootBuildDir) "t"))) (se! :docs #(let [_ %] (fp! (ge :bootBuildDir) "docs"))) (se! :libDir #(let [_ %] (fp! (ge :basedir) (ge :deps-path)))) (se! :srcDir #(let [_ %] (fp! (ge :basedir) "src/main"))) (se! :tstDir #(let [_ %] (fp! (ge :basedir) "src/test"))) (se! :buildTestDir #(let [_ %] (fp! (ge :qaDir) (ge :cout)))) (se! :reportTestDir #(let [_ %] (fp! (ge :qaDir) "r"))) (se! :packDir #(let [_ %] (fp! (ge :bootBuildDir) "p"))) (se! :mdirs #(let [_ %] [(ge :bootBuildDir) (ge :distDir) (ge :libDir) (ge :qaDir) (ge :cczDir) (ge :jczDir)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn toggleDoco "Toggle api docs" [b] (se! :wantDocs b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootSyncCPath "Add these file paths to class-path" [& paths] (doseq [p paths] (pom/add-classpath p))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootEnvPaths! "File paths and class paths for builds" [] (se! :compiler-args #(let [_ %] {:line "-Xlint:deprecation -Xlint:unchecked"})) (se! :compile-opts #(let [_ %] {:includeantruntime false :debug (ge :debug) :fork true})) (se! :cpath #(let [_ %] [[:location (fp! (ge :basedir) "attic")] [:location (ge :jczDir)] [:location (ge :cczDir)] [:fileset {:dir (ge :libDir) :includes "**/*.jar"}]])) (se! :tpath #(let [_ %] (->> (ge :cpath) (cons [:location (ge :buildTestDir)]) (into [])))) (se! :javac-opts #(let [_ %] (merge {:srcdir (fp! (ge :srcDir) "java") :destdir (ge :jczDir) :target (ge :java-ver) :debugLevel "lines,vars,source"} (ge :compile-opts)))) (se! :cjpath #(let [_ %] (->> (ge :cpath) (cons [:location (fp! (ge :srcDir) "clojure")]) (into [])))) (se! :tjpath #(let [_ %] (->> (ge :cjpath) (concat [[:location (fp! (ge :tstDir) "clojure")] [:location (ge :buildTestDir)]]) (into [])))) (se! :cljc-opts #(let [_ %] {:classname "clojure.lang.Compile" :fork true :failonerror true :maxmemory "2048m"})) (se! :cljc-sys-props #(let [_ %] {(ge :warnonref) (ge :warn-reflection) :clojure.compile.path (ge :cczDir)})) (se! :cjnested #(let [_ %] [[:sysprops (ge :cljc-sys-props)] [:classpath (ge :cjpath)]])) (se! :cjnested-raw #(let [_ %] [[:sysprops (-> (ge :cljc-sys-props) (assoc (ge :warnonref) false))] [:classpath (ge :cjpath)]])) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootEnv! "Setup env-vars and paths - must be called by the user" ([] (bootEnv! nil nil)) ([options] (bootEnv! options nil)) ([options post] (swap! u-vars merge options) (bootEnvVars!) (bootEnvPaths!) (bootSyncCPath (str (ge :jczDir) "/")) (if (fn? post) (post)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro bootSpit "Write to file" [^String data file] `(spit* ~file ~data)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootSpitJson "Write JSON object to file" [json file] (bootSpit (js/write-str json) file)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro bootSlurp "Read file content as string" [file] `(slurp* ~file)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootSlurpJson "Read file content as JSON" [file] (-> (bootSlurp file) (js/read-str :key-fn keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn packAll "Pack all content" {:no-doc true} [initor] (let [root (ge :packDir) dist (ge :distDir) ver (ge :version) src (ge :srcDir)] ;;clean and init the pack dir (a/cleanDir root) (if (fn? initor) (initor root)) ;; copy license stuff (a/runTarget* "pack/lics" (a/antCopy {:todir root} [[:fileset {:dir (ge :basedir) :includes "*.md,LICENSE"}]])) ;; copy source (a/runTarget* "pack/src" (a/antCopy {:todir (fp! root "src/main/clojure")} [[:fileset {:dir (fp! src "clojure")}]]) (a/antCopy {:todir (fp! root "src/main/java")} [[:fileset {:dir (fp! src "java")}]])) ;; copy distro jars (a/runTarget* "pack/dist" (a/antCopy {:todir (fp! root "dist")} [[:fileset {:dir dist :includes "*.jar"}]])) (a/runTarget* "pack/lib" (a/antCopy {:todir (fp! root "lib")} [[:fileset {:dir (ge :libDir)}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn tarAll "Tar everything" {:no-doc true} [] (let [root (ge :packDir) dist (ge :distDir)] (a/runTarget* "pack/all" (a/antTar {:destFile (fp! dist (str (idAndVer) ".tar.gz")) :compression "gzip"} [[:tarfileset {:dir root :excludes "bin/**"}] [:tarfileset {:dir root :mode "755" :includes "bin/**"}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- dumpVars "" [m] (persistent! (reduce #(let [[k v] %2] (assoc! %1 k (ge k))) (transient {}) m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn dbgBootVars "" {:no-doc true} [] {:l-vars (dumpVars @l-vars) :u-vars (dumpVars @u-vars)}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/task-options! uber {:as-jars true} aot {:all true}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask testJava "Test java" [] (bc/with-pre-wrap fileset (buildJavaTest) (runJavaTest) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask testClj "Test clojure" [] (bc/with-pre-wrap fileset (buildCljTest) (runCljTest) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask juber "Pull all dependent files to target folder" [] (bc/with-pre-wrap fileset (let [target (io/file (ge :basedir) (ge :deps-path)) jars (bc/output-files fileset) to (io/file (ge :libDir))] (a/runTarget "juber" (for [j (seq jars) :let [dir (:dir j) pn (:path j) ;;boot prepends a hash to the jar file, dunno why, ;;but i dont like it, so ripping it out mt (re-matches #"^[0-9a-z]*-(.*)" pn)]] (if (== (count mt) 2) (a/antCopy {:file (fp! dir pn) :tofile (fp! to (last mt))}) (a/antCopy {:file (fp! dir pn) :todir to})))) (println (format "copied (%d) jars to %s" (count jars) to)) fileset))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask nullfs "Return a empty fileset" [] (bc/with-pre-wrap fileset (bc/new-fileset))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask libjars "Resolve all dependencies (jars)" [] (a/cleanDir (io/file (ge :libDir))) (comp (uber)(juber)(nullfs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask initBuild "Prepare for a build" [] (bc/with-pre-wrap fileset (clrBuild) (preBuild) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask buildr "Compile all source files" [] (bc/with-pre-wrap fileset (compileJava) (compileClj) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask jar! "Create final jar file" [] (bc/with-pre-wrap fileset (let [p (str (ge :project)) v (fp! (ge :jczDir) p "version.properties")] (if (.exists (io/file v)) (replaceFile! v #(cs/replace % "@@pom.version@@" (ge :version))))) (jarFiles) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask postPOM! "Write out the pom files to output folder" [] (bc/with-pre-wrap fileset (doseq [f (seq (bc/output-files fileset))] (let [^String pn (:path f) dir (:dir f) tf (io/file (ge :jczDir) pn) pd (.getParentFile tf)] (when (.startsWith pn "META-INF") (.mkdirs pd) (spit* tf (slurp* (fp! dir pn)))))) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask pom! "Run the default pom task" [] (comp (nullfs) (pom :project (ge :project) :version (ge :version)) (postPOM!) (nullfs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask packDistro "Package all output files into a tar file" [] (bc/with-pre-wrap fileset (let [] (packAll (fn [root] (map #(.mkdirs (io/file root %)) ["dist" "lib" "docs"]))) (if (ge :wantDocs) (genDocs)) (tarAll) nil) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask localInstall "Install artifact to local maven repo" [] (comp (install :file (str (ge :distDir) "/" (idAndVer) ".jar")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
3079
;; 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 (c) 2013-2016, <NAME>. All rights reserved. (ns ^{:doc "Various boot-clj helpers." :author "<NAME>" } czlab.pariah.boot (:require [boot.task.built-in :refer [install pom aot uber target]] [boot.core :as bc] [cemerick.pomegranate :as pom] [flatland.ordered.map :as fom] [flatland.ordered.set :as fos] [clojure.data.json :as js] [clojure.java.io :as io] [clojure.string :as cs] [czlab.pariah.antlib :as a]) (:import [clojure.lang APersistentMap APersistentVector] [java.util Stack] [java.io File] [java.util.regex Pattern])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;pull in flatland stuff to force things compiled (def ^:private dummy-1 (fom/ordered-map)) (def ^:private dummy-2 (fos/ordered-set)) ;;default local vars (defonce ^:private l-vars (atom {})) ;;user vars (defonce ^:private u-vars (atom {})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private spit* "Slurp utf-8" [f c] `(spit ~f ~c :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private slurp* "Spit utf-8" [f] `(slurp ~f :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private lsfs "List files" [a & args] `(.listFiles (io/file ~a ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private ficp "File's canonical path name" [a & args] `(.getCanonicalPath (io/file ~a ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn se! "Set a local var" [k v] (swap! l-vars assoc k v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn localVars "Get the local vars" ^APersistentMap [] @l-vars) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn replaceFile! "Replace content of a file" [file work] {:pre [(fn? work)]} (spit* file (-> (slurp* file) (work)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- gpaths "Recurse and look for folders containing files with this extension" [top out ^String ext] (doseq [^File f (lsfs top) :let [p (.getParentFile f) n (.getName f)]] (cond (.isDirectory f) (gpaths f out ext) (.endsWith n ext) (when-not (contains? @out p) (swap! out conj p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- grepFolderPaths "Recurse a folder, picking out sub-folders which contain files with the given extension" [root ^String ext] (let [rlen (-> (ficp root) (.length )) out (atom []) bin (atom #{})] (gpaths root bin ext) (doseq [k @bin :let [kp (ficp k)]] (swap! out conj (.substring kp (inc rlen)))) @out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn fp! "Constructs a file path" [& args] (clojure.string/join "/" args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- glocal "Get the value for this local var" [k] (let [v (@l-vars k)] (if (fn? v) (v k) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn ge "Get the value for this local var" ([k] (ge k false)) ([k local?] (let [rc (if local? (glocal k) (if-some [v (@u-vars k)] (if (fn? v) (v k) v) (glocal k)))] ;;sometimes we really want nothing to be returned (if (not= :nichts rc) (or rc (bc/get-env k)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private minitask "Wraps it like an ant task" [func & forms] `(do (println (str ~func ":")) ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro artifactID "Get the name of this artifact" [] `(name (ge :project))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro idAndVer "Id and version" [] `(str (artifactID) "-" (ge :version))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- listCljNsps "Generate a list of clojure namespaces based on scanning for .clj files recursively" ^APersistentVector [root & paths] (let [base #(cs/replace (.getName ^File %) #"\.[^\.]+$" "") dot #(cs/replace % "/" ".") ffs #(let [^File f %] (and (.isFile f) (.endsWith (.getName f) ".clj")))] (sort (reduce (fn [memo path] (let [nsp (dot path)] (concat memo (map #(str nsp "." (base %)) (filter ffs (lsfs root path)))))) [] paths)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn clrBuild "Clean build folders" [] (minitask "clean/build" (a/cleanDir (io/file (ge :bootBuildDir))) (a/cleanDir (io/file (ge :libDir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn preBuild "Prepare build folders" [] (minitask "pre/build" (doseq [s (ge :mdirs)] (.mkdirs (io/file s))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileJava "Compile java files and copy resources to output dir" [] (let [ex (ge :exclude-java)] (a/runTarget* "compile/src/java" (a/antJavac (ge :javac-opts) [[:compilerarg (ge :compiler-args)] [:include "**/*.java"] [:exclude ex] [:classpath (ge :cpath)]]) (a/antCopy {:todir (ge :jczDir)} [[:fileset {:dir (fp! (ge :srcDir) "java") :excludes "**/*.java"}] [:fileset {:dir (fp! (ge :srcDir) "resources")}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileClj "Compile clojure files and copy resources to output dir" [] (let [root (io/file (ge :srcDir) "clojure") ps (grepFolderPaths root ".clj") ex (ge :exclude-clj) out (atom '())] ;;figure out all files(namespaces) (doseq [p ps] (swap! out concat (partition-all 24 (listCljNsps root p)))) ;;compile each namespace (minitask "compile/src/clojure" (doseq [p @out :let [p (filter #(let [^String s1 %1] (cond (string? ex) (not (.matches s1 ^String ex)) (instance? Pattern ex) (nil? (re-matches ex s1)) :else true)) p)] :when (> (count p) 0)] (a/runTasks* (a/antJava (ge :cljc-opts) (concat [[:argvalues p]] (ge :cjnested))))) (a/runTasks* (a/antCopy {:todir (ge :cczDir)} [[:fileset {:dir root :excludes "**/*.clj"}]]))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- jarFiles "Create the jar file" [] (let [d {:excludes "**/log4j.*,**/log4j2.*,**/logback.*"} j [:fileset (merge {:dir (ge :jczDir)} d)] c [:fileset (merge {:dir (ge :cczDir)} d)]] (a/runTarget* "jar/files" (a/antJar {:destFile (fp! (ge :distDir) (str (idAndVer) ".jar"))} [j c])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- preTest "Prepare for test" [] (minitask "pre/test" (.mkdirs (io/file (ge :buildTestDir))) (.mkdirs (io/file (ge :reportTestDir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileJavaTest "Compile java test files" [] (a/runTarget* "compile/test/java" (a/antJavac (merge (ge :javac-opts) {:srcdir (fp! (ge :tstDir) "java") :destdir (ge :buildTestDir)}) [[:include "**/*.java"] [:classpath (ge :tpath)] [:compilerarg (ge :compiler-args)]]) (a/antCopy {:todir (ge :buildTestDir)} [[:fileset {:dir (fp! (ge :tstDir) "java") :excludes "**/*.java"}]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileCljTest "Compile clojure test files" [] (let [root (io/file (ge :tstDir) "clojure") ps (grepFolderPaths root ".clj") out (atom '())] (doseq [p ps] (swap! out concat (partition-all 24 (listCljNsps root p)))) (minitask "compile/test/clojure" (doseq [p @out] (a/runTasks* (a/antJava (ge :cljc-opts) [[:sysprops (assoc (ge :cljc-sys-props) :clojure.compile.path (ge :buildTestDir))] [:classpath (ge :tjpath)] [:argvalues p]]))) (a/runTasks* (a/antCopy {:todir (ge :buildTestDir)} [[:fileset {:dir root :excludes "**/*.clj"}]]))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- runCljTest "Execute clojure test cases" [] (a/runTarget* "run/test/clojure" (a/antJunit {:logFailedTests true :showOutput false :printsummary true :fork true :haltonfailure true} [[:classpath (ge :tjpath)] [:formatter {:type "plain" :useFile false}] [:test {:name (ge :test-runner) :todir (ge :reportTestDir)} [[:formatter {:type "xml"}]]]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- runJavaTest "Execute java test cases" [] (a/runTarget* "run/test/java" (a/antJunit {:logFailedTests true :showOutput false :printsummary true :fork true :haltonfailure true} [[:classpath (ge :tpath)] [:formatter {:type "plain" :useFile false}] [:batchtest {:todir (ge :reportTestDir)} [[:fileset {:dir (ge :buildTestDir)} [[:include "**/JUnit.*"]]] [:formatter {:type "xml"}]]]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- buildJavaTest "Build for java tests" [] (a/cleanDir (io/file (ge :buildTestDir))) (preTest) (compileJavaTest)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- buildCljTest "Build for clojure tests" [] (buildJavaTest) (compileCljTest)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runCmd "Run an external command" {:no-doc true} [cmd workDir args] (a/runTarget* (str "cmd:" cmd) (a/antExec {:executable cmd :dir workDir :spawn false} [[:argvalues (or args [])]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn genDocs "Generate api docs" [] (let [rootDir (fp! (ge :packDir) "docs") srcDir (ge :srcDir)] (a/cleanDir rootDir) (a/runTarget* "pack/docs" (a/antJavadoc {:destdir (fp! rootDir "java") :access "protected" :author true :nodeprecated false :nodeprecatedlist false :noindex false :nonavbar false :notree false :source (ge :java-ver) :splitindex true :use true :version true} [[:fileset {:dir (fp! srcDir "java") :includes "**/*.java"}] [:classpath (ge :cpath)]]) (a/antJava {:classname "czlab.pariah.codox" :fork true :failonerror true} [[:argvalues [(ge :basedir) (fp! srcDir "clojure") (fp! rootDir "clojure")]] [:classpath (ge :cjpath) ]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootEnvVars! "Basic vars" [] (se! :warnonref :clojure.compile.warn-on-reflection) (se! :homedir (System/getProperty "user.home")) (se! :basedir (System/getProperty "user.dir")) (se! :java-ver "1.8") (se! :deps-path "lib") (se! :warn-reflection true) (se! :pmode "dev") (se! :bld "out") (se! :cout "z") (se! :jcz "j") (se! :ccz "c") (se! :web "w") (se! :bootBuildDir #(let [_ %] (fp! (ge :basedir) (ge :bld)))) (se! :jczDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :jcz)))) (se! :cczDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :ccz)))) (se! :webDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :web)))) (se! :distDir #(let [_ %] (fp! (ge :bootBuildDir) "d"))) (se! :qaDir #(let [_ %] (fp! (ge :bootBuildDir) "t"))) (se! :docs #(let [_ %] (fp! (ge :bootBuildDir) "docs"))) (se! :libDir #(let [_ %] (fp! (ge :basedir) (ge :deps-path)))) (se! :srcDir #(let [_ %] (fp! (ge :basedir) "src/main"))) (se! :tstDir #(let [_ %] (fp! (ge :basedir) "src/test"))) (se! :buildTestDir #(let [_ %] (fp! (ge :qaDir) (ge :cout)))) (se! :reportTestDir #(let [_ %] (fp! (ge :qaDir) "r"))) (se! :packDir #(let [_ %] (fp! (ge :bootBuildDir) "p"))) (se! :mdirs #(let [_ %] [(ge :bootBuildDir) (ge :distDir) (ge :libDir) (ge :qaDir) (ge :cczDir) (ge :jczDir)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn toggleDoco "Toggle api docs" [b] (se! :wantDocs b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootSyncCPath "Add these file paths to class-path" [& paths] (doseq [p paths] (pom/add-classpath p))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootEnvPaths! "File paths and class paths for builds" [] (se! :compiler-args #(let [_ %] {:line "-Xlint:deprecation -Xlint:unchecked"})) (se! :compile-opts #(let [_ %] {:includeantruntime false :debug (ge :debug) :fork true})) (se! :cpath #(let [_ %] [[:location (fp! (ge :basedir) "attic")] [:location (ge :jczDir)] [:location (ge :cczDir)] [:fileset {:dir (ge :libDir) :includes "**/*.jar"}]])) (se! :tpath #(let [_ %] (->> (ge :cpath) (cons [:location (ge :buildTestDir)]) (into [])))) (se! :javac-opts #(let [_ %] (merge {:srcdir (fp! (ge :srcDir) "java") :destdir (ge :jczDir) :target (ge :java-ver) :debugLevel "lines,vars,source"} (ge :compile-opts)))) (se! :cjpath #(let [_ %] (->> (ge :cpath) (cons [:location (fp! (ge :srcDir) "clojure")]) (into [])))) (se! :tjpath #(let [_ %] (->> (ge :cjpath) (concat [[:location (fp! (ge :tstDir) "clojure")] [:location (ge :buildTestDir)]]) (into [])))) (se! :cljc-opts #(let [_ %] {:classname "clojure.lang.Compile" :fork true :failonerror true :maxmemory "2048m"})) (se! :cljc-sys-props #(let [_ %] {(ge :warnonref) (ge :warn-reflection) :clojure.compile.path (ge :cczDir)})) (se! :cjnested #(let [_ %] [[:sysprops (ge :cljc-sys-props)] [:classpath (ge :cjpath)]])) (se! :cjnested-raw #(let [_ %] [[:sysprops (-> (ge :cljc-sys-props) (assoc (ge :warnonref) false))] [:classpath (ge :cjpath)]])) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootEnv! "Setup env-vars and paths - must be called by the user" ([] (bootEnv! nil nil)) ([options] (bootEnv! options nil)) ([options post] (swap! u-vars merge options) (bootEnvVars!) (bootEnvPaths!) (bootSyncCPath (str (ge :jczDir) "/")) (if (fn? post) (post)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro bootSpit "Write to file" [^String data file] `(spit* ~file ~data)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootSpitJson "Write JSON object to file" [json file] (bootSpit (js/write-str json) file)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro bootSlurp "Read file content as string" [file] `(slurp* ~file)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootSlurpJson "Read file content as JSON" [file] (-> (bootSlurp file) (js/read-str :key-fn keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn packAll "Pack all content" {:no-doc true} [initor] (let [root (ge :packDir) dist (ge :distDir) ver (ge :version) src (ge :srcDir)] ;;clean and init the pack dir (a/cleanDir root) (if (fn? initor) (initor root)) ;; copy license stuff (a/runTarget* "pack/lics" (a/antCopy {:todir root} [[:fileset {:dir (ge :basedir) :includes "*.md,LICENSE"}]])) ;; copy source (a/runTarget* "pack/src" (a/antCopy {:todir (fp! root "src/main/clojure")} [[:fileset {:dir (fp! src "clojure")}]]) (a/antCopy {:todir (fp! root "src/main/java")} [[:fileset {:dir (fp! src "java")}]])) ;; copy distro jars (a/runTarget* "pack/dist" (a/antCopy {:todir (fp! root "dist")} [[:fileset {:dir dist :includes "*.jar"}]])) (a/runTarget* "pack/lib" (a/antCopy {:todir (fp! root "lib")} [[:fileset {:dir (ge :libDir)}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn tarAll "Tar everything" {:no-doc true} [] (let [root (ge :packDir) dist (ge :distDir)] (a/runTarget* "pack/all" (a/antTar {:destFile (fp! dist (str (idAndVer) ".tar.gz")) :compression "gzip"} [[:tarfileset {:dir root :excludes "bin/**"}] [:tarfileset {:dir root :mode "755" :includes "bin/**"}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- dumpVars "" [m] (persistent! (reduce #(let [[k v] %2] (assoc! %1 k (ge k))) (transient {}) m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn dbgBootVars "" {:no-doc true} [] {:l-vars (dumpVars @l-vars) :u-vars (dumpVars @u-vars)}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/task-options! uber {:as-jars true} aot {:all true}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask testJava "Test java" [] (bc/with-pre-wrap fileset (buildJavaTest) (runJavaTest) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask testClj "Test clojure" [] (bc/with-pre-wrap fileset (buildCljTest) (runCljTest) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask juber "Pull all dependent files to target folder" [] (bc/with-pre-wrap fileset (let [target (io/file (ge :basedir) (ge :deps-path)) jars (bc/output-files fileset) to (io/file (ge :libDir))] (a/runTarget "juber" (for [j (seq jars) :let [dir (:dir j) pn (:path j) ;;boot prepends a hash to the jar file, dunno why, ;;but i dont like it, so ripping it out mt (re-matches #"^[0-9a-z]*-(.*)" pn)]] (if (== (count mt) 2) (a/antCopy {:file (fp! dir pn) :tofile (fp! to (last mt))}) (a/antCopy {:file (fp! dir pn) :todir to})))) (println (format "copied (%d) jars to %s" (count jars) to)) fileset))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask nullfs "Return a empty fileset" [] (bc/with-pre-wrap fileset (bc/new-fileset))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask libjars "Resolve all dependencies (jars)" [] (a/cleanDir (io/file (ge :libDir))) (comp (uber)(juber)(nullfs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask initBuild "Prepare for a build" [] (bc/with-pre-wrap fileset (clrBuild) (preBuild) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask buildr "Compile all source files" [] (bc/with-pre-wrap fileset (compileJava) (compileClj) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask jar! "Create final jar file" [] (bc/with-pre-wrap fileset (let [p (str (ge :project)) v (fp! (ge :jczDir) p "version.properties")] (if (.exists (io/file v)) (replaceFile! v #(cs/replace % "@@pom.version@@" (ge :version))))) (jarFiles) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask postPOM! "Write out the pom files to output folder" [] (bc/with-pre-wrap fileset (doseq [f (seq (bc/output-files fileset))] (let [^String pn (:path f) dir (:dir f) tf (io/file (ge :jczDir) pn) pd (.getParentFile tf)] (when (.startsWith pn "META-INF") (.mkdirs pd) (spit* tf (slurp* (fp! dir pn)))))) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask pom! "Run the default pom task" [] (comp (nullfs) (pom :project (ge :project) :version (ge :version)) (postPOM!) (nullfs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask packDistro "Package all output files into a tar file" [] (bc/with-pre-wrap fileset (let [] (packAll (fn [root] (map #(.mkdirs (io/file root %)) ["dist" "lib" "docs"]))) (if (ge :wantDocs) (genDocs)) (tarAll) nil) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask localInstall "Install artifact to local maven repo" [] (comp (install :file (str (ge :distDir) "/" (idAndVer) ".jar")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;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 (c) 2013-2016, PI:NAME:<NAME>END_PI. All rights reserved. (ns ^{:doc "Various boot-clj helpers." :author "PI:NAME:<NAME>END_PI" } czlab.pariah.boot (:require [boot.task.built-in :refer [install pom aot uber target]] [boot.core :as bc] [cemerick.pomegranate :as pom] [flatland.ordered.map :as fom] [flatland.ordered.set :as fos] [clojure.data.json :as js] [clojure.java.io :as io] [clojure.string :as cs] [czlab.pariah.antlib :as a]) (:import [clojure.lang APersistentMap APersistentVector] [java.util Stack] [java.io File] [java.util.regex Pattern])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;pull in flatland stuff to force things compiled (def ^:private dummy-1 (fom/ordered-map)) (def ^:private dummy-2 (fos/ordered-set)) ;;default local vars (defonce ^:private l-vars (atom {})) ;;user vars (defonce ^:private u-vars (atom {})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private spit* "Slurp utf-8" [f c] `(spit ~f ~c :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private slurp* "Spit utf-8" [f] `(slurp ~f :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private lsfs "List files" [a & args] `(.listFiles (io/file ~a ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private ficp "File's canonical path name" [a & args] `(.getCanonicalPath (io/file ~a ~@args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn se! "Set a local var" [k v] (swap! l-vars assoc k v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn localVars "Get the local vars" ^APersistentMap [] @l-vars) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn replaceFile! "Replace content of a file" [file work] {:pre [(fn? work)]} (spit* file (-> (slurp* file) (work)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- gpaths "Recurse and look for folders containing files with this extension" [top out ^String ext] (doseq [^File f (lsfs top) :let [p (.getParentFile f) n (.getName f)]] (cond (.isDirectory f) (gpaths f out ext) (.endsWith n ext) (when-not (contains? @out p) (swap! out conj p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- grepFolderPaths "Recurse a folder, picking out sub-folders which contain files with the given extension" [root ^String ext] (let [rlen (-> (ficp root) (.length )) out (atom []) bin (atom #{})] (gpaths root bin ext) (doseq [k @bin :let [kp (ficp k)]] (swap! out conj (.substring kp (inc rlen)))) @out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn fp! "Constructs a file path" [& args] (clojure.string/join "/" args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- glocal "Get the value for this local var" [k] (let [v (@l-vars k)] (if (fn? v) (v k) v))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn ge "Get the value for this local var" ([k] (ge k false)) ([k local?] (let [rc (if local? (glocal k) (if-some [v (@u-vars k)] (if (fn? v) (v k) v) (glocal k)))] ;;sometimes we really want nothing to be returned (if (not= :nichts rc) (or rc (bc/get-env k)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private minitask "Wraps it like an ant task" [func & forms] `(do (println (str ~func ":")) ~@forms)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro artifactID "Get the name of this artifact" [] `(name (ge :project))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro idAndVer "Id and version" [] `(str (artifactID) "-" (ge :version))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- listCljNsps "Generate a list of clojure namespaces based on scanning for .clj files recursively" ^APersistentVector [root & paths] (let [base #(cs/replace (.getName ^File %) #"\.[^\.]+$" "") dot #(cs/replace % "/" ".") ffs #(let [^File f %] (and (.isFile f) (.endsWith (.getName f) ".clj")))] (sort (reduce (fn [memo path] (let [nsp (dot path)] (concat memo (map #(str nsp "." (base %)) (filter ffs (lsfs root path)))))) [] paths)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn clrBuild "Clean build folders" [] (minitask "clean/build" (a/cleanDir (io/file (ge :bootBuildDir))) (a/cleanDir (io/file (ge :libDir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn preBuild "Prepare build folders" [] (minitask "pre/build" (doseq [s (ge :mdirs)] (.mkdirs (io/file s))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileJava "Compile java files and copy resources to output dir" [] (let [ex (ge :exclude-java)] (a/runTarget* "compile/src/java" (a/antJavac (ge :javac-opts) [[:compilerarg (ge :compiler-args)] [:include "**/*.java"] [:exclude ex] [:classpath (ge :cpath)]]) (a/antCopy {:todir (ge :jczDir)} [[:fileset {:dir (fp! (ge :srcDir) "java") :excludes "**/*.java"}] [:fileset {:dir (fp! (ge :srcDir) "resources")}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileClj "Compile clojure files and copy resources to output dir" [] (let [root (io/file (ge :srcDir) "clojure") ps (grepFolderPaths root ".clj") ex (ge :exclude-clj) out (atom '())] ;;figure out all files(namespaces) (doseq [p ps] (swap! out concat (partition-all 24 (listCljNsps root p)))) ;;compile each namespace (minitask "compile/src/clojure" (doseq [p @out :let [p (filter #(let [^String s1 %1] (cond (string? ex) (not (.matches s1 ^String ex)) (instance? Pattern ex) (nil? (re-matches ex s1)) :else true)) p)] :when (> (count p) 0)] (a/runTasks* (a/antJava (ge :cljc-opts) (concat [[:argvalues p]] (ge :cjnested))))) (a/runTasks* (a/antCopy {:todir (ge :cczDir)} [[:fileset {:dir root :excludes "**/*.clj"}]]))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- jarFiles "Create the jar file" [] (let [d {:excludes "**/log4j.*,**/log4j2.*,**/logback.*"} j [:fileset (merge {:dir (ge :jczDir)} d)] c [:fileset (merge {:dir (ge :cczDir)} d)]] (a/runTarget* "jar/files" (a/antJar {:destFile (fp! (ge :distDir) (str (idAndVer) ".jar"))} [j c])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- preTest "Prepare for test" [] (minitask "pre/test" (.mkdirs (io/file (ge :buildTestDir))) (.mkdirs (io/file (ge :reportTestDir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileJavaTest "Compile java test files" [] (a/runTarget* "compile/test/java" (a/antJavac (merge (ge :javac-opts) {:srcdir (fp! (ge :tstDir) "java") :destdir (ge :buildTestDir)}) [[:include "**/*.java"] [:classpath (ge :tpath)] [:compilerarg (ge :compiler-args)]]) (a/antCopy {:todir (ge :buildTestDir)} [[:fileset {:dir (fp! (ge :tstDir) "java") :excludes "**/*.java"}]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- compileCljTest "Compile clojure test files" [] (let [root (io/file (ge :tstDir) "clojure") ps (grepFolderPaths root ".clj") out (atom '())] (doseq [p ps] (swap! out concat (partition-all 24 (listCljNsps root p)))) (minitask "compile/test/clojure" (doseq [p @out] (a/runTasks* (a/antJava (ge :cljc-opts) [[:sysprops (assoc (ge :cljc-sys-props) :clojure.compile.path (ge :buildTestDir))] [:classpath (ge :tjpath)] [:argvalues p]]))) (a/runTasks* (a/antCopy {:todir (ge :buildTestDir)} [[:fileset {:dir root :excludes "**/*.clj"}]]))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- runCljTest "Execute clojure test cases" [] (a/runTarget* "run/test/clojure" (a/antJunit {:logFailedTests true :showOutput false :printsummary true :fork true :haltonfailure true} [[:classpath (ge :tjpath)] [:formatter {:type "plain" :useFile false}] [:test {:name (ge :test-runner) :todir (ge :reportTestDir)} [[:formatter {:type "xml"}]]]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- runJavaTest "Execute java test cases" [] (a/runTarget* "run/test/java" (a/antJunit {:logFailedTests true :showOutput false :printsummary true :fork true :haltonfailure true} [[:classpath (ge :tpath)] [:formatter {:type "plain" :useFile false}] [:batchtest {:todir (ge :reportTestDir)} [[:fileset {:dir (ge :buildTestDir)} [[:include "**/JUnit.*"]]] [:formatter {:type "xml"}]]]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- buildJavaTest "Build for java tests" [] (a/cleanDir (io/file (ge :buildTestDir))) (preTest) (compileJavaTest)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- buildCljTest "Build for clojure tests" [] (buildJavaTest) (compileCljTest)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runCmd "Run an external command" {:no-doc true} [cmd workDir args] (a/runTarget* (str "cmd:" cmd) (a/antExec {:executable cmd :dir workDir :spawn false} [[:argvalues (or args [])]]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn genDocs "Generate api docs" [] (let [rootDir (fp! (ge :packDir) "docs") srcDir (ge :srcDir)] (a/cleanDir rootDir) (a/runTarget* "pack/docs" (a/antJavadoc {:destdir (fp! rootDir "java") :access "protected" :author true :nodeprecated false :nodeprecatedlist false :noindex false :nonavbar false :notree false :source (ge :java-ver) :splitindex true :use true :version true} [[:fileset {:dir (fp! srcDir "java") :includes "**/*.java"}] [:classpath (ge :cpath)]]) (a/antJava {:classname "czlab.pariah.codox" :fork true :failonerror true} [[:argvalues [(ge :basedir) (fp! srcDir "clojure") (fp! rootDir "clojure")]] [:classpath (ge :cjpath) ]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootEnvVars! "Basic vars" [] (se! :warnonref :clojure.compile.warn-on-reflection) (se! :homedir (System/getProperty "user.home")) (se! :basedir (System/getProperty "user.dir")) (se! :java-ver "1.8") (se! :deps-path "lib") (se! :warn-reflection true) (se! :pmode "dev") (se! :bld "out") (se! :cout "z") (se! :jcz "j") (se! :ccz "c") (se! :web "w") (se! :bootBuildDir #(let [_ %] (fp! (ge :basedir) (ge :bld)))) (se! :jczDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :jcz)))) (se! :cczDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :ccz)))) (se! :webDir #(let [_ %] (fp! (ge :bootBuildDir) (ge :web)))) (se! :distDir #(let [_ %] (fp! (ge :bootBuildDir) "d"))) (se! :qaDir #(let [_ %] (fp! (ge :bootBuildDir) "t"))) (se! :docs #(let [_ %] (fp! (ge :bootBuildDir) "docs"))) (se! :libDir #(let [_ %] (fp! (ge :basedir) (ge :deps-path)))) (se! :srcDir #(let [_ %] (fp! (ge :basedir) "src/main"))) (se! :tstDir #(let [_ %] (fp! (ge :basedir) "src/test"))) (se! :buildTestDir #(let [_ %] (fp! (ge :qaDir) (ge :cout)))) (se! :reportTestDir #(let [_ %] (fp! (ge :qaDir) "r"))) (se! :packDir #(let [_ %] (fp! (ge :bootBuildDir) "p"))) (se! :mdirs #(let [_ %] [(ge :bootBuildDir) (ge :distDir) (ge :libDir) (ge :qaDir) (ge :cczDir) (ge :jczDir)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn toggleDoco "Toggle api docs" [b] (se! :wantDocs b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootSyncCPath "Add these file paths to class-path" [& paths] (doseq [p paths] (pom/add-classpath p))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- bootEnvPaths! "File paths and class paths for builds" [] (se! :compiler-args #(let [_ %] {:line "-Xlint:deprecation -Xlint:unchecked"})) (se! :compile-opts #(let [_ %] {:includeantruntime false :debug (ge :debug) :fork true})) (se! :cpath #(let [_ %] [[:location (fp! (ge :basedir) "attic")] [:location (ge :jczDir)] [:location (ge :cczDir)] [:fileset {:dir (ge :libDir) :includes "**/*.jar"}]])) (se! :tpath #(let [_ %] (->> (ge :cpath) (cons [:location (ge :buildTestDir)]) (into [])))) (se! :javac-opts #(let [_ %] (merge {:srcdir (fp! (ge :srcDir) "java") :destdir (ge :jczDir) :target (ge :java-ver) :debugLevel "lines,vars,source"} (ge :compile-opts)))) (se! :cjpath #(let [_ %] (->> (ge :cpath) (cons [:location (fp! (ge :srcDir) "clojure")]) (into [])))) (se! :tjpath #(let [_ %] (->> (ge :cjpath) (concat [[:location (fp! (ge :tstDir) "clojure")] [:location (ge :buildTestDir)]]) (into [])))) (se! :cljc-opts #(let [_ %] {:classname "clojure.lang.Compile" :fork true :failonerror true :maxmemory "2048m"})) (se! :cljc-sys-props #(let [_ %] {(ge :warnonref) (ge :warn-reflection) :clojure.compile.path (ge :cczDir)})) (se! :cjnested #(let [_ %] [[:sysprops (ge :cljc-sys-props)] [:classpath (ge :cjpath)]])) (se! :cjnested-raw #(let [_ %] [[:sysprops (-> (ge :cljc-sys-props) (assoc (ge :warnonref) false))] [:classpath (ge :cjpath)]])) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootEnv! "Setup env-vars and paths - must be called by the user" ([] (bootEnv! nil nil)) ([options] (bootEnv! options nil)) ([options post] (swap! u-vars merge options) (bootEnvVars!) (bootEnvPaths!) (bootSyncCPath (str (ge :jczDir) "/")) (if (fn? post) (post)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro bootSpit "Write to file" [^String data file] `(spit* ~file ~data)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootSpitJson "Write JSON object to file" [json file] (bootSpit (js/write-str json) file)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro bootSlurp "Read file content as string" [file] `(slurp* ~file)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn bootSlurpJson "Read file content as JSON" [file] (-> (bootSlurp file) (js/read-str :key-fn keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn packAll "Pack all content" {:no-doc true} [initor] (let [root (ge :packDir) dist (ge :distDir) ver (ge :version) src (ge :srcDir)] ;;clean and init the pack dir (a/cleanDir root) (if (fn? initor) (initor root)) ;; copy license stuff (a/runTarget* "pack/lics" (a/antCopy {:todir root} [[:fileset {:dir (ge :basedir) :includes "*.md,LICENSE"}]])) ;; copy source (a/runTarget* "pack/src" (a/antCopy {:todir (fp! root "src/main/clojure")} [[:fileset {:dir (fp! src "clojure")}]]) (a/antCopy {:todir (fp! root "src/main/java")} [[:fileset {:dir (fp! src "java")}]])) ;; copy distro jars (a/runTarget* "pack/dist" (a/antCopy {:todir (fp! root "dist")} [[:fileset {:dir dist :includes "*.jar"}]])) (a/runTarget* "pack/lib" (a/antCopy {:todir (fp! root "lib")} [[:fileset {:dir (ge :libDir)}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn tarAll "Tar everything" {:no-doc true} [] (let [root (ge :packDir) dist (ge :distDir)] (a/runTarget* "pack/all" (a/antTar {:destFile (fp! dist (str (idAndVer) ".tar.gz")) :compression "gzip"} [[:tarfileset {:dir root :excludes "bin/**"}] [:tarfileset {:dir root :mode "755" :includes "bin/**"}]])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- dumpVars "" [m] (persistent! (reduce #(let [[k v] %2] (assoc! %1 k (ge k))) (transient {}) m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn dbgBootVars "" {:no-doc true} [] {:l-vars (dumpVars @l-vars) :u-vars (dumpVars @u-vars)}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/task-options! uber {:as-jars true} aot {:all true}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask testJava "Test java" [] (bc/with-pre-wrap fileset (buildJavaTest) (runJavaTest) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask testClj "Test clojure" [] (bc/with-pre-wrap fileset (buildCljTest) (runCljTest) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask juber "Pull all dependent files to target folder" [] (bc/with-pre-wrap fileset (let [target (io/file (ge :basedir) (ge :deps-path)) jars (bc/output-files fileset) to (io/file (ge :libDir))] (a/runTarget "juber" (for [j (seq jars) :let [dir (:dir j) pn (:path j) ;;boot prepends a hash to the jar file, dunno why, ;;but i dont like it, so ripping it out mt (re-matches #"^[0-9a-z]*-(.*)" pn)]] (if (== (count mt) 2) (a/antCopy {:file (fp! dir pn) :tofile (fp! to (last mt))}) (a/antCopy {:file (fp! dir pn) :todir to})))) (println (format "copied (%d) jars to %s" (count jars) to)) fileset))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask nullfs "Return a empty fileset" [] (bc/with-pre-wrap fileset (bc/new-fileset))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask libjars "Resolve all dependencies (jars)" [] (a/cleanDir (io/file (ge :libDir))) (comp (uber)(juber)(nullfs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask initBuild "Prepare for a build" [] (bc/with-pre-wrap fileset (clrBuild) (preBuild) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask buildr "Compile all source files" [] (bc/with-pre-wrap fileset (compileJava) (compileClj) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask jar! "Create final jar file" [] (bc/with-pre-wrap fileset (let [p (str (ge :project)) v (fp! (ge :jczDir) p "version.properties")] (if (.exists (io/file v)) (replaceFile! v #(cs/replace % "@@pom.version@@" (ge :version))))) (jarFiles) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask postPOM! "Write out the pom files to output folder" [] (bc/with-pre-wrap fileset (doseq [f (seq (bc/output-files fileset))] (let [^String pn (:path f) dir (:dir f) tf (io/file (ge :jczDir) pn) pd (.getParentFile tf)] (when (.startsWith pn "META-INF") (.mkdirs pd) (spit* tf (slurp* (fp! dir pn)))))) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask pom! "Run the default pom task" [] (comp (nullfs) (pom :project (ge :project) :version (ge :version)) (postPOM!) (nullfs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask packDistro "Package all output files into a tar file" [] (bc/with-pre-wrap fileset (let [] (packAll (fn [root] (map #(.mkdirs (io/file root %)) ["dist" "lib" "docs"]))) (if (ge :wantDocs) (genDocs)) (tarAll) nil) fileset)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (bc/deftask localInstall "Install artifact to local maven repo" [] (comp (install :file (str (ge :distDir) "/" (idAndVer) ".jar")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": "\"}\n {:value 2700.0 :type \"revenue\" :comentario \"Bico\" :date \"01/12/2016\"}\n {:value 29.0 :type \"expen", "end": 215, "score": 0.9864861965179443, "start": 211, "tag": "NAME", "value": "Bico" } ]
map-filter-reduce.clj
talesbaz/clojure-playground
0
(defn summary [transaction] (select-keys transaction [:value :type])) (def transactions [{:value 33.0 :type "expense" :comentario "Almoço" :date "19/11/2016"} {:value 2700.0 :type "revenue" :comentario "Bico" :date "01/12/2016"} {:value 29.0 :type "expense" :comentario "Livro de Clojure" :date "03/12/2016"}]) ; list some fields of transactions (map summary transactions) (defn expense? [transaction] (= (:type transaction) "expense")) ; filter just expense transactions (filter expense? transactions) (defn get-value [transaction] (:value transaction)) ; Get expense values (map get-value (filter expense? transactions)) ; Wrapper (defn get-expense-values [transactions] (map get-value (filter expense? transactions))) ; Sum expenses (reduce +(get-expense-values transactions))
48436
(defn summary [transaction] (select-keys transaction [:value :type])) (def transactions [{:value 33.0 :type "expense" :comentario "Almoço" :date "19/11/2016"} {:value 2700.0 :type "revenue" :comentario "<NAME>" :date "01/12/2016"} {:value 29.0 :type "expense" :comentario "Livro de Clojure" :date "03/12/2016"}]) ; list some fields of transactions (map summary transactions) (defn expense? [transaction] (= (:type transaction) "expense")) ; filter just expense transactions (filter expense? transactions) (defn get-value [transaction] (:value transaction)) ; Get expense values (map get-value (filter expense? transactions)) ; Wrapper (defn get-expense-values [transactions] (map get-value (filter expense? transactions))) ; Sum expenses (reduce +(get-expense-values transactions))
true
(defn summary [transaction] (select-keys transaction [:value :type])) (def transactions [{:value 33.0 :type "expense" :comentario "Almoço" :date "19/11/2016"} {:value 2700.0 :type "revenue" :comentario "PI:NAME:<NAME>END_PI" :date "01/12/2016"} {:value 29.0 :type "expense" :comentario "Livro de Clojure" :date "03/12/2016"}]) ; list some fields of transactions (map summary transactions) (defn expense? [transaction] (= (:type transaction) "expense")) ; filter just expense transactions (filter expense? transactions) (defn get-value [transaction] (:value transaction)) ; Get expense values (map get-value (filter expense? transactions)) ; Wrapper (defn get-expense-values [transactions] (map get-value (filter expense? transactions))) ; Sum expenses (reduce +(get-expense-values transactions))
[ { "context": ", \"W\" 23, \"X\" 24, \"Y\" 25, \"Z\" 26})\n;; (def name1 \"BETTY\")\n;; (println \"name length: \" (count name1))\n\n ;", "end": 426, "score": 0.9960281848907471, "start": 421, "tag": "NAME", "value": "BETTY" } ]
names.clj
kavithaiii/name-scores
0
;; This program uses names.txt ;; execute this program at REPL prompt of clojure ;; copy this file and paste on REPL terminal (defn sum [x] (reduce + x)) (defn find-char-value [name1] (def stringmap {"A" 1, "B" 2, "C" 3, "D" 4, "E" 5, "F" 6, "G" 7, "H" 8, "I" 9, "J" 10, "K" 11, "L" 12, "M" 13, "N" 14, "O" 15, "P" 16, "Q" 17, "R" 18, "S" 19, "T" 20, "U" 21, "V" 22, "W" 23, "X" 24, "Y" 25, "Z" 26}) ;; (def name1 "BETTY") ;; (println "name length: " (count name1)) ;; (defn sum [x] (reduce + x)) (def sum-of-char (sum (loop [i 0 character-arr []] (if (< i (count name1)) (let [val (stringmap (str (nth (seq (char-array name1)) i)))] (recur (inc i) (conj character-arr val))) character-arr)))) (println "sum-of-char >>>" sum-of-char) sum-of-char) (defn read-names [] (with-open [rdr (clojure.java.io/reader "names.txt")] (doseq [line (line-seq rdr)] (def us (clojure.string/replace line #"[\"]" "")) ;; (println us) (def us1 (clojure.string/split us #",")) ;; (println us1) ;; (println "sorted line >>>" (sort us1)) (def sorted-names-list (sort us1)) (println "count >>>" (count sorted-names-list)) (def name-list-length (count sorted-names-list)) (println "name list length " name-list-length) ;; (defn sum [x] (reduce + x)) (def sum-of-names (sum (loop [i 0 name-value-arr []] (if (< i name-list-length) (do (def n1 (nth sorted-names-list i)) ;; (println ">>>>>" n1 " is at postion " i) (def name-position-in-array (+ i 1)) ;; (println "npInArray add one to it >>>" name-position-in-array) (def name-value (* (find-char-value n1) name-position-in-array)) (println "sum of each char in a name MULTIPLIED by name position in array >>> " name-value) (recur (inc i) (conj name-value-arr name-value))) name-value-arr) ) ) ) (println "final value - NAME SCORE >>>> " sum-of-names) ) ) )
86158
;; This program uses names.txt ;; execute this program at REPL prompt of clojure ;; copy this file and paste on REPL terminal (defn sum [x] (reduce + x)) (defn find-char-value [name1] (def stringmap {"A" 1, "B" 2, "C" 3, "D" 4, "E" 5, "F" 6, "G" 7, "H" 8, "I" 9, "J" 10, "K" 11, "L" 12, "M" 13, "N" 14, "O" 15, "P" 16, "Q" 17, "R" 18, "S" 19, "T" 20, "U" 21, "V" 22, "W" 23, "X" 24, "Y" 25, "Z" 26}) ;; (def name1 "<NAME>") ;; (println "name length: " (count name1)) ;; (defn sum [x] (reduce + x)) (def sum-of-char (sum (loop [i 0 character-arr []] (if (< i (count name1)) (let [val (stringmap (str (nth (seq (char-array name1)) i)))] (recur (inc i) (conj character-arr val))) character-arr)))) (println "sum-of-char >>>" sum-of-char) sum-of-char) (defn read-names [] (with-open [rdr (clojure.java.io/reader "names.txt")] (doseq [line (line-seq rdr)] (def us (clojure.string/replace line #"[\"]" "")) ;; (println us) (def us1 (clojure.string/split us #",")) ;; (println us1) ;; (println "sorted line >>>" (sort us1)) (def sorted-names-list (sort us1)) (println "count >>>" (count sorted-names-list)) (def name-list-length (count sorted-names-list)) (println "name list length " name-list-length) ;; (defn sum [x] (reduce + x)) (def sum-of-names (sum (loop [i 0 name-value-arr []] (if (< i name-list-length) (do (def n1 (nth sorted-names-list i)) ;; (println ">>>>>" n1 " is at postion " i) (def name-position-in-array (+ i 1)) ;; (println "npInArray add one to it >>>" name-position-in-array) (def name-value (* (find-char-value n1) name-position-in-array)) (println "sum of each char in a name MULTIPLIED by name position in array >>> " name-value) (recur (inc i) (conj name-value-arr name-value))) name-value-arr) ) ) ) (println "final value - NAME SCORE >>>> " sum-of-names) ) ) )
true
;; This program uses names.txt ;; execute this program at REPL prompt of clojure ;; copy this file and paste on REPL terminal (defn sum [x] (reduce + x)) (defn find-char-value [name1] (def stringmap {"A" 1, "B" 2, "C" 3, "D" 4, "E" 5, "F" 6, "G" 7, "H" 8, "I" 9, "J" 10, "K" 11, "L" 12, "M" 13, "N" 14, "O" 15, "P" 16, "Q" 17, "R" 18, "S" 19, "T" 20, "U" 21, "V" 22, "W" 23, "X" 24, "Y" 25, "Z" 26}) ;; (def name1 "PI:NAME:<NAME>END_PI") ;; (println "name length: " (count name1)) ;; (defn sum [x] (reduce + x)) (def sum-of-char (sum (loop [i 0 character-arr []] (if (< i (count name1)) (let [val (stringmap (str (nth (seq (char-array name1)) i)))] (recur (inc i) (conj character-arr val))) character-arr)))) (println "sum-of-char >>>" sum-of-char) sum-of-char) (defn read-names [] (with-open [rdr (clojure.java.io/reader "names.txt")] (doseq [line (line-seq rdr)] (def us (clojure.string/replace line #"[\"]" "")) ;; (println us) (def us1 (clojure.string/split us #",")) ;; (println us1) ;; (println "sorted line >>>" (sort us1)) (def sorted-names-list (sort us1)) (println "count >>>" (count sorted-names-list)) (def name-list-length (count sorted-names-list)) (println "name list length " name-list-length) ;; (defn sum [x] (reduce + x)) (def sum-of-names (sum (loop [i 0 name-value-arr []] (if (< i name-list-length) (do (def n1 (nth sorted-names-list i)) ;; (println ">>>>>" n1 " is at postion " i) (def name-position-in-array (+ i 1)) ;; (println "npInArray add one to it >>>" name-position-in-array) (def name-value (* (find-char-value n1) name-position-in-array)) (println "sum of each char in a name MULTIPLIED by name position in array >>> " name-value) (recur (inc i) (conj name-value-arr name-value))) name-value-arr) ) ) ) (println "final value - NAME SCORE >>>> " sum-of-names) ) ) )
[ { "context": ";; Copyright 2021 Zane Littrell\n;;\n;; Licensed under the Apache License, Version ", "end": 31, "score": 0.9998777508735657, "start": 18, "tag": "NAME", "value": "Zane Littrell" } ]
test/app/cells_test.clj
CapitalistLepton/nomenclature
0
;; Copyright 2021 Zane Littrell ;; ;; 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 app.cells-test (:require [clojure.test :refer [deftest is testing]] [app.cells :as cells])) (deftest make-entity-test (testing "Make a basic entity" (let [name [:A :1 :5] owner :testowner form :clay expected {:name name :owner owner :form form}] (is (= expected (cells/make-entity name owner form)))))) (deftest move-index-test (testing "Calculate new index correctly" (let [index 5 dx 1 dy 0 size 5] (is (= 6 (cells/move-index index [dx dy] size))))) (testing "Move past max index" (let [index 20 dx 0 dy 1 size 5] (is (= 0 (cells/move-index index [dx dy] size)))))) (deftest move-cells-test (testing "Move single entity correctly" (let [ent {:name [:2 :0 :0] :owner :player1 :form :clay} cells [ent nil nil nil] expected (list [1 ent] [1 nil] [2 nil] [3 nil])] (is (= expected (cells/move-cells cells 2)))))) (deftest filter-collisions-test (testing "Group collided entities" (let [ent {:name [:2 :0 :0] :owner :player1 :form :clay} indexed-cells (list [1 ent] [1 nil] [2 nil] [3 nil]) expected ['() (list ent) '() '()]] (is (= expected (cells/filter-collisions indexed-cells 2)))))) (deftest handle-collisions-test (testing "Test initial logic" (let [cell-list [[1 2] [3]] expected '(1 3)] (is (= expected (cells/handle-collisions cell-list))))) (testing "nil with empty list" (is (= '(nil) (cells/handle-collisions [[]])))))
100266
;; Copyright 2021 <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 app.cells-test (:require [clojure.test :refer [deftest is testing]] [app.cells :as cells])) (deftest make-entity-test (testing "Make a basic entity" (let [name [:A :1 :5] owner :testowner form :clay expected {:name name :owner owner :form form}] (is (= expected (cells/make-entity name owner form)))))) (deftest move-index-test (testing "Calculate new index correctly" (let [index 5 dx 1 dy 0 size 5] (is (= 6 (cells/move-index index [dx dy] size))))) (testing "Move past max index" (let [index 20 dx 0 dy 1 size 5] (is (= 0 (cells/move-index index [dx dy] size)))))) (deftest move-cells-test (testing "Move single entity correctly" (let [ent {:name [:2 :0 :0] :owner :player1 :form :clay} cells [ent nil nil nil] expected (list [1 ent] [1 nil] [2 nil] [3 nil])] (is (= expected (cells/move-cells cells 2)))))) (deftest filter-collisions-test (testing "Group collided entities" (let [ent {:name [:2 :0 :0] :owner :player1 :form :clay} indexed-cells (list [1 ent] [1 nil] [2 nil] [3 nil]) expected ['() (list ent) '() '()]] (is (= expected (cells/filter-collisions indexed-cells 2)))))) (deftest handle-collisions-test (testing "Test initial logic" (let [cell-list [[1 2] [3]] expected '(1 3)] (is (= expected (cells/handle-collisions cell-list))))) (testing "nil with empty list" (is (= '(nil) (cells/handle-collisions [[]])))))
true
;; Copyright 2021 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 app.cells-test (:require [clojure.test :refer [deftest is testing]] [app.cells :as cells])) (deftest make-entity-test (testing "Make a basic entity" (let [name [:A :1 :5] owner :testowner form :clay expected {:name name :owner owner :form form}] (is (= expected (cells/make-entity name owner form)))))) (deftest move-index-test (testing "Calculate new index correctly" (let [index 5 dx 1 dy 0 size 5] (is (= 6 (cells/move-index index [dx dy] size))))) (testing "Move past max index" (let [index 20 dx 0 dy 1 size 5] (is (= 0 (cells/move-index index [dx dy] size)))))) (deftest move-cells-test (testing "Move single entity correctly" (let [ent {:name [:2 :0 :0] :owner :player1 :form :clay} cells [ent nil nil nil] expected (list [1 ent] [1 nil] [2 nil] [3 nil])] (is (= expected (cells/move-cells cells 2)))))) (deftest filter-collisions-test (testing "Group collided entities" (let [ent {:name [:2 :0 :0] :owner :player1 :form :clay} indexed-cells (list [1 ent] [1 nil] [2 nil] [3 nil]) expected ['() (list ent) '() '()]] (is (= expected (cells/filter-collisions indexed-cells 2)))))) (deftest handle-collisions-test (testing "Test initial logic" (let [cell-list [[1 2] [3]] expected '(1 3)] (is (= expected (cells/handle-collisions cell-list))))) (testing "nil with empty list" (is (= '(nil) (cells/handle-collisions [[]])))))
[ { "context": "ge, London, All rights reserved.\n;\n; Contributors: Jony Hudson\n;\n; Released under the MIT license..\n;\n\n(ns darwi", "end": 134, "score": 0.9998077154159546, "start": 123, "tag": "NAME", "value": "Jony Hudson" } ]
src/darwin/evolution/pareto.clj
AlgorithmicScience/darwin
22
; ; This file is part of darwin. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: Jony Hudson ; ; Released under the MIT license.. ; (ns darwin.evolution.pareto "Functions for computing Pareto dominance, rank etc. Currently limited to two-objective comparison, but the API should be easy to extend to more.") (defn dominates "Does i1 Pareto-dominate i2, as judged by the values associated with the given keys, k1 and k2. Lower scores are considered better." [[k1 k2] i1 i2] (or (and (<= (k1 i1) (k1 i2)) (< (k2 i1) (k2 i2))) (and (<= (k2 i1) (k2 i2)) (< (k1 i1) (k1 i2))))) (defn dominated-set "Returns the individuals that i dominates wrt k1 and k2. Note that it doesn't return a set, rather a list (which I guess is a multiset) but `dominated-multiset` is too much of a mouthful." [[k1 k2] individuals i] (filter #(dominates [k1 k2] i %) individuals)) (defn dominator-set "Returns the individuals that dominate i wrt k1 and k2. As above, it doesn't return a set." [[k1 k2] individuals i] (filter #(dominates [k1 k2] % i) individuals)) (defn dominated-count "Count how many individuals i dominates wrt to k1 and k2." [[k1 k2] individuals i] (count (dominated-set [k1 k2] individuals i))) (defn- individual-dominated? "Is an individual i dominated by any of the given individuals wrt the keys k1 and k2?" [[k1 k2] individuals i] (reduce #(or %1 %2) (map #(dominates [k1 k2] % i) individuals))) (defn non-dominated-individuals "Returns the individuals that are non-dominated with respect to k1 and k2." [[k1 k2] individuals] (filter #(not (individual-dominated? [k1 k2] individuals %)) individuals))
68659
; ; This file is part of darwin. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: <NAME> ; ; Released under the MIT license.. ; (ns darwin.evolution.pareto "Functions for computing Pareto dominance, rank etc. Currently limited to two-objective comparison, but the API should be easy to extend to more.") (defn dominates "Does i1 Pareto-dominate i2, as judged by the values associated with the given keys, k1 and k2. Lower scores are considered better." [[k1 k2] i1 i2] (or (and (<= (k1 i1) (k1 i2)) (< (k2 i1) (k2 i2))) (and (<= (k2 i1) (k2 i2)) (< (k1 i1) (k1 i2))))) (defn dominated-set "Returns the individuals that i dominates wrt k1 and k2. Note that it doesn't return a set, rather a list (which I guess is a multiset) but `dominated-multiset` is too much of a mouthful." [[k1 k2] individuals i] (filter #(dominates [k1 k2] i %) individuals)) (defn dominator-set "Returns the individuals that dominate i wrt k1 and k2. As above, it doesn't return a set." [[k1 k2] individuals i] (filter #(dominates [k1 k2] % i) individuals)) (defn dominated-count "Count how many individuals i dominates wrt to k1 and k2." [[k1 k2] individuals i] (count (dominated-set [k1 k2] individuals i))) (defn- individual-dominated? "Is an individual i dominated by any of the given individuals wrt the keys k1 and k2?" [[k1 k2] individuals i] (reduce #(or %1 %2) (map #(dominates [k1 k2] % i) individuals))) (defn non-dominated-individuals "Returns the individuals that are non-dominated with respect to k1 and k2." [[k1 k2] individuals] (filter #(not (individual-dominated? [k1 k2] individuals %)) individuals))
true
; ; This file is part of darwin. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: PI:NAME:<NAME>END_PI ; ; Released under the MIT license.. ; (ns darwin.evolution.pareto "Functions for computing Pareto dominance, rank etc. Currently limited to two-objective comparison, but the API should be easy to extend to more.") (defn dominates "Does i1 Pareto-dominate i2, as judged by the values associated with the given keys, k1 and k2. Lower scores are considered better." [[k1 k2] i1 i2] (or (and (<= (k1 i1) (k1 i2)) (< (k2 i1) (k2 i2))) (and (<= (k2 i1) (k2 i2)) (< (k1 i1) (k1 i2))))) (defn dominated-set "Returns the individuals that i dominates wrt k1 and k2. Note that it doesn't return a set, rather a list (which I guess is a multiset) but `dominated-multiset` is too much of a mouthful." [[k1 k2] individuals i] (filter #(dominates [k1 k2] i %) individuals)) (defn dominator-set "Returns the individuals that dominate i wrt k1 and k2. As above, it doesn't return a set." [[k1 k2] individuals i] (filter #(dominates [k1 k2] % i) individuals)) (defn dominated-count "Count how many individuals i dominates wrt to k1 and k2." [[k1 k2] individuals i] (count (dominated-set [k1 k2] individuals i))) (defn- individual-dominated? "Is an individual i dominated by any of the given individuals wrt the keys k1 and k2?" [[k1 k2] individuals i] (reduce #(or %1 %2) (map #(dominates [k1 k2] % i) individuals))) (defn non-dominated-individuals "Returns the individuals that are non-dominated with respect to k1 and k2." [[k1 k2] individuals] (filter #(not (individual-dominated? [k1 k2] individuals %)) individuals))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.999811053276062, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
data/train/clojure/f6090d961ec94adfe37f359c9d5ceea2afb02869spec_test_instrument_debug.clj
harshp8l/deep-learning-lang-detection
84
; 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 adventofcode1.spec-test-instrument-debug (:refer-clojure :exclude [test]) (:require [clojure.pprint :as pp] [clojure.spec :as s] [clojure.spec.gen :as gen] [clojure.string :as str] [clojure.spec.test :as stest] )) (in-ns 'clojure.spec.test.check) (in-ns 'clojure.spec.test) ;;(alias 'stc 'clojure.spec.test.check) (defn spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (let [specs fn-spec] (let [cargs (when (:args specs) (conform! v :args (:args specs) args args)) ret (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args)) cret (when (:ret specs) (conform! v :ret (:ret specs) ret args))] (when (and (:args specs) (:ret specs) (:fn specs)) (conform! v :fn (:fn specs) {:args cargs :ret cret} args)) ret))) (.applyTo ^clojure.lang.IFn f args))))) (defn- instrument-1 [s opts] (when-let [v (resolve s)] (when-not (-> v meta :macro) (let [spec (s/get-spec v) {:keys [raw wrapped]} (get @instrumented-vars v) current @v to-wrap (if (= wrapped current) raw current) ospec (or (instrument-choose-spec spec s opts) (throw (no-fspec v spec))) ofn (instrument-choose-fn to-wrap ospec s opts) checked (spec-checking-fn v ofn ospec)] (alter-var-root v (constantly checked)) (swap! instrumented-vars assoc v {:raw to-wrap :wrapped checked}) (->sym v))))) (defn instrument "Instruments the vars named by sym-or-syms, a symbol or collection of symbols, or all instrumentable vars if sym-or-syms is not specified. If a var has an :args fn-spec, sets the var's root binding to a fn that checks arg conformance (throwing an exception on failure) before delegating to the original fn. The opts map can be used to override registered specs, and/or to replace fn implementations entirely. Opts for symbols not included in sym-or-syms are ignored. This facilitates sharing a common options map across many different calls to instrument. The opts map may have the following keys: :spec a map from var-name symbols to override specs :stub a set of var-name symbols to be replaced by stubs :gen a map from spec names to generator overrides :replace a map from var-name symbols to replacement fns :spec overrides registered fn-specs with specs your provide. Use :spec overrides to provide specs for libraries that do not have them, or to constrain your own use of a fn to a subset of its spec'ed contract. :stub replaces a fn with a stub that checks :args, then uses the :ret spec to generate a return value. :gen overrides are used only for :stub generation. :replace replaces a fn with a fn that checks args conformance, then invokes the fn you provide, enabling arbitrary stubbing and mocking. :spec can be used in combination with :stub or :replace. Returns a collection of syms naming the vars instrumented." ([] (instrument (instrumentable-syms))) ([sym-or-syms] (instrument sym-or-syms nil)) ([sym-or-syms opts] (locking instrumented-vars (into [] (comp (filter (instrumentable-syms opts)) (distinct) (map #(instrument-1 % opts)) (remove nil?)) (collectionize sym-or-syms))))) ;; old definition; https://github.com/clojure/clojure/blob/0bc837b9c25ae62185795b2bf2c7952bf6e12d9e/src/clj/clojure/spec.clj #_(defn- spec-checking-fn [v f] (let [conform! (fn [v role spec data args] (let [conformed (conform spec data)] (if (= ::invalid conformed) (let [ed (assoc (explain-data* spec [role] [] [] data) ::args args)] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (explain-out ed))) ed))) conformed)))] (c/fn [& args] (if *instrument-enabled* (with-instrument-disabled (let [specs (fn-specs v)] (let [cargs (when (:args specs) (conform! v :args (:args specs) args args)) ret (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args)) cret (when (:ret specs) (conform! v :ret (:ret specs) ret args))] (when (c/and (:args specs) (:ret specs) (:fn specs)) (conform! v :fn (:fn specs) {:args cargs :ret cret} args)) ret))) (.applyTo ^clojure.lang.IFn f args))))) ;; 1.9-alpha14 version #_(defn- spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (when (:args fn-spec) (conform! v :args (:args fn-spec) args args)) (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args))) (.applyTo ^clojure.lang.IFn f args)))))
20708
; 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 adventofcode1.spec-test-instrument-debug (:refer-clojure :exclude [test]) (:require [clojure.pprint :as pp] [clojure.spec :as s] [clojure.spec.gen :as gen] [clojure.string :as str] [clojure.spec.test :as stest] )) (in-ns 'clojure.spec.test.check) (in-ns 'clojure.spec.test) ;;(alias 'stc 'clojure.spec.test.check) (defn spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (let [specs fn-spec] (let [cargs (when (:args specs) (conform! v :args (:args specs) args args)) ret (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args)) cret (when (:ret specs) (conform! v :ret (:ret specs) ret args))] (when (and (:args specs) (:ret specs) (:fn specs)) (conform! v :fn (:fn specs) {:args cargs :ret cret} args)) ret))) (.applyTo ^clojure.lang.IFn f args))))) (defn- instrument-1 [s opts] (when-let [v (resolve s)] (when-not (-> v meta :macro) (let [spec (s/get-spec v) {:keys [raw wrapped]} (get @instrumented-vars v) current @v to-wrap (if (= wrapped current) raw current) ospec (or (instrument-choose-spec spec s opts) (throw (no-fspec v spec))) ofn (instrument-choose-fn to-wrap ospec s opts) checked (spec-checking-fn v ofn ospec)] (alter-var-root v (constantly checked)) (swap! instrumented-vars assoc v {:raw to-wrap :wrapped checked}) (->sym v))))) (defn instrument "Instruments the vars named by sym-or-syms, a symbol or collection of symbols, or all instrumentable vars if sym-or-syms is not specified. If a var has an :args fn-spec, sets the var's root binding to a fn that checks arg conformance (throwing an exception on failure) before delegating to the original fn. The opts map can be used to override registered specs, and/or to replace fn implementations entirely. Opts for symbols not included in sym-or-syms are ignored. This facilitates sharing a common options map across many different calls to instrument. The opts map may have the following keys: :spec a map from var-name symbols to override specs :stub a set of var-name symbols to be replaced by stubs :gen a map from spec names to generator overrides :replace a map from var-name symbols to replacement fns :spec overrides registered fn-specs with specs your provide. Use :spec overrides to provide specs for libraries that do not have them, or to constrain your own use of a fn to a subset of its spec'ed contract. :stub replaces a fn with a stub that checks :args, then uses the :ret spec to generate a return value. :gen overrides are used only for :stub generation. :replace replaces a fn with a fn that checks args conformance, then invokes the fn you provide, enabling arbitrary stubbing and mocking. :spec can be used in combination with :stub or :replace. Returns a collection of syms naming the vars instrumented." ([] (instrument (instrumentable-syms))) ([sym-or-syms] (instrument sym-or-syms nil)) ([sym-or-syms opts] (locking instrumented-vars (into [] (comp (filter (instrumentable-syms opts)) (distinct) (map #(instrument-1 % opts)) (remove nil?)) (collectionize sym-or-syms))))) ;; old definition; https://github.com/clojure/clojure/blob/0bc837b9c25ae62185795b2bf2c7952bf6e12d9e/src/clj/clojure/spec.clj #_(defn- spec-checking-fn [v f] (let [conform! (fn [v role spec data args] (let [conformed (conform spec data)] (if (= ::invalid conformed) (let [ed (assoc (explain-data* spec [role] [] [] data) ::args args)] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (explain-out ed))) ed))) conformed)))] (c/fn [& args] (if *instrument-enabled* (with-instrument-disabled (let [specs (fn-specs v)] (let [cargs (when (:args specs) (conform! v :args (:args specs) args args)) ret (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args)) cret (when (:ret specs) (conform! v :ret (:ret specs) ret args))] (when (c/and (:args specs) (:ret specs) (:fn specs)) (conform! v :fn (:fn specs) {:args cargs :ret cret} args)) ret))) (.applyTo ^clojure.lang.IFn f args))))) ;; 1.9-alpha14 version #_(defn- spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (when (:args fn-spec) (conform! v :args (:args fn-spec) args args)) (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args))) (.applyTo ^clojure.lang.IFn f 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. (ns adventofcode1.spec-test-instrument-debug (:refer-clojure :exclude [test]) (:require [clojure.pprint :as pp] [clojure.spec :as s] [clojure.spec.gen :as gen] [clojure.string :as str] [clojure.spec.test :as stest] )) (in-ns 'clojure.spec.test.check) (in-ns 'clojure.spec.test) ;;(alias 'stc 'clojure.spec.test.check) (defn spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (let [specs fn-spec] (let [cargs (when (:args specs) (conform! v :args (:args specs) args args)) ret (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args)) cret (when (:ret specs) (conform! v :ret (:ret specs) ret args))] (when (and (:args specs) (:ret specs) (:fn specs)) (conform! v :fn (:fn specs) {:args cargs :ret cret} args)) ret))) (.applyTo ^clojure.lang.IFn f args))))) (defn- instrument-1 [s opts] (when-let [v (resolve s)] (when-not (-> v meta :macro) (let [spec (s/get-spec v) {:keys [raw wrapped]} (get @instrumented-vars v) current @v to-wrap (if (= wrapped current) raw current) ospec (or (instrument-choose-spec spec s opts) (throw (no-fspec v spec))) ofn (instrument-choose-fn to-wrap ospec s opts) checked (spec-checking-fn v ofn ospec)] (alter-var-root v (constantly checked)) (swap! instrumented-vars assoc v {:raw to-wrap :wrapped checked}) (->sym v))))) (defn instrument "Instruments the vars named by sym-or-syms, a symbol or collection of symbols, or all instrumentable vars if sym-or-syms is not specified. If a var has an :args fn-spec, sets the var's root binding to a fn that checks arg conformance (throwing an exception on failure) before delegating to the original fn. The opts map can be used to override registered specs, and/or to replace fn implementations entirely. Opts for symbols not included in sym-or-syms are ignored. This facilitates sharing a common options map across many different calls to instrument. The opts map may have the following keys: :spec a map from var-name symbols to override specs :stub a set of var-name symbols to be replaced by stubs :gen a map from spec names to generator overrides :replace a map from var-name symbols to replacement fns :spec overrides registered fn-specs with specs your provide. Use :spec overrides to provide specs for libraries that do not have them, or to constrain your own use of a fn to a subset of its spec'ed contract. :stub replaces a fn with a stub that checks :args, then uses the :ret spec to generate a return value. :gen overrides are used only for :stub generation. :replace replaces a fn with a fn that checks args conformance, then invokes the fn you provide, enabling arbitrary stubbing and mocking. :spec can be used in combination with :stub or :replace. Returns a collection of syms naming the vars instrumented." ([] (instrument (instrumentable-syms))) ([sym-or-syms] (instrument sym-or-syms nil)) ([sym-or-syms opts] (locking instrumented-vars (into [] (comp (filter (instrumentable-syms opts)) (distinct) (map #(instrument-1 % opts)) (remove nil?)) (collectionize sym-or-syms))))) ;; old definition; https://github.com/clojure/clojure/blob/0bc837b9c25ae62185795b2bf2c7952bf6e12d9e/src/clj/clojure/spec.clj #_(defn- spec-checking-fn [v f] (let [conform! (fn [v role spec data args] (let [conformed (conform spec data)] (if (= ::invalid conformed) (let [ed (assoc (explain-data* spec [role] [] [] data) ::args args)] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (explain-out ed))) ed))) conformed)))] (c/fn [& args] (if *instrument-enabled* (with-instrument-disabled (let [specs (fn-specs v)] (let [cargs (when (:args specs) (conform! v :args (:args specs) args args)) ret (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args)) cret (when (:ret specs) (conform! v :ret (:ret specs) ret args))] (when (c/and (:args specs) (:ret specs) (:fn specs)) (conform! v :fn (:fn specs) {:args cargs :ret cret} args)) ret))) (.applyTo ^clojure.lang.IFn f args))))) ;; 1.9-alpha14 version #_(defn- spec-checking-fn [v f fn-spec] (let [fn-spec (@#'s/maybe-spec fn-spec) conform! (fn [v role spec data args] (let [conformed (s/conform spec data)] (if (= ::s/invalid conformed) (let [caller (->> (.getStackTrace (Thread/currentThread)) stacktrace-relevant-to-instrument first) ed (merge (assoc (s/explain-data* spec [role] [] [] data) ::s/args args ::s/failure :instrument) (when caller {::caller (dissoc caller :class :method)}))] (throw (ex-info (str "Call to " v " did not conform to spec:\n" (with-out-str (s/explain-out ed))) ed))) conformed)))] (fn [& args] (if *instrument-enabled* (with-instrument-disabled (when (:args fn-spec) (conform! v :args (:args fn-spec) args args)) (binding [*instrument-enabled* true] (.applyTo ^clojure.lang.IFn f args))) (.applyTo ^clojure.lang.IFn f args)))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998113512992859, "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.9998354911804199, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/tasks/leiningen/builtins.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 leiningen.builtins (:require [clojure.java.io :as io] [leiningen.util.http-cache :as http-cache])) (defn- builtins-zip [archive sha] (if sha (http-cache/download (format "https://%s/archive/%s/engine/share/builtins.zip" archive sha)) (io/file (format "%s/share/builtins.zip" (get (System/getenv) "DYNAMO_HOME"))))) (defn builtins [project & [git-sha]] (let [sha (or git-sha (:engine project)) archive-domain (get project :archive-domain)] (io/copy (builtins-zip archive-domain sha) (io/file "generated-resources/builtins.zip"))))
43145
;; 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 leiningen.builtins (:require [clojure.java.io :as io] [leiningen.util.http-cache :as http-cache])) (defn- builtins-zip [archive sha] (if sha (http-cache/download (format "https://%s/archive/%s/engine/share/builtins.zip" archive sha)) (io/file (format "%s/share/builtins.zip" (get (System/getenv) "DYNAMO_HOME"))))) (defn builtins [project & [git-sha]] (let [sha (or git-sha (:engine project)) archive-domain (get project :archive-domain)] (io/copy (builtins-zip archive-domain sha) (io/file "generated-resources/builtins.zip"))))
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 leiningen.builtins (:require [clojure.java.io :as io] [leiningen.util.http-cache :as http-cache])) (defn- builtins-zip [archive sha] (if sha (http-cache/download (format "https://%s/archive/%s/engine/share/builtins.zip" archive sha)) (io/file (format "%s/share/builtins.zip" (get (System/getenv) "DYNAMO_HOME"))))) (defn builtins [project & [git-sha]] (let [sha (or git-sha (:engine project)) archive-domain (get project :archive-domain)] (io/copy (builtins-zip archive-domain sha) (io/file "generated-resources/builtins.zip"))))
[ { "context": "makes-blood-puns? false, :has-pulse? true :name \"McFishwich\"}\n 1 {:makes-blood-puns? false, :has-pulse? tru", "end": 89, "score": 0.9770858883857727, "start": 79, "tag": "NAME", "value": "McFishwich" }, { "context": "makes-blood-puns? false, :has-pulse? true :name \"McMackson\"}\n 2 {:makes-blood-puns? true, :has-pulse? fal", "end": 158, "score": 0.9972068667411804, "start": 149, "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": 233, "score": 0.9997008442878723, "start": 218, "tag": "NAME", "value": "Damon Salvatore" }, { "context": "makes-blood-puns? true, :has-pulse? true :name \"Mickey Mouse\"}})\n \n (defn vampire-related-details\n [social-se", "end": 305, "score": 0.9992006421089172, "start": 293, "tag": "NAME", "value": "Mickey Mouse" } ]
clojure-noob/src/clojure_noob/vampireHunt.clj
christianzach/chz-clojure
0
(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)) (time (def mapped-details (map vampire-related-details (range 0 1000000)))) (time (identify-vampire (range 0 100000)))
2528
(def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "<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)) (time (def mapped-details (map vampire-related-details (range 0 1000000)))) (time (identify-vampire (range 0 100000)))
true
(def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "PI: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)) (time (def mapped-details (map vampire-related-details (range 0 1000000)))) (time (identify-vampire (range 0 100000)))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998208284378052, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
src/clj/cljm/compiler.clj
joshaber/clojurem
31
; 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. (set! *warn-on-reflection* true) (ns cljm.compiler (:refer-clojure :exclude [munge macroexpand-1]) (:require [clojure.java.io :as io] [clojure.string :as string] [cljm.tagged-literals :as tags] [cljm.analyzer :as ana] [clojure.pprint :as pp]) (:import java.lang.StringBuilder)) (declare munge) (declare init-func-name) (def include-core true) (def ^:dynamic *externs* nil) (def ^:dynamic *static-exprs* nil) (defmacro ^:private debug-prn [& args] `(.println System/err (str ~@args))) (def js-reserved #{"abstract" "boolean" "break" "byte" "case" "catch" "char" "class" "const" "continue" "debugger" "default" "delete" "do" "double" "else" "enum" "export" "extends" "final" "finally" "float" "for" "function" "goto" "if" "implements" "import" "in" "instanceof" "int" "interface" "let" "long" "native" "new" "package" "private" "protected" "public" "return" "short" "static" "super" "switch" "synchronized" "this" "throw" "throws" "transient" "try" "typeof" "var" "void" "volatile" "while" "with" "yield" "methods"}) (def ^:dynamic *position* nil) (def cljm-reserved-file-names #{"deps.cljm"}) (defn munge ([s] (munge s js-reserved)) ([s reserved] (let [ss (string/replace (str s) #"\/(.)" ".$1") ; Division is special ss (string/replace (str s) #"\." "_DOT_") ss (apply str (map #(if (reserved %) (str % "$") %) (string/split ss #"(?<=\.)|(?=\.)"))) ms (clojure.lang.Compiler/munge ss)] (if (symbol? s) (symbol ms) ms)))) (defn- comma-sep [xs] (interpose ", " xs)) (defn- escape-char [^Character c] (let [cp (.hashCode c)] (case cp ; Handle printable escapes before ASCII 34 "\\\"" 92 "\\\\" ; Handle non-printable escapes 8 "\\b" 12 "\\f" 10 "\\n" 13 "\\r" 9 "\\t" (if (< 31 cp 127) c ; Print simple ASCII characters (format "\\u%04X" cp))))) ; Any other character is Unicode (defn- escape-string [^CharSequence s] (let [sb (StringBuilder. (count s))] (doseq [c s] (.append sb (escape-char c))) (.toString sb))) (defn- wrap-in-double-quotes [x] (str \" x \")) (defmulti emit :op) (defn emits [& xs] (doseq [x xs] (cond (nil? x) nil (map? x) (emit x) (seq? x) (apply emits x) (fn? x) (x) :else (do (let [s (print-str x)] (when *position* (swap! *position* (fn [[line column]] [line (+ column (count s))]))) (print s))))) nil) (defn ^String emit-str [expr] (with-out-str (emit expr))) (defn emitln [& xs] (apply emits xs) ;; Prints column-aligned line number comments; good test of *position*. ;(when *position* ; (let [[line column] @*position*] ; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)]))))) (println) (when *position* (swap! *position* (fn [[line column]] [(inc line) 0]))) nil) (defn sel-parts "Splits a selector into its constituent parts, keeping any colons. Returns a sequence of strings." [sel] (map second (re-seq #"(:|[a-zA-Z0-9_]+\:?)" sel))) (defn- emit-comma-sep [xs] (doseq [x xs] (emits ", ") (emits x)) (emits ", nil")) (defn emit-method-parts "Given remaining selector parts and arguments, returns a string representing the rest of an Objective-C message send. selparts and args should both be sequences of strings." [selparts args] (emits (cond (empty? selparts) (emit-comma-sep args) (empty? args) (emits " " (first selparts)) :else (emits " " (first selparts) (first args))) ; If we had both a selector part and an argument this time, (if (and (and (seq selparts) (seq args)) ; ... and we have at least one more of either (or (next selparts) (next args))) ; ... recur (emit-method-parts (next selparts) (next args))))) (defmulti emit-constant class) (defmethod emit-constant nil [x] (emits "nil")) (defmethod emit-constant Long [x] (emits "@" x)) (defmethod emit-constant Integer [x] (emits "@" x)) ; reader puts Integers in metadata (defmethod emit-constant Double [x] (emits "@" x)) (defmethod emit-constant String [x] (emits "@" (wrap-in-double-quotes (escape-string x)))) (defmethod emit-constant Boolean [x] (emits (if x "@(YES)" "@(NO)"))) (defmethod emit-constant Character [x] (emits "@" (wrap-in-double-quotes (escape-char x)))) (defmethod emit-constant java.util.regex.Pattern [x] (let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))] (emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags))) (defmethod emit-constant clojure.lang.Keyword [x] (emits "cljm_keyword(@\":") (emits (if (namespace x) (str (namespace x) "/") "") (name x)) (emits "\")")) (defmethod emit-constant clojure.lang.Symbol [x] (emits "cljm_symbol(@\"'") (emits (if (namespace x) (str (namespace x) "/") "") (name x)) (emits "\")")) (defn- emit-meta-constant [x & body] (if (meta x) (do (emits "cljm.core.with_meta(" body ",") (emit-constant (meta x)) (emits ")")) (emits body))) (defmethod emit-constant clojure.lang.PersistentList$EmptyList [x] (emit-meta-constant x "@[]")) (defmethod emit-constant clojure.lang.PersistentList [x] (emit-meta-constant x (concat ["cljm.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.Cons [x] (emit-meta-constant x (concat ["cljm.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.IPersistentVector [x] (emit-meta-constant x (concat ["cljm.core.vec(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defmethod emit-constant clojure.lang.IPersistentMap [x] (emit-meta-constant x (concat ["cljm.core.hash_map("] (comma-sep (map #(fn [] (emit-constant %)) (apply concat x))) [")"]))) (defmethod emit-constant clojure.lang.PersistentHashSet [x] (emit-meta-constant x (concat ["cljm.core.set(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defn emit-block [context statements ret] (when statements (emits statements)) (emit ret)) (defmacro emit-wrap [env & body] `(let [env# ~env] (when (= :return (:context env#)) (emits "return ")) ~@body (when-not (= :expr (:context env#)) (emitln ";")))) (defmethod emit :no-op [m]) (defmethod emit :var [{:keys [info env] :as arg}] (let [n (:name info) n (if (= (namespace n) "js") (name n) n) dynamic (:dynamic info) local (:local info) field (:field info) ns (:ns info) type? (:type info) is-protocol? (:is-protocol info)] (emit-wrap env (if-not local (if is-protocol? (emits "@protocol(" (munge n) ")") (do (if-not dynamic (emits (munge n)) (emits "cljm_var_lookup(@\"" n "\")")) (if-not (or (= ns 'ObjectiveCClass) type?) (emits ".value")) (when (or (= ns 'ObjectiveCClass) type?) (emits ".class")))) (if field (emits "[self " (munge n) "]") (emits (munge n))))))) (defmethod emit :meta [{:keys [expr meta env]}] (emit-wrap env (emits "cljm.core.with_meta(" expr "," meta ")"))) (defmethod emit :map [{:keys [env keys vals]}] (emit-wrap env (if (zero? (count keys)) (emits "@{}") (emits "@{ " (comma-sep (map (fn [k v] (with-out-str (emit k) (print ": ") (emit v))) keys vals)) " }")))) (defmethod emit :vector [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "@[]") (emits "@[ " (comma-sep items) " ]")))) (defmethod emit :set [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "[NSSet set]") (emits "[NSSet setWithObjects:" (comma-sep items) ", nil]")))) (defmethod emit :constant [{:keys [form env]}] (when-not (= :statement (:context env)) (emit-wrap env (emit-constant form)))) (defn get-tag [e] (or (-> e :tag) (-> e :info :tag))) (defn infer-tag [e] (if-let [tag (get-tag e)] tag (case (:op e) :let (infer-tag (:ret e)) :if (let [then-tag (infer-tag (:then e)) else-tag (infer-tag (:else e))] (when (= then-tag else-tag) then-tag)) :constant (case (:form e) true 'boolean false 'boolean nil) nil))) (defn safe-test? [e] (let [tag (infer-tag e)] (or (#{'boolean 'seq} tag) (when (= (:op e) :constant) (let [form (:form e)] (not (or (and (string? form) (= form "")) (and (number? form) (zero? form))))))))) (defmethod emit :if [{:keys [test then else env]}] (let [context (:context env)] (if (= :expr context) (emits "cljm_truthy(" test ") ? " then " : " else) (do (emitln "if(cljm_truthy(" test ")) {") (emitln then) (emitln "} else {") (emitln else) (emitln "}"))))) (defmethod emit :throw [{:keys [throw env]}] (if (= :expr (:context env)) (emits "(function(){throw " throw "})()") (emitln "throw " throw ";"))) (defn emit-comment "Emit a nicely formatted comment string." [doc jsdoc] (let [docs (when doc [doc]) docs (if jsdoc (concat docs jsdoc) docs) docs (remove nil? docs)] (letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)] (emitln "* " (string/trim next-line))))] (when (seq docs) (emitln "/**") (doseq [e docs] (when e (print-comment-lines e))) (emitln "*/"))))) (defn add-extern! [ast] (swap! *externs* conj ast)) (defn add-static-expr! [ast] (swap! *static-exprs* conj ast)) (defmethod emit :def [{:keys [name init env doc dynamic protocol] :as ast}] ;; TODO: don't extern private fn's (if-not protocol (do (add-extern! ast) (when init (emit-comment doc (:jsdoc init)) (if-not dynamic (let [mname (munge name)] (emits mname " = [[CLJMVar alloc] initWithValue:" init "]")) (emits "cljm_var_def(@\"" name "\", " init ")")) (when-not (= :expr (:context env)) (emitln ";"))) (emitln)))) (defn emit-apply-to [{:keys [name params env]}] (let [arglist (gensym "arglist__") delegate-name (str (munge name) "__delegate") params (map munge params)] (emitln "(function (" arglist "){") (doseq [[i param] (map-indexed vector (butlast params))] (emits "var " param " = cljm.core.first(") (dotimes [_ i] (emits "cljm.core.next(")) (emits arglist ")") (dotimes [_ i] (emits ")")) (emitln ";")) (if (< 1 (count params)) (do (emits "var " (last params) " = cljm.core.rest(") (dotimes [_ (- (count params) 2)] (emits "cljm.core.next(")) (emits arglist) (dotimes [_ (- (count params) 2)] (emits ")")) (emitln ");") (emitln "return " delegate-name "(" (string/join ", " params) ");")) (do (emits "var " (last params) " = ") (emits "cljm.core.seq(" arglist ");") (emitln ";") (emitln "return " delegate-name "(" (string/join ", " params) ");"))) (emits "})"))) (defn emit-start-fn-var [args imp-fn] (emits "[[CLJMFunction alloc] initWithBlock:^ id (") (emits (comma-sep (map #(str "id " (munge %)) args))) (when-not imp-fn (when (> (count args) 0) (emits ", ")) (emits "id cljm_vararg, ...")) (emitln ") {")) (defn emit-end-fn-var [] (emitln "}]")) (defn emit-fn-method [{:keys [gthis name variadic params statements ret env recurs max-fixed-arity]} imp-fn] (emit-wrap env (emit-start-fn-var params imp-fn) (when imp-fn (let [n (munge (first params))] (when (not= n 'self) (emitln "id self = " n ";")))) (when recurs (emitln "while(YES) {")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emit-end-fn-var))) (defn emit-variadic-fn-method [{:keys [gthis name variadic params statements ret env recurs max-fixed-arity] :as f} imp-fn] (emit-wrap env (emit-start-fn-var (drop-last params) imp-fn) (when imp-fn (let [n (munge (first params))] (when (not= n 'self) (emitln "id self = " n ";")))) (let [lastn (munge (last params))] (emitln "NSMutableArray *" lastn " = [NSMutableArray array];") (emitln "va_list cljm_args;") (emitln "va_start(cljm_args, cljm_vararg);") (emitln "for (id cljm_currentArg = cljm_vararg; cljm_currentArg != nil; cljm_currentArg = va_arg(cljm_args, id)) {") (emitln "\t[" lastn " addObject:cljm_currentArg];") (emitln "}") (emitln "va_end(cljm_args);")) (when recurs (emitln "while(YES) {")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emit-end-fn-var))) (defmethod emit :fn [{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets imp-fn]}] ;;fn statements get erased, serve no purpose and can pollute scope if named (when-not (= :statement (:context env)) (let [loop-locals (->> (concat (mapcat :names (filter #(and % @(:flag %)) recur-frames)) (mapcat :names loop-lets)) (map munge) seq)] (when loop-locals (when (= :return (:context env)) (emits "return ")) (emitln "((function (" (comma-sep loop-locals) "){") (when-not (= :return (:context env)) (emits "return "))) (if (= 1 (count methods)) (if variadic (emit-variadic-fn-method (assoc (first methods) :name name) imp-fn) (emit-fn-method (assoc (first methods) :name name) imp-fn)) (let [has-name? (and name true) name (or name (gensym)) mname (munge name) maxparams (map munge (apply max-key count (map :params methods))) mmap (into {} (map (fn [method] [(munge (symbol (str mname "__" (count (:params method))))) method]) methods)) ms (sort-by #(-> % second :params count) (seq mmap))] (when (= :return (:context env)) (emits "return ")) (emitln "[[CLJMFunction alloc] initWithBlock:^ id (id cljm_vararg, ...) {") (emitln "__block CLJMVar *" mname ";") (doseq [[n meth] ms] (emits "CLJMFunction *" n " = ") (if (:variadic meth) (emit-variadic-fn-method meth imp-fn) (emit-fn-method meth imp-fn)) (emitln ";") (emitln)) (emitln mname " = [[CLJMVar alloc] initWithValue:[[CLJMFunction alloc] initWithBlock:^ id (NSArray *cljm_args) {") (emitln "switch(cljm_args.count) {") (doseq [[n meth] ms] (if (:variadic meth) (do (emitln "default:") (emitln "return ((id (^)(id, ...))[" n " block])(cljm_args[0], nil);") (emitln "break;")) (let [pcnt (count (:params meth))] (emitln "case " pcnt ":") (emits "return ((id (^)(id, ...))[" n " block])(") (dotimes [n pcnt] (emits "cljm_args[" n "], ")) (emits "nil);") ; (emitln "return ((id (^)(id, ...))[" n " block])(cljm_args[0], nil);") (emitln "break;")))) (emitln "}") (emitln "return nil;") (emitln "}]];") (emitln "NSMutableArray *cljm_collectedArgs = [NSMutableArray array];") (emitln "va_list cljm_args;") (emitln "va_start(cljm_args, cljm_vararg);") (emitln "for (id cljm_currentArg = cljm_vararg; cljm_currentArg != nil; cljm_currentArg = va_arg(cljm_args, id)) {") (emitln "\t[cljm_collectedArgs addObject:cljm_currentArg];") (emitln "}") (emitln "va_end(cljm_args);") (emitln "return ((id (^)(NSArray *))[(CLJMFunction *)[" mname " value] block])(cljm_collectedArgs);") (emitln "}]"))) (when loop-locals (emitln ";})(" (comma-sep loop-locals) "))"))))) (defmethod emit :do [{:keys [statements ret env]}] (let [context (:context env)] (when (and statements (= :expr context)) (emits "{")) ;(when statements (emitln "{")) (emit-block context statements ret) ;(when statements (emits "}")) (when (and statements (= :expr context)) (emits "}")))) (defmethod emit :try* [{:keys [env try catch name finally]}] (let [context (:context env) subcontext (if (= :expr context) :return context)] (if (or name finally) (do (when (= :expr context) (emits "(function (){")) (emits "try{") (let [{:keys [statements ret]} try] (emit-block subcontext statements ret)) (emits "}") (when name (emits "catch (" (munge name) "){") (when catch (let [{:keys [statements ret]} catch] (emit-block subcontext statements ret))) (emits "}")) (when finally (let [{:keys [statements ret]} finally] (assert (not= :constant (:op ret)) "finally block cannot contain constant") (emits "finally {") (emit-block subcontext statements ret) (emits "}"))) (when (= :expr context) (emits "})()"))) (let [{:keys [statements ret]} try] (when (and statements (= :expr context)) (emits "(function (){")) (emit-block subcontext statements ret) (when (and statements (= :expr context)) (emits "})()")))))) (defmethod emit :let [{:keys [bindings statements ret env loop]}] (let [context (:context env)] (when (= :expr context) (emits "^ id {")) (doseq [{:keys [name init]} bindings] (emitln "id " (munge name) " = " init ";")) (when loop (emitln "while(YES) {")) (emit-block (if (= :expr context) :return context) statements ret) (when loop (emitln "break;") (emitln "}")) ;(emits "}") (when (= :expr context) (emits "}()")))) (defmethod emit :recur [{:keys [frame exprs env]}] (let [temps (vec (take (count exprs) (repeatedly gensym))) names (:names frame)] (emitln "{") (dotimes [i (count exprs)] (emitln "id " (temps i) " = " (exprs i) ";")) (dotimes [i (count exprs)] (emitln (munge (names i)) " = " (temps i) ";")) (emitln "continue;") (emitln "}"))) (defmethod emit :letfn [{:keys [bindings statements ret env]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [name init]} bindings] (emitln "id " (munge name) " = " init ";")) (emit-block (if (= :expr context) :return context) statements ret) (when (= :expr context) (emits "})()")))) (defn protocol-prefix [psym] (str (-> (str psym) (.replace \. \$) (.replace \/ \$)) "$")) (defn protocol-munge [p x] (str (munge p) "_" (munge x))) (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) variadic? (:variadic info) dynamic? (:dynamic info) fn-name (:name info) mname (munge fn-name) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) kwname (-> f :form) protocol (:protocol info) local? (:local info) ns (:ns info) c-call? (= ns 'c)] (emit-wrap env (cond protocol (let [pmname (protocol-munge protocol (apply str (drop 1 (last (string/split (str fn-name) #"/")))))] (emits "[(id<" (munge protocol) ">) " (first args) " ") (emits pmname) (doseq [arg (rest args)] (emits ":" arg " ")) (emits "]")) keyword? (emits "[" (first args) " objectForKey:cljm_keyword(@\"" kwname "\")]") c-call? (emits (name fn-name) "(" (comma-sep args) ")") :else (do (emits "((id (^)(") (emits (comma-sep (map (fn [x] (str "id")) (concat args (list "cljm_args"))))) (emits ", ...))") (if-not local? (emits "[")) (emits "(CLJMFunction *)[") (if dynamic? (emits "cljm_var_lookup(@\"" fn-name "\")") (emits mname)) (if-not local? (emits " value]")) (emits " block])(") (emits (comma-sep (conj args "nil")) ")")))))) (comment (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) fn? (and ana/*cljm-static-fns* (not (:dynamic info)) (:fn-var info)) protocol (:protocol info) proto? (let [tag (infer-tag (first (:args expr)))] (and protocol tag (or ana/*cljm-static-fns* (:protocol-inline env)) (or (= protocol tag) (when-let [ps (:protocols (ana/resolve-existing-var (dissoc env :locals) tag))] (ps protocol))))) opt-not? (and (= (:name info) 'cljm.core/not) (= (infer-tag (first (:args expr))) 'boolean)) ns (:ns info) js? (= ns 'js) goog? (when ns (or (= ns 'goog) (when-let [ns-str (str ns)] (= (get (string/split ns-str #"\.") 0 nil) "goog")))) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) [f variadic-invoke] (if fn? (let [arity (count args) variadic? (:variadic info) mps (:method-params info) mfa (:max-fixed-arity info)] (cond ;; if only one method, no renaming needed (and (not variadic?) (= (count mps) 1)) [f nil] ;; direct dispatch to variadic case (and variadic? (> arity mfa)) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljm$lang$arity$variadic")))) {:max-fixed-arity mfa}] ;; direct dispatch to specific arity case :else (let [arities (map count mps)] (if (some #{arity} arities) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljm$lang$arity$" arity)))) nil] [f nil])))) [f nil])] (emit-wrap env (cond opt-not? (emits "!(" (first args) ")") proto? (let [pimpl (str (protocol-prefix protocol) (munge (name (:name info))) "$arity$" (count args))] (emits (first args) "." pimpl "(" (comma-sep args) ")")) keyword? (emits "(new cljm.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")") variadic-invoke (let [mfa (:max-fixed-arity variadic-invoke)] (emits f "(" (comma-sep (take mfa args)) (when-not (zero? mfa) ",") "cljm.core.array_seq([" (comma-sep (drop mfa args)) "], 0))")) (or fn? js? goog?) (emits f "(" (comma-sep args) ")") :else (if (and ana/*cljm-static-fns* (= (:op f) :var)) (let [fprop (str ".cljm$lang$arity$" (count args))] (emits "(" f fprop " ? " f fprop "(" (comma-sep args) ") : " f ".call(" (comma-sep (cons "null" args)) "))")) (if variadic? (emits f "(" (comma-sep args) ", nil)") (emits f "(" (comma-sep args) ")")))))))) (defmethod emit :new [{:keys [ctor args env]}] (emit-wrap env (let [method (first args) init-args (rest args) init-meth (if (seq args) (reduce (fn [xs x] (str xs ":")) "initWithFields" args) "init")] (emits "[[" ctor " alloc]") (emit-method-parts (sel-parts init-meth) args) (emits "]")))) (defmethod emit :set! [{:keys [target val env]}] (emit-wrap env (emits target " = " val))) (defmethod emit :ns [{:keys [name requires uses requires-macros env]}] (emitln "#import <Foundation/Foundation.h>") (emitln "#import <CLJMRuntime/CLJMRuntime.h>") (emitln "#import <objc/runtime.h>") (when include-core (when-not (= name 'cljm.core) (emitln "#import \"cljm_DOT_core.h\""))) (emitln "#import \"" (munge name) ".h\"") (doseq [lib (into (vals requires) (distinct (vals uses)))] (emitln "#import \"" (munge lib) ".h\""))) (defmethod emit :defprotocol* [ast] (add-extern! ast)) (defmethod emit :deftype* [{:keys [t fields pmasks reify] :as ast}] (when-not reify (add-extern! ast) (add-static-expr! ast))) (defmethod emit :defrecord* [{:keys [t fields pmasks]}] (let [fields (concat (map munge fields) '[__meta __extmap])] (emitln "") (emitln "/**") (emitln "* @constructor") (doseq [fld fields] (emitln "* @param {*} " fld)) (emitln "* @param {*=} __meta ") (emitln "* @param {*=} __extmap") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljm$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "if(arguments.length>" (- (count fields) 2) "){") (emitln "this.__meta = __meta;") (emitln "this.__extmap = __extmap;") (emitln "} else {") (emits "this.__meta=") (emit-constant nil) (emitln ";") (emits "this.__extmap=") (emit-constant nil) (emitln ";") (emitln "}") (emitln "})"))) (defmethod emit :dot [{:keys [target field method args env]}] (emit-wrap env (if field (emits "[" target " " (munge field #{}) "]") (do (emits "[" target) (emit-method-parts (sel-parts (str method)) args) (emits "]"))))) (defmethod emit :objc [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defmethod emit :js [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defmulti emit-static :op) (declare objc-class-munge) (defmethod emit-static :deftype* [{:keys [t methods]}] (emitln) (emitln "@implementation " (objc-class-munge t)) (emitln "@end") (emitln)) (defn forms-seq "Seq of forms in a Clojure or ClojureScript file." ([f] (forms-seq f (clojure.lang.LineNumberingPushbackReader. (io/reader f)))) ([f ^java.io.PushbackReader rdr] (if-let [form (binding [*ns* ana/*reader-ns*] (read rdr nil nil))] (lazy-seq (cons form (forms-seq f rdr))) (.close rdr)))) (defn rename-to "Change the file extension from .cljm to .m. Takes a File or a String. Always returns a String." [file-str ext] (clojure.string/replace file-str #"\.cljm$" ext)) (defn mkdirs "Create all parent directories for the passed file." [^java.io.File f] (.mkdirs (.getParentFile (.getCanonicalFile f)))) (defmacro with-core-cljm "Ensure that core.cljm has been loaded." [& body] `(do (when include-core (when-not (:defs (get @ana/namespaces 'cljm.core)) (ana/analyze-file "cljm/core.cljm"))) ~@body)) (defn compile-file* [src dest] (with-core-cljm (with-open [out ^java.io.Writer (io/make-writer dest {})] (binding [*out* out ana/*cljm-ns* 'cljm.user ana/*cljm-file* (.getPath ^java.io.File src) *data-readers* tags/*cljm-data-readers* *position* (atom [0 0]) *static-exprs* (atom [])] (loop [forms (forms-seq src) ns-name nil deps nil] (if (seq forms) (let [env (ana/empty-env) ast (ana/analyze env (first forms))] ; (binding [*out* *err*] ; (println "Goodbye, world!") ; (clojure.pprint/pprint ast)) (emit ast) (if (= (:op ast) :ns) (let [found-ns (:name ast)] ; TODO: It'd be nice to only init namespaces that are ; actually used. (emitln "__attribute__((constructor))") (emitln "void " (init-func-name found-ns) "(void) {\n") (emitln "@autoreleasepool {") (recur (rest forms) found-ns (merge (:uses ast) (:requires ast)))) (recur (rest forms) ns-name deps))) (do (emitln "}") (emitln "}") (doseq [ast @*static-exprs*] (emit-static ast)) {:ns (or ns-name 'cljm.user) :provides [ns-name] :requires (if (= ns-name 'cljm.core) (set (vals deps)) (conj (set (vals deps)) 'cljm.core)) :file dest}))))))) (defn requires-compilation? "Return true if the src file requires compilation." [^java.io.File src ^java.io.File dest] ; for the sake of debugging right now, we'll always recompile everything true) ; (or (not (.exists dest)) ; (> (.lastModified src) (.lastModified dest)))) (defmulti emit-h :op) (defmethod emit-h :defprotocol* [{:keys [p index methods]}] (emitln) (emitln "@protocol " (munge p) " <NSObject>") (emitln) (doseq [method methods] (let [mname (protocol-munge p (apply str (drop 1 (seq (str (first method)))))) arities (take-while vector? (drop 1 method)) has-comment? (string? (last method)) comment (if has-comment? (last method) nil)] (when has-comment? (emit-comment comment "")) (doseq [arity arities] (emits "- (id)" mname) (doseq [arg (drop 1 arity)] (emits ":(id)" (munge arg) " ")) (emits ";") (emitln)) (emitln))) (emitln) (emitln "@end") (emitln)) (defmethod emit-h :def [ast] (let [mname (munge (:name ast))] (emitln "CLJMVar *" mname ";"))) (defn- objc-class-munge [t] (if (= (string/upper-case (namespace t)) (namespace t)) (str (namespace t) (name t)) (munge t))) (defn- selector-name [sel] (let [ssel (seq sel)] (apply str (cond (= (first ssel) \-) (drop 1 ssel) (= (last ssel) \!) (drop-last ssel) :else ssel)))) (defmethod emit-h :deftype* [{:keys [t fields superclass protocols methods env] :as ast}] (emitln) (let [class-name (objc-class-munge t) superclass (objc-class-munge superclass)] (emits "@interface " class-name " : " superclass)) (when (seq? (seq protocols)) (emits " <" (comma-sep (map objc-class-munge protocols)) ">")) (emitln) (emitln) (doseq [p fields] (let [tag (-> p meta :tag) type (cond (= 'iboutlet tag) "IBOutlet id" nil? "id" :else tag)] (emitln "@property (nonatomic, strong) " type " " (munge p) ";"))) (emitln) (doseq [[p ms] methods] (doseq [m ms] (let [p-ns (:ns (ana/resolve-existing-var (dissoc env :locals) p)) prefix (if (= p-ns 'ObjectiveCClass) "" (str (munge (str p-ns "/" p)) "_")) mname (str prefix (selector-name (str (first m)))) parts (string/split mname #":") pair-args (fn [sel arg] (str (munge sel) ":(id)" (munge arg) " ")) args (drop 1 (second m)) sel-parts (if (seq args) (apply str (map pair-args (concat parts (repeat "")) args)) (str (first parts)))] (emitln "- (id)" sel-parts ";") (emitln)))) (emitln) (emitln "@end") (emitln)) (defn generate-header [externs file] (let [dest-file (io/file file)] (with-open [out ^java.io.Writer (io/make-writer dest-file {})] (binding [*out* out] (emitln "@class CLJMVar;") (emitln) (doseq [ast externs] (emit-h ast)))))) (defn compile-file "Compiles src to a file of the same name, but with a .js extension, in the src file's directory. With dest argument, write file to provided location. If the dest argument is a file outside the source tree, missing parent directories will be created. The src file will only be compiled if the dest file has an older modification time. Both src and dest may be either a String or a File. Returns a map containing {:ns .. :provides .. :requires .. :file ..}. If the file was not compiled returns only {:file ...}" ([src] (let [dest (rename-to src ".m")] (compile-file src dest))) ([src dest] (binding [*externs* (atom [])] (let [src-file (io/file src) dest-file (io/file dest)] (if (.exists src-file) (if (requires-compilation? src-file dest-file) (do (mkdirs dest-file) (assoc (compile-file* src-file dest-file) :externs @*externs*)) {:file dest-file, :externs []}) (throw (java.io.FileNotFoundException. (str "The file " src " does not exist.")))))))) (defn init-func-name [ns] (munge (str ns "/cljm-ns-init"))) (comment ;; flex compile-file (do (compile-file "/tmp/hello.cljm" "/tmp/something.js") (slurp "/tmp/hello.js") (compile-file "/tmp/somescript.cljm") (slurp "/tmp/somescript.js"))) (defn path-seq [file-str] (->> java.io.File/separator java.util.regex.Pattern/quote re-pattern (string/split file-str))) (defn to-path ([parts] (to-path parts java.io.File/separator)) ([parts sep] (apply str (interpose sep parts)))) (defn to-target-file "Given the source root directory, the output target directory and file under the source root, produce the target file." [^java.io.File dir ^String target ^java.io.File file ext] (let [dir-path (path-seq (.getAbsolutePath dir)) file-path (path-seq (.getAbsolutePath file)) relative-path (drop (count dir-path) file-path) parents (butlast relative-path) parent-file (java.io.File. ^String (to-path (cons target parents)))] (java.io.File. parent-file ^String (rename-to (last relative-path) ext)))) (defn cljm-files-in "Return a sequence of all .cljm files in the given directory." [dir] (filter #(let [name (.getName ^java.io.File %)] (and (.endsWith name ".cljm") (not= \. (first name)) (not (contains? cljm-reserved-file-names name)))) (file-seq dir))) (defn move-and-rename [^java.io.File m-file ^java.io.File h-file ns target-dir] (let [mname (munge ns)] (.renameTo m-file (java.io.File. (str target-dir java.io.File/separator mname ".m"))) (.renameTo h-file (java.io.File. (str target-dir java.io.File/separator mname ".h"))))) (defn compile-root "Looks recursively in src-dir for .cljm files and compiles them to .m files. If target-dir is provided, output will go into this directory mirroring the source directory structure. Returns a list of maps containing information about each file which was compiled in dependency order." ([src-dir] (compile-root src-dir "out")) ([src-dir target-dir] (let [src-dir-file (io/file src-dir)] (loop [cljm-files (cljm-files-in src-dir-file) output-files []] (if (seq cljm-files) (let [cljm-file (first cljm-files) m-file ^java.io.File (to-target-file src-dir-file target-dir cljm-file ".m") h-file ^java.io.File (to-target-file src-dir-file target-dir cljm-file ".h") ns-info (compile-file cljm-file m-file)] (generate-header (:externs ns-info) h-file) (move-and-rename m-file h-file (:ns ns-info) target-dir) (recur (rest cljm-files) (conj output-files (assoc ns-info :file-name (.getPath m-file))))) output-files)))))
79540
; 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. (set! *warn-on-reflection* true) (ns cljm.compiler (:refer-clojure :exclude [munge macroexpand-1]) (:require [clojure.java.io :as io] [clojure.string :as string] [cljm.tagged-literals :as tags] [cljm.analyzer :as ana] [clojure.pprint :as pp]) (:import java.lang.StringBuilder)) (declare munge) (declare init-func-name) (def include-core true) (def ^:dynamic *externs* nil) (def ^:dynamic *static-exprs* nil) (defmacro ^:private debug-prn [& args] `(.println System/err (str ~@args))) (def js-reserved #{"abstract" "boolean" "break" "byte" "case" "catch" "char" "class" "const" "continue" "debugger" "default" "delete" "do" "double" "else" "enum" "export" "extends" "final" "finally" "float" "for" "function" "goto" "if" "implements" "import" "in" "instanceof" "int" "interface" "let" "long" "native" "new" "package" "private" "protected" "public" "return" "short" "static" "super" "switch" "synchronized" "this" "throw" "throws" "transient" "try" "typeof" "var" "void" "volatile" "while" "with" "yield" "methods"}) (def ^:dynamic *position* nil) (def cljm-reserved-file-names #{"deps.cljm"}) (defn munge ([s] (munge s js-reserved)) ([s reserved] (let [ss (string/replace (str s) #"\/(.)" ".$1") ; Division is special ss (string/replace (str s) #"\." "_DOT_") ss (apply str (map #(if (reserved %) (str % "$") %) (string/split ss #"(?<=\.)|(?=\.)"))) ms (clojure.lang.Compiler/munge ss)] (if (symbol? s) (symbol ms) ms)))) (defn- comma-sep [xs] (interpose ", " xs)) (defn- escape-char [^Character c] (let [cp (.hashCode c)] (case cp ; Handle printable escapes before ASCII 34 "\\\"" 92 "\\\\" ; Handle non-printable escapes 8 "\\b" 12 "\\f" 10 "\\n" 13 "\\r" 9 "\\t" (if (< 31 cp 127) c ; Print simple ASCII characters (format "\\u%04X" cp))))) ; Any other character is Unicode (defn- escape-string [^CharSequence s] (let [sb (StringBuilder. (count s))] (doseq [c s] (.append sb (escape-char c))) (.toString sb))) (defn- wrap-in-double-quotes [x] (str \" x \")) (defmulti emit :op) (defn emits [& xs] (doseq [x xs] (cond (nil? x) nil (map? x) (emit x) (seq? x) (apply emits x) (fn? x) (x) :else (do (let [s (print-str x)] (when *position* (swap! *position* (fn [[line column]] [line (+ column (count s))]))) (print s))))) nil) (defn ^String emit-str [expr] (with-out-str (emit expr))) (defn emitln [& xs] (apply emits xs) ;; Prints column-aligned line number comments; good test of *position*. ;(when *position* ; (let [[line column] @*position*] ; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)]))))) (println) (when *position* (swap! *position* (fn [[line column]] [(inc line) 0]))) nil) (defn sel-parts "Splits a selector into its constituent parts, keeping any colons. Returns a sequence of strings." [sel] (map second (re-seq #"(:|[a-zA-Z0-9_]+\:?)" sel))) (defn- emit-comma-sep [xs] (doseq [x xs] (emits ", ") (emits x)) (emits ", nil")) (defn emit-method-parts "Given remaining selector parts and arguments, returns a string representing the rest of an Objective-C message send. selparts and args should both be sequences of strings." [selparts args] (emits (cond (empty? selparts) (emit-comma-sep args) (empty? args) (emits " " (first selparts)) :else (emits " " (first selparts) (first args))) ; If we had both a selector part and an argument this time, (if (and (and (seq selparts) (seq args)) ; ... and we have at least one more of either (or (next selparts) (next args))) ; ... recur (emit-method-parts (next selparts) (next args))))) (defmulti emit-constant class) (defmethod emit-constant nil [x] (emits "nil")) (defmethod emit-constant Long [x] (emits "@" x)) (defmethod emit-constant Integer [x] (emits "@" x)) ; reader puts Integers in metadata (defmethod emit-constant Double [x] (emits "@" x)) (defmethod emit-constant String [x] (emits "@" (wrap-in-double-quotes (escape-string x)))) (defmethod emit-constant Boolean [x] (emits (if x "@(YES)" "@(NO)"))) (defmethod emit-constant Character [x] (emits "@" (wrap-in-double-quotes (escape-char x)))) (defmethod emit-constant java.util.regex.Pattern [x] (let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))] (emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags))) (defmethod emit-constant clojure.lang.Keyword [x] (emits "cljm_keyword(@\":") (emits (if (namespace x) (str (namespace x) "/") "") (name x)) (emits "\")")) (defmethod emit-constant clojure.lang.Symbol [x] (emits "cljm_symbol(@\"'") (emits (if (namespace x) (str (namespace x) "/") "") (name x)) (emits "\")")) (defn- emit-meta-constant [x & body] (if (meta x) (do (emits "cljm.core.with_meta(" body ",") (emit-constant (meta x)) (emits ")")) (emits body))) (defmethod emit-constant clojure.lang.PersistentList$EmptyList [x] (emit-meta-constant x "@[]")) (defmethod emit-constant clojure.lang.PersistentList [x] (emit-meta-constant x (concat ["cljm.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.Cons [x] (emit-meta-constant x (concat ["cljm.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.IPersistentVector [x] (emit-meta-constant x (concat ["cljm.core.vec(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defmethod emit-constant clojure.lang.IPersistentMap [x] (emit-meta-constant x (concat ["cljm.core.hash_map("] (comma-sep (map #(fn [] (emit-constant %)) (apply concat x))) [")"]))) (defmethod emit-constant clojure.lang.PersistentHashSet [x] (emit-meta-constant x (concat ["cljm.core.set(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defn emit-block [context statements ret] (when statements (emits statements)) (emit ret)) (defmacro emit-wrap [env & body] `(let [env# ~env] (when (= :return (:context env#)) (emits "return ")) ~@body (when-not (= :expr (:context env#)) (emitln ";")))) (defmethod emit :no-op [m]) (defmethod emit :var [{:keys [info env] :as arg}] (let [n (:name info) n (if (= (namespace n) "js") (name n) n) dynamic (:dynamic info) local (:local info) field (:field info) ns (:ns info) type? (:type info) is-protocol? (:is-protocol info)] (emit-wrap env (if-not local (if is-protocol? (emits "@protocol(" (munge n) ")") (do (if-not dynamic (emits (munge n)) (emits "cljm_var_lookup(@\"" n "\")")) (if-not (or (= ns 'ObjectiveCClass) type?) (emits ".value")) (when (or (= ns 'ObjectiveCClass) type?) (emits ".class")))) (if field (emits "[self " (munge n) "]") (emits (munge n))))))) (defmethod emit :meta [{:keys [expr meta env]}] (emit-wrap env (emits "cljm.core.with_meta(" expr "," meta ")"))) (defmethod emit :map [{:keys [env keys vals]}] (emit-wrap env (if (zero? (count keys)) (emits "@{}") (emits "@{ " (comma-sep (map (fn [k v] (with-out-str (emit k) (print ": ") (emit v))) keys vals)) " }")))) (defmethod emit :vector [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "@[]") (emits "@[ " (comma-sep items) " ]")))) (defmethod emit :set [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "[NSSet set]") (emits "[NSSet setWithObjects:" (comma-sep items) ", nil]")))) (defmethod emit :constant [{:keys [form env]}] (when-not (= :statement (:context env)) (emit-wrap env (emit-constant form)))) (defn get-tag [e] (or (-> e :tag) (-> e :info :tag))) (defn infer-tag [e] (if-let [tag (get-tag e)] tag (case (:op e) :let (infer-tag (:ret e)) :if (let [then-tag (infer-tag (:then e)) else-tag (infer-tag (:else e))] (when (= then-tag else-tag) then-tag)) :constant (case (:form e) true 'boolean false 'boolean nil) nil))) (defn safe-test? [e] (let [tag (infer-tag e)] (or (#{'boolean 'seq} tag) (when (= (:op e) :constant) (let [form (:form e)] (not (or (and (string? form) (= form "")) (and (number? form) (zero? form))))))))) (defmethod emit :if [{:keys [test then else env]}] (let [context (:context env)] (if (= :expr context) (emits "cljm_truthy(" test ") ? " then " : " else) (do (emitln "if(cljm_truthy(" test ")) {") (emitln then) (emitln "} else {") (emitln else) (emitln "}"))))) (defmethod emit :throw [{:keys [throw env]}] (if (= :expr (:context env)) (emits "(function(){throw " throw "})()") (emitln "throw " throw ";"))) (defn emit-comment "Emit a nicely formatted comment string." [doc jsdoc] (let [docs (when doc [doc]) docs (if jsdoc (concat docs jsdoc) docs) docs (remove nil? docs)] (letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)] (emitln "* " (string/trim next-line))))] (when (seq docs) (emitln "/**") (doseq [e docs] (when e (print-comment-lines e))) (emitln "*/"))))) (defn add-extern! [ast] (swap! *externs* conj ast)) (defn add-static-expr! [ast] (swap! *static-exprs* conj ast)) (defmethod emit :def [{:keys [name init env doc dynamic protocol] :as ast}] ;; TODO: don't extern private fn's (if-not protocol (do (add-extern! ast) (when init (emit-comment doc (:jsdoc init)) (if-not dynamic (let [mname (munge name)] (emits mname " = [[CLJMVar alloc] initWithValue:" init "]")) (emits "cljm_var_def(@\"" name "\", " init ")")) (when-not (= :expr (:context env)) (emitln ";"))) (emitln)))) (defn emit-apply-to [{:keys [name params env]}] (let [arglist (gensym "arglist__") delegate-name (str (munge name) "__delegate") params (map munge params)] (emitln "(function (" arglist "){") (doseq [[i param] (map-indexed vector (butlast params))] (emits "var " param " = cljm.core.first(") (dotimes [_ i] (emits "cljm.core.next(")) (emits arglist ")") (dotimes [_ i] (emits ")")) (emitln ";")) (if (< 1 (count params)) (do (emits "var " (last params) " = cljm.core.rest(") (dotimes [_ (- (count params) 2)] (emits "cljm.core.next(")) (emits arglist) (dotimes [_ (- (count params) 2)] (emits ")")) (emitln ");") (emitln "return " delegate-name "(" (string/join ", " params) ");")) (do (emits "var " (last params) " = ") (emits "cljm.core.seq(" arglist ");") (emitln ";") (emitln "return " delegate-name "(" (string/join ", " params) ");"))) (emits "})"))) (defn emit-start-fn-var [args imp-fn] (emits "[[CLJMFunction alloc] initWithBlock:^ id (") (emits (comma-sep (map #(str "id " (munge %)) args))) (when-not imp-fn (when (> (count args) 0) (emits ", ")) (emits "id cljm_vararg, ...")) (emitln ") {")) (defn emit-end-fn-var [] (emitln "}]")) (defn emit-fn-method [{:keys [gthis name variadic params statements ret env recurs max-fixed-arity]} imp-fn] (emit-wrap env (emit-start-fn-var params imp-fn) (when imp-fn (let [n (munge (first params))] (when (not= n 'self) (emitln "id self = " n ";")))) (when recurs (emitln "while(YES) {")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emit-end-fn-var))) (defn emit-variadic-fn-method [{:keys [gthis name variadic params statements ret env recurs max-fixed-arity] :as f} imp-fn] (emit-wrap env (emit-start-fn-var (drop-last params) imp-fn) (when imp-fn (let [n (munge (first params))] (when (not= n 'self) (emitln "id self = " n ";")))) (let [lastn (munge (last params))] (emitln "NSMutableArray *" lastn " = [NSMutableArray array];") (emitln "va_list cljm_args;") (emitln "va_start(cljm_args, cljm_vararg);") (emitln "for (id cljm_currentArg = cljm_vararg; cljm_currentArg != nil; cljm_currentArg = va_arg(cljm_args, id)) {") (emitln "\t[" lastn " addObject:cljm_currentArg];") (emitln "}") (emitln "va_end(cljm_args);")) (when recurs (emitln "while(YES) {")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emit-end-fn-var))) (defmethod emit :fn [{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets imp-fn]}] ;;fn statements get erased, serve no purpose and can pollute scope if named (when-not (= :statement (:context env)) (let [loop-locals (->> (concat (mapcat :names (filter #(and % @(:flag %)) recur-frames)) (mapcat :names loop-lets)) (map munge) seq)] (when loop-locals (when (= :return (:context env)) (emits "return ")) (emitln "((function (" (comma-sep loop-locals) "){") (when-not (= :return (:context env)) (emits "return "))) (if (= 1 (count methods)) (if variadic (emit-variadic-fn-method (assoc (first methods) :name name) imp-fn) (emit-fn-method (assoc (first methods) :name name) imp-fn)) (let [has-name? (and name true) name (or name (gensym)) mname (munge name) maxparams (map munge (apply max-key count (map :params methods))) mmap (into {} (map (fn [method] [(munge (symbol (str mname "__" (count (:params method))))) method]) methods)) ms (sort-by #(-> % second :params count) (seq mmap))] (when (= :return (:context env)) (emits "return ")) (emitln "[[CLJMFunction alloc] initWithBlock:^ id (id cljm_vararg, ...) {") (emitln "__block CLJMVar *" mname ";") (doseq [[n meth] ms] (emits "CLJMFunction *" n " = ") (if (:variadic meth) (emit-variadic-fn-method meth imp-fn) (emit-fn-method meth imp-fn)) (emitln ";") (emitln)) (emitln mname " = [[CLJMVar alloc] initWithValue:[[CLJMFunction alloc] initWithBlock:^ id (NSArray *cljm_args) {") (emitln "switch(cljm_args.count) {") (doseq [[n meth] ms] (if (:variadic meth) (do (emitln "default:") (emitln "return ((id (^)(id, ...))[" n " block])(cljm_args[0], nil);") (emitln "break;")) (let [pcnt (count (:params meth))] (emitln "case " pcnt ":") (emits "return ((id (^)(id, ...))[" n " block])(") (dotimes [n pcnt] (emits "cljm_args[" n "], ")) (emits "nil);") ; (emitln "return ((id (^)(id, ...))[" n " block])(cljm_args[0], nil);") (emitln "break;")))) (emitln "}") (emitln "return nil;") (emitln "}]];") (emitln "NSMutableArray *cljm_collectedArgs = [NSMutableArray array];") (emitln "va_list cljm_args;") (emitln "va_start(cljm_args, cljm_vararg);") (emitln "for (id cljm_currentArg = cljm_vararg; cljm_currentArg != nil; cljm_currentArg = va_arg(cljm_args, id)) {") (emitln "\t[cljm_collectedArgs addObject:cljm_currentArg];") (emitln "}") (emitln "va_end(cljm_args);") (emitln "return ((id (^)(NSArray *))[(CLJMFunction *)[" mname " value] block])(cljm_collectedArgs);") (emitln "}]"))) (when loop-locals (emitln ";})(" (comma-sep loop-locals) "))"))))) (defmethod emit :do [{:keys [statements ret env]}] (let [context (:context env)] (when (and statements (= :expr context)) (emits "{")) ;(when statements (emitln "{")) (emit-block context statements ret) ;(when statements (emits "}")) (when (and statements (= :expr context)) (emits "}")))) (defmethod emit :try* [{:keys [env try catch name finally]}] (let [context (:context env) subcontext (if (= :expr context) :return context)] (if (or name finally) (do (when (= :expr context) (emits "(function (){")) (emits "try{") (let [{:keys [statements ret]} try] (emit-block subcontext statements ret)) (emits "}") (when name (emits "catch (" (munge name) "){") (when catch (let [{:keys [statements ret]} catch] (emit-block subcontext statements ret))) (emits "}")) (when finally (let [{:keys [statements ret]} finally] (assert (not= :constant (:op ret)) "finally block cannot contain constant") (emits "finally {") (emit-block subcontext statements ret) (emits "}"))) (when (= :expr context) (emits "})()"))) (let [{:keys [statements ret]} try] (when (and statements (= :expr context)) (emits "(function (){")) (emit-block subcontext statements ret) (when (and statements (= :expr context)) (emits "})()")))))) (defmethod emit :let [{:keys [bindings statements ret env loop]}] (let [context (:context env)] (when (= :expr context) (emits "^ id {")) (doseq [{:keys [name init]} bindings] (emitln "id " (munge name) " = " init ";")) (when loop (emitln "while(YES) {")) (emit-block (if (= :expr context) :return context) statements ret) (when loop (emitln "break;") (emitln "}")) ;(emits "}") (when (= :expr context) (emits "}()")))) (defmethod emit :recur [{:keys [frame exprs env]}] (let [temps (vec (take (count exprs) (repeatedly gensym))) names (:names frame)] (emitln "{") (dotimes [i (count exprs)] (emitln "id " (temps i) " = " (exprs i) ";")) (dotimes [i (count exprs)] (emitln (munge (names i)) " = " (temps i) ";")) (emitln "continue;") (emitln "}"))) (defmethod emit :letfn [{:keys [bindings statements ret env]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [name init]} bindings] (emitln "id " (munge name) " = " init ";")) (emit-block (if (= :expr context) :return context) statements ret) (when (= :expr context) (emits "})()")))) (defn protocol-prefix [psym] (str (-> (str psym) (.replace \. \$) (.replace \/ \$)) "$")) (defn protocol-munge [p x] (str (munge p) "_" (munge x))) (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) variadic? (:variadic info) dynamic? (:dynamic info) fn-name (:name info) mname (munge fn-name) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) kwname (-> f :form) protocol (:protocol info) local? (:local info) ns (:ns info) c-call? (= ns 'c)] (emit-wrap env (cond protocol (let [pmname (protocol-munge protocol (apply str (drop 1 (last (string/split (str fn-name) #"/")))))] (emits "[(id<" (munge protocol) ">) " (first args) " ") (emits pmname) (doseq [arg (rest args)] (emits ":" arg " ")) (emits "]")) keyword? (emits "[" (first args) " objectForKey:cljm_keyword(@\"" kwname "\")]") c-call? (emits (name fn-name) "(" (comma-sep args) ")") :else (do (emits "((id (^)(") (emits (comma-sep (map (fn [x] (str "id")) (concat args (list "cljm_args"))))) (emits ", ...))") (if-not local? (emits "[")) (emits "(CLJMFunction *)[") (if dynamic? (emits "cljm_var_lookup(@\"" fn-name "\")") (emits mname)) (if-not local? (emits " value]")) (emits " block])(") (emits (comma-sep (conj args "nil")) ")")))))) (comment (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) fn? (and ana/*cljm-static-fns* (not (:dynamic info)) (:fn-var info)) protocol (:protocol info) proto? (let [tag (infer-tag (first (:args expr)))] (and protocol tag (or ana/*cljm-static-fns* (:protocol-inline env)) (or (= protocol tag) (when-let [ps (:protocols (ana/resolve-existing-var (dissoc env :locals) tag))] (ps protocol))))) opt-not? (and (= (:name info) 'cljm.core/not) (= (infer-tag (first (:args expr))) 'boolean)) ns (:ns info) js? (= ns 'js) goog? (when ns (or (= ns 'goog) (when-let [ns-str (str ns)] (= (get (string/split ns-str #"\.") 0 nil) "goog")))) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) [f variadic-invoke] (if fn? (let [arity (count args) variadic? (:variadic info) mps (:method-params info) mfa (:max-fixed-arity info)] (cond ;; if only one method, no renaming needed (and (not variadic?) (= (count mps) 1)) [f nil] ;; direct dispatch to variadic case (and variadic? (> arity mfa)) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljm$lang$arity$variadic")))) {:max-fixed-arity mfa}] ;; direct dispatch to specific arity case :else (let [arities (map count mps)] (if (some #{arity} arities) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljm$lang$arity$" arity)))) nil] [f nil])))) [f nil])] (emit-wrap env (cond opt-not? (emits "!(" (first args) ")") proto? (let [pimpl (str (protocol-prefix protocol) (munge (name (:name info))) "$arity$" (count args))] (emits (first args) "." pimpl "(" (comma-sep args) ")")) keyword? (emits "(new cljm.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")") variadic-invoke (let [mfa (:max-fixed-arity variadic-invoke)] (emits f "(" (comma-sep (take mfa args)) (when-not (zero? mfa) ",") "cljm.core.array_seq([" (comma-sep (drop mfa args)) "], 0))")) (or fn? js? goog?) (emits f "(" (comma-sep args) ")") :else (if (and ana/*cljm-static-fns* (= (:op f) :var)) (let [fprop (str ".cljm$lang$arity$" (count args))] (emits "(" f fprop " ? " f fprop "(" (comma-sep args) ") : " f ".call(" (comma-sep (cons "null" args)) "))")) (if variadic? (emits f "(" (comma-sep args) ", nil)") (emits f "(" (comma-sep args) ")")))))))) (defmethod emit :new [{:keys [ctor args env]}] (emit-wrap env (let [method (first args) init-args (rest args) init-meth (if (seq args) (reduce (fn [xs x] (str xs ":")) "initWithFields" args) "init")] (emits "[[" ctor " alloc]") (emit-method-parts (sel-parts init-meth) args) (emits "]")))) (defmethod emit :set! [{:keys [target val env]}] (emit-wrap env (emits target " = " val))) (defmethod emit :ns [{:keys [name requires uses requires-macros env]}] (emitln "#import <Foundation/Foundation.h>") (emitln "#import <CLJMRuntime/CLJMRuntime.h>") (emitln "#import <objc/runtime.h>") (when include-core (when-not (= name 'cljm.core) (emitln "#import \"cljm_DOT_core.h\""))) (emitln "#import \"" (munge name) ".h\"") (doseq [lib (into (vals requires) (distinct (vals uses)))] (emitln "#import \"" (munge lib) ".h\""))) (defmethod emit :defprotocol* [ast] (add-extern! ast)) (defmethod emit :deftype* [{:keys [t fields pmasks reify] :as ast}] (when-not reify (add-extern! ast) (add-static-expr! ast))) (defmethod emit :defrecord* [{:keys [t fields pmasks]}] (let [fields (concat (map munge fields) '[__meta __extmap])] (emitln "") (emitln "/**") (emitln "* @constructor") (doseq [fld fields] (emitln "* @param {*} " fld)) (emitln "* @param {*=} __meta ") (emitln "* @param {*=} __extmap") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljm$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "if(arguments.length>" (- (count fields) 2) "){") (emitln "this.__meta = __meta;") (emitln "this.__extmap = __extmap;") (emitln "} else {") (emits "this.__meta=") (emit-constant nil) (emitln ";") (emits "this.__extmap=") (emit-constant nil) (emitln ";") (emitln "}") (emitln "})"))) (defmethod emit :dot [{:keys [target field method args env]}] (emit-wrap env (if field (emits "[" target " " (munge field #{}) "]") (do (emits "[" target) (emit-method-parts (sel-parts (str method)) args) (emits "]"))))) (defmethod emit :objc [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defmethod emit :js [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defmulti emit-static :op) (declare objc-class-munge) (defmethod emit-static :deftype* [{:keys [t methods]}] (emitln) (emitln "@implementation " (objc-class-munge t)) (emitln "@end") (emitln)) (defn forms-seq "Seq of forms in a Clojure or ClojureScript file." ([f] (forms-seq f (clojure.lang.LineNumberingPushbackReader. (io/reader f)))) ([f ^java.io.PushbackReader rdr] (if-let [form (binding [*ns* ana/*reader-ns*] (read rdr nil nil))] (lazy-seq (cons form (forms-seq f rdr))) (.close rdr)))) (defn rename-to "Change the file extension from .cljm to .m. Takes a File or a String. Always returns a String." [file-str ext] (clojure.string/replace file-str #"\.cljm$" ext)) (defn mkdirs "Create all parent directories for the passed file." [^java.io.File f] (.mkdirs (.getParentFile (.getCanonicalFile f)))) (defmacro with-core-cljm "Ensure that core.cljm has been loaded." [& body] `(do (when include-core (when-not (:defs (get @ana/namespaces 'cljm.core)) (ana/analyze-file "cljm/core.cljm"))) ~@body)) (defn compile-file* [src dest] (with-core-cljm (with-open [out ^java.io.Writer (io/make-writer dest {})] (binding [*out* out ana/*cljm-ns* 'cljm.user ana/*cljm-file* (.getPath ^java.io.File src) *data-readers* tags/*cljm-data-readers* *position* (atom [0 0]) *static-exprs* (atom [])] (loop [forms (forms-seq src) ns-name nil deps nil] (if (seq forms) (let [env (ana/empty-env) ast (ana/analyze env (first forms))] ; (binding [*out* *err*] ; (println "Goodbye, world!") ; (clojure.pprint/pprint ast)) (emit ast) (if (= (:op ast) :ns) (let [found-ns (:name ast)] ; TODO: It'd be nice to only init namespaces that are ; actually used. (emitln "__attribute__((constructor))") (emitln "void " (init-func-name found-ns) "(void) {\n") (emitln "@autoreleasepool {") (recur (rest forms) found-ns (merge (:uses ast) (:requires ast)))) (recur (rest forms) ns-name deps))) (do (emitln "}") (emitln "}") (doseq [ast @*static-exprs*] (emit-static ast)) {:ns (or ns-name 'cljm.user) :provides [ns-name] :requires (if (= ns-name 'cljm.core) (set (vals deps)) (conj (set (vals deps)) 'cljm.core)) :file dest}))))))) (defn requires-compilation? "Return true if the src file requires compilation." [^java.io.File src ^java.io.File dest] ; for the sake of debugging right now, we'll always recompile everything true) ; (or (not (.exists dest)) ; (> (.lastModified src) (.lastModified dest)))) (defmulti emit-h :op) (defmethod emit-h :defprotocol* [{:keys [p index methods]}] (emitln) (emitln "@protocol " (munge p) " <NSObject>") (emitln) (doseq [method methods] (let [mname (protocol-munge p (apply str (drop 1 (seq (str (first method)))))) arities (take-while vector? (drop 1 method)) has-comment? (string? (last method)) comment (if has-comment? (last method) nil)] (when has-comment? (emit-comment comment "")) (doseq [arity arities] (emits "- (id)" mname) (doseq [arg (drop 1 arity)] (emits ":(id)" (munge arg) " ")) (emits ";") (emitln)) (emitln))) (emitln) (emitln "@end") (emitln)) (defmethod emit-h :def [ast] (let [mname (munge (:name ast))] (emitln "CLJMVar *" mname ";"))) (defn- objc-class-munge [t] (if (= (string/upper-case (namespace t)) (namespace t)) (str (namespace t) (name t)) (munge t))) (defn- selector-name [sel] (let [ssel (seq sel)] (apply str (cond (= (first ssel) \-) (drop 1 ssel) (= (last ssel) \!) (drop-last ssel) :else ssel)))) (defmethod emit-h :deftype* [{:keys [t fields superclass protocols methods env] :as ast}] (emitln) (let [class-name (objc-class-munge t) superclass (objc-class-munge superclass)] (emits "@interface " class-name " : " superclass)) (when (seq? (seq protocols)) (emits " <" (comma-sep (map objc-class-munge protocols)) ">")) (emitln) (emitln) (doseq [p fields] (let [tag (-> p meta :tag) type (cond (= 'iboutlet tag) "IBOutlet id" nil? "id" :else tag)] (emitln "@property (nonatomic, strong) " type " " (munge p) ";"))) (emitln) (doseq [[p ms] methods] (doseq [m ms] (let [p-ns (:ns (ana/resolve-existing-var (dissoc env :locals) p)) prefix (if (= p-ns 'ObjectiveCClass) "" (str (munge (str p-ns "/" p)) "_")) mname (str prefix (selector-name (str (first m)))) parts (string/split mname #":") pair-args (fn [sel arg] (str (munge sel) ":(id)" (munge arg) " ")) args (drop 1 (second m)) sel-parts (if (seq args) (apply str (map pair-args (concat parts (repeat "")) args)) (str (first parts)))] (emitln "- (id)" sel-parts ";") (emitln)))) (emitln) (emitln "@end") (emitln)) (defn generate-header [externs file] (let [dest-file (io/file file)] (with-open [out ^java.io.Writer (io/make-writer dest-file {})] (binding [*out* out] (emitln "@class CLJMVar;") (emitln) (doseq [ast externs] (emit-h ast)))))) (defn compile-file "Compiles src to a file of the same name, but with a .js extension, in the src file's directory. With dest argument, write file to provided location. If the dest argument is a file outside the source tree, missing parent directories will be created. The src file will only be compiled if the dest file has an older modification time. Both src and dest may be either a String or a File. Returns a map containing {:ns .. :provides .. :requires .. :file ..}. If the file was not compiled returns only {:file ...}" ([src] (let [dest (rename-to src ".m")] (compile-file src dest))) ([src dest] (binding [*externs* (atom [])] (let [src-file (io/file src) dest-file (io/file dest)] (if (.exists src-file) (if (requires-compilation? src-file dest-file) (do (mkdirs dest-file) (assoc (compile-file* src-file dest-file) :externs @*externs*)) {:file dest-file, :externs []}) (throw (java.io.FileNotFoundException. (str "The file " src " does not exist.")))))))) (defn init-func-name [ns] (munge (str ns "/cljm-ns-init"))) (comment ;; flex compile-file (do (compile-file "/tmp/hello.cljm" "/tmp/something.js") (slurp "/tmp/hello.js") (compile-file "/tmp/somescript.cljm") (slurp "/tmp/somescript.js"))) (defn path-seq [file-str] (->> java.io.File/separator java.util.regex.Pattern/quote re-pattern (string/split file-str))) (defn to-path ([parts] (to-path parts java.io.File/separator)) ([parts sep] (apply str (interpose sep parts)))) (defn to-target-file "Given the source root directory, the output target directory and file under the source root, produce the target file." [^java.io.File dir ^String target ^java.io.File file ext] (let [dir-path (path-seq (.getAbsolutePath dir)) file-path (path-seq (.getAbsolutePath file)) relative-path (drop (count dir-path) file-path) parents (butlast relative-path) parent-file (java.io.File. ^String (to-path (cons target parents)))] (java.io.File. parent-file ^String (rename-to (last relative-path) ext)))) (defn cljm-files-in "Return a sequence of all .cljm files in the given directory." [dir] (filter #(let [name (.getName ^java.io.File %)] (and (.endsWith name ".cljm") (not= \. (first name)) (not (contains? cljm-reserved-file-names name)))) (file-seq dir))) (defn move-and-rename [^java.io.File m-file ^java.io.File h-file ns target-dir] (let [mname (munge ns)] (.renameTo m-file (java.io.File. (str target-dir java.io.File/separator mname ".m"))) (.renameTo h-file (java.io.File. (str target-dir java.io.File/separator mname ".h"))))) (defn compile-root "Looks recursively in src-dir for .cljm files and compiles them to .m files. If target-dir is provided, output will go into this directory mirroring the source directory structure. Returns a list of maps containing information about each file which was compiled in dependency order." ([src-dir] (compile-root src-dir "out")) ([src-dir target-dir] (let [src-dir-file (io/file src-dir)] (loop [cljm-files (cljm-files-in src-dir-file) output-files []] (if (seq cljm-files) (let [cljm-file (first cljm-files) m-file ^java.io.File (to-target-file src-dir-file target-dir cljm-file ".m") h-file ^java.io.File (to-target-file src-dir-file target-dir cljm-file ".h") ns-info (compile-file cljm-file m-file)] (generate-header (:externs ns-info) h-file) (move-and-rename m-file h-file (:ns ns-info) target-dir) (recur (rest cljm-files) (conj output-files (assoc ns-info :file-name (.getPath m-file))))) output-files)))))
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. (set! *warn-on-reflection* true) (ns cljm.compiler (:refer-clojure :exclude [munge macroexpand-1]) (:require [clojure.java.io :as io] [clojure.string :as string] [cljm.tagged-literals :as tags] [cljm.analyzer :as ana] [clojure.pprint :as pp]) (:import java.lang.StringBuilder)) (declare munge) (declare init-func-name) (def include-core true) (def ^:dynamic *externs* nil) (def ^:dynamic *static-exprs* nil) (defmacro ^:private debug-prn [& args] `(.println System/err (str ~@args))) (def js-reserved #{"abstract" "boolean" "break" "byte" "case" "catch" "char" "class" "const" "continue" "debugger" "default" "delete" "do" "double" "else" "enum" "export" "extends" "final" "finally" "float" "for" "function" "goto" "if" "implements" "import" "in" "instanceof" "int" "interface" "let" "long" "native" "new" "package" "private" "protected" "public" "return" "short" "static" "super" "switch" "synchronized" "this" "throw" "throws" "transient" "try" "typeof" "var" "void" "volatile" "while" "with" "yield" "methods"}) (def ^:dynamic *position* nil) (def cljm-reserved-file-names #{"deps.cljm"}) (defn munge ([s] (munge s js-reserved)) ([s reserved] (let [ss (string/replace (str s) #"\/(.)" ".$1") ; Division is special ss (string/replace (str s) #"\." "_DOT_") ss (apply str (map #(if (reserved %) (str % "$") %) (string/split ss #"(?<=\.)|(?=\.)"))) ms (clojure.lang.Compiler/munge ss)] (if (symbol? s) (symbol ms) ms)))) (defn- comma-sep [xs] (interpose ", " xs)) (defn- escape-char [^Character c] (let [cp (.hashCode c)] (case cp ; Handle printable escapes before ASCII 34 "\\\"" 92 "\\\\" ; Handle non-printable escapes 8 "\\b" 12 "\\f" 10 "\\n" 13 "\\r" 9 "\\t" (if (< 31 cp 127) c ; Print simple ASCII characters (format "\\u%04X" cp))))) ; Any other character is Unicode (defn- escape-string [^CharSequence s] (let [sb (StringBuilder. (count s))] (doseq [c s] (.append sb (escape-char c))) (.toString sb))) (defn- wrap-in-double-quotes [x] (str \" x \")) (defmulti emit :op) (defn emits [& xs] (doseq [x xs] (cond (nil? x) nil (map? x) (emit x) (seq? x) (apply emits x) (fn? x) (x) :else (do (let [s (print-str x)] (when *position* (swap! *position* (fn [[line column]] [line (+ column (count s))]))) (print s))))) nil) (defn ^String emit-str [expr] (with-out-str (emit expr))) (defn emitln [& xs] (apply emits xs) ;; Prints column-aligned line number comments; good test of *position*. ;(when *position* ; (let [[line column] @*position*] ; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)]))))) (println) (when *position* (swap! *position* (fn [[line column]] [(inc line) 0]))) nil) (defn sel-parts "Splits a selector into its constituent parts, keeping any colons. Returns a sequence of strings." [sel] (map second (re-seq #"(:|[a-zA-Z0-9_]+\:?)" sel))) (defn- emit-comma-sep [xs] (doseq [x xs] (emits ", ") (emits x)) (emits ", nil")) (defn emit-method-parts "Given remaining selector parts and arguments, returns a string representing the rest of an Objective-C message send. selparts and args should both be sequences of strings." [selparts args] (emits (cond (empty? selparts) (emit-comma-sep args) (empty? args) (emits " " (first selparts)) :else (emits " " (first selparts) (first args))) ; If we had both a selector part and an argument this time, (if (and (and (seq selparts) (seq args)) ; ... and we have at least one more of either (or (next selparts) (next args))) ; ... recur (emit-method-parts (next selparts) (next args))))) (defmulti emit-constant class) (defmethod emit-constant nil [x] (emits "nil")) (defmethod emit-constant Long [x] (emits "@" x)) (defmethod emit-constant Integer [x] (emits "@" x)) ; reader puts Integers in metadata (defmethod emit-constant Double [x] (emits "@" x)) (defmethod emit-constant String [x] (emits "@" (wrap-in-double-quotes (escape-string x)))) (defmethod emit-constant Boolean [x] (emits (if x "@(YES)" "@(NO)"))) (defmethod emit-constant Character [x] (emits "@" (wrap-in-double-quotes (escape-char x)))) (defmethod emit-constant java.util.regex.Pattern [x] (let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))] (emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags))) (defmethod emit-constant clojure.lang.Keyword [x] (emits "cljm_keyword(@\":") (emits (if (namespace x) (str (namespace x) "/") "") (name x)) (emits "\")")) (defmethod emit-constant clojure.lang.Symbol [x] (emits "cljm_symbol(@\"'") (emits (if (namespace x) (str (namespace x) "/") "") (name x)) (emits "\")")) (defn- emit-meta-constant [x & body] (if (meta x) (do (emits "cljm.core.with_meta(" body ",") (emit-constant (meta x)) (emits ")")) (emits body))) (defmethod emit-constant clojure.lang.PersistentList$EmptyList [x] (emit-meta-constant x "@[]")) (defmethod emit-constant clojure.lang.PersistentList [x] (emit-meta-constant x (concat ["cljm.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.Cons [x] (emit-meta-constant x (concat ["cljm.core.list("] (comma-sep (map #(fn [] (emit-constant %)) x)) [")"]))) (defmethod emit-constant clojure.lang.IPersistentVector [x] (emit-meta-constant x (concat ["cljm.core.vec(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defmethod emit-constant clojure.lang.IPersistentMap [x] (emit-meta-constant x (concat ["cljm.core.hash_map("] (comma-sep (map #(fn [] (emit-constant %)) (apply concat x))) [")"]))) (defmethod emit-constant clojure.lang.PersistentHashSet [x] (emit-meta-constant x (concat ["cljm.core.set(["] (comma-sep (map #(fn [] (emit-constant %)) x)) ["])"]))) (defn emit-block [context statements ret] (when statements (emits statements)) (emit ret)) (defmacro emit-wrap [env & body] `(let [env# ~env] (when (= :return (:context env#)) (emits "return ")) ~@body (when-not (= :expr (:context env#)) (emitln ";")))) (defmethod emit :no-op [m]) (defmethod emit :var [{:keys [info env] :as arg}] (let [n (:name info) n (if (= (namespace n) "js") (name n) n) dynamic (:dynamic info) local (:local info) field (:field info) ns (:ns info) type? (:type info) is-protocol? (:is-protocol info)] (emit-wrap env (if-not local (if is-protocol? (emits "@protocol(" (munge n) ")") (do (if-not dynamic (emits (munge n)) (emits "cljm_var_lookup(@\"" n "\")")) (if-not (or (= ns 'ObjectiveCClass) type?) (emits ".value")) (when (or (= ns 'ObjectiveCClass) type?) (emits ".class")))) (if field (emits "[self " (munge n) "]") (emits (munge n))))))) (defmethod emit :meta [{:keys [expr meta env]}] (emit-wrap env (emits "cljm.core.with_meta(" expr "," meta ")"))) (defmethod emit :map [{:keys [env keys vals]}] (emit-wrap env (if (zero? (count keys)) (emits "@{}") (emits "@{ " (comma-sep (map (fn [k v] (with-out-str (emit k) (print ": ") (emit v))) keys vals)) " }")))) (defmethod emit :vector [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "@[]") (emits "@[ " (comma-sep items) " ]")))) (defmethod emit :set [{:keys [items env]}] (emit-wrap env (if (empty? items) (emits "[NSSet set]") (emits "[NSSet setWithObjects:" (comma-sep items) ", nil]")))) (defmethod emit :constant [{:keys [form env]}] (when-not (= :statement (:context env)) (emit-wrap env (emit-constant form)))) (defn get-tag [e] (or (-> e :tag) (-> e :info :tag))) (defn infer-tag [e] (if-let [tag (get-tag e)] tag (case (:op e) :let (infer-tag (:ret e)) :if (let [then-tag (infer-tag (:then e)) else-tag (infer-tag (:else e))] (when (= then-tag else-tag) then-tag)) :constant (case (:form e) true 'boolean false 'boolean nil) nil))) (defn safe-test? [e] (let [tag (infer-tag e)] (or (#{'boolean 'seq} tag) (when (= (:op e) :constant) (let [form (:form e)] (not (or (and (string? form) (= form "")) (and (number? form) (zero? form))))))))) (defmethod emit :if [{:keys [test then else env]}] (let [context (:context env)] (if (= :expr context) (emits "cljm_truthy(" test ") ? " then " : " else) (do (emitln "if(cljm_truthy(" test ")) {") (emitln then) (emitln "} else {") (emitln else) (emitln "}"))))) (defmethod emit :throw [{:keys [throw env]}] (if (= :expr (:context env)) (emits "(function(){throw " throw "})()") (emitln "throw " throw ";"))) (defn emit-comment "Emit a nicely formatted comment string." [doc jsdoc] (let [docs (when doc [doc]) docs (if jsdoc (concat docs jsdoc) docs) docs (remove nil? docs)] (letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)] (emitln "* " (string/trim next-line))))] (when (seq docs) (emitln "/**") (doseq [e docs] (when e (print-comment-lines e))) (emitln "*/"))))) (defn add-extern! [ast] (swap! *externs* conj ast)) (defn add-static-expr! [ast] (swap! *static-exprs* conj ast)) (defmethod emit :def [{:keys [name init env doc dynamic protocol] :as ast}] ;; TODO: don't extern private fn's (if-not protocol (do (add-extern! ast) (when init (emit-comment doc (:jsdoc init)) (if-not dynamic (let [mname (munge name)] (emits mname " = [[CLJMVar alloc] initWithValue:" init "]")) (emits "cljm_var_def(@\"" name "\", " init ")")) (when-not (= :expr (:context env)) (emitln ";"))) (emitln)))) (defn emit-apply-to [{:keys [name params env]}] (let [arglist (gensym "arglist__") delegate-name (str (munge name) "__delegate") params (map munge params)] (emitln "(function (" arglist "){") (doseq [[i param] (map-indexed vector (butlast params))] (emits "var " param " = cljm.core.first(") (dotimes [_ i] (emits "cljm.core.next(")) (emits arglist ")") (dotimes [_ i] (emits ")")) (emitln ";")) (if (< 1 (count params)) (do (emits "var " (last params) " = cljm.core.rest(") (dotimes [_ (- (count params) 2)] (emits "cljm.core.next(")) (emits arglist) (dotimes [_ (- (count params) 2)] (emits ")")) (emitln ");") (emitln "return " delegate-name "(" (string/join ", " params) ");")) (do (emits "var " (last params) " = ") (emits "cljm.core.seq(" arglist ");") (emitln ";") (emitln "return " delegate-name "(" (string/join ", " params) ");"))) (emits "})"))) (defn emit-start-fn-var [args imp-fn] (emits "[[CLJMFunction alloc] initWithBlock:^ id (") (emits (comma-sep (map #(str "id " (munge %)) args))) (when-not imp-fn (when (> (count args) 0) (emits ", ")) (emits "id cljm_vararg, ...")) (emitln ") {")) (defn emit-end-fn-var [] (emitln "}]")) (defn emit-fn-method [{:keys [gthis name variadic params statements ret env recurs max-fixed-arity]} imp-fn] (emit-wrap env (emit-start-fn-var params imp-fn) (when imp-fn (let [n (munge (first params))] (when (not= n 'self) (emitln "id self = " n ";")))) (when recurs (emitln "while(YES) {")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emit-end-fn-var))) (defn emit-variadic-fn-method [{:keys [gthis name variadic params statements ret env recurs max-fixed-arity] :as f} imp-fn] (emit-wrap env (emit-start-fn-var (drop-last params) imp-fn) (when imp-fn (let [n (munge (first params))] (when (not= n 'self) (emitln "id self = " n ";")))) (let [lastn (munge (last params))] (emitln "NSMutableArray *" lastn " = [NSMutableArray array];") (emitln "va_list cljm_args;") (emitln "va_start(cljm_args, cljm_vararg);") (emitln "for (id cljm_currentArg = cljm_vararg; cljm_currentArg != nil; cljm_currentArg = va_arg(cljm_args, id)) {") (emitln "\t[" lastn " addObject:cljm_currentArg];") (emitln "}") (emitln "va_end(cljm_args);")) (when recurs (emitln "while(YES) {")) (emit-block :return statements ret) (when recurs (emitln "break;") (emitln "}")) (emit-end-fn-var))) (defmethod emit :fn [{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets imp-fn]}] ;;fn statements get erased, serve no purpose and can pollute scope if named (when-not (= :statement (:context env)) (let [loop-locals (->> (concat (mapcat :names (filter #(and % @(:flag %)) recur-frames)) (mapcat :names loop-lets)) (map munge) seq)] (when loop-locals (when (= :return (:context env)) (emits "return ")) (emitln "((function (" (comma-sep loop-locals) "){") (when-not (= :return (:context env)) (emits "return "))) (if (= 1 (count methods)) (if variadic (emit-variadic-fn-method (assoc (first methods) :name name) imp-fn) (emit-fn-method (assoc (first methods) :name name) imp-fn)) (let [has-name? (and name true) name (or name (gensym)) mname (munge name) maxparams (map munge (apply max-key count (map :params methods))) mmap (into {} (map (fn [method] [(munge (symbol (str mname "__" (count (:params method))))) method]) methods)) ms (sort-by #(-> % second :params count) (seq mmap))] (when (= :return (:context env)) (emits "return ")) (emitln "[[CLJMFunction alloc] initWithBlock:^ id (id cljm_vararg, ...) {") (emitln "__block CLJMVar *" mname ";") (doseq [[n meth] ms] (emits "CLJMFunction *" n " = ") (if (:variadic meth) (emit-variadic-fn-method meth imp-fn) (emit-fn-method meth imp-fn)) (emitln ";") (emitln)) (emitln mname " = [[CLJMVar alloc] initWithValue:[[CLJMFunction alloc] initWithBlock:^ id (NSArray *cljm_args) {") (emitln "switch(cljm_args.count) {") (doseq [[n meth] ms] (if (:variadic meth) (do (emitln "default:") (emitln "return ((id (^)(id, ...))[" n " block])(cljm_args[0], nil);") (emitln "break;")) (let [pcnt (count (:params meth))] (emitln "case " pcnt ":") (emits "return ((id (^)(id, ...))[" n " block])(") (dotimes [n pcnt] (emits "cljm_args[" n "], ")) (emits "nil);") ; (emitln "return ((id (^)(id, ...))[" n " block])(cljm_args[0], nil);") (emitln "break;")))) (emitln "}") (emitln "return nil;") (emitln "}]];") (emitln "NSMutableArray *cljm_collectedArgs = [NSMutableArray array];") (emitln "va_list cljm_args;") (emitln "va_start(cljm_args, cljm_vararg);") (emitln "for (id cljm_currentArg = cljm_vararg; cljm_currentArg != nil; cljm_currentArg = va_arg(cljm_args, id)) {") (emitln "\t[cljm_collectedArgs addObject:cljm_currentArg];") (emitln "}") (emitln "va_end(cljm_args);") (emitln "return ((id (^)(NSArray *))[(CLJMFunction *)[" mname " value] block])(cljm_collectedArgs);") (emitln "}]"))) (when loop-locals (emitln ";})(" (comma-sep loop-locals) "))"))))) (defmethod emit :do [{:keys [statements ret env]}] (let [context (:context env)] (when (and statements (= :expr context)) (emits "{")) ;(when statements (emitln "{")) (emit-block context statements ret) ;(when statements (emits "}")) (when (and statements (= :expr context)) (emits "}")))) (defmethod emit :try* [{:keys [env try catch name finally]}] (let [context (:context env) subcontext (if (= :expr context) :return context)] (if (or name finally) (do (when (= :expr context) (emits "(function (){")) (emits "try{") (let [{:keys [statements ret]} try] (emit-block subcontext statements ret)) (emits "}") (when name (emits "catch (" (munge name) "){") (when catch (let [{:keys [statements ret]} catch] (emit-block subcontext statements ret))) (emits "}")) (when finally (let [{:keys [statements ret]} finally] (assert (not= :constant (:op ret)) "finally block cannot contain constant") (emits "finally {") (emit-block subcontext statements ret) (emits "}"))) (when (= :expr context) (emits "})()"))) (let [{:keys [statements ret]} try] (when (and statements (= :expr context)) (emits "(function (){")) (emit-block subcontext statements ret) (when (and statements (= :expr context)) (emits "})()")))))) (defmethod emit :let [{:keys [bindings statements ret env loop]}] (let [context (:context env)] (when (= :expr context) (emits "^ id {")) (doseq [{:keys [name init]} bindings] (emitln "id " (munge name) " = " init ";")) (when loop (emitln "while(YES) {")) (emit-block (if (= :expr context) :return context) statements ret) (when loop (emitln "break;") (emitln "}")) ;(emits "}") (when (= :expr context) (emits "}()")))) (defmethod emit :recur [{:keys [frame exprs env]}] (let [temps (vec (take (count exprs) (repeatedly gensym))) names (:names frame)] (emitln "{") (dotimes [i (count exprs)] (emitln "id " (temps i) " = " (exprs i) ";")) (dotimes [i (count exprs)] (emitln (munge (names i)) " = " (temps i) ";")) (emitln "continue;") (emitln "}"))) (defmethod emit :letfn [{:keys [bindings statements ret env]}] (let [context (:context env)] (when (= :expr context) (emits "(function (){")) (doseq [{:keys [name init]} bindings] (emitln "id " (munge name) " = " init ";")) (emit-block (if (= :expr context) :return context) statements ret) (when (= :expr context) (emits "})()")))) (defn protocol-prefix [psym] (str (-> (str psym) (.replace \. \$) (.replace \/ \$)) "$")) (defn protocol-munge [p x] (str (munge p) "_" (munge x))) (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) variadic? (:variadic info) dynamic? (:dynamic info) fn-name (:name info) mname (munge fn-name) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) kwname (-> f :form) protocol (:protocol info) local? (:local info) ns (:ns info) c-call? (= ns 'c)] (emit-wrap env (cond protocol (let [pmname (protocol-munge protocol (apply str (drop 1 (last (string/split (str fn-name) #"/")))))] (emits "[(id<" (munge protocol) ">) " (first args) " ") (emits pmname) (doseq [arg (rest args)] (emits ":" arg " ")) (emits "]")) keyword? (emits "[" (first args) " objectForKey:cljm_keyword(@\"" kwname "\")]") c-call? (emits (name fn-name) "(" (comma-sep args) ")") :else (do (emits "((id (^)(") (emits (comma-sep (map (fn [x] (str "id")) (concat args (list "cljm_args"))))) (emits ", ...))") (if-not local? (emits "[")) (emits "(CLJMFunction *)[") (if dynamic? (emits "cljm_var_lookup(@\"" fn-name "\")") (emits mname)) (if-not local? (emits " value]")) (emits " block])(") (emits (comma-sep (conj args "nil")) ")")))))) (comment (defmethod emit :invoke [{:keys [f args env] :as expr}] (let [info (:info f) fn? (and ana/*cljm-static-fns* (not (:dynamic info)) (:fn-var info)) protocol (:protocol info) proto? (let [tag (infer-tag (first (:args expr)))] (and protocol tag (or ana/*cljm-static-fns* (:protocol-inline env)) (or (= protocol tag) (when-let [ps (:protocols (ana/resolve-existing-var (dissoc env :locals) tag))] (ps protocol))))) opt-not? (and (= (:name info) 'cljm.core/not) (= (infer-tag (first (:args expr))) 'boolean)) ns (:ns info) js? (= ns 'js) goog? (when ns (or (= ns 'goog) (when-let [ns-str (str ns)] (= (get (string/split ns-str #"\.") 0 nil) "goog")))) keyword? (and (= (-> f :op) :constant) (keyword? (-> f :form))) [f variadic-invoke] (if fn? (let [arity (count args) variadic? (:variadic info) mps (:method-params info) mfa (:max-fixed-arity info)] (cond ;; if only one method, no renaming needed (and (not variadic?) (= (count mps) 1)) [f nil] ;; direct dispatch to variadic case (and variadic? (> arity mfa)) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljm$lang$arity$variadic")))) {:max-fixed-arity mfa}] ;; direct dispatch to specific arity case :else (let [arities (map count mps)] (if (some #{arity} arities) [(update-in f [:info :name] (fn [name] (symbol (str (munge name) ".cljm$lang$arity$" arity)))) nil] [f nil])))) [f nil])] (emit-wrap env (cond opt-not? (emits "!(" (first args) ")") proto? (let [pimpl (str (protocol-prefix protocol) (munge (name (:name info))) "$arity$" (count args))] (emits (first args) "." pimpl "(" (comma-sep args) ")")) keyword? (emits "(new cljm.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")") variadic-invoke (let [mfa (:max-fixed-arity variadic-invoke)] (emits f "(" (comma-sep (take mfa args)) (when-not (zero? mfa) ",") "cljm.core.array_seq([" (comma-sep (drop mfa args)) "], 0))")) (or fn? js? goog?) (emits f "(" (comma-sep args) ")") :else (if (and ana/*cljm-static-fns* (= (:op f) :var)) (let [fprop (str ".cljm$lang$arity$" (count args))] (emits "(" f fprop " ? " f fprop "(" (comma-sep args) ") : " f ".call(" (comma-sep (cons "null" args)) "))")) (if variadic? (emits f "(" (comma-sep args) ", nil)") (emits f "(" (comma-sep args) ")")))))))) (defmethod emit :new [{:keys [ctor args env]}] (emit-wrap env (let [method (first args) init-args (rest args) init-meth (if (seq args) (reduce (fn [xs x] (str xs ":")) "initWithFields" args) "init")] (emits "[[" ctor " alloc]") (emit-method-parts (sel-parts init-meth) args) (emits "]")))) (defmethod emit :set! [{:keys [target val env]}] (emit-wrap env (emits target " = " val))) (defmethod emit :ns [{:keys [name requires uses requires-macros env]}] (emitln "#import <Foundation/Foundation.h>") (emitln "#import <CLJMRuntime/CLJMRuntime.h>") (emitln "#import <objc/runtime.h>") (when include-core (when-not (= name 'cljm.core) (emitln "#import \"cljm_DOT_core.h\""))) (emitln "#import \"" (munge name) ".h\"") (doseq [lib (into (vals requires) (distinct (vals uses)))] (emitln "#import \"" (munge lib) ".h\""))) (defmethod emit :defprotocol* [ast] (add-extern! ast)) (defmethod emit :deftype* [{:keys [t fields pmasks reify] :as ast}] (when-not reify (add-extern! ast) (add-static-expr! ast))) (defmethod emit :defrecord* [{:keys [t fields pmasks]}] (let [fields (concat (map munge fields) '[__meta __extmap])] (emitln "") (emitln "/**") (emitln "* @constructor") (doseq [fld fields] (emitln "* @param {*} " fld)) (emitln "* @param {*=} __meta ") (emitln "* @param {*=} __extmap") (emitln "*/") (emitln (munge t) " = (function (" (comma-sep fields) "){") (doseq [fld fields] (emitln "this." fld " = " fld ";")) (doseq [[pno pmask] pmasks] (emitln "this.cljm$lang$protocol_mask$partition" pno "$ = " pmask ";")) (emitln "if(arguments.length>" (- (count fields) 2) "){") (emitln "this.__meta = __meta;") (emitln "this.__extmap = __extmap;") (emitln "} else {") (emits "this.__meta=") (emit-constant nil) (emitln ";") (emits "this.__extmap=") (emit-constant nil) (emitln ";") (emitln "}") (emitln "})"))) (defmethod emit :dot [{:keys [target field method args env]}] (emit-wrap env (if field (emits "[" target " " (munge field #{}) "]") (do (emits "[" target) (emit-method-parts (sel-parts (str method)) args) (emits "]"))))) (defmethod emit :objc [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defmethod emit :js [{:keys [env code segs args]}] (emit-wrap env (if code (emits code) (emits (interleave (concat segs (repeat nil)) (concat args [nil])))))) (defmulti emit-static :op) (declare objc-class-munge) (defmethod emit-static :deftype* [{:keys [t methods]}] (emitln) (emitln "@implementation " (objc-class-munge t)) (emitln "@end") (emitln)) (defn forms-seq "Seq of forms in a Clojure or ClojureScript file." ([f] (forms-seq f (clojure.lang.LineNumberingPushbackReader. (io/reader f)))) ([f ^java.io.PushbackReader rdr] (if-let [form (binding [*ns* ana/*reader-ns*] (read rdr nil nil))] (lazy-seq (cons form (forms-seq f rdr))) (.close rdr)))) (defn rename-to "Change the file extension from .cljm to .m. Takes a File or a String. Always returns a String." [file-str ext] (clojure.string/replace file-str #"\.cljm$" ext)) (defn mkdirs "Create all parent directories for the passed file." [^java.io.File f] (.mkdirs (.getParentFile (.getCanonicalFile f)))) (defmacro with-core-cljm "Ensure that core.cljm has been loaded." [& body] `(do (when include-core (when-not (:defs (get @ana/namespaces 'cljm.core)) (ana/analyze-file "cljm/core.cljm"))) ~@body)) (defn compile-file* [src dest] (with-core-cljm (with-open [out ^java.io.Writer (io/make-writer dest {})] (binding [*out* out ana/*cljm-ns* 'cljm.user ana/*cljm-file* (.getPath ^java.io.File src) *data-readers* tags/*cljm-data-readers* *position* (atom [0 0]) *static-exprs* (atom [])] (loop [forms (forms-seq src) ns-name nil deps nil] (if (seq forms) (let [env (ana/empty-env) ast (ana/analyze env (first forms))] ; (binding [*out* *err*] ; (println "Goodbye, world!") ; (clojure.pprint/pprint ast)) (emit ast) (if (= (:op ast) :ns) (let [found-ns (:name ast)] ; TODO: It'd be nice to only init namespaces that are ; actually used. (emitln "__attribute__((constructor))") (emitln "void " (init-func-name found-ns) "(void) {\n") (emitln "@autoreleasepool {") (recur (rest forms) found-ns (merge (:uses ast) (:requires ast)))) (recur (rest forms) ns-name deps))) (do (emitln "}") (emitln "}") (doseq [ast @*static-exprs*] (emit-static ast)) {:ns (or ns-name 'cljm.user) :provides [ns-name] :requires (if (= ns-name 'cljm.core) (set (vals deps)) (conj (set (vals deps)) 'cljm.core)) :file dest}))))))) (defn requires-compilation? "Return true if the src file requires compilation." [^java.io.File src ^java.io.File dest] ; for the sake of debugging right now, we'll always recompile everything true) ; (or (not (.exists dest)) ; (> (.lastModified src) (.lastModified dest)))) (defmulti emit-h :op) (defmethod emit-h :defprotocol* [{:keys [p index methods]}] (emitln) (emitln "@protocol " (munge p) " <NSObject>") (emitln) (doseq [method methods] (let [mname (protocol-munge p (apply str (drop 1 (seq (str (first method)))))) arities (take-while vector? (drop 1 method)) has-comment? (string? (last method)) comment (if has-comment? (last method) nil)] (when has-comment? (emit-comment comment "")) (doseq [arity arities] (emits "- (id)" mname) (doseq [arg (drop 1 arity)] (emits ":(id)" (munge arg) " ")) (emits ";") (emitln)) (emitln))) (emitln) (emitln "@end") (emitln)) (defmethod emit-h :def [ast] (let [mname (munge (:name ast))] (emitln "CLJMVar *" mname ";"))) (defn- objc-class-munge [t] (if (= (string/upper-case (namespace t)) (namespace t)) (str (namespace t) (name t)) (munge t))) (defn- selector-name [sel] (let [ssel (seq sel)] (apply str (cond (= (first ssel) \-) (drop 1 ssel) (= (last ssel) \!) (drop-last ssel) :else ssel)))) (defmethod emit-h :deftype* [{:keys [t fields superclass protocols methods env] :as ast}] (emitln) (let [class-name (objc-class-munge t) superclass (objc-class-munge superclass)] (emits "@interface " class-name " : " superclass)) (when (seq? (seq protocols)) (emits " <" (comma-sep (map objc-class-munge protocols)) ">")) (emitln) (emitln) (doseq [p fields] (let [tag (-> p meta :tag) type (cond (= 'iboutlet tag) "IBOutlet id" nil? "id" :else tag)] (emitln "@property (nonatomic, strong) " type " " (munge p) ";"))) (emitln) (doseq [[p ms] methods] (doseq [m ms] (let [p-ns (:ns (ana/resolve-existing-var (dissoc env :locals) p)) prefix (if (= p-ns 'ObjectiveCClass) "" (str (munge (str p-ns "/" p)) "_")) mname (str prefix (selector-name (str (first m)))) parts (string/split mname #":") pair-args (fn [sel arg] (str (munge sel) ":(id)" (munge arg) " ")) args (drop 1 (second m)) sel-parts (if (seq args) (apply str (map pair-args (concat parts (repeat "")) args)) (str (first parts)))] (emitln "- (id)" sel-parts ";") (emitln)))) (emitln) (emitln "@end") (emitln)) (defn generate-header [externs file] (let [dest-file (io/file file)] (with-open [out ^java.io.Writer (io/make-writer dest-file {})] (binding [*out* out] (emitln "@class CLJMVar;") (emitln) (doseq [ast externs] (emit-h ast)))))) (defn compile-file "Compiles src to a file of the same name, but with a .js extension, in the src file's directory. With dest argument, write file to provided location. If the dest argument is a file outside the source tree, missing parent directories will be created. The src file will only be compiled if the dest file has an older modification time. Both src and dest may be either a String or a File. Returns a map containing {:ns .. :provides .. :requires .. :file ..}. If the file was not compiled returns only {:file ...}" ([src] (let [dest (rename-to src ".m")] (compile-file src dest))) ([src dest] (binding [*externs* (atom [])] (let [src-file (io/file src) dest-file (io/file dest)] (if (.exists src-file) (if (requires-compilation? src-file dest-file) (do (mkdirs dest-file) (assoc (compile-file* src-file dest-file) :externs @*externs*)) {:file dest-file, :externs []}) (throw (java.io.FileNotFoundException. (str "The file " src " does not exist.")))))))) (defn init-func-name [ns] (munge (str ns "/cljm-ns-init"))) (comment ;; flex compile-file (do (compile-file "/tmp/hello.cljm" "/tmp/something.js") (slurp "/tmp/hello.js") (compile-file "/tmp/somescript.cljm") (slurp "/tmp/somescript.js"))) (defn path-seq [file-str] (->> java.io.File/separator java.util.regex.Pattern/quote re-pattern (string/split file-str))) (defn to-path ([parts] (to-path parts java.io.File/separator)) ([parts sep] (apply str (interpose sep parts)))) (defn to-target-file "Given the source root directory, the output target directory and file under the source root, produce the target file." [^java.io.File dir ^String target ^java.io.File file ext] (let [dir-path (path-seq (.getAbsolutePath dir)) file-path (path-seq (.getAbsolutePath file)) relative-path (drop (count dir-path) file-path) parents (butlast relative-path) parent-file (java.io.File. ^String (to-path (cons target parents)))] (java.io.File. parent-file ^String (rename-to (last relative-path) ext)))) (defn cljm-files-in "Return a sequence of all .cljm files in the given directory." [dir] (filter #(let [name (.getName ^java.io.File %)] (and (.endsWith name ".cljm") (not= \. (first name)) (not (contains? cljm-reserved-file-names name)))) (file-seq dir))) (defn move-and-rename [^java.io.File m-file ^java.io.File h-file ns target-dir] (let [mname (munge ns)] (.renameTo m-file (java.io.File. (str target-dir java.io.File/separator mname ".m"))) (.renameTo h-file (java.io.File. (str target-dir java.io.File/separator mname ".h"))))) (defn compile-root "Looks recursively in src-dir for .cljm files and compiles them to .m files. If target-dir is provided, output will go into this directory mirroring the source directory structure. Returns a list of maps containing information about each file which was compiled in dependency order." ([src-dir] (compile-root src-dir "out")) ([src-dir target-dir] (let [src-dir-file (io/file src-dir)] (loop [cljm-files (cljm-files-in src-dir-file) output-files []] (if (seq cljm-files) (let [cljm-file (first cljm-files) m-file ^java.io.File (to-target-file src-dir-file target-dir cljm-file ".m") h-file ^java.io.File (to-target-file src-dir-file target-dir cljm-file ".h") ns-info (compile-file cljm-file m-file)] (generate-header (:externs ns-info) h-file) (move-and-rename m-file h-file (:ns ns-info) target-dir) (recur (rest cljm-files) (conj output-files (assoc ns-info :file-name (.getPath m-file))))) output-files)))))
[ { "context": "(ns #^{:author \"Mikael Reponen\"}\n cutter.opencv\n (:require [clojure.tools.name", "end": 30, "score": 0.9998813271522522, "start": 16, "tag": "NAME", "value": "Mikael Reponen" } ]
src/cutter/opencv.clj
Viritystila/cutter
0
(ns #^{:author "Mikael Reponen"} cutter.opencv (:require [clojure.tools.namespace.repl :refer [refresh]] [watchtower.core :as watcher] [clojure.java.io :as io] [while-let.core :as while-let] [cutter.general :refel :all] [clojure.core.async :as async :refer [>! <! >!! <!! go go-loop chan sliding-buffer dropping-buffer close! thread alts! alts!! timeout]] clojure.string) (:import ;[org.bytedeco.javacpp Pointer] ;[org.bytedeco.javacpp BytePointer] ;[org.bytedeco.javacpp v4l2] ;[org.opencv.core Mat Core CvType] ;[org.opencv.videoio Videoio VideoCapture] ;[org.opencv.video Video] ;[org.opencv.imgproc Imgproc] ;[org.opencv.imgcodecs Imgcodecs] ; (java.awt.image BufferedImage DataBuffer DataBufferByte WritableRaster) ; (java.io File FileInputStream) ; (java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder) ; (java.util Calendar) ; (java.util List) ; (javax.imageio ImageIO) ; (java.lang.reflect Field) (org.lwjgl BufferUtils) ; (org.lwjgl.glfw GLFW GLFWErrorCallback GLFWKeyCallback) (org.lwjgl.opengl GL GL11 GL12 GL13 GL15 GL20 GL30 GL40) )) ; (defn buffer-from-mat-address [mat] (let [address (.getDeclaredField java.nio.Buffer "address") capacity (.getDeclaredField java.nio.Buffer "capacity") _ (.setAccessible address true) _ (.setAccessible capacity true) bb (java.nio.ByteBuffer/allocateDirect 0) _ (.order bb (java.nio.ByteOrder/nativeOrder)) mat_address (.dataAddr mat) mat_step (.step1 mat) mat_rows (.rows mat) mat_size (* mat_step mat_rows) _ (.setLong address bb mat_address) _ (.setInt capacity bb mat_size)] bb)) (defn oc-mat-to-bytebuffer [mat] (let [height (.height mat) width (.width mat) channels (.channels mat) size (* height width channels) data (byte-array size) _ (.get mat 0 0 data)] ^ByteBuffer (-> (BufferUtils/createByteBuffer size) (.put data) (.flip)))) (defn matInfo [mat] [(buffer-from-mat-address mat) ;(oc-mat-to-bytebuffer mat) ;(.dataAddr mat) (.rows mat) (.step1 mat) (.elemSize1 mat) (.height mat) (.width mat) (.channels mat) mat 0]) (defn oc-new-mat ([int_0 int_1 int_2 org_opencv_core_scalar_3 ] (new org.opencv.core.Mat int_0 int_1 int_2 org_opencv_core_scalar_3 )) ([org_opencv_core_size_0 int_1 org_opencv_core_scalar_2 ] (new org.opencv.core.Mat org_opencv_core_size_0 int_1 org_opencv_core_scalar_2 )) ([org_opencv_core_mat_0 org_opencv_core_range_1 ] (new org.opencv.core.Mat org_opencv_core_mat_0 org_opencv_core_range_1 )) ([long_0 ] (new org.opencv.core.Mat long_0 )) ([] (new org.opencv.core.Mat ))) (defn oc-tex-internal-format "return the internal-format for the glTexImage2D call for this image" ^Integer [image] (let [image-type (.type image) internal-format (cond (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB8 (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB8 (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA8 (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA8 :else GL11/GL_RGB8)] internal-format)) (defn oc-tex-format "return the format for the glTexImage2D call for this image" ^Integer [image] (let [image-type (.type image) format (cond (= image-type org.opencv.core.CvType/CV_8UC3) GL12/GL_BGR (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB (= image-type org.opencv.core.CvType/CV_8UC4) GL12/GL_BGRA (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA :else GL12/GL_BGR)] format)) (defn oc-mat-to-bytebuffer [mat] (let [height (.height mat) width (.width mat) channels (.channels mat) size (* height width channels) data (byte-array size) _ (.get mat 0 0 data)] ^ByteBuffer (-> (BufferUtils/createByteBuffer size) (.put data) (.flip)))) (defn oc_load_image [filename] (let [mat (org.opencv.imgcodecs.Imgcodecs/imread filename org.opencv.imgcodecs.Imgcodecs/IMREAD_COLOR)] mat)) (defn oc_load_image_2 [filename mat] (let [mat (org.opencv.imgcodecs.Imgcodecs/imreadmulti filename mat org.opencv.imgcodecs.Imgcodecs/IMREAD_COLOR)] mat)) ;;camera (defn oc-set-capture-property [dispatch capture val] (let [] (case dispatch :pos-msec (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_MSEC val) :pos-frames (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_FRAMES val) :pos-avi-ratio (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_AVI_RATIO val) :frame-width (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_WIDTH val) :frame-height (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_HEIGHT val) :fps (.set capture org.opencv.videoio.Videoio/CAP_PROP_FPS val) :fourcc (.set capture org.opencv.videoio.Videoio/CAP_PROP_FOURCC val) :frame-count (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_COUNT val) :brightness (.set capture org.opencv.videoio.Videoio/CAP_PROP_BRIGHTNESS val) :contrast (.set capture org.opencv.videoio.Videoio/CAP_PROP_CONTRAST val) :saturation (.set capture org.opencv.videoio.Videoio/CAP_PROP_SATURATION val) :hue (.set capture org.opencv.videoio.Videoio/CAP_PROP_HUE val) :default (throw (Exception. "Unknown Property."))))) (defn oc-get-capture-property [dispatch capture] (let [] (case dispatch :pos-msec (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_MSEC) :pos-frames (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_FRAMES) :pos-avi-ratio (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_AVI_RATIO) :frame-width (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_WIDTH) :frame-height (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_HEIGHT) :fps (.get capture org.opencv.videoio.Videoio/CAP_PROP_FPS) :fourcc (.get capture org.opencv.videoio.Videoio/CAP_PROP_FOURCC) :frame-count (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_COUNT) :brightness (.get capture org.opencv.videoio.Videoio/CAP_PROP_BRIGHTNESS) :contrast (.get capture org.opencv.videoio.Videoio/CAP_PROP_CONTRAST) :saturation (.get capture org.opencv.videoio.Videoio/CAP_PROP_SATURATION) :hue (.get capture org.opencv.videoio.Videoio/CAP_PROP_HUE) :default (throw (Exception. "Unknown Property."))))) (defn oc-open-camera-device [camera-device] (let [vc (new org.opencv.videoio.VideoCapture) vco (.open vc camera-device)] vc)) (defn oc-release [capture] (if (= nil capture) (println "nil") (do (println "release" capture) (.release capture)))) (defn oc-query-frame [capture buffer] (let [flag (.read capture buffer)] (if (= flag true) nil (Thread/sleep 100)) buffer)) ;(read-string (str (last "/dev/video0")))
61202
(ns #^{:author "<NAME>"} cutter.opencv (:require [clojure.tools.namespace.repl :refer [refresh]] [watchtower.core :as watcher] [clojure.java.io :as io] [while-let.core :as while-let] [cutter.general :refel :all] [clojure.core.async :as async :refer [>! <! >!! <!! go go-loop chan sliding-buffer dropping-buffer close! thread alts! alts!! timeout]] clojure.string) (:import ;[org.bytedeco.javacpp Pointer] ;[org.bytedeco.javacpp BytePointer] ;[org.bytedeco.javacpp v4l2] ;[org.opencv.core Mat Core CvType] ;[org.opencv.videoio Videoio VideoCapture] ;[org.opencv.video Video] ;[org.opencv.imgproc Imgproc] ;[org.opencv.imgcodecs Imgcodecs] ; (java.awt.image BufferedImage DataBuffer DataBufferByte WritableRaster) ; (java.io File FileInputStream) ; (java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder) ; (java.util Calendar) ; (java.util List) ; (javax.imageio ImageIO) ; (java.lang.reflect Field) (org.lwjgl BufferUtils) ; (org.lwjgl.glfw GLFW GLFWErrorCallback GLFWKeyCallback) (org.lwjgl.opengl GL GL11 GL12 GL13 GL15 GL20 GL30 GL40) )) ; (defn buffer-from-mat-address [mat] (let [address (.getDeclaredField java.nio.Buffer "address") capacity (.getDeclaredField java.nio.Buffer "capacity") _ (.setAccessible address true) _ (.setAccessible capacity true) bb (java.nio.ByteBuffer/allocateDirect 0) _ (.order bb (java.nio.ByteOrder/nativeOrder)) mat_address (.dataAddr mat) mat_step (.step1 mat) mat_rows (.rows mat) mat_size (* mat_step mat_rows) _ (.setLong address bb mat_address) _ (.setInt capacity bb mat_size)] bb)) (defn oc-mat-to-bytebuffer [mat] (let [height (.height mat) width (.width mat) channels (.channels mat) size (* height width channels) data (byte-array size) _ (.get mat 0 0 data)] ^ByteBuffer (-> (BufferUtils/createByteBuffer size) (.put data) (.flip)))) (defn matInfo [mat] [(buffer-from-mat-address mat) ;(oc-mat-to-bytebuffer mat) ;(.dataAddr mat) (.rows mat) (.step1 mat) (.elemSize1 mat) (.height mat) (.width mat) (.channels mat) mat 0]) (defn oc-new-mat ([int_0 int_1 int_2 org_opencv_core_scalar_3 ] (new org.opencv.core.Mat int_0 int_1 int_2 org_opencv_core_scalar_3 )) ([org_opencv_core_size_0 int_1 org_opencv_core_scalar_2 ] (new org.opencv.core.Mat org_opencv_core_size_0 int_1 org_opencv_core_scalar_2 )) ([org_opencv_core_mat_0 org_opencv_core_range_1 ] (new org.opencv.core.Mat org_opencv_core_mat_0 org_opencv_core_range_1 )) ([long_0 ] (new org.opencv.core.Mat long_0 )) ([] (new org.opencv.core.Mat ))) (defn oc-tex-internal-format "return the internal-format for the glTexImage2D call for this image" ^Integer [image] (let [image-type (.type image) internal-format (cond (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB8 (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB8 (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA8 (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA8 :else GL11/GL_RGB8)] internal-format)) (defn oc-tex-format "return the format for the glTexImage2D call for this image" ^Integer [image] (let [image-type (.type image) format (cond (= image-type org.opencv.core.CvType/CV_8UC3) GL12/GL_BGR (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB (= image-type org.opencv.core.CvType/CV_8UC4) GL12/GL_BGRA (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA :else GL12/GL_BGR)] format)) (defn oc-mat-to-bytebuffer [mat] (let [height (.height mat) width (.width mat) channels (.channels mat) size (* height width channels) data (byte-array size) _ (.get mat 0 0 data)] ^ByteBuffer (-> (BufferUtils/createByteBuffer size) (.put data) (.flip)))) (defn oc_load_image [filename] (let [mat (org.opencv.imgcodecs.Imgcodecs/imread filename org.opencv.imgcodecs.Imgcodecs/IMREAD_COLOR)] mat)) (defn oc_load_image_2 [filename mat] (let [mat (org.opencv.imgcodecs.Imgcodecs/imreadmulti filename mat org.opencv.imgcodecs.Imgcodecs/IMREAD_COLOR)] mat)) ;;camera (defn oc-set-capture-property [dispatch capture val] (let [] (case dispatch :pos-msec (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_MSEC val) :pos-frames (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_FRAMES val) :pos-avi-ratio (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_AVI_RATIO val) :frame-width (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_WIDTH val) :frame-height (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_HEIGHT val) :fps (.set capture org.opencv.videoio.Videoio/CAP_PROP_FPS val) :fourcc (.set capture org.opencv.videoio.Videoio/CAP_PROP_FOURCC val) :frame-count (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_COUNT val) :brightness (.set capture org.opencv.videoio.Videoio/CAP_PROP_BRIGHTNESS val) :contrast (.set capture org.opencv.videoio.Videoio/CAP_PROP_CONTRAST val) :saturation (.set capture org.opencv.videoio.Videoio/CAP_PROP_SATURATION val) :hue (.set capture org.opencv.videoio.Videoio/CAP_PROP_HUE val) :default (throw (Exception. "Unknown Property."))))) (defn oc-get-capture-property [dispatch capture] (let [] (case dispatch :pos-msec (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_MSEC) :pos-frames (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_FRAMES) :pos-avi-ratio (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_AVI_RATIO) :frame-width (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_WIDTH) :frame-height (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_HEIGHT) :fps (.get capture org.opencv.videoio.Videoio/CAP_PROP_FPS) :fourcc (.get capture org.opencv.videoio.Videoio/CAP_PROP_FOURCC) :frame-count (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_COUNT) :brightness (.get capture org.opencv.videoio.Videoio/CAP_PROP_BRIGHTNESS) :contrast (.get capture org.opencv.videoio.Videoio/CAP_PROP_CONTRAST) :saturation (.get capture org.opencv.videoio.Videoio/CAP_PROP_SATURATION) :hue (.get capture org.opencv.videoio.Videoio/CAP_PROP_HUE) :default (throw (Exception. "Unknown Property."))))) (defn oc-open-camera-device [camera-device] (let [vc (new org.opencv.videoio.VideoCapture) vco (.open vc camera-device)] vc)) (defn oc-release [capture] (if (= nil capture) (println "nil") (do (println "release" capture) (.release capture)))) (defn oc-query-frame [capture buffer] (let [flag (.read capture buffer)] (if (= flag true) nil (Thread/sleep 100)) buffer)) ;(read-string (str (last "/dev/video0")))
true
(ns #^{:author "PI:NAME:<NAME>END_PI"} cutter.opencv (:require [clojure.tools.namespace.repl :refer [refresh]] [watchtower.core :as watcher] [clojure.java.io :as io] [while-let.core :as while-let] [cutter.general :refel :all] [clojure.core.async :as async :refer [>! <! >!! <!! go go-loop chan sliding-buffer dropping-buffer close! thread alts! alts!! timeout]] clojure.string) (:import ;[org.bytedeco.javacpp Pointer] ;[org.bytedeco.javacpp BytePointer] ;[org.bytedeco.javacpp v4l2] ;[org.opencv.core Mat Core CvType] ;[org.opencv.videoio Videoio VideoCapture] ;[org.opencv.video Video] ;[org.opencv.imgproc Imgproc] ;[org.opencv.imgcodecs Imgcodecs] ; (java.awt.image BufferedImage DataBuffer DataBufferByte WritableRaster) ; (java.io File FileInputStream) ; (java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder) ; (java.util Calendar) ; (java.util List) ; (javax.imageio ImageIO) ; (java.lang.reflect Field) (org.lwjgl BufferUtils) ; (org.lwjgl.glfw GLFW GLFWErrorCallback GLFWKeyCallback) (org.lwjgl.opengl GL GL11 GL12 GL13 GL15 GL20 GL30 GL40) )) ; (defn buffer-from-mat-address [mat] (let [address (.getDeclaredField java.nio.Buffer "address") capacity (.getDeclaredField java.nio.Buffer "capacity") _ (.setAccessible address true) _ (.setAccessible capacity true) bb (java.nio.ByteBuffer/allocateDirect 0) _ (.order bb (java.nio.ByteOrder/nativeOrder)) mat_address (.dataAddr mat) mat_step (.step1 mat) mat_rows (.rows mat) mat_size (* mat_step mat_rows) _ (.setLong address bb mat_address) _ (.setInt capacity bb mat_size)] bb)) (defn oc-mat-to-bytebuffer [mat] (let [height (.height mat) width (.width mat) channels (.channels mat) size (* height width channels) data (byte-array size) _ (.get mat 0 0 data)] ^ByteBuffer (-> (BufferUtils/createByteBuffer size) (.put data) (.flip)))) (defn matInfo [mat] [(buffer-from-mat-address mat) ;(oc-mat-to-bytebuffer mat) ;(.dataAddr mat) (.rows mat) (.step1 mat) (.elemSize1 mat) (.height mat) (.width mat) (.channels mat) mat 0]) (defn oc-new-mat ([int_0 int_1 int_2 org_opencv_core_scalar_3 ] (new org.opencv.core.Mat int_0 int_1 int_2 org_opencv_core_scalar_3 )) ([org_opencv_core_size_0 int_1 org_opencv_core_scalar_2 ] (new org.opencv.core.Mat org_opencv_core_size_0 int_1 org_opencv_core_scalar_2 )) ([org_opencv_core_mat_0 org_opencv_core_range_1 ] (new org.opencv.core.Mat org_opencv_core_mat_0 org_opencv_core_range_1 )) ([long_0 ] (new org.opencv.core.Mat long_0 )) ([] (new org.opencv.core.Mat ))) (defn oc-tex-internal-format "return the internal-format for the glTexImage2D call for this image" ^Integer [image] (let [image-type (.type image) internal-format (cond (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB8 (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB8 (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA8 (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA8 :else GL11/GL_RGB8)] internal-format)) (defn oc-tex-format "return the format for the glTexImage2D call for this image" ^Integer [image] (let [image-type (.type image) format (cond (= image-type org.opencv.core.CvType/CV_8UC3) GL12/GL_BGR (= image-type org.opencv.core.CvType/CV_8UC3) GL11/GL_RGB (= image-type org.opencv.core.CvType/CV_8UC4) GL12/GL_BGRA (= image-type org.opencv.core.CvType/CV_8UC4) GL11/GL_RGBA :else GL12/GL_BGR)] format)) (defn oc-mat-to-bytebuffer [mat] (let [height (.height mat) width (.width mat) channels (.channels mat) size (* height width channels) data (byte-array size) _ (.get mat 0 0 data)] ^ByteBuffer (-> (BufferUtils/createByteBuffer size) (.put data) (.flip)))) (defn oc_load_image [filename] (let [mat (org.opencv.imgcodecs.Imgcodecs/imread filename org.opencv.imgcodecs.Imgcodecs/IMREAD_COLOR)] mat)) (defn oc_load_image_2 [filename mat] (let [mat (org.opencv.imgcodecs.Imgcodecs/imreadmulti filename mat org.opencv.imgcodecs.Imgcodecs/IMREAD_COLOR)] mat)) ;;camera (defn oc-set-capture-property [dispatch capture val] (let [] (case dispatch :pos-msec (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_MSEC val) :pos-frames (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_FRAMES val) :pos-avi-ratio (.set capture org.opencv.videoio.Videoio/CAP_PROP_POS_AVI_RATIO val) :frame-width (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_WIDTH val) :frame-height (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_HEIGHT val) :fps (.set capture org.opencv.videoio.Videoio/CAP_PROP_FPS val) :fourcc (.set capture org.opencv.videoio.Videoio/CAP_PROP_FOURCC val) :frame-count (.set capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_COUNT val) :brightness (.set capture org.opencv.videoio.Videoio/CAP_PROP_BRIGHTNESS val) :contrast (.set capture org.opencv.videoio.Videoio/CAP_PROP_CONTRAST val) :saturation (.set capture org.opencv.videoio.Videoio/CAP_PROP_SATURATION val) :hue (.set capture org.opencv.videoio.Videoio/CAP_PROP_HUE val) :default (throw (Exception. "Unknown Property."))))) (defn oc-get-capture-property [dispatch capture] (let [] (case dispatch :pos-msec (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_MSEC) :pos-frames (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_FRAMES) :pos-avi-ratio (.get capture org.opencv.videoio.Videoio/CAP_PROP_POS_AVI_RATIO) :frame-width (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_WIDTH) :frame-height (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_HEIGHT) :fps (.get capture org.opencv.videoio.Videoio/CAP_PROP_FPS) :fourcc (.get capture org.opencv.videoio.Videoio/CAP_PROP_FOURCC) :frame-count (.get capture org.opencv.videoio.Videoio/CAP_PROP_FRAME_COUNT) :brightness (.get capture org.opencv.videoio.Videoio/CAP_PROP_BRIGHTNESS) :contrast (.get capture org.opencv.videoio.Videoio/CAP_PROP_CONTRAST) :saturation (.get capture org.opencv.videoio.Videoio/CAP_PROP_SATURATION) :hue (.get capture org.opencv.videoio.Videoio/CAP_PROP_HUE) :default (throw (Exception. "Unknown Property."))))) (defn oc-open-camera-device [camera-device] (let [vc (new org.opencv.videoio.VideoCapture) vco (.open vc camera-device)] vc)) (defn oc-release [capture] (if (= nil capture) (println "nil") (do (println "release" capture) (.release capture)))) (defn oc-query-frame [capture buffer] (let [flag (.read capture buffer)] (if (= flag true) nil (Thread/sleep 100)) buffer)) ;(read-string (str (last "/dev/video0")))
[ { "context": "\n ; add dht bootstrap node\n (add-node! \"rkJ0ws6PQz8FU7VvTW~Lelhb6DM=:rkJ0wkX6jrW3HJBNdhuLlWCUPKDAlX8T23lrTOeMGK8=:B5QFqHHlCT5fOA2QWLAlAKba1hIjW-KBt2HCqwtJg8JFa2KnjAzcexyveYT8HOcMB~W6nhwhzQ7~sywFkvcvRkKHbf6LqP0X43q9y2ADFk2t9LpUle-L-x34ZodEEDxQbwWo74f-rX5IemW2-Du-8NH-o124OGvq5N4uT4PjtxmgSVrBYVLjZRYFUWgdmgR1lVOncfMDbXzXGf~HdY97s9ZFHYyi7ymwzlk4bBN9-Pd4I1tJB2sYBzk62s3gzY1TlDKOdy7qy1Eyr4SEISAopJrvAnSkS1eIFyCoqfzzrBWM11uWppWetf3AkHxGitJIQe73wmZrrO36jHNewIct54v2iF~~3cqBVlT4ptX1Dc-thjrxXoV73A0HUASldCeFZSVJFMQgOQK9U85NQscAokftpyp4Ai89YWaUvSDcZPd-mQuA275zifPwp8s8UfYV5EBqvdHnfeJjxmyTcKR3g5Ft8ABai9yywxoA7yoABD4EGzsFtAh0nOLcmbM944zdAAAA:35701\")\n (println \"DHT initialized\")))\n ; m", "end": 10390, "score": 0.9857737421989441, "start": 9800, "tag": "KEY", "value": "rkJ0ws6PQz8FU7VvTW~Lelhb6DM=:rkJ0wkX6jrW3HJBNdhuLlWCUPKDAlX8T23lrTOeMGK8=:B5QFqHHlCT5fOA2QWLAlAKba1hIjW-KBt2HCqwtJg8JFa2KnjAzcexyveYT8HOcMB~W6nhwhzQ7~sywFkvcvRkKHbf6LqP0X43q9y2ADFk2t9LpUle-L-x34ZodEEDxQbwWo74f-rX5IemW2-Du-8NH-o124OGvq5N4uT4PjtxmgSVrBYVLjZRYFUWgdmgR1lVOncfMDbXzXGf~HdY97s9ZFHYyi7ymwzlk4bBN9-Pd4I1tJB2sYBzk62s3gzY1TlDKOdy7qy1Eyr4SEISAopJrvAnSkS1eIFyCoqfzzrBWM11uWppWetf3AkHxGitJIQe73wmZrrO36jHNewIct54v2iF~~3cqBVlT4ptX1Dc-thjrxXoV73A0HUASldCeFZSVJFMQgOQK9U85NQscAokftpyp4Ai89YWaUvSDcZPd-mQuA275zifPwp8s8UfYV5EBqvdHnfeJjxmyTcKR3g5Ft8ABai9yywxoA7yoABD4EGzsFtAh0nOLcmbM944zdAAAA" }, { "context": "t8ABai9yywxoA7yoABD4EGzsFtAh0nOLcmbM944zdAAAA:35701\")\n (println \"DHT initialized\")))\n ; make su", "end": 10396, "score": 0.9239972829818726, "start": 10395, "tag": "KEY", "value": "1" } ]
common/clojure/nightweb/torrents_dht.clj
anandprabhakar0507/Nightweb
136
(ns nightweb.torrents-dht (:require [clojure.java.io :as java.io] [nightweb.constants :as c] [nightweb.crypto :as crypto] [nightweb.db :as db] [nightweb.io :as io] [nightweb.formats :as f] [nightweb.torrents :as t]) (:import [net.i2p.data Destination] [org.klomp.snark Peer Snark SnarkManager] [org.klomp.snark.dht DHT NodeInfo CustomQueryHandler])) ; dht nodes (defn get-node-info-for-peer [^Peer peer] (let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager)) ^Destination destination (.getAddress (.getPeerID peer))] (.getNodeInfo dht destination))) (defn get-public-node [] (if-let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager))] (.toPersistentString (.getNodeInfo dht nil)) (println "Failed to get public node"))) (defn get-private-node [] (if-let [socket-manager (.getSocketManager (.util ^SnarkManager @t/manager))] (.getSession socket-manager) (println "Failed to get private node"))) (defn add-node! [node-info-str] (if-let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager))] (let [^NodeInfo ninfo (.heardAbout dht (NodeInfo. node-info-str))] (.setPermanent ninfo true)) (println "Failed to add bootstrap node"))) (defn is-connecting? [] (if-let [util (.util ^SnarkManager @t/manager)] (.isConnecting util) true)) ; sending meta links (defn send-custom-query! "Sends a query over KRPC." [node-info method args] (let [query (doto (java.util.HashMap.) (.put "q" method) (.put "a" args))] (-> (.util ^SnarkManager @t/manager) .getDHT (.sendQuery node-info query true)))) (defn send-meta-link! "Sends the relevant meta link to all peers in a given user torrent." ([] (when-let [torrent (-> (c/get-user-pub-torrent-file @c/my-hash-str) (t/get-torrent-by-path))] (send-meta-link! torrent))) ([^Snark torrent] (let [info-hash-str (f/base32-encode (.getInfoHash torrent)) args (io/read-link-file info-hash-str)] (t/iterate-peers torrent (fn [peer] (-> (get-node-info-for-peer peer) (send-custom-query! "announce_meta" args))))))) (defn send-meta-link-periodically! "Sends the relevant meta link to all peers in each user torrent." [seconds] (future (while true (Thread/sleep (* seconds 1000)) (t/iterate-torrents (fn [^Snark torrent] (when (.getPersistent torrent) (send-meta-link! torrent))))))) ; ingest meta torrents (defn add-user-hash! "Begins following the supplied user hash if we aren't already." [their-hash-bytes] (when their-hash-bytes (let [their-hash-str (f/base32-encode their-hash-bytes) path (c/get-user-dir their-hash-str)] (when-not (io/file-exists? path) (io/make-dir! path) (t/add-hash! path their-hash-str true send-meta-link!))))) (defn remove-user-hash! "Removes a user completely if nobody we care about is following them." [their-hash-bytes] (when (and their-hash-bytes (not (c/is-me? their-hash-bytes true)) (-> (for [my-user-hash @c/my-hash-list] (db/get-fav-data {:ptrhash their-hash-bytes} my-user-hash)) doall flatten count (= 0))) (let [^String their-hash-str (f/base32-encode their-hash-bytes) user-dir (c/get-user-dir their-hash-str)] (println "Deleting user" their-hash-str) (t/iterate-torrents (fn [^Snark torrent] (when (>= (.indexOf (.getDataDir torrent) their-hash-str) 0) (t/remove-torrent! (.getName torrent))))) (io/delete-file-recursively! user-dir) (db/delete-user! their-hash-bytes) (io/iterate-dir (c/get-user-dir) #(remove-user-hash! (f/base32-decode %)))))) (defn on-recv-fav! "Add or remove user if necessary based on a fav we received." [user-hash ptr-hash status] ; if this is from a user we care about (when (or (c/is-me? user-hash true) (->> (for [my-user-hash @c/my-hash-list] (db/get-single-fav-data {:userhash user-hash} my-user-hash)) doall (filter #(= 1 (:status %))) count (= 0) not)) (case status ; if the fav has a status of 0, unfollow them if necessary 0 (remove-user-hash! ptr-hash) ; if the fav has a status of 1, make sure we are following them 1 (add-user-hash! ptr-hash) nil))) (defn on-recv-meta-file! "Ingests a given file from a meta torrent" [user-hash-bytes meta-file] ; insert it into the db (db/insert-meta-data! user-hash-bytes meta-file) ; if this is a fav of a user, act on it if necessary (let [meta-contents (:contents meta-file)] (when (and (= "fav" (:dir-name meta-file)) (nil? (get meta-contents "ptrtime"))) (on-recv-fav! user-hash-bytes (f/b-decode-bytes (get meta-contents "ptrhash")) (f/b-decode-long (get meta-contents "status")))))) (defn on-recv-meta! "Ingests all files in a meta torrent." [^Snark torrent] (let [parent-dir (.getParentFile (java.io/file (.getName torrent))) user-hash-bytes (f/base32-decode (.getName parent-dir)) paths (.getFiles (.getMetaInfo torrent))] ; iterate over the files in this torrent (doseq [path-leaves paths] (on-recv-meta-file! user-hash-bytes (io/read-meta-file parent-dir path-leaves))) ; remove any files that the torrent no longer contains (when-not (c/is-me? user-hash-bytes true) (io/delete-orphaned-files! user-hash-bytes paths)))) ; receiving meta links (defn parse-meta-link "Creates a map of parsed values from a given meta link." [link] (let [{data-val "data" sig-val "sig"} link data-map (f/b-decode-map (f/b-decode (f/b-decode-bytes data-val))) {user-hash-val "user_hash" link-hash-val "link_hash" time-val "mtime"} data-map user-hash-bytes (f/b-decode-bytes user-hash-val) link-hash-bytes (f/b-decode-bytes link-hash-val) time-num (f/b-decode-long time-val)] (when (and link data-val user-hash-bytes) {:link (f/b-encode link) :data (f/b-decode-bytes data-val) :sig (f/b-decode-bytes sig-val) :user-hash-str (f/base32-encode user-hash-bytes) :link-hash-str (f/base32-encode link-hash-bytes) :time time-num}))) (defn validate-meta-link "Makes sure a meta link has the required values and signature." [link-map] (and link-map (:time link-map) (<= (:time link-map) (.getTime (java.util.Date.))) (let [user-hash-str (:user-hash-str link-map) pub-key-path (c/get-user-pub-file user-hash-str)] (crypto/verify-signature (io/read-key-file pub-key-path) (:sig link-map) (:data link-map))))) (defn save-meta-link! "Saves a meta link to the disk." [link-map] (let [user-hash-str (:user-hash-str link-map) link-path (c/get-meta-link-file user-hash-str)] (io/write-file! link-path (:link link-map)))) (defn replace-meta-link! "Stops sharing a given meta torrent and begins downloading an updated one." [user-hash-str old-link-map new-link-map] (let [user-dir (c/get-user-dir user-hash-str) meta-torrent-path (c/get-meta-torrent-file user-hash-str)] (t/remove-torrent! meta-torrent-path) (when-let [old-hash-str (:link-hash-str old-link-map)] (t/remove-torrent! old-hash-str)) (save-meta-link! new-link-map) (t/add-hash! user-dir (:link-hash-str new-link-map) false on-recv-meta!) (println "Saved meta link"))) (defn compare-meta-link! "Checks if a given meta link is newer than the one we already have." [link-map] (let [user-hash-str (:user-hash-str link-map) my-link (io/read-link-file user-hash-str) my-link-map (parse-meta-link my-link) my-time (:time my-link-map) their-time (:time link-map)] (if (not= my-time their-time) (if (validate-meta-link link-map) (if (or (nil? my-time) (> their-time my-time)) (replace-meta-link! user-hash-str my-link-map link-map) my-link) my-link) (comment "Received identical link")))) (defn receive-meta-link! "Parses and, if necessary, saves a given meta link." [args] (if-let [link (parse-meta-link args)] (compare-meta-link! link) (println "Meta link can't be parsed"))) ; initialization (defn init-dht "Sets the node keys, query handler, and bootstrap node for DHT." [] ; set the node keys from the disk (let [priv-node (io/read-priv-node-key-file) pub-node (io/read-pub-node-key-file)] (when (and priv-node pub-node) (.setDHTNode (.util ^SnarkManager @t/manager) priv-node pub-node))) ; set the custom query handler (.setDHTCustomQueryHandler (.util ^SnarkManager @t/manager) (reify CustomQueryHandler (receiveQuery [this method args] (case method "announce_meta" (receive-meta-link! args) nil)) (receiveResponse [this args] (receive-meta-link! args)))) ; set the init callback (.setDHTInitCallback (.util ^SnarkManager @t/manager) (fn [] (let [priv-node (get-private-node) pub-node (get-public-node)] (when (and priv-node pub-node) (io/write-priv-node-key-file! priv-node) (io/write-pub-node-key-file! pub-node))) ; add dht bootstrap node (add-node! "rkJ0ws6PQz8FU7VvTW~Lelhb6DM=:rkJ0wkX6jrW3HJBNdhuLlWCUPKDAlX8T23lrTOeMGK8=:B5QFqHHlCT5fOA2QWLAlAKba1hIjW-KBt2HCqwtJg8JFa2KnjAzcexyveYT8HOcMB~W6nhwhzQ7~sywFkvcvRkKHbf6LqP0X43q9y2ADFk2t9LpUle-L-x34ZodEEDxQbwWo74f-rX5IemW2-Du-8NH-o124OGvq5N4uT4PjtxmgSVrBYVLjZRYFUWgdmgR1lVOncfMDbXzXGf~HdY97s9ZFHYyi7ymwzlk4bBN9-Pd4I1tJB2sYBzk62s3gzY1TlDKOdy7qy1Eyr4SEISAopJrvAnSkS1eIFyCoqfzzrBWM11uWppWetf3AkHxGitJIQe73wmZrrO36jHNewIct54v2iF~~3cqBVlT4ptX1Dc-thjrxXoV73A0HUASldCeFZSVJFMQgOQK9U85NQscAokftpyp4Ai89YWaUvSDcZPd-mQuA275zifPwp8s8UfYV5EBqvdHnfeJjxmyTcKR3g5Ft8ABai9yywxoA7yoABD4EGzsFtAh0nOLcmbM944zdAAAA:35701") (println "DHT initialized"))) ; make sure we always have the newest meta link from our user torrents (send-meta-link-periodically! 60))
94321
(ns nightweb.torrents-dht (:require [clojure.java.io :as java.io] [nightweb.constants :as c] [nightweb.crypto :as crypto] [nightweb.db :as db] [nightweb.io :as io] [nightweb.formats :as f] [nightweb.torrents :as t]) (:import [net.i2p.data Destination] [org.klomp.snark Peer Snark SnarkManager] [org.klomp.snark.dht DHT NodeInfo CustomQueryHandler])) ; dht nodes (defn get-node-info-for-peer [^Peer peer] (let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager)) ^Destination destination (.getAddress (.getPeerID peer))] (.getNodeInfo dht destination))) (defn get-public-node [] (if-let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager))] (.toPersistentString (.getNodeInfo dht nil)) (println "Failed to get public node"))) (defn get-private-node [] (if-let [socket-manager (.getSocketManager (.util ^SnarkManager @t/manager))] (.getSession socket-manager) (println "Failed to get private node"))) (defn add-node! [node-info-str] (if-let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager))] (let [^NodeInfo ninfo (.heardAbout dht (NodeInfo. node-info-str))] (.setPermanent ninfo true)) (println "Failed to add bootstrap node"))) (defn is-connecting? [] (if-let [util (.util ^SnarkManager @t/manager)] (.isConnecting util) true)) ; sending meta links (defn send-custom-query! "Sends a query over KRPC." [node-info method args] (let [query (doto (java.util.HashMap.) (.put "q" method) (.put "a" args))] (-> (.util ^SnarkManager @t/manager) .getDHT (.sendQuery node-info query true)))) (defn send-meta-link! "Sends the relevant meta link to all peers in a given user torrent." ([] (when-let [torrent (-> (c/get-user-pub-torrent-file @c/my-hash-str) (t/get-torrent-by-path))] (send-meta-link! torrent))) ([^Snark torrent] (let [info-hash-str (f/base32-encode (.getInfoHash torrent)) args (io/read-link-file info-hash-str)] (t/iterate-peers torrent (fn [peer] (-> (get-node-info-for-peer peer) (send-custom-query! "announce_meta" args))))))) (defn send-meta-link-periodically! "Sends the relevant meta link to all peers in each user torrent." [seconds] (future (while true (Thread/sleep (* seconds 1000)) (t/iterate-torrents (fn [^Snark torrent] (when (.getPersistent torrent) (send-meta-link! torrent))))))) ; ingest meta torrents (defn add-user-hash! "Begins following the supplied user hash if we aren't already." [their-hash-bytes] (when their-hash-bytes (let [their-hash-str (f/base32-encode their-hash-bytes) path (c/get-user-dir their-hash-str)] (when-not (io/file-exists? path) (io/make-dir! path) (t/add-hash! path their-hash-str true send-meta-link!))))) (defn remove-user-hash! "Removes a user completely if nobody we care about is following them." [their-hash-bytes] (when (and their-hash-bytes (not (c/is-me? their-hash-bytes true)) (-> (for [my-user-hash @c/my-hash-list] (db/get-fav-data {:ptrhash their-hash-bytes} my-user-hash)) doall flatten count (= 0))) (let [^String their-hash-str (f/base32-encode their-hash-bytes) user-dir (c/get-user-dir their-hash-str)] (println "Deleting user" their-hash-str) (t/iterate-torrents (fn [^Snark torrent] (when (>= (.indexOf (.getDataDir torrent) their-hash-str) 0) (t/remove-torrent! (.getName torrent))))) (io/delete-file-recursively! user-dir) (db/delete-user! their-hash-bytes) (io/iterate-dir (c/get-user-dir) #(remove-user-hash! (f/base32-decode %)))))) (defn on-recv-fav! "Add or remove user if necessary based on a fav we received." [user-hash ptr-hash status] ; if this is from a user we care about (when (or (c/is-me? user-hash true) (->> (for [my-user-hash @c/my-hash-list] (db/get-single-fav-data {:userhash user-hash} my-user-hash)) doall (filter #(= 1 (:status %))) count (= 0) not)) (case status ; if the fav has a status of 0, unfollow them if necessary 0 (remove-user-hash! ptr-hash) ; if the fav has a status of 1, make sure we are following them 1 (add-user-hash! ptr-hash) nil))) (defn on-recv-meta-file! "Ingests a given file from a meta torrent" [user-hash-bytes meta-file] ; insert it into the db (db/insert-meta-data! user-hash-bytes meta-file) ; if this is a fav of a user, act on it if necessary (let [meta-contents (:contents meta-file)] (when (and (= "fav" (:dir-name meta-file)) (nil? (get meta-contents "ptrtime"))) (on-recv-fav! user-hash-bytes (f/b-decode-bytes (get meta-contents "ptrhash")) (f/b-decode-long (get meta-contents "status")))))) (defn on-recv-meta! "Ingests all files in a meta torrent." [^Snark torrent] (let [parent-dir (.getParentFile (java.io/file (.getName torrent))) user-hash-bytes (f/base32-decode (.getName parent-dir)) paths (.getFiles (.getMetaInfo torrent))] ; iterate over the files in this torrent (doseq [path-leaves paths] (on-recv-meta-file! user-hash-bytes (io/read-meta-file parent-dir path-leaves))) ; remove any files that the torrent no longer contains (when-not (c/is-me? user-hash-bytes true) (io/delete-orphaned-files! user-hash-bytes paths)))) ; receiving meta links (defn parse-meta-link "Creates a map of parsed values from a given meta link." [link] (let [{data-val "data" sig-val "sig"} link data-map (f/b-decode-map (f/b-decode (f/b-decode-bytes data-val))) {user-hash-val "user_hash" link-hash-val "link_hash" time-val "mtime"} data-map user-hash-bytes (f/b-decode-bytes user-hash-val) link-hash-bytes (f/b-decode-bytes link-hash-val) time-num (f/b-decode-long time-val)] (when (and link data-val user-hash-bytes) {:link (f/b-encode link) :data (f/b-decode-bytes data-val) :sig (f/b-decode-bytes sig-val) :user-hash-str (f/base32-encode user-hash-bytes) :link-hash-str (f/base32-encode link-hash-bytes) :time time-num}))) (defn validate-meta-link "Makes sure a meta link has the required values and signature." [link-map] (and link-map (:time link-map) (<= (:time link-map) (.getTime (java.util.Date.))) (let [user-hash-str (:user-hash-str link-map) pub-key-path (c/get-user-pub-file user-hash-str)] (crypto/verify-signature (io/read-key-file pub-key-path) (:sig link-map) (:data link-map))))) (defn save-meta-link! "Saves a meta link to the disk." [link-map] (let [user-hash-str (:user-hash-str link-map) link-path (c/get-meta-link-file user-hash-str)] (io/write-file! link-path (:link link-map)))) (defn replace-meta-link! "Stops sharing a given meta torrent and begins downloading an updated one." [user-hash-str old-link-map new-link-map] (let [user-dir (c/get-user-dir user-hash-str) meta-torrent-path (c/get-meta-torrent-file user-hash-str)] (t/remove-torrent! meta-torrent-path) (when-let [old-hash-str (:link-hash-str old-link-map)] (t/remove-torrent! old-hash-str)) (save-meta-link! new-link-map) (t/add-hash! user-dir (:link-hash-str new-link-map) false on-recv-meta!) (println "Saved meta link"))) (defn compare-meta-link! "Checks if a given meta link is newer than the one we already have." [link-map] (let [user-hash-str (:user-hash-str link-map) my-link (io/read-link-file user-hash-str) my-link-map (parse-meta-link my-link) my-time (:time my-link-map) their-time (:time link-map)] (if (not= my-time their-time) (if (validate-meta-link link-map) (if (or (nil? my-time) (> their-time my-time)) (replace-meta-link! user-hash-str my-link-map link-map) my-link) my-link) (comment "Received identical link")))) (defn receive-meta-link! "Parses and, if necessary, saves a given meta link." [args] (if-let [link (parse-meta-link args)] (compare-meta-link! link) (println "Meta link can't be parsed"))) ; initialization (defn init-dht "Sets the node keys, query handler, and bootstrap node for DHT." [] ; set the node keys from the disk (let [priv-node (io/read-priv-node-key-file) pub-node (io/read-pub-node-key-file)] (when (and priv-node pub-node) (.setDHTNode (.util ^SnarkManager @t/manager) priv-node pub-node))) ; set the custom query handler (.setDHTCustomQueryHandler (.util ^SnarkManager @t/manager) (reify CustomQueryHandler (receiveQuery [this method args] (case method "announce_meta" (receive-meta-link! args) nil)) (receiveResponse [this args] (receive-meta-link! args)))) ; set the init callback (.setDHTInitCallback (.util ^SnarkManager @t/manager) (fn [] (let [priv-node (get-private-node) pub-node (get-public-node)] (when (and priv-node pub-node) (io/write-priv-node-key-file! priv-node) (io/write-pub-node-key-file! pub-node))) ; add dht bootstrap node (add-node! "<KEY>:3570<KEY>") (println "DHT initialized"))) ; make sure we always have the newest meta link from our user torrents (send-meta-link-periodically! 60))
true
(ns nightweb.torrents-dht (:require [clojure.java.io :as java.io] [nightweb.constants :as c] [nightweb.crypto :as crypto] [nightweb.db :as db] [nightweb.io :as io] [nightweb.formats :as f] [nightweb.torrents :as t]) (:import [net.i2p.data Destination] [org.klomp.snark Peer Snark SnarkManager] [org.klomp.snark.dht DHT NodeInfo CustomQueryHandler])) ; dht nodes (defn get-node-info-for-peer [^Peer peer] (let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager)) ^Destination destination (.getAddress (.getPeerID peer))] (.getNodeInfo dht destination))) (defn get-public-node [] (if-let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager))] (.toPersistentString (.getNodeInfo dht nil)) (println "Failed to get public node"))) (defn get-private-node [] (if-let [socket-manager (.getSocketManager (.util ^SnarkManager @t/manager))] (.getSession socket-manager) (println "Failed to get private node"))) (defn add-node! [node-info-str] (if-let [^DHT dht (.getDHT (.util ^SnarkManager @t/manager))] (let [^NodeInfo ninfo (.heardAbout dht (NodeInfo. node-info-str))] (.setPermanent ninfo true)) (println "Failed to add bootstrap node"))) (defn is-connecting? [] (if-let [util (.util ^SnarkManager @t/manager)] (.isConnecting util) true)) ; sending meta links (defn send-custom-query! "Sends a query over KRPC." [node-info method args] (let [query (doto (java.util.HashMap.) (.put "q" method) (.put "a" args))] (-> (.util ^SnarkManager @t/manager) .getDHT (.sendQuery node-info query true)))) (defn send-meta-link! "Sends the relevant meta link to all peers in a given user torrent." ([] (when-let [torrent (-> (c/get-user-pub-torrent-file @c/my-hash-str) (t/get-torrent-by-path))] (send-meta-link! torrent))) ([^Snark torrent] (let [info-hash-str (f/base32-encode (.getInfoHash torrent)) args (io/read-link-file info-hash-str)] (t/iterate-peers torrent (fn [peer] (-> (get-node-info-for-peer peer) (send-custom-query! "announce_meta" args))))))) (defn send-meta-link-periodically! "Sends the relevant meta link to all peers in each user torrent." [seconds] (future (while true (Thread/sleep (* seconds 1000)) (t/iterate-torrents (fn [^Snark torrent] (when (.getPersistent torrent) (send-meta-link! torrent))))))) ; ingest meta torrents (defn add-user-hash! "Begins following the supplied user hash if we aren't already." [their-hash-bytes] (when their-hash-bytes (let [their-hash-str (f/base32-encode their-hash-bytes) path (c/get-user-dir their-hash-str)] (when-not (io/file-exists? path) (io/make-dir! path) (t/add-hash! path their-hash-str true send-meta-link!))))) (defn remove-user-hash! "Removes a user completely if nobody we care about is following them." [their-hash-bytes] (when (and their-hash-bytes (not (c/is-me? their-hash-bytes true)) (-> (for [my-user-hash @c/my-hash-list] (db/get-fav-data {:ptrhash their-hash-bytes} my-user-hash)) doall flatten count (= 0))) (let [^String their-hash-str (f/base32-encode their-hash-bytes) user-dir (c/get-user-dir their-hash-str)] (println "Deleting user" their-hash-str) (t/iterate-torrents (fn [^Snark torrent] (when (>= (.indexOf (.getDataDir torrent) their-hash-str) 0) (t/remove-torrent! (.getName torrent))))) (io/delete-file-recursively! user-dir) (db/delete-user! their-hash-bytes) (io/iterate-dir (c/get-user-dir) #(remove-user-hash! (f/base32-decode %)))))) (defn on-recv-fav! "Add or remove user if necessary based on a fav we received." [user-hash ptr-hash status] ; if this is from a user we care about (when (or (c/is-me? user-hash true) (->> (for [my-user-hash @c/my-hash-list] (db/get-single-fav-data {:userhash user-hash} my-user-hash)) doall (filter #(= 1 (:status %))) count (= 0) not)) (case status ; if the fav has a status of 0, unfollow them if necessary 0 (remove-user-hash! ptr-hash) ; if the fav has a status of 1, make sure we are following them 1 (add-user-hash! ptr-hash) nil))) (defn on-recv-meta-file! "Ingests a given file from a meta torrent" [user-hash-bytes meta-file] ; insert it into the db (db/insert-meta-data! user-hash-bytes meta-file) ; if this is a fav of a user, act on it if necessary (let [meta-contents (:contents meta-file)] (when (and (= "fav" (:dir-name meta-file)) (nil? (get meta-contents "ptrtime"))) (on-recv-fav! user-hash-bytes (f/b-decode-bytes (get meta-contents "ptrhash")) (f/b-decode-long (get meta-contents "status")))))) (defn on-recv-meta! "Ingests all files in a meta torrent." [^Snark torrent] (let [parent-dir (.getParentFile (java.io/file (.getName torrent))) user-hash-bytes (f/base32-decode (.getName parent-dir)) paths (.getFiles (.getMetaInfo torrent))] ; iterate over the files in this torrent (doseq [path-leaves paths] (on-recv-meta-file! user-hash-bytes (io/read-meta-file parent-dir path-leaves))) ; remove any files that the torrent no longer contains (when-not (c/is-me? user-hash-bytes true) (io/delete-orphaned-files! user-hash-bytes paths)))) ; receiving meta links (defn parse-meta-link "Creates a map of parsed values from a given meta link." [link] (let [{data-val "data" sig-val "sig"} link data-map (f/b-decode-map (f/b-decode (f/b-decode-bytes data-val))) {user-hash-val "user_hash" link-hash-val "link_hash" time-val "mtime"} data-map user-hash-bytes (f/b-decode-bytes user-hash-val) link-hash-bytes (f/b-decode-bytes link-hash-val) time-num (f/b-decode-long time-val)] (when (and link data-val user-hash-bytes) {:link (f/b-encode link) :data (f/b-decode-bytes data-val) :sig (f/b-decode-bytes sig-val) :user-hash-str (f/base32-encode user-hash-bytes) :link-hash-str (f/base32-encode link-hash-bytes) :time time-num}))) (defn validate-meta-link "Makes sure a meta link has the required values and signature." [link-map] (and link-map (:time link-map) (<= (:time link-map) (.getTime (java.util.Date.))) (let [user-hash-str (:user-hash-str link-map) pub-key-path (c/get-user-pub-file user-hash-str)] (crypto/verify-signature (io/read-key-file pub-key-path) (:sig link-map) (:data link-map))))) (defn save-meta-link! "Saves a meta link to the disk." [link-map] (let [user-hash-str (:user-hash-str link-map) link-path (c/get-meta-link-file user-hash-str)] (io/write-file! link-path (:link link-map)))) (defn replace-meta-link! "Stops sharing a given meta torrent and begins downloading an updated one." [user-hash-str old-link-map new-link-map] (let [user-dir (c/get-user-dir user-hash-str) meta-torrent-path (c/get-meta-torrent-file user-hash-str)] (t/remove-torrent! meta-torrent-path) (when-let [old-hash-str (:link-hash-str old-link-map)] (t/remove-torrent! old-hash-str)) (save-meta-link! new-link-map) (t/add-hash! user-dir (:link-hash-str new-link-map) false on-recv-meta!) (println "Saved meta link"))) (defn compare-meta-link! "Checks if a given meta link is newer than the one we already have." [link-map] (let [user-hash-str (:user-hash-str link-map) my-link (io/read-link-file user-hash-str) my-link-map (parse-meta-link my-link) my-time (:time my-link-map) their-time (:time link-map)] (if (not= my-time their-time) (if (validate-meta-link link-map) (if (or (nil? my-time) (> their-time my-time)) (replace-meta-link! user-hash-str my-link-map link-map) my-link) my-link) (comment "Received identical link")))) (defn receive-meta-link! "Parses and, if necessary, saves a given meta link." [args] (if-let [link (parse-meta-link args)] (compare-meta-link! link) (println "Meta link can't be parsed"))) ; initialization (defn init-dht "Sets the node keys, query handler, and bootstrap node for DHT." [] ; set the node keys from the disk (let [priv-node (io/read-priv-node-key-file) pub-node (io/read-pub-node-key-file)] (when (and priv-node pub-node) (.setDHTNode (.util ^SnarkManager @t/manager) priv-node pub-node))) ; set the custom query handler (.setDHTCustomQueryHandler (.util ^SnarkManager @t/manager) (reify CustomQueryHandler (receiveQuery [this method args] (case method "announce_meta" (receive-meta-link! args) nil)) (receiveResponse [this args] (receive-meta-link! args)))) ; set the init callback (.setDHTInitCallback (.util ^SnarkManager @t/manager) (fn [] (let [priv-node (get-private-node) pub-node (get-public-node)] (when (and priv-node pub-node) (io/write-priv-node-key-file! priv-node) (io/write-pub-node-key-file! pub-node))) ; add dht bootstrap node (add-node! "PI:KEY:<KEY>END_PI:3570PI:KEY:<KEY>END_PI") (println "DHT initialized"))) ; make sure we always have the newest meta link from our user torrents (send-meta-link-periodically! 60))
[ { "context": "; Copyright 2018-2021 Rahul De\n;\n; Use of this source code is governed by an MIT", "end": 30, "score": 0.9998666048049927, "start": 22, "tag": "NAME", "value": "Rahul De" } ]
common/src/common/errors.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 common.errors (:require [langohr.basic :as lb] [clojure.data.json :as json] [taoensso.timbre :as log])) (defn publish-error [chan message] (log/error message) (lb/publish chan "" ; Default exchange "bob.errors" (json/write-str {:message message} :key-fn #(subs (str %) 1)) {:content-type "application/json" :type "message/error"}))
20957
; 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 common.errors (:require [langohr.basic :as lb] [clojure.data.json :as json] [taoensso.timbre :as log])) (defn publish-error [chan message] (log/error message) (lb/publish chan "" ; Default exchange "bob.errors" (json/write-str {:message message} :key-fn #(subs (str %) 1)) {:content-type "application/json" :type "message/error"}))
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 common.errors (:require [langohr.basic :as lb] [clojure.data.json :as json] [taoensso.timbre :as log])) (defn publish-error [chan message] (log/error message) (lb/publish chan "" ; Default exchange "bob.errors" (json/write-str {:message message} :key-fn #(subs (str %) 1)) {:content-type "application/json" :type "message/error"}))
[ { "context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998838901519775, "start": 25, "tag": "NAME", "value": "Esko Luontola" }, { "context": "\n(def ^:dynamic *user*)\n\n(def user-profile-keys [:sub :name :nickname :email :email_verified :picture])\n\n(defn user-session [jwt", "end": 329, "score": 0.7953791618347168, "start": 301, "tag": "KEY", "value": "sub :name :nickname :email :" }, { "context": "-profile-keys [:sub :name :nickname :email :email_verified :picture])\n\n(defn user-session [jwt user-id]\n {::user (->", "end": 352, "score": 0.7689593434333801, "start": 335, "tag": "KEY", "value": "verified :picture" } ]
src/territory_bro/authentication.clj
JessRoberts/territory_assistant
0
;; Copyright © 2015-2019 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.authentication (:require [territory-bro.config :refer [env]])) (def ^:dynamic *user*) (def user-profile-keys [:sub :name :nickname :email :email_verified :picture]) (defn user-session [jwt user-id] {::user (-> (select-keys jwt user-profile-keys) (assoc :user/id user-id))}) (defn with-authenticated-user* [request f] (binding [*user* (get-in request [:session ::user])] (f))) (defmacro with-authenticated-user [request & body] `(with-authenticated-user* ~request (fn [] ~@body)))
33199
;; Copyright © 2015-2019 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.authentication (:require [territory-bro.config :refer [env]])) (def ^:dynamic *user*) (def user-profile-keys [:<KEY>email_<KEY>]) (defn user-session [jwt user-id] {::user (-> (select-keys jwt user-profile-keys) (assoc :user/id user-id))}) (defn with-authenticated-user* [request f] (binding [*user* (get-in request [:session ::user])] (f))) (defmacro with-authenticated-user [request & body] `(with-authenticated-user* ~request (fn [] ~@body)))
true
;; Copyright © 2015-2019 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.authentication (:require [territory-bro.config :refer [env]])) (def ^:dynamic *user*) (def user-profile-keys [:PI:KEY:<KEY>END_PIemail_PI:KEY:<KEY>END_PI]) (defn user-session [jwt user-id] {::user (-> (select-keys jwt user-profile-keys) (assoc :user/id user-id))}) (defn with-authenticated-user* [request f] (binding [*user* (get-in request [:session ::user])] (f))) (defmacro with-authenticated-user [request & body] `(with-authenticated-user* ~request (fn [] ~@body)))
[ { "context": "(ns clj-derp.core\n ^{:author \"Frank Shearar\",\n :doc\n\"This file defines the derivative of a", "end": 44, "score": 0.9998798370361328, "start": 31, "tag": "NAME", "value": "Frank Shearar" } ]
src/clj_derp/core.clj
frankshearar/clj-derp
1
(ns clj-derp.core ^{:author "Frank Shearar", :doc "This file defines the derivative of a context free grammar, and provides a simple API for parsing streams."} (:require [clojure.set :as set]) (:require [clojure.string :as string]) (:require [clojure.core.cache :as cache])) (defn cart-prod [set-one set-two concat-fn] "Return the Cartesian product of set-one and set-two." (set (mapcat (fn [a] (map (fn [b] (apply concat-fn [a b])) set-two)) set-one))) (defmacro defn-fix [name bottom fn] `(let* [*cache*# (atom (cache/soft-cache-factory {})) *changed?*# (atom false) *running?*# (atom false) *visited*# (atom {})] (defn ~name [x#] (let [cached?# (cache/has? (deref *cache*#) x#) cached# (cache/lookup (deref *cache*#) x#) run?# (deref *running?*#)] (cond (and cached?# (not run?#)) cached# (and run?# (get (deref *visited*#) x#)) (if cached?# cached# ~bottom) run?# (do (swap! *visited*# assoc x# true) (let [new-val# (apply ~fn [x#])] (when (not (= new-val# cached#)) (swap! *changed?*# (fn [_#] true)) (swap! *cache*# (fn [c#] (if cached?# (cache/hit c# x#) (cache/miss c# x# new-val#))))) new-val#)) (and (not cached?#) (not run?#)) (do (swap! *changed?*# (fn [_#] true)) (swap! *running?*# (fn [_#] true)) (swap! *visited*# (fn [_#] {})) (let [v# (atom ~bottom)] (while (deref *changed?*#) (swap! *changed?*# (fn [_#] false)) (swap! *visited*# (fn [_#] {})) (swap! v# (fn [_#] (apply ~fn [x#])))) (deref v#)))))))) (defn- memoize-with-cache [f new-cache] (let [cache (atom new-cache) recalc (fn [args] (let [answer (apply f args)] (swap! cache (fn [c] (cache/miss c args answer))) answer))] (fn [& args] (if (cache/has? @cache args) (do (swap! cache (fn [c] (cache/hit c args))) (if-let [answer (cache/lookup @cache args)] answer (recalc args))) (recalc args))))) (defn memoized ^{:doc "Given a function f, return a memoized function using either a given cache, or a cache using soft references."} ([f] (memoize-with-cache f (cache/soft-cache-factory {}))) ([f cache] (memoize-with-cache f cache))) (defprotocol Parser (d-int [this token]) (compact-int [this]) (empty-int? [this]) (nullable-int? [this]) (parse-null-int [this])) (defprotocol ComparableParser "Since we use Delays, equality comparison becomes troublesome. This protocol gives us a chance to force any delays, permitting us to still compare graphs for structural equality." (eq [this that])) (defprotocol StructuralParser "A means for a parser to expose its subparsers in a uniform manner." (subparsers [this])) (defprotocol PrintableParser "A protocol to provide for the printing of a graph in dotfile format." (print-node [this int-map] "Print this parser as part of a dotfile. int-map maps parsers to integers.")) (def compact (memoized (fn [parser] (compact-int parser)))) (def d (memoized (fn [parser token] (d-int parser token)))) (defn-fix parse-null {} (fn [parser] (parse-null-int parser))) (defn-fix nullable? false (fn [parser] (nullable-int? parser))) (defn-fix empty-p? false (fn [parser] (empty-int? parser))) (defn singleton-parse? [parser] (= 1 (count (parse-null parser)))) ;; We forward declare the helper constructors because we use them ;; in the defrecords. (declare empty-p) (declare eps) (declare eps*) (declare eps**) (declare lit) (declare alt) (declare cat) (declare red) (declare star) ;; We have to forward declare helpers like these because we use them ;; in the defrecords. (declare red?) (defrecord empty-parser [] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [label=\"empty\"]" (get int-map this :not-found))) Parser (d-int [this _] this) (compact-int [this] this) (empty-int? [_] true) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord empty-string-parser [tree-set] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"eps* | %s\"]" (get int-map this) tree-set)) Parser (d-int [this _] (empty-p)) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] true) (parse-null-int [_] tree-set)) (defrecord literal-parser [token] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"token | %s\"]" (get int-map this) token)) Parser (d-int [this t] (if (= token t) (eps* token) (empty-p))) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord literal-set-parser [token-set] ;; A parser that can consume one of a set of literals. You may think of ;; (lit+ 1 2) as being an optimised form of (alt (lit 1) (lit 2)). ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"token | %s\"]" (get int-map this) token-set)) Parser (d-int [this t] (if (contains? token-set t) (eps* t) (empty-p))) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord red-parser [parser fn] ComparableParser ;; There's a major limitation here: there is no = for ;; functions, so if you really care about equality of ;; reduction parsers, you need to control what functions ;; you use: perhaps define a handful of primitives that ;; you can compose as necessary. (eq [this that] (and (eq (:parser this) (:parser that)) (= (:fn this) (:fn that)))) StructuralParser (subparsers [this] [(:parser this)]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) sub-n (get int-map parser)] (string/join "\n" [(format "\"%s\" [label=\"red\"]" this-n) (format "\"%s\" -> \"%s\"" this-n sub-n)]))) Parser (d-int [this t] (red (d parser t) fn)) (compact-int [this] (cond (red? parser) (red (compact parser) (comp fn (:fn parser))) :else (red (compact parser) fn))) (empty-int? [this] (empty-p? parser)) (nullable-int? [this] (nullable? parser)) (parse-null-int [this] (set (map fn (parse-null parser))))) (defrecord star-parser [parser] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [this] [parser]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) sub-n (get int-map parser)] (string/join "\n" [(format "\"%s\" [label=\"star\"]" this-n) (format "\"%s\" -> \"%s\"" this-n sub-n)]))) Parser (d-int [this t] (cat (d parser t) this)) (compact-int [this] (star (compact parser))) (empty-int? [_] false) (nullable-int? [this] (or (nullable? parser) (empty-p? parser))) (parse-null-int [this] #{'()})) (defn- -is-seq [t] "If t isn't a seq (a list), make it one. Can't use sequence because t might not be a collection." (if (seq? t) t (list t))) (defn- -append [t l] "Add t to the back of l, forcing either or both into listy-ness" (concat (-is-seq l) (-is-seq t))) (defn- -prepend [t l] "Add t to the front of l, forcing either or both into listy-ness" (concat (-is-seq t) (-is-seq l))) (defrecord sequence-parser [fst snd] ComparableParser (eq [this that] (and (eq (force (:fst this)) (force (:fst that))) (eq (force (:snd this)) (force (:snd that))))) StructuralParser (subparsers [this] [(force fst) (force snd)]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) fst-n (get int-map (force fst)) snd-n (get int-map (force snd))] (string/join "\n" [(format "\"%s\" [shape=\"none\", margin=0, label=<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\" cellpadding=\"4\"><tr><td colspan=\"2\">seq</td></tr><tr><td port=\"L\">L</td><td port=\"R\">R</td></tr></table>>]" this-n) (format "\"%s\":L -> \"%s\"" this-n fst-n) (format "\"%s\":R -> \"%s\"" this-n snd-n)]))) Parser (d-int [this t] (let [fst (force fst) snd (force snd)] (if (nullable? fst) (alt (cat (eps** (parse-null fst)) (d snd t)) (cat (d fst t) snd)) (cat (d fst t) snd)))) (compact-int [this] (let [fst (force (:fst this)) snd (force (:snd this))] (cond (empty-p? fst) snd (empty-p? snd) fst (singleton-parse? fst) (let [t (first (parse-null fst))] (red snd (fn [w2] (-prepend t w2)))) (singleton-parse? snd) (let [t (first (parse-null snd))] (red fst (fn [w1] (-append t w1)))) :else (let [c1 (compact fst) c2 (compact snd)] (if (= [c1 c2] [fst snd]) ; = effectively means pointer equality here this (cat c1 c2)))))) (empty-int? [this] (or (empty-p? (force fst)) (empty-p? (force snd)))) (nullable-int? [this] (and (nullable? (force fst)) (nullable? (force snd)))) (parse-null-int [this] (cart-prod (parse-null (force fst)) (parse-null (force snd)) (fn [a b] [a b])))) (defrecord union-parser [left right] ComparableParser (eq [this that] (and (eq (force (:left this)) (force (:left that))) (eq (force (:right this)) (force (:right that))))) StructuralParser (subparsers [this] [(force (:left this)) (force (:right this))]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) left-n (get int-map (force left)) right-n (get int-map (force right))] (string/join "\n" [(format "\"%s\" [label=\"or\"]" this-n) (format "\"%s\" -> \"%s\"" this-n left-n) (format "\"%s\" -> \"%s\"" this-n right-n)]))) Parser (d-int [this t] (alt (d (force (:left this)) t) (d (force (:right this)) t))) (compact-int [this] (let [l-empty (eq (empty-p) (force (:left this))) r-empty (eq (empty-p) (force (:right this)))] (cond (and l-empty r-empty) (empty-p) (and (not l-empty) r-empty) (compact (force (:left this))) (and l-empty (not r-empty)) (compact (force (:right this))) :else this))) (empty-int? [this] (and (empty-p? (force (:left this))) (empty-p? (force (:right this))))) (nullable-int? [this] (or (nullable? (force (:left this))) (nullable? (force (:right this))))) (parse-null-int [p] (set/union (parse-null (force (:left p))) (parse-null (force (:right p)))))) ;; Utility constructors (defn empty-p [] "The empty language parser." (empty-parser.)) (defn eps [] "That parser whose language is just the empty string." (empty-string-parser. #{nil})) (defn eps* [token] "A parser that stores a partial parse tree. You probably don't need to use this function." (empty-string-parser. #{token})) ;; A temporary function until I find out the syntax for multimethods (defn eps** [token-set] "Like eps*, but takes a set of parse trees." (empty-string-parser. token-set)) (defn lit [token] "A parser that consumes exactly this token." (literal-parser. token)) (defn lit+ [& rest] "Given any number of tokens, make a parser that can accept any of them." (case (count rest) 0 (eps) 1 (lit (first rest)) (literal-set-parser. (set rest)))) (defn lit* [l] "Given a seq of tokens, make a parser that can accept any of them" (apply lit+ l)) (defn alt "Make a parser that can act as any of a number of subparsers" ([] (empty-p)) ([a & parsers] (if parsers (union-parser. (delay a) (delay (apply alt parsers))) a))) (defn cat "Define a parser whose subparsers each consume things in sequence" ([] (empty-p)) ([a & parsers] (if parsers (sequence-parser. (delay a) (delay (apply cat parsers))) a))) (defn red [parser arity-1-fn] "Define a parser that runs some function over the parse trees of its subparsers. This is the hook for any semantic actions you might need." (red-parser. parser arity-1-fn)) (defn star [parser] "The Kleene star parser" (star-parser. parser)) (defn red? [parser] (instance? red-parser parser)) (defn parse [parser input] (if (empty? input) (parse-null parser) (parse (d parser (first input)) (rest input)))) (defn in? [needle haystack] (some #(= needle %) haystack)) (defn not-in? [needle haystack] (not (in? needle haystack))) (defn- search-1 [p fn seed cache] "Apply fn to each subparser in p in pre-order, returning the collected results in a dictionary mapping p to (fn p). Skip elements in cache." (let [val (apply fn [p])] (assoc (merge seed (reduce merge (map #(search-1 % fn seed (conj cache p)) (filter #(not-in? % cache) (subparsers p))))) p val))) (defn search [p fn] "A cycle-safe map over p." (let [visited #{}] (search-1 p fn {} visited))) (defn mark-uniquely [parser] "Recursively 'mark' the subparsers of p by associating each parser with a unique integer" (let [n (atom -1)] (search parser (fn [p] (swap! n inc))))) (defn print-as-digraph [parser] "Return a parser in a dot format string." (let [int-map (mark-uniquely parser)] (string/join "\n" (concat ["digraph {"] (vals (search parser #(print-node % int-map))) ["}"]))))
20212
(ns clj-derp.core ^{:author "<NAME>", :doc "This file defines the derivative of a context free grammar, and provides a simple API for parsing streams."} (:require [clojure.set :as set]) (:require [clojure.string :as string]) (:require [clojure.core.cache :as cache])) (defn cart-prod [set-one set-two concat-fn] "Return the Cartesian product of set-one and set-two." (set (mapcat (fn [a] (map (fn [b] (apply concat-fn [a b])) set-two)) set-one))) (defmacro defn-fix [name bottom fn] `(let* [*cache*# (atom (cache/soft-cache-factory {})) *changed?*# (atom false) *running?*# (atom false) *visited*# (atom {})] (defn ~name [x#] (let [cached?# (cache/has? (deref *cache*#) x#) cached# (cache/lookup (deref *cache*#) x#) run?# (deref *running?*#)] (cond (and cached?# (not run?#)) cached# (and run?# (get (deref *visited*#) x#)) (if cached?# cached# ~bottom) run?# (do (swap! *visited*# assoc x# true) (let [new-val# (apply ~fn [x#])] (when (not (= new-val# cached#)) (swap! *changed?*# (fn [_#] true)) (swap! *cache*# (fn [c#] (if cached?# (cache/hit c# x#) (cache/miss c# x# new-val#))))) new-val#)) (and (not cached?#) (not run?#)) (do (swap! *changed?*# (fn [_#] true)) (swap! *running?*# (fn [_#] true)) (swap! *visited*# (fn [_#] {})) (let [v# (atom ~bottom)] (while (deref *changed?*#) (swap! *changed?*# (fn [_#] false)) (swap! *visited*# (fn [_#] {})) (swap! v# (fn [_#] (apply ~fn [x#])))) (deref v#)))))))) (defn- memoize-with-cache [f new-cache] (let [cache (atom new-cache) recalc (fn [args] (let [answer (apply f args)] (swap! cache (fn [c] (cache/miss c args answer))) answer))] (fn [& args] (if (cache/has? @cache args) (do (swap! cache (fn [c] (cache/hit c args))) (if-let [answer (cache/lookup @cache args)] answer (recalc args))) (recalc args))))) (defn memoized ^{:doc "Given a function f, return a memoized function using either a given cache, or a cache using soft references."} ([f] (memoize-with-cache f (cache/soft-cache-factory {}))) ([f cache] (memoize-with-cache f cache))) (defprotocol Parser (d-int [this token]) (compact-int [this]) (empty-int? [this]) (nullable-int? [this]) (parse-null-int [this])) (defprotocol ComparableParser "Since we use Delays, equality comparison becomes troublesome. This protocol gives us a chance to force any delays, permitting us to still compare graphs for structural equality." (eq [this that])) (defprotocol StructuralParser "A means for a parser to expose its subparsers in a uniform manner." (subparsers [this])) (defprotocol PrintableParser "A protocol to provide for the printing of a graph in dotfile format." (print-node [this int-map] "Print this parser as part of a dotfile. int-map maps parsers to integers.")) (def compact (memoized (fn [parser] (compact-int parser)))) (def d (memoized (fn [parser token] (d-int parser token)))) (defn-fix parse-null {} (fn [parser] (parse-null-int parser))) (defn-fix nullable? false (fn [parser] (nullable-int? parser))) (defn-fix empty-p? false (fn [parser] (empty-int? parser))) (defn singleton-parse? [parser] (= 1 (count (parse-null parser)))) ;; We forward declare the helper constructors because we use them ;; in the defrecords. (declare empty-p) (declare eps) (declare eps*) (declare eps**) (declare lit) (declare alt) (declare cat) (declare red) (declare star) ;; We have to forward declare helpers like these because we use them ;; in the defrecords. (declare red?) (defrecord empty-parser [] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [label=\"empty\"]" (get int-map this :not-found))) Parser (d-int [this _] this) (compact-int [this] this) (empty-int? [_] true) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord empty-string-parser [tree-set] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"eps* | %s\"]" (get int-map this) tree-set)) Parser (d-int [this _] (empty-p)) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] true) (parse-null-int [_] tree-set)) (defrecord literal-parser [token] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"token | %s\"]" (get int-map this) token)) Parser (d-int [this t] (if (= token t) (eps* token) (empty-p))) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord literal-set-parser [token-set] ;; A parser that can consume one of a set of literals. You may think of ;; (lit+ 1 2) as being an optimised form of (alt (lit 1) (lit 2)). ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"token | %s\"]" (get int-map this) token-set)) Parser (d-int [this t] (if (contains? token-set t) (eps* t) (empty-p))) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord red-parser [parser fn] ComparableParser ;; There's a major limitation here: there is no = for ;; functions, so if you really care about equality of ;; reduction parsers, you need to control what functions ;; you use: perhaps define a handful of primitives that ;; you can compose as necessary. (eq [this that] (and (eq (:parser this) (:parser that)) (= (:fn this) (:fn that)))) StructuralParser (subparsers [this] [(:parser this)]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) sub-n (get int-map parser)] (string/join "\n" [(format "\"%s\" [label=\"red\"]" this-n) (format "\"%s\" -> \"%s\"" this-n sub-n)]))) Parser (d-int [this t] (red (d parser t) fn)) (compact-int [this] (cond (red? parser) (red (compact parser) (comp fn (:fn parser))) :else (red (compact parser) fn))) (empty-int? [this] (empty-p? parser)) (nullable-int? [this] (nullable? parser)) (parse-null-int [this] (set (map fn (parse-null parser))))) (defrecord star-parser [parser] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [this] [parser]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) sub-n (get int-map parser)] (string/join "\n" [(format "\"%s\" [label=\"star\"]" this-n) (format "\"%s\" -> \"%s\"" this-n sub-n)]))) Parser (d-int [this t] (cat (d parser t) this)) (compact-int [this] (star (compact parser))) (empty-int? [_] false) (nullable-int? [this] (or (nullable? parser) (empty-p? parser))) (parse-null-int [this] #{'()})) (defn- -is-seq [t] "If t isn't a seq (a list), make it one. Can't use sequence because t might not be a collection." (if (seq? t) t (list t))) (defn- -append [t l] "Add t to the back of l, forcing either or both into listy-ness" (concat (-is-seq l) (-is-seq t))) (defn- -prepend [t l] "Add t to the front of l, forcing either or both into listy-ness" (concat (-is-seq t) (-is-seq l))) (defrecord sequence-parser [fst snd] ComparableParser (eq [this that] (and (eq (force (:fst this)) (force (:fst that))) (eq (force (:snd this)) (force (:snd that))))) StructuralParser (subparsers [this] [(force fst) (force snd)]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) fst-n (get int-map (force fst)) snd-n (get int-map (force snd))] (string/join "\n" [(format "\"%s\" [shape=\"none\", margin=0, label=<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\" cellpadding=\"4\"><tr><td colspan=\"2\">seq</td></tr><tr><td port=\"L\">L</td><td port=\"R\">R</td></tr></table>>]" this-n) (format "\"%s\":L -> \"%s\"" this-n fst-n) (format "\"%s\":R -> \"%s\"" this-n snd-n)]))) Parser (d-int [this t] (let [fst (force fst) snd (force snd)] (if (nullable? fst) (alt (cat (eps** (parse-null fst)) (d snd t)) (cat (d fst t) snd)) (cat (d fst t) snd)))) (compact-int [this] (let [fst (force (:fst this)) snd (force (:snd this))] (cond (empty-p? fst) snd (empty-p? snd) fst (singleton-parse? fst) (let [t (first (parse-null fst))] (red snd (fn [w2] (-prepend t w2)))) (singleton-parse? snd) (let [t (first (parse-null snd))] (red fst (fn [w1] (-append t w1)))) :else (let [c1 (compact fst) c2 (compact snd)] (if (= [c1 c2] [fst snd]) ; = effectively means pointer equality here this (cat c1 c2)))))) (empty-int? [this] (or (empty-p? (force fst)) (empty-p? (force snd)))) (nullable-int? [this] (and (nullable? (force fst)) (nullable? (force snd)))) (parse-null-int [this] (cart-prod (parse-null (force fst)) (parse-null (force snd)) (fn [a b] [a b])))) (defrecord union-parser [left right] ComparableParser (eq [this that] (and (eq (force (:left this)) (force (:left that))) (eq (force (:right this)) (force (:right that))))) StructuralParser (subparsers [this] [(force (:left this)) (force (:right this))]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) left-n (get int-map (force left)) right-n (get int-map (force right))] (string/join "\n" [(format "\"%s\" [label=\"or\"]" this-n) (format "\"%s\" -> \"%s\"" this-n left-n) (format "\"%s\" -> \"%s\"" this-n right-n)]))) Parser (d-int [this t] (alt (d (force (:left this)) t) (d (force (:right this)) t))) (compact-int [this] (let [l-empty (eq (empty-p) (force (:left this))) r-empty (eq (empty-p) (force (:right this)))] (cond (and l-empty r-empty) (empty-p) (and (not l-empty) r-empty) (compact (force (:left this))) (and l-empty (not r-empty)) (compact (force (:right this))) :else this))) (empty-int? [this] (and (empty-p? (force (:left this))) (empty-p? (force (:right this))))) (nullable-int? [this] (or (nullable? (force (:left this))) (nullable? (force (:right this))))) (parse-null-int [p] (set/union (parse-null (force (:left p))) (parse-null (force (:right p)))))) ;; Utility constructors (defn empty-p [] "The empty language parser." (empty-parser.)) (defn eps [] "That parser whose language is just the empty string." (empty-string-parser. #{nil})) (defn eps* [token] "A parser that stores a partial parse tree. You probably don't need to use this function." (empty-string-parser. #{token})) ;; A temporary function until I find out the syntax for multimethods (defn eps** [token-set] "Like eps*, but takes a set of parse trees." (empty-string-parser. token-set)) (defn lit [token] "A parser that consumes exactly this token." (literal-parser. token)) (defn lit+ [& rest] "Given any number of tokens, make a parser that can accept any of them." (case (count rest) 0 (eps) 1 (lit (first rest)) (literal-set-parser. (set rest)))) (defn lit* [l] "Given a seq of tokens, make a parser that can accept any of them" (apply lit+ l)) (defn alt "Make a parser that can act as any of a number of subparsers" ([] (empty-p)) ([a & parsers] (if parsers (union-parser. (delay a) (delay (apply alt parsers))) a))) (defn cat "Define a parser whose subparsers each consume things in sequence" ([] (empty-p)) ([a & parsers] (if parsers (sequence-parser. (delay a) (delay (apply cat parsers))) a))) (defn red [parser arity-1-fn] "Define a parser that runs some function over the parse trees of its subparsers. This is the hook for any semantic actions you might need." (red-parser. parser arity-1-fn)) (defn star [parser] "The Kleene star parser" (star-parser. parser)) (defn red? [parser] (instance? red-parser parser)) (defn parse [parser input] (if (empty? input) (parse-null parser) (parse (d parser (first input)) (rest input)))) (defn in? [needle haystack] (some #(= needle %) haystack)) (defn not-in? [needle haystack] (not (in? needle haystack))) (defn- search-1 [p fn seed cache] "Apply fn to each subparser in p in pre-order, returning the collected results in a dictionary mapping p to (fn p). Skip elements in cache." (let [val (apply fn [p])] (assoc (merge seed (reduce merge (map #(search-1 % fn seed (conj cache p)) (filter #(not-in? % cache) (subparsers p))))) p val))) (defn search [p fn] "A cycle-safe map over p." (let [visited #{}] (search-1 p fn {} visited))) (defn mark-uniquely [parser] "Recursively 'mark' the subparsers of p by associating each parser with a unique integer" (let [n (atom -1)] (search parser (fn [p] (swap! n inc))))) (defn print-as-digraph [parser] "Return a parser in a dot format string." (let [int-map (mark-uniquely parser)] (string/join "\n" (concat ["digraph {"] (vals (search parser #(print-node % int-map))) ["}"]))))
true
(ns clj-derp.core ^{:author "PI:NAME:<NAME>END_PI", :doc "This file defines the derivative of a context free grammar, and provides a simple API for parsing streams."} (:require [clojure.set :as set]) (:require [clojure.string :as string]) (:require [clojure.core.cache :as cache])) (defn cart-prod [set-one set-two concat-fn] "Return the Cartesian product of set-one and set-two." (set (mapcat (fn [a] (map (fn [b] (apply concat-fn [a b])) set-two)) set-one))) (defmacro defn-fix [name bottom fn] `(let* [*cache*# (atom (cache/soft-cache-factory {})) *changed?*# (atom false) *running?*# (atom false) *visited*# (atom {})] (defn ~name [x#] (let [cached?# (cache/has? (deref *cache*#) x#) cached# (cache/lookup (deref *cache*#) x#) run?# (deref *running?*#)] (cond (and cached?# (not run?#)) cached# (and run?# (get (deref *visited*#) x#)) (if cached?# cached# ~bottom) run?# (do (swap! *visited*# assoc x# true) (let [new-val# (apply ~fn [x#])] (when (not (= new-val# cached#)) (swap! *changed?*# (fn [_#] true)) (swap! *cache*# (fn [c#] (if cached?# (cache/hit c# x#) (cache/miss c# x# new-val#))))) new-val#)) (and (not cached?#) (not run?#)) (do (swap! *changed?*# (fn [_#] true)) (swap! *running?*# (fn [_#] true)) (swap! *visited*# (fn [_#] {})) (let [v# (atom ~bottom)] (while (deref *changed?*#) (swap! *changed?*# (fn [_#] false)) (swap! *visited*# (fn [_#] {})) (swap! v# (fn [_#] (apply ~fn [x#])))) (deref v#)))))))) (defn- memoize-with-cache [f new-cache] (let [cache (atom new-cache) recalc (fn [args] (let [answer (apply f args)] (swap! cache (fn [c] (cache/miss c args answer))) answer))] (fn [& args] (if (cache/has? @cache args) (do (swap! cache (fn [c] (cache/hit c args))) (if-let [answer (cache/lookup @cache args)] answer (recalc args))) (recalc args))))) (defn memoized ^{:doc "Given a function f, return a memoized function using either a given cache, or a cache using soft references."} ([f] (memoize-with-cache f (cache/soft-cache-factory {}))) ([f cache] (memoize-with-cache f cache))) (defprotocol Parser (d-int [this token]) (compact-int [this]) (empty-int? [this]) (nullable-int? [this]) (parse-null-int [this])) (defprotocol ComparableParser "Since we use Delays, equality comparison becomes troublesome. This protocol gives us a chance to force any delays, permitting us to still compare graphs for structural equality." (eq [this that])) (defprotocol StructuralParser "A means for a parser to expose its subparsers in a uniform manner." (subparsers [this])) (defprotocol PrintableParser "A protocol to provide for the printing of a graph in dotfile format." (print-node [this int-map] "Print this parser as part of a dotfile. int-map maps parsers to integers.")) (def compact (memoized (fn [parser] (compact-int parser)))) (def d (memoized (fn [parser token] (d-int parser token)))) (defn-fix parse-null {} (fn [parser] (parse-null-int parser))) (defn-fix nullable? false (fn [parser] (nullable-int? parser))) (defn-fix empty-p? false (fn [parser] (empty-int? parser))) (defn singleton-parse? [parser] (= 1 (count (parse-null parser)))) ;; We forward declare the helper constructors because we use them ;; in the defrecords. (declare empty-p) (declare eps) (declare eps*) (declare eps**) (declare lit) (declare alt) (declare cat) (declare red) (declare star) ;; We have to forward declare helpers like these because we use them ;; in the defrecords. (declare red?) (defrecord empty-parser [] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [label=\"empty\"]" (get int-map this :not-found))) Parser (d-int [this _] this) (compact-int [this] this) (empty-int? [_] true) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord empty-string-parser [tree-set] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"eps* | %s\"]" (get int-map this) tree-set)) Parser (d-int [this _] (empty-p)) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] true) (parse-null-int [_] tree-set)) (defrecord literal-parser [token] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"token | %s\"]" (get int-map this) token)) Parser (d-int [this t] (if (= token t) (eps* token) (empty-p))) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord literal-set-parser [token-set] ;; A parser that can consume one of a set of literals. You may think of ;; (lit+ 1 2) as being an optimised form of (alt (lit 1) (lit 2)). ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [_] []) PrintableParser (print-node [this int-map] (format "\"%s\" [shape=\"record\", label=\"token | %s\"]" (get int-map this) token-set)) Parser (d-int [this t] (if (contains? token-set t) (eps* t) (empty-p))) (compact-int [this] this) (empty-int? [_] false) (nullable-int? [this] false) (parse-null-int [_] #{})) (defrecord red-parser [parser fn] ComparableParser ;; There's a major limitation here: there is no = for ;; functions, so if you really care about equality of ;; reduction parsers, you need to control what functions ;; you use: perhaps define a handful of primitives that ;; you can compose as necessary. (eq [this that] (and (eq (:parser this) (:parser that)) (= (:fn this) (:fn that)))) StructuralParser (subparsers [this] [(:parser this)]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) sub-n (get int-map parser)] (string/join "\n" [(format "\"%s\" [label=\"red\"]" this-n) (format "\"%s\" -> \"%s\"" this-n sub-n)]))) Parser (d-int [this t] (red (d parser t) fn)) (compact-int [this] (cond (red? parser) (red (compact parser) (comp fn (:fn parser))) :else (red (compact parser) fn))) (empty-int? [this] (empty-p? parser)) (nullable-int? [this] (nullable? parser)) (parse-null-int [this] (set (map fn (parse-null parser))))) (defrecord star-parser [parser] ComparableParser (eq [this that] (= this that)) StructuralParser (subparsers [this] [parser]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) sub-n (get int-map parser)] (string/join "\n" [(format "\"%s\" [label=\"star\"]" this-n) (format "\"%s\" -> \"%s\"" this-n sub-n)]))) Parser (d-int [this t] (cat (d parser t) this)) (compact-int [this] (star (compact parser))) (empty-int? [_] false) (nullable-int? [this] (or (nullable? parser) (empty-p? parser))) (parse-null-int [this] #{'()})) (defn- -is-seq [t] "If t isn't a seq (a list), make it one. Can't use sequence because t might not be a collection." (if (seq? t) t (list t))) (defn- -append [t l] "Add t to the back of l, forcing either or both into listy-ness" (concat (-is-seq l) (-is-seq t))) (defn- -prepend [t l] "Add t to the front of l, forcing either or both into listy-ness" (concat (-is-seq t) (-is-seq l))) (defrecord sequence-parser [fst snd] ComparableParser (eq [this that] (and (eq (force (:fst this)) (force (:fst that))) (eq (force (:snd this)) (force (:snd that))))) StructuralParser (subparsers [this] [(force fst) (force snd)]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) fst-n (get int-map (force fst)) snd-n (get int-map (force snd))] (string/join "\n" [(format "\"%s\" [shape=\"none\", margin=0, label=<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\" cellpadding=\"4\"><tr><td colspan=\"2\">seq</td></tr><tr><td port=\"L\">L</td><td port=\"R\">R</td></tr></table>>]" this-n) (format "\"%s\":L -> \"%s\"" this-n fst-n) (format "\"%s\":R -> \"%s\"" this-n snd-n)]))) Parser (d-int [this t] (let [fst (force fst) snd (force snd)] (if (nullable? fst) (alt (cat (eps** (parse-null fst)) (d snd t)) (cat (d fst t) snd)) (cat (d fst t) snd)))) (compact-int [this] (let [fst (force (:fst this)) snd (force (:snd this))] (cond (empty-p? fst) snd (empty-p? snd) fst (singleton-parse? fst) (let [t (first (parse-null fst))] (red snd (fn [w2] (-prepend t w2)))) (singleton-parse? snd) (let [t (first (parse-null snd))] (red fst (fn [w1] (-append t w1)))) :else (let [c1 (compact fst) c2 (compact snd)] (if (= [c1 c2] [fst snd]) ; = effectively means pointer equality here this (cat c1 c2)))))) (empty-int? [this] (or (empty-p? (force fst)) (empty-p? (force snd)))) (nullable-int? [this] (and (nullable? (force fst)) (nullable? (force snd)))) (parse-null-int [this] (cart-prod (parse-null (force fst)) (parse-null (force snd)) (fn [a b] [a b])))) (defrecord union-parser [left right] ComparableParser (eq [this that] (and (eq (force (:left this)) (force (:left that))) (eq (force (:right this)) (force (:right that))))) StructuralParser (subparsers [this] [(force (:left this)) (force (:right this))]) PrintableParser (print-node [this int-map] (let [this-n (get int-map this) left-n (get int-map (force left)) right-n (get int-map (force right))] (string/join "\n" [(format "\"%s\" [label=\"or\"]" this-n) (format "\"%s\" -> \"%s\"" this-n left-n) (format "\"%s\" -> \"%s\"" this-n right-n)]))) Parser (d-int [this t] (alt (d (force (:left this)) t) (d (force (:right this)) t))) (compact-int [this] (let [l-empty (eq (empty-p) (force (:left this))) r-empty (eq (empty-p) (force (:right this)))] (cond (and l-empty r-empty) (empty-p) (and (not l-empty) r-empty) (compact (force (:left this))) (and l-empty (not r-empty)) (compact (force (:right this))) :else this))) (empty-int? [this] (and (empty-p? (force (:left this))) (empty-p? (force (:right this))))) (nullable-int? [this] (or (nullable? (force (:left this))) (nullable? (force (:right this))))) (parse-null-int [p] (set/union (parse-null (force (:left p))) (parse-null (force (:right p)))))) ;; Utility constructors (defn empty-p [] "The empty language parser." (empty-parser.)) (defn eps [] "That parser whose language is just the empty string." (empty-string-parser. #{nil})) (defn eps* [token] "A parser that stores a partial parse tree. You probably don't need to use this function." (empty-string-parser. #{token})) ;; A temporary function until I find out the syntax for multimethods (defn eps** [token-set] "Like eps*, but takes a set of parse trees." (empty-string-parser. token-set)) (defn lit [token] "A parser that consumes exactly this token." (literal-parser. token)) (defn lit+ [& rest] "Given any number of tokens, make a parser that can accept any of them." (case (count rest) 0 (eps) 1 (lit (first rest)) (literal-set-parser. (set rest)))) (defn lit* [l] "Given a seq of tokens, make a parser that can accept any of them" (apply lit+ l)) (defn alt "Make a parser that can act as any of a number of subparsers" ([] (empty-p)) ([a & parsers] (if parsers (union-parser. (delay a) (delay (apply alt parsers))) a))) (defn cat "Define a parser whose subparsers each consume things in sequence" ([] (empty-p)) ([a & parsers] (if parsers (sequence-parser. (delay a) (delay (apply cat parsers))) a))) (defn red [parser arity-1-fn] "Define a parser that runs some function over the parse trees of its subparsers. This is the hook for any semantic actions you might need." (red-parser. parser arity-1-fn)) (defn star [parser] "The Kleene star parser" (star-parser. parser)) (defn red? [parser] (instance? red-parser parser)) (defn parse [parser input] (if (empty? input) (parse-null parser) (parse (d parser (first input)) (rest input)))) (defn in? [needle haystack] (some #(= needle %) haystack)) (defn not-in? [needle haystack] (not (in? needle haystack))) (defn- search-1 [p fn seed cache] "Apply fn to each subparser in p in pre-order, returning the collected results in a dictionary mapping p to (fn p). Skip elements in cache." (let [val (apply fn [p])] (assoc (merge seed (reduce merge (map #(search-1 % fn seed (conj cache p)) (filter #(not-in? % cache) (subparsers p))))) p val))) (defn search [p fn] "A cycle-safe map over p." (let [visited #{}] (search-1 p fn {} visited))) (defn mark-uniquely [parser] "Recursively 'mark' the subparsers of p by associating each parser with a unique integer" (let [n (atom -1)] (search parser (fn [p] (swap! n inc))))) (defn print-as-digraph [parser] "Return a parser in a dot format string." (let [int-map (mark-uniquely parser)] (string/join "\n" (concat ["digraph {"] (vals (search parser #(print-node % int-map))) ["}"]))))
[ { "context": " for user\"\n (let [{user-id :id} (get-user \"test@auto.com\")\n response (client/get (str \"http:/", "end": 1259, "score": 0.9999175071716309, "start": 1246, "tag": "EMAIL", "value": "test@auto.com" } ]
test/clarkenciel_site/core_test.clj
clarkenciel/clarkenciel-site
0
(ns clarkenciel-site.core-test (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [clarkenciel-site.test-config :refer :all] [clarkenciel-site.db.core :refer :all] [clj-http.client :as client])) (use-fixtures :each (make-app 10003) database-fixture) (deftest test-routes (testing "public routes" (testing "posts routes" (testing "listing posts" (let [response (client/get "http://localhost:10003/api/posts" {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "posts for tags" (let [response (client/get "http://localhost:10003/api/posts/for_tag/music" {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "posts for user" (let [{user-id :id} (get-user "test@auto.com") response (client/get (str "http://localhost:10003/api/posts/for_user/" user-id) {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "post for post id" (let [{{[post] :posts} :body} (client/get "http://localhost:10003/api/posts" {:as :json}) response (client/get (str "http://localhost:10003/api/posts/" (:id post)) {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (let [{:keys [title body author]} (get-in response [:body :post])] (is (= title "test title")) (is (= body "test body")))))) (testing "auth routes" (testing "logging in"))) (testing "secure routes" (testing "post routes" (testing "post creation")) (testing "user routes" (testing "user creation") (testing "user removal") (testing "user listing")) (testing "auth routes" (testing "logging out"))))
37418
(ns clarkenciel-site.core-test (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [clarkenciel-site.test-config :refer :all] [clarkenciel-site.db.core :refer :all] [clj-http.client :as client])) (use-fixtures :each (make-app 10003) database-fixture) (deftest test-routes (testing "public routes" (testing "posts routes" (testing "listing posts" (let [response (client/get "http://localhost:10003/api/posts" {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "posts for tags" (let [response (client/get "http://localhost:10003/api/posts/for_tag/music" {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "posts for user" (let [{user-id :id} (get-user "<EMAIL>") response (client/get (str "http://localhost:10003/api/posts/for_user/" user-id) {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "post for post id" (let [{{[post] :posts} :body} (client/get "http://localhost:10003/api/posts" {:as :json}) response (client/get (str "http://localhost:10003/api/posts/" (:id post)) {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (let [{:keys [title body author]} (get-in response [:body :post])] (is (= title "test title")) (is (= body "test body")))))) (testing "auth routes" (testing "logging in"))) (testing "secure routes" (testing "post routes" (testing "post creation")) (testing "user routes" (testing "user creation") (testing "user removal") (testing "user listing")) (testing "auth routes" (testing "logging out"))))
true
(ns clarkenciel-site.core-test (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [clarkenciel-site.test-config :refer :all] [clarkenciel-site.db.core :refer :all] [clj-http.client :as client])) (use-fixtures :each (make-app 10003) database-fixture) (deftest test-routes (testing "public routes" (testing "posts routes" (testing "listing posts" (let [response (client/get "http://localhost:10003/api/posts" {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "posts for tags" (let [response (client/get "http://localhost:10003/api/posts/for_tag/music" {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "posts for user" (let [{user-id :id} (get-user "PI:EMAIL:<EMAIL>END_PI") response (client/get (str "http://localhost:10003/api/posts/for_user/" user-id) {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (is (= (sequential? (get-in response [:body :posts])))))) (testing "post for post id" (let [{{[post] :posts} :body} (client/get "http://localhost:10003/api/posts" {:as :json}) response (client/get (str "http://localhost:10003/api/posts/" (:id post)) {:as :json})] (is (= (:status response) 200)) (is (= (get-in response [:headers "Content-Type"]) "application/json; charset=utf-8")) (let [{:keys [title body author]} (get-in response [:body :post])] (is (= title "test title")) (is (= body "test body")))))) (testing "auth routes" (testing "logging in"))) (testing "secure routes" (testing "post routes" (testing "post creation")) (testing "user routes" (testing "user creation") (testing "user removal") (testing "user listing")) (testing "auth routes" (testing "logging out"))))
[ { "context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.999885082244873, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
src/territory_bro/infra/foreign_key.clj
3breadt/territory-bro
2
;; Copyright © 2015-2020 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.infra.foreign-key (:require [schema.core :as s] [schema.macros :as macros] [schema.spec.core :as spec] [schema.spec.variant :as variant])) (def ^:dynamic *reference-checkers* {}) (defrecord References [entity-type id-schema] s/Schema (spec [this] (variant/variant-spec spec/+no-precondition+ [{:schema id-schema}] nil (fn postcondition [id] (let [checker (get *reference-checkers* entity-type)] (when (nil? checker) (throw (IllegalStateException. (str "No reference checker for " entity-type " in " 'territory-bro.infra.foreign-key/*reference-checkers*)))) (when-not (true? (checker id)) (macros/validation-error this id (list 'foreign-key/references entity-type id) 'violated)))))) (explain [_this] (list 'foreign-key/references entity-type (s/explain id-schema)))) (defn references [entity-type id-schema] (References. entity-type id-schema))
80702
;; Copyright © 2015-2020 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.infra.foreign-key (:require [schema.core :as s] [schema.macros :as macros] [schema.spec.core :as spec] [schema.spec.variant :as variant])) (def ^:dynamic *reference-checkers* {}) (defrecord References [entity-type id-schema] s/Schema (spec [this] (variant/variant-spec spec/+no-precondition+ [{:schema id-schema}] nil (fn postcondition [id] (let [checker (get *reference-checkers* entity-type)] (when (nil? checker) (throw (IllegalStateException. (str "No reference checker for " entity-type " in " 'territory-bro.infra.foreign-key/*reference-checkers*)))) (when-not (true? (checker id)) (macros/validation-error this id (list 'foreign-key/references entity-type id) 'violated)))))) (explain [_this] (list 'foreign-key/references entity-type (s/explain id-schema)))) (defn references [entity-type id-schema] (References. entity-type id-schema))
true
;; Copyright © 2015-2020 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.infra.foreign-key (:require [schema.core :as s] [schema.macros :as macros] [schema.spec.core :as spec] [schema.spec.variant :as variant])) (def ^:dynamic *reference-checkers* {}) (defrecord References [entity-type id-schema] s/Schema (spec [this] (variant/variant-spec spec/+no-precondition+ [{:schema id-schema}] nil (fn postcondition [id] (let [checker (get *reference-checkers* entity-type)] (when (nil? checker) (throw (IllegalStateException. (str "No reference checker for " entity-type " in " 'territory-bro.infra.foreign-key/*reference-checkers*)))) (when-not (true? (checker id)) (macros/validation-error this id (list 'foreign-key/references entity-type id) 'violated)))))) (explain [_this] (list 'foreign-key/references entity-type (s/explain id-schema)))) (defn references [entity-type id-schema] (References. entity-type id-schema))
[ { "context": ";; Copyright (c) 2015-2022 Michael Schaeffer\n;;\n;; Licensed as below.\n;;\n;; Portions Copyright", "end": 44, "score": 0.999794602394104, "start": 27, "tag": "NAME", "value": "Michael Schaeffer" } ]
src/sql_file/middleware.clj
mschaef/sql-file
1
;; Copyright (c) 2015-2022 Michael Schaeffer ;; ;; Licensed as below. ;; ;; Portions Copyright (c) 2014 KSM Technology Partners ;; ;; 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 ;; ;; The license is also includes at the root of the project in the file ;; 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. ;; ;; You must not remove this notice, or any other, from this software. (ns sql-file.middleware (:require [clojure.tools.logging :as log] [clojure.java.jdbc :as jdbc])) (def ^:dynamic *db* nil) (defn call-with-db-connection [ fn db-connection ] (jdbc/with-db-connection [ conn db-connection ] (binding [ *db* conn ] (fn)))) (defmacro with-db-connection [ db-connection & body ] `(call-with-db-connection (fn [] ~@body) ~db-connection)) (defn current-db-connection [] (when (not *db*) (throw (RuntimeException. "No current database connection for query."))) *db*) (defn wrap-db-connection [ app db-connection ] (fn [ req ] (call-with-db-connection (fn [] (app req)) db-connection)))
30070
;; Copyright (c) 2015-2022 <NAME> ;; ;; Licensed as below. ;; ;; Portions Copyright (c) 2014 KSM Technology Partners ;; ;; 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 ;; ;; The license is also includes at the root of the project in the file ;; 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. ;; ;; You must not remove this notice, or any other, from this software. (ns sql-file.middleware (:require [clojure.tools.logging :as log] [clojure.java.jdbc :as jdbc])) (def ^:dynamic *db* nil) (defn call-with-db-connection [ fn db-connection ] (jdbc/with-db-connection [ conn db-connection ] (binding [ *db* conn ] (fn)))) (defmacro with-db-connection [ db-connection & body ] `(call-with-db-connection (fn [] ~@body) ~db-connection)) (defn current-db-connection [] (when (not *db*) (throw (RuntimeException. "No current database connection for query."))) *db*) (defn wrap-db-connection [ app db-connection ] (fn [ req ] (call-with-db-connection (fn [] (app req)) db-connection)))
true
;; Copyright (c) 2015-2022 PI:NAME:<NAME>END_PI ;; ;; Licensed as below. ;; ;; Portions Copyright (c) 2014 KSM Technology Partners ;; ;; 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 ;; ;; The license is also includes at the root of the project in the file ;; 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. ;; ;; You must not remove this notice, or any other, from this software. (ns sql-file.middleware (:require [clojure.tools.logging :as log] [clojure.java.jdbc :as jdbc])) (def ^:dynamic *db* nil) (defn call-with-db-connection [ fn db-connection ] (jdbc/with-db-connection [ conn db-connection ] (binding [ *db* conn ] (fn)))) (defmacro with-db-connection [ db-connection & body ] `(call-with-db-connection (fn [] ~@body) ~db-connection)) (defn current-db-connection [] (when (not *db*) (throw (RuntimeException. "No current database connection for query."))) *db*) (defn wrap-db-connection [ app db-connection ] (fn [ req ] (call-with-db-connection (fn [] (app req)) db-connection)))
[ { "context": " [:id \"ptaoussanis\"]\n [:name \"Peter Taoussanis\"]]])\n\n :deploy-repositories {\"releases\" {:url \"h", "end": 1131, "score": 0.9998645782470703, "start": 1115, "tag": "NAME", "value": "Peter Taoussanis" } ]
com.taoensso/nippy/project.clj
juxt/clojars-mirrors
0
(defproject pro.juxt.clojars-mirrors.com.taoensso/nippy "3.1.1" :description "High-performance serialization library for Clojure (mirrored from Clojars by JUXT)" :url "https://github.com/ptaoussanis/nippy" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :scm {:dir "../.."} :dependencies [^:inline-dep [com.taoensso/nippy "3.1.1" :exclusions [org.clojure/tools.reader org.iq80.snappy/snappy org.lz4/lz4-java org.tukaani/xz]] [org.clojure/tools.reader "1.3.4"] [org.iq80.snappy/snappy "0.4"] [org.lz4/lz4-java "1.7.1"] [org.tukaani/xz "1.8"]] :plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]] :mranderson {:project-prefix "juxt.clojars-mirrors"} :jar-exclusions [#".cljx$"] :pom-addition ([:developers [:developer [:id "ptaoussanis"] [:name "Peter Taoussanis"]]]) :deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2" :creds :gpg} "snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots" :creds :gpg}})
41272
(defproject pro.juxt.clojars-mirrors.com.taoensso/nippy "3.1.1" :description "High-performance serialization library for Clojure (mirrored from Clojars by JUXT)" :url "https://github.com/ptaoussanis/nippy" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :scm {:dir "../.."} :dependencies [^:inline-dep [com.taoensso/nippy "3.1.1" :exclusions [org.clojure/tools.reader org.iq80.snappy/snappy org.lz4/lz4-java org.tukaani/xz]] [org.clojure/tools.reader "1.3.4"] [org.iq80.snappy/snappy "0.4"] [org.lz4/lz4-java "1.7.1"] [org.tukaani/xz "1.8"]] :plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]] :mranderson {:project-prefix "juxt.clojars-mirrors"} :jar-exclusions [#".cljx$"] :pom-addition ([:developers [:developer [:id "ptaoussanis"] [:name "<NAME>"]]]) :deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2" :creds :gpg} "snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots" :creds :gpg}})
true
(defproject pro.juxt.clojars-mirrors.com.taoensso/nippy "3.1.1" :description "High-performance serialization library for Clojure (mirrored from Clojars by JUXT)" :url "https://github.com/ptaoussanis/nippy" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :scm {:dir "../.."} :dependencies [^:inline-dep [com.taoensso/nippy "3.1.1" :exclusions [org.clojure/tools.reader org.iq80.snappy/snappy org.lz4/lz4-java org.tukaani/xz]] [org.clojure/tools.reader "1.3.4"] [org.iq80.snappy/snappy "0.4"] [org.lz4/lz4-java "1.7.1"] [org.tukaani/xz "1.8"]] :plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]] :mranderson {:project-prefix "juxt.clojars-mirrors"} :jar-exclusions [#".cljx$"] :pom-addition ([:developers [:developer [:id "ptaoussanis"] [:name "PI:NAME:<NAME>END_PI"]]]) :deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2" :creds :gpg} "snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots" :creds :gpg}})
[ { "context": "(ns\n ^{:doc \"Handy trig fns\"\n :author \"Sam Aaron\"}\n overtone.algo.trig)\n\n(defn cosr\n \"Scaled, sh", "end": 56, "score": 0.9998877644538879, "start": 47, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/algo/trig.clj
ABaldwinHunter/overtone
3,870
(ns ^{:doc "Handy trig fns" :author "Sam Aaron"} overtone.algo.trig) (defn cosr "Scaled, shifted (i.e. mul-add) cosine fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled cosine fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's cosr. (cosr 0 2 10 8) ;=> 12 (cosr 2 2 10 8) ;=> 10 (cosr 4 2 10 8) ;=> 8 (cosr 6 2 10 8) ;=> 10 (cosr 8 2 10 8) ;=> 12" [idx range centre period] (+ centre (* range (Math/cos (* 2 Math/PI idx (/ 1 period)))))) (defn sinr "Scaled, shifted (i.e. mul-add) sine fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled sine fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's sinr. (sinr 0 2 10 8) ;=> 10 (sinr 2 2 10 8) ;=> 12 (sinr 4 2 10 8) ;=> 10 (sinr 6 2 10 8) ;=> 8 (sinr 8 2 10 8) ;=> 10" [idx range centre period] (+ centre (* range (Math/sin (* 2 Math/PI idx (/ 1 period)))))) (defn tanr "Scaled, shifted (i.e. mul-add) tan fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled tan fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's tanr. (tanr 0 2 10 8) ;=> 10 (tanr 1.999999 2 10 8) ;=> ~2546489 (tanr 2 2 10 8) ;=> ~3.2665 (tanr 4 2 10 8) ;=> 10 (tanr 5.999999 2 10 8) ;=> ~2546489 (tanr 6 2 10 8) ;=> ~1.0886 (tanr 8 2 10 8) ;=> 10" [idx range centre period] (+ centre (* range (Math/tan (* 2 Math/PI idx (/ 1 period))))))
72708
(ns ^{:doc "Handy trig fns" :author "<NAME>"} overtone.algo.trig) (defn cosr "Scaled, shifted (i.e. mul-add) cosine fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled cosine fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's cosr. (cosr 0 2 10 8) ;=> 12 (cosr 2 2 10 8) ;=> 10 (cosr 4 2 10 8) ;=> 8 (cosr 6 2 10 8) ;=> 10 (cosr 8 2 10 8) ;=> 12" [idx range centre period] (+ centre (* range (Math/cos (* 2 Math/PI idx (/ 1 period)))))) (defn sinr "Scaled, shifted (i.e. mul-add) sine fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled sine fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's sinr. (sinr 0 2 10 8) ;=> 10 (sinr 2 2 10 8) ;=> 12 (sinr 4 2 10 8) ;=> 10 (sinr 6 2 10 8) ;=> 8 (sinr 8 2 10 8) ;=> 10" [idx range centre period] (+ centre (* range (Math/sin (* 2 Math/PI idx (/ 1 period)))))) (defn tanr "Scaled, shifted (i.e. mul-add) tan fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled tan fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's tanr. (tanr 0 2 10 8) ;=> 10 (tanr 1.999999 2 10 8) ;=> ~2546489 (tanr 2 2 10 8) ;=> ~3.2665 (tanr 4 2 10 8) ;=> 10 (tanr 5.999999 2 10 8) ;=> ~2546489 (tanr 6 2 10 8) ;=> ~1.0886 (tanr 8 2 10 8) ;=> 10" [idx range centre period] (+ centre (* range (Math/tan (* 2 Math/PI idx (/ 1 period))))))
true
(ns ^{:doc "Handy trig fns" :author "PI:NAME:<NAME>END_PI"} overtone.algo.trig) (defn cosr "Scaled, shifted (i.e. mul-add) cosine fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled cosine fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's cosr. (cosr 0 2 10 8) ;=> 12 (cosr 2 2 10 8) ;=> 10 (cosr 4 2 10 8) ;=> 8 (cosr 6 2 10 8) ;=> 10 (cosr 8 2 10 8) ;=> 12" [idx range centre period] (+ centre (* range (Math/cos (* 2 Math/PI idx (/ 1 period)))))) (defn sinr "Scaled, shifted (i.e. mul-add) sine fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled sine fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's sinr. (sinr 0 2 10 8) ;=> 10 (sinr 2 2 10 8) ;=> 12 (sinr 4 2 10 8) ;=> 10 (sinr 6 2 10 8) ;=> 8 (sinr 8 2 10 8) ;=> 10" [idx range centre period] (+ centre (* range (Math/sin (* 2 Math/PI idx (/ 1 period)))))) (defn tanr "Scaled, shifted (i.e. mul-add) tan fn with the frequency specified in terms of the idx (typically representing the beat). Returns a value at idx along a scaled tan fn with specified centre and range. The frequency is defined to be period idxs. Similar to Impromptu's tanr. (tanr 0 2 10 8) ;=> 10 (tanr 1.999999 2 10 8) ;=> ~2546489 (tanr 2 2 10 8) ;=> ~3.2665 (tanr 4 2 10 8) ;=> 10 (tanr 5.999999 2 10 8) ;=> ~2546489 (tanr 6 2 10 8) ;=> ~1.0886 (tanr 8 2 10 8) ;=> 10" [idx range centre period] (+ centre (* range (Math/tan (* 2 Math/PI idx (/ 1 period))))))
[ { "context": "om.dept24c.vivo.test-user)\n\n(def test-identifier \"test@tester.com\")\n(def test-secret \"laughable\")\n(def test-subject", "end": 70, "score": 0.9999247789382935, "start": 55, "tag": "EMAIL", "value": "test@tester.com" } ]
dev/com/dept24c/vivo/test_user.cljc
danmidwood/vivo
4
(ns com.dept24c.vivo.test-user) (def test-identifier "test@tester.com") (def test-secret "laughable") (def test-subject-id "f9ba8537-476c-4b4f-86c5-a1263bb26138")
55225
(ns com.dept24c.vivo.test-user) (def test-identifier "<EMAIL>") (def test-secret "laughable") (def test-subject-id "f9ba8537-476c-4b4f-86c5-a1263bb26138")
true
(ns com.dept24c.vivo.test-user) (def test-identifier "PI:EMAIL:<EMAIL>END_PI") (def test-secret "laughable") (def test-subject-id "f9ba8537-476c-4b4f-86c5-a1263bb26138")
[ { "context": ".core :refer [cond cond->]]))\n\n(def account-id\n \"012345678901\")\n\n(def region\n \"za-south-1\")\n\n(defmulti resolve", "end": 353, "score": 0.9958377480506897, "start": 341, "tag": "KEY", "value": "012345678901" }, { "context": " (def template\n (json/read-str (slurp \"/Users/marc/Development/sinistral/dobby/build/service.git/tar", "end": 5650, "score": 0.8956024646759033, "start": 5646, "tag": "USERNAME", "value": "marc" }, { "context": "egisterPackageS3IntegrationApiGatewayExecutionRole3D8D6388\"])\n seq\n first\n ((partial localise", "end": 6279, "score": 0.6817854046821594, "start": 6271, "tag": "KEY", "value": "3D8D6388" } ]
cdk-sfn/source/sinistral/aws_mis/cdk_sfn.clj
sinistral/aws-mis
1
(ns sinistral.aws-mis.cdk-sfn (:refer-clojure :exclude [cond cond->]) (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.walk :as walk] [familiar.alpha.core :refer [cond cond->]])) (def account-id "012345678901") (def region "za-south-1") (defmulti resolve-get-att-arn (fn [[_ resource-type]] resource-type)) (defmethod resolve-get-att-arn "AWS::Lambda::Function" [[resource-name resource-type]] (format "arn:aws:lambda:%s:%s:function:%s" region account-id resource-name)) (defmethod resolve-get-att-arn "AWS::IAM::Role" [[resource-name resource-type]] (format "arn:aws:iam::%s:role/%s" account-id resource-name)) (defmulti resolve-ref (fn [[_ resource-type]] resource-type)) (defmethod resolve-ref "AWS::Lambda::Function" [[resource-name resource-type]] (format "arn:aws:lambda:%s:%s:function:%s" region account-id resource-name)) (defmethod resolve-ref "AWS::SQS::Queue" [[resource-name resource-type]] (format "https://sqs.%s.amazonaws.com/%s/%s" region account-id resource-name)) (defmethod resolve-ref "AWS::StepFunctions::StateMachine" [[resource-name resource-type]] (format "arn:aws:states:%s:%s:stateMachine:%s" region account-id resource-name)) (defmulti localise-resource (fn [_ [_ resource-properties]] (get resource-properties "Type"))) (defmethod localise-resource :default [_ [resource-name resource-properties :as resource]] resource) (defmethod localise-resource "AWS::StepFunctions::StateMachine" [resource-type-map [res-key res-def :as res-entry]] (walk/prewalk (fn [x] (letfn [(get-att-arn? [x] (and (map? x) (-> x keys #{["Fn::GetAtt"]}) (-> x vals first second #{"Arn"}))) (partition-ref? [x] (and (map? x) (-> x keys #{["Ref"]}) (-> x vals #{["AWS::Partition"]}))) (ref? [x] (and (map? x) (-> x keys #{["Ref"]})))] (cond [(get-att-arn? x) (resolve-get-att-arn (first (select-keys resource-type-map [(-> x vals ffirst)])))] [(partition-ref? x) "aws"] [(ref? x) (resolve-ref (first (select-keys resource-type-map [(-> x vals first)])))] [:else x]))) res-entry)) (defn localise [t] (let [resources (seq (get t "Resources")) resource-type-map (into {} (map (fn [[logical-name properties]] [logical-name (get properties "Type")]) resources))] (merge t {"Resources" (into {} (map (partial localise-resource resource-type-map) resources))}))) (defn- definition-string [t sm-id] (->> (apply str/join (get-in t ["Resources" sm-id "Properties" "DefinitionString" "Fn::Join"])) json/read-str (walk/postwalk (fn [x] (if (and (map? x) (contains? x "Comment")) (dissoc x "Comment") ; The embedded comments tend to cause problems with shell quoting when passing the ; definition string to the CLI, so we strip them out. x))) json/write-str)) (defn- select-sm [t sm-id] (letfn [(typeof? [[_ res-def] res-type] (boolean (#{res-type} (get res-def "Type"))))] (get (into {} (filter #(typeof? % "AWS::StepFunctions::StateMachine") (seq (get t "Resources")))) sm-id))) (def ^:private mandatory-opts #{:template}) (defn- missing-mandatory? [opts] (not-every? opts mandatory-opts)) (def ^:private cli-opts [[nil "--definition-string" "Given the ID (-i) of a Step Functions State Machine, emit the JSON definition string that might be passed to 'aws stepfunctions create-state-machine --definition ...'"] ["-h" "--help"] ["-i" "--state-machine-id ID" "Limit output to the State Machine with the specified logical ID in the template."] ["-l" "--localise" "Localise the Resource definitions in Step Functions State Machine definitions."] ["-t" "--template TEMPLATE" "CDK-synthesised template (i.e.: cdk --no-staging synth)" :validate [#(.exists (io/as-file %)) "Template file does not exist."]]]) (defn process-template ([options] (process-template (json/read-str (slurp (:template options))) options)) ([template options] (cond-> template [(:localise options) localise] [(:definition-string options) (definition-string (:state-machine-id options))] [(and (:state-machine-id options) (not (:definition-string options))) (select-sm (:state-machine-id options))] [true (identity)]))) (defn -main [& args] (let [{:keys [options arguments summary errors]} (cli/parse-opts args cli-opts)] (cond [(:help options) (println summary)] [errors (throw (ex-info "Invocation error" {:errors errors}))] [(missing-mandatory? options) (throw (ex-info "Invocation error" {:required mandatory-opts}))] [:else (println (process-template options))]))) (comment (def template (json/read-str (slurp "/Users/marc/Development/sinistral/dobby/build/service.git/target/dobby-service.json"))) (def res-def-seq (seq (get template "Resources"))) (def res-type-map (into {} (map (fn [[logical-name properties]] [logical-name (get properties "Type")]) res-def-seq))) (def sm-def (-> template (get "Resources") (select-keys ["BuildEventProcessingStateMachine201911304B29E4ED"]) seq first ((partial localise-resource res-type-map)))) (-> template (get "Resources") (select-keys ["RegisterPackageS3IntegrationApiGatewayExecutionRole3D8D6388"]) seq first ((partial localise-resource res-type-map))) )
105916
(ns sinistral.aws-mis.cdk-sfn (:refer-clojure :exclude [cond cond->]) (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.walk :as walk] [familiar.alpha.core :refer [cond cond->]])) (def account-id "<KEY>") (def region "za-south-1") (defmulti resolve-get-att-arn (fn [[_ resource-type]] resource-type)) (defmethod resolve-get-att-arn "AWS::Lambda::Function" [[resource-name resource-type]] (format "arn:aws:lambda:%s:%s:function:%s" region account-id resource-name)) (defmethod resolve-get-att-arn "AWS::IAM::Role" [[resource-name resource-type]] (format "arn:aws:iam::%s:role/%s" account-id resource-name)) (defmulti resolve-ref (fn [[_ resource-type]] resource-type)) (defmethod resolve-ref "AWS::Lambda::Function" [[resource-name resource-type]] (format "arn:aws:lambda:%s:%s:function:%s" region account-id resource-name)) (defmethod resolve-ref "AWS::SQS::Queue" [[resource-name resource-type]] (format "https://sqs.%s.amazonaws.com/%s/%s" region account-id resource-name)) (defmethod resolve-ref "AWS::StepFunctions::StateMachine" [[resource-name resource-type]] (format "arn:aws:states:%s:%s:stateMachine:%s" region account-id resource-name)) (defmulti localise-resource (fn [_ [_ resource-properties]] (get resource-properties "Type"))) (defmethod localise-resource :default [_ [resource-name resource-properties :as resource]] resource) (defmethod localise-resource "AWS::StepFunctions::StateMachine" [resource-type-map [res-key res-def :as res-entry]] (walk/prewalk (fn [x] (letfn [(get-att-arn? [x] (and (map? x) (-> x keys #{["Fn::GetAtt"]}) (-> x vals first second #{"Arn"}))) (partition-ref? [x] (and (map? x) (-> x keys #{["Ref"]}) (-> x vals #{["AWS::Partition"]}))) (ref? [x] (and (map? x) (-> x keys #{["Ref"]})))] (cond [(get-att-arn? x) (resolve-get-att-arn (first (select-keys resource-type-map [(-> x vals ffirst)])))] [(partition-ref? x) "aws"] [(ref? x) (resolve-ref (first (select-keys resource-type-map [(-> x vals first)])))] [:else x]))) res-entry)) (defn localise [t] (let [resources (seq (get t "Resources")) resource-type-map (into {} (map (fn [[logical-name properties]] [logical-name (get properties "Type")]) resources))] (merge t {"Resources" (into {} (map (partial localise-resource resource-type-map) resources))}))) (defn- definition-string [t sm-id] (->> (apply str/join (get-in t ["Resources" sm-id "Properties" "DefinitionString" "Fn::Join"])) json/read-str (walk/postwalk (fn [x] (if (and (map? x) (contains? x "Comment")) (dissoc x "Comment") ; The embedded comments tend to cause problems with shell quoting when passing the ; definition string to the CLI, so we strip them out. x))) json/write-str)) (defn- select-sm [t sm-id] (letfn [(typeof? [[_ res-def] res-type] (boolean (#{res-type} (get res-def "Type"))))] (get (into {} (filter #(typeof? % "AWS::StepFunctions::StateMachine") (seq (get t "Resources")))) sm-id))) (def ^:private mandatory-opts #{:template}) (defn- missing-mandatory? [opts] (not-every? opts mandatory-opts)) (def ^:private cli-opts [[nil "--definition-string" "Given the ID (-i) of a Step Functions State Machine, emit the JSON definition string that might be passed to 'aws stepfunctions create-state-machine --definition ...'"] ["-h" "--help"] ["-i" "--state-machine-id ID" "Limit output to the State Machine with the specified logical ID in the template."] ["-l" "--localise" "Localise the Resource definitions in Step Functions State Machine definitions."] ["-t" "--template TEMPLATE" "CDK-synthesised template (i.e.: cdk --no-staging synth)" :validate [#(.exists (io/as-file %)) "Template file does not exist."]]]) (defn process-template ([options] (process-template (json/read-str (slurp (:template options))) options)) ([template options] (cond-> template [(:localise options) localise] [(:definition-string options) (definition-string (:state-machine-id options))] [(and (:state-machine-id options) (not (:definition-string options))) (select-sm (:state-machine-id options))] [true (identity)]))) (defn -main [& args] (let [{:keys [options arguments summary errors]} (cli/parse-opts args cli-opts)] (cond [(:help options) (println summary)] [errors (throw (ex-info "Invocation error" {:errors errors}))] [(missing-mandatory? options) (throw (ex-info "Invocation error" {:required mandatory-opts}))] [:else (println (process-template options))]))) (comment (def template (json/read-str (slurp "/Users/marc/Development/sinistral/dobby/build/service.git/target/dobby-service.json"))) (def res-def-seq (seq (get template "Resources"))) (def res-type-map (into {} (map (fn [[logical-name properties]] [logical-name (get properties "Type")]) res-def-seq))) (def sm-def (-> template (get "Resources") (select-keys ["BuildEventProcessingStateMachine201911304B29E4ED"]) seq first ((partial localise-resource res-type-map)))) (-> template (get "Resources") (select-keys ["RegisterPackageS3IntegrationApiGatewayExecutionRole<KEY>"]) seq first ((partial localise-resource res-type-map))) )
true
(ns sinistral.aws-mis.cdk-sfn (:refer-clojure :exclude [cond cond->]) (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.walk :as walk] [familiar.alpha.core :refer [cond cond->]])) (def account-id "PI:KEY:<KEY>END_PI") (def region "za-south-1") (defmulti resolve-get-att-arn (fn [[_ resource-type]] resource-type)) (defmethod resolve-get-att-arn "AWS::Lambda::Function" [[resource-name resource-type]] (format "arn:aws:lambda:%s:%s:function:%s" region account-id resource-name)) (defmethod resolve-get-att-arn "AWS::IAM::Role" [[resource-name resource-type]] (format "arn:aws:iam::%s:role/%s" account-id resource-name)) (defmulti resolve-ref (fn [[_ resource-type]] resource-type)) (defmethod resolve-ref "AWS::Lambda::Function" [[resource-name resource-type]] (format "arn:aws:lambda:%s:%s:function:%s" region account-id resource-name)) (defmethod resolve-ref "AWS::SQS::Queue" [[resource-name resource-type]] (format "https://sqs.%s.amazonaws.com/%s/%s" region account-id resource-name)) (defmethod resolve-ref "AWS::StepFunctions::StateMachine" [[resource-name resource-type]] (format "arn:aws:states:%s:%s:stateMachine:%s" region account-id resource-name)) (defmulti localise-resource (fn [_ [_ resource-properties]] (get resource-properties "Type"))) (defmethod localise-resource :default [_ [resource-name resource-properties :as resource]] resource) (defmethod localise-resource "AWS::StepFunctions::StateMachine" [resource-type-map [res-key res-def :as res-entry]] (walk/prewalk (fn [x] (letfn [(get-att-arn? [x] (and (map? x) (-> x keys #{["Fn::GetAtt"]}) (-> x vals first second #{"Arn"}))) (partition-ref? [x] (and (map? x) (-> x keys #{["Ref"]}) (-> x vals #{["AWS::Partition"]}))) (ref? [x] (and (map? x) (-> x keys #{["Ref"]})))] (cond [(get-att-arn? x) (resolve-get-att-arn (first (select-keys resource-type-map [(-> x vals ffirst)])))] [(partition-ref? x) "aws"] [(ref? x) (resolve-ref (first (select-keys resource-type-map [(-> x vals first)])))] [:else x]))) res-entry)) (defn localise [t] (let [resources (seq (get t "Resources")) resource-type-map (into {} (map (fn [[logical-name properties]] [logical-name (get properties "Type")]) resources))] (merge t {"Resources" (into {} (map (partial localise-resource resource-type-map) resources))}))) (defn- definition-string [t sm-id] (->> (apply str/join (get-in t ["Resources" sm-id "Properties" "DefinitionString" "Fn::Join"])) json/read-str (walk/postwalk (fn [x] (if (and (map? x) (contains? x "Comment")) (dissoc x "Comment") ; The embedded comments tend to cause problems with shell quoting when passing the ; definition string to the CLI, so we strip them out. x))) json/write-str)) (defn- select-sm [t sm-id] (letfn [(typeof? [[_ res-def] res-type] (boolean (#{res-type} (get res-def "Type"))))] (get (into {} (filter #(typeof? % "AWS::StepFunctions::StateMachine") (seq (get t "Resources")))) sm-id))) (def ^:private mandatory-opts #{:template}) (defn- missing-mandatory? [opts] (not-every? opts mandatory-opts)) (def ^:private cli-opts [[nil "--definition-string" "Given the ID (-i) of a Step Functions State Machine, emit the JSON definition string that might be passed to 'aws stepfunctions create-state-machine --definition ...'"] ["-h" "--help"] ["-i" "--state-machine-id ID" "Limit output to the State Machine with the specified logical ID in the template."] ["-l" "--localise" "Localise the Resource definitions in Step Functions State Machine definitions."] ["-t" "--template TEMPLATE" "CDK-synthesised template (i.e.: cdk --no-staging synth)" :validate [#(.exists (io/as-file %)) "Template file does not exist."]]]) (defn process-template ([options] (process-template (json/read-str (slurp (:template options))) options)) ([template options] (cond-> template [(:localise options) localise] [(:definition-string options) (definition-string (:state-machine-id options))] [(and (:state-machine-id options) (not (:definition-string options))) (select-sm (:state-machine-id options))] [true (identity)]))) (defn -main [& args] (let [{:keys [options arguments summary errors]} (cli/parse-opts args cli-opts)] (cond [(:help options) (println summary)] [errors (throw (ex-info "Invocation error" {:errors errors}))] [(missing-mandatory? options) (throw (ex-info "Invocation error" {:required mandatory-opts}))] [:else (println (process-template options))]))) (comment (def template (json/read-str (slurp "/Users/marc/Development/sinistral/dobby/build/service.git/target/dobby-service.json"))) (def res-def-seq (seq (get template "Resources"))) (def res-type-map (into {} (map (fn [[logical-name properties]] [logical-name (get properties "Type")]) res-def-seq))) (def sm-def (-> template (get "Resources") (select-keys ["BuildEventProcessingStateMachine201911304B29E4ED"]) seq first ((partial localise-resource res-type-map)))) (-> template (get "Resources") (select-keys ["RegisterPackageS3IntegrationApiGatewayExecutionRolePI:KEY:<KEY>END_PI"]) seq first ((partial localise-resource res-type-map))) )
[ { "context": " :dbname \"league-stats.db\"\n :username \"sa\"\n :password \"superSecureYou'llNeverGuess\"}", "end": 980, "score": 0.9840487241744995, "start": 978, "tag": "USERNAME", "value": "sa" }, { "context": "ats.db\"\n :username \"sa\"\n :password \"superSecureYou'llNeverGuess\"}})\n\n(defn build-routes\n [config]\n (routes\n (", "end": 1028, "score": 0.9993361830711365, "start": 1001, "tag": "PASSWORD", "value": "superSecureYou'llNeverGuess" } ]
src/league_stats_backend/core.clj
youhavethewrong/league-stats-backend
1
(ns league-stats-backend.core (:require [clojure.java.io :as io] [taoensso.timbre :as log] [compojure.core :refer [routes GET POST]] [compojure.handler :as handler] [ring.middleware.json :refer [wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.cors :refer [wrap-cors]] [league-stats-backend.client :as client] [league-stats-backend.db :as db] [league-stats-backend.resource :as resource] [league-stats-backend.system :as system] [com.stuartsierra.component :as component]) (:gen-class)) (def config {:port 8337 :user-agent "League Stats v0.0.1" :tournament-stats-url "http://api.lolesports.com/api/v2/tournamentPlayerStats?tournamentId=" :schedule-items-url "http://api.lolesports.com/api/v1/scheduleItems?leagueId=" :db {:dbtype "sqlite" :dbname "league-stats.db" :username "sa" :password "superSecureYou'llNeverGuess"}}) (defn build-routes [config] (routes (GET "/leagues" [] (resource/get-leagues config)) (GET "/tournaments" [] (resource/get-all-tournaments config)) (GET "/tournaments/:league-id" [league-id] (resource/get-tournaments config league-id)) (GET "/stats/:tournament-id" [tournament-id] (resource/get-stats config tournament-id)) (POST "/tournaments" [] (resource/refresh-tournaments config)) (POST "/stats" [] (resource/refresh-stats config)) (resource/not-found "No resource is available here."))) (defn wrap-request-logging [handler] (fn [{:keys [remote-addr request-method uri] :as request}] (let [start (System/currentTimeMillis) response (handler request) status (:status response) finish (System/currentTimeMillis) total (- finish start)] (log/info (format "%s %s %s %s (%dms)" remote-addr request-method uri status total)) response))) (defn start [config] (log/info "[Starting!]") (log/info (str "\n" (slurp (io/resource "banner.txt")))) (let [handler (-> (build-routes config) (wrap-cors :access-control-allow-origin [#".*"] :access-control-allow-methods [:get :post]) wrap-request-logging wrap-params wrap-json-response)] (system/system (assoc config :handler handler)))) (defn -main [& args] (component/start (start config)))
41779
(ns league-stats-backend.core (:require [clojure.java.io :as io] [taoensso.timbre :as log] [compojure.core :refer [routes GET POST]] [compojure.handler :as handler] [ring.middleware.json :refer [wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.cors :refer [wrap-cors]] [league-stats-backend.client :as client] [league-stats-backend.db :as db] [league-stats-backend.resource :as resource] [league-stats-backend.system :as system] [com.stuartsierra.component :as component]) (:gen-class)) (def config {:port 8337 :user-agent "League Stats v0.0.1" :tournament-stats-url "http://api.lolesports.com/api/v2/tournamentPlayerStats?tournamentId=" :schedule-items-url "http://api.lolesports.com/api/v1/scheduleItems?leagueId=" :db {:dbtype "sqlite" :dbname "league-stats.db" :username "sa" :password "<PASSWORD>"}}) (defn build-routes [config] (routes (GET "/leagues" [] (resource/get-leagues config)) (GET "/tournaments" [] (resource/get-all-tournaments config)) (GET "/tournaments/:league-id" [league-id] (resource/get-tournaments config league-id)) (GET "/stats/:tournament-id" [tournament-id] (resource/get-stats config tournament-id)) (POST "/tournaments" [] (resource/refresh-tournaments config)) (POST "/stats" [] (resource/refresh-stats config)) (resource/not-found "No resource is available here."))) (defn wrap-request-logging [handler] (fn [{:keys [remote-addr request-method uri] :as request}] (let [start (System/currentTimeMillis) response (handler request) status (:status response) finish (System/currentTimeMillis) total (- finish start)] (log/info (format "%s %s %s %s (%dms)" remote-addr request-method uri status total)) response))) (defn start [config] (log/info "[Starting!]") (log/info (str "\n" (slurp (io/resource "banner.txt")))) (let [handler (-> (build-routes config) (wrap-cors :access-control-allow-origin [#".*"] :access-control-allow-methods [:get :post]) wrap-request-logging wrap-params wrap-json-response)] (system/system (assoc config :handler handler)))) (defn -main [& args] (component/start (start config)))
true
(ns league-stats-backend.core (:require [clojure.java.io :as io] [taoensso.timbre :as log] [compojure.core :refer [routes GET POST]] [compojure.handler :as handler] [ring.middleware.json :refer [wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.cors :refer [wrap-cors]] [league-stats-backend.client :as client] [league-stats-backend.db :as db] [league-stats-backend.resource :as resource] [league-stats-backend.system :as system] [com.stuartsierra.component :as component]) (:gen-class)) (def config {:port 8337 :user-agent "League Stats v0.0.1" :tournament-stats-url "http://api.lolesports.com/api/v2/tournamentPlayerStats?tournamentId=" :schedule-items-url "http://api.lolesports.com/api/v1/scheduleItems?leagueId=" :db {:dbtype "sqlite" :dbname "league-stats.db" :username "sa" :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (defn build-routes [config] (routes (GET "/leagues" [] (resource/get-leagues config)) (GET "/tournaments" [] (resource/get-all-tournaments config)) (GET "/tournaments/:league-id" [league-id] (resource/get-tournaments config league-id)) (GET "/stats/:tournament-id" [tournament-id] (resource/get-stats config tournament-id)) (POST "/tournaments" [] (resource/refresh-tournaments config)) (POST "/stats" [] (resource/refresh-stats config)) (resource/not-found "No resource is available here."))) (defn wrap-request-logging [handler] (fn [{:keys [remote-addr request-method uri] :as request}] (let [start (System/currentTimeMillis) response (handler request) status (:status response) finish (System/currentTimeMillis) total (- finish start)] (log/info (format "%s %s %s %s (%dms)" remote-addr request-method uri status total)) response))) (defn start [config] (log/info "[Starting!]") (log/info (str "\n" (slurp (io/resource "banner.txt")))) (let [handler (-> (build-routes config) (wrap-cors :access-control-allow-origin [#".*"] :access-control-allow-methods [:get :post]) wrap-request-logging wrap-params wrap-json-response)] (system/system (assoc config :handler handler)))) (defn -main [& args] (component/start (start config)))
[ { "context": ";; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre", "end": 33, "score": 0.9998773336410522, "start": 22, "tag": "NAME", "value": "Diego Souza" }, { "context": ";; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaakl", "end": 50, "score": 0.9998512268066406, "start": 35, "tag": "EMAIL", "value": "dsouza@c0d3.xxx" }, { "context": "iego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com>\n;;\n;; Licensed under the Ap", "end": 92, "score": 0.9998763203620911, "start": 74, "tag": "NAME", "value": "Alexandre Baaklini" }, { "context": "d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com>\n;;\n;; Licensed under the Apache License, Version", "end": 113, "score": 0.999917209148407, "start": 94, "tag": "EMAIL", "value": "abaaklini@gmail.com" } ]
src/blackbox/src/leela/blackbox/storage/s3.clj
locaweb/leela
22
;; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx> ;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.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 leela.blackbox.storage.s3 (:use [clj-time.core :only [date-time year month day]] [clj-time.coerce] [clojure.tools.logging :only [info warn]] [clojurewerkz.cassaforte.query] ) (:import [java.io PrintWriter InputStreamReader ByteArrayInputStream ByteArrayOutputStream]) (:require [clojure.string :as s] [leela.blackbox.f :as f] [aws.sdk.s3 :as s3] ) ) (defstruct failed-oper :statuscode :errorcode) (defn list-bucket ([with-client bucket] (s3/list-objects with-client bucket)) ([with-client bucket node?] (s3/list-objects with-client bucket {:prefix (str node?)}))) (defn del-archived-tattr [with-client bucket k] (s3/delete-object with-client bucket k)) (defn get-archived-tattr [with-client bucket attr] (try (let [data (s3/get-object with-client bucket attr)] (:content data)) (catch Exception e (if-not (= 404 (.getStatusCode e)) (throw e))) ) ) (defn create-bucket [with-client bucket] (s3/create-bucket with-client bucket)) (defn delete-bucket ([with-client bucket] (try (s3/delete-bucket with-client bucket) (catch Exception e (if (= 409 (.getStatusCode e)) (struct failed-oper (.getStatusCode e) (.getErrorCode e)) (throw e))))) ([with-client bucket flag?] (if (= flag? true) (do (doall (map (fn [b] (del-archived-tattr with-client bucket (:key b))) (:objects (list-bucket with-client bucket)))) (s3/delete-bucket with-client bucket)) (s3/delete-bucket with-client bucket)))) (defn put-archived-tattr [with-client bucket attr data] (try (s3/put-object with-client bucket attr (ByteArrayInputStream. data) {:content-length (count data)}) (catch Exception e (if (= "NoSuchBucket" (.getErrorCode e)) (struct failed-oper (.getStatusCode e) (.getErrorCode e)) (throw e)))))
48517
;; Copyright 2014 (c) <NAME> <<EMAIL>> ;; Copyright 2014 (c) <NAME> <<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 leela.blackbox.storage.s3 (:use [clj-time.core :only [date-time year month day]] [clj-time.coerce] [clojure.tools.logging :only [info warn]] [clojurewerkz.cassaforte.query] ) (:import [java.io PrintWriter InputStreamReader ByteArrayInputStream ByteArrayOutputStream]) (:require [clojure.string :as s] [leela.blackbox.f :as f] [aws.sdk.s3 :as s3] ) ) (defstruct failed-oper :statuscode :errorcode) (defn list-bucket ([with-client bucket] (s3/list-objects with-client bucket)) ([with-client bucket node?] (s3/list-objects with-client bucket {:prefix (str node?)}))) (defn del-archived-tattr [with-client bucket k] (s3/delete-object with-client bucket k)) (defn get-archived-tattr [with-client bucket attr] (try (let [data (s3/get-object with-client bucket attr)] (:content data)) (catch Exception e (if-not (= 404 (.getStatusCode e)) (throw e))) ) ) (defn create-bucket [with-client bucket] (s3/create-bucket with-client bucket)) (defn delete-bucket ([with-client bucket] (try (s3/delete-bucket with-client bucket) (catch Exception e (if (= 409 (.getStatusCode e)) (struct failed-oper (.getStatusCode e) (.getErrorCode e)) (throw e))))) ([with-client bucket flag?] (if (= flag? true) (do (doall (map (fn [b] (del-archived-tattr with-client bucket (:key b))) (:objects (list-bucket with-client bucket)))) (s3/delete-bucket with-client bucket)) (s3/delete-bucket with-client bucket)))) (defn put-archived-tattr [with-client bucket attr data] (try (s3/put-object with-client bucket attr (ByteArrayInputStream. data) {:content-length (count data)}) (catch Exception e (if (= "NoSuchBucket" (.getErrorCode e)) (struct failed-oper (.getStatusCode e) (.getErrorCode e)) (throw e)))))
true
;; Copyright 2014 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Copyright 2014 (c) PI:NAME:<NAME>END_PI <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 leela.blackbox.storage.s3 (:use [clj-time.core :only [date-time year month day]] [clj-time.coerce] [clojure.tools.logging :only [info warn]] [clojurewerkz.cassaforte.query] ) (:import [java.io PrintWriter InputStreamReader ByteArrayInputStream ByteArrayOutputStream]) (:require [clojure.string :as s] [leela.blackbox.f :as f] [aws.sdk.s3 :as s3] ) ) (defstruct failed-oper :statuscode :errorcode) (defn list-bucket ([with-client bucket] (s3/list-objects with-client bucket)) ([with-client bucket node?] (s3/list-objects with-client bucket {:prefix (str node?)}))) (defn del-archived-tattr [with-client bucket k] (s3/delete-object with-client bucket k)) (defn get-archived-tattr [with-client bucket attr] (try (let [data (s3/get-object with-client bucket attr)] (:content data)) (catch Exception e (if-not (= 404 (.getStatusCode e)) (throw e))) ) ) (defn create-bucket [with-client bucket] (s3/create-bucket with-client bucket)) (defn delete-bucket ([with-client bucket] (try (s3/delete-bucket with-client bucket) (catch Exception e (if (= 409 (.getStatusCode e)) (struct failed-oper (.getStatusCode e) (.getErrorCode e)) (throw e))))) ([with-client bucket flag?] (if (= flag? true) (do (doall (map (fn [b] (del-archived-tattr with-client bucket (:key b))) (:objects (list-bucket with-client bucket)))) (s3/delete-bucket with-client bucket)) (s3/delete-bucket with-client bucket)))) (defn put-archived-tattr [with-client bucket attr data] (try (s3/put-object with-client bucket attr (ByteArrayInputStream. data) {:content-length (count data)}) (catch Exception e (if (= "NoSuchBucket" (.getErrorCode e)) (struct failed-oper (.getStatusCode e) (.getErrorCode e)) (throw e)))))
[ { "context": " (= @f1 @f2))\n \"mbox::mailto:alicefaux@example.org\"\n \"mbox::mailto:bobfake@example.org\"\n ", "end": 1174, "score": 0.999829888343811, "start": 1153, "tag": "EMAIL", "value": "alicefaux@example.org" }, { "context": "ilto:alicefaux@example.org\"\n \"mbox::mailto:bobfake@example.org\"\n \"mbox::mailto:frederstaz@example.org\")))", "end": 1217, "score": 0.9997084736824036, "start": 1198, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": "mailto:bobfake@example.org\"\n \"mbox::mailto:frederstaz@example.org\"))))\n\n(deftest xapi-test\n (testing \"sim returns ", "end": 1263, "score": 0.9997732043266296, "start": 1241, "tag": "EMAIL", "value": "frederstaz@example.org" }, { "context": " (get skeleton actor-id))\n \"mbox::mailto:alicefaux@example.org\"\n \"mbox::mailto:bobfake@example.org\"\n ", "end": 1666, "score": 0.9997791051864624, "start": 1645, "tag": "EMAIL", "value": "alicefaux@example.org" }, { "context": "ilto:alicefaux@example.org\"\n \"mbox::mailto:bobfake@example.org\"\n \"mbox::mailto:frederstaz@example.org\")))", "end": 1709, "score": 0.9997650384902954, "start": 1690, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": "mailto:bobfake@example.org\"\n \"mbox::mailto:frederstaz@example.org\"))))\n\n(deftest stack-test\n (testing \"that we can", "end": 1755, "score": 0.9996172189712524, "start": 1733, "tag": "EMAIL", "value": "frederstaz@example.org" }, { "context": "skeleton\n (get \"mbox::mailto:bobfake@example.org\")\n (nth 10000))))))\n\n(deftes", "end": 2072, "score": 0.9998709559440613, "start": 2053, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": " :select-agents [\"mbox::mailto:bobfake@example.org\"])]\n (is (every?\n #(= \"mailto:bobf", "end": 2968, "score": 0.9957032203674316, "start": 2949, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": ".org\"])]\n (is (every?\n #(= \"mailto:bobfake@example.org\"\n (get-in % [\"actor\" \"mbox\"]))\n ", "end": 3033, "score": 0.9998272657394409, "start": 3014, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": "s in personae are generated\"\n (is (= #{\"mailto:alicefaux@example.org\"\n \"mailto:bobfake@example.org\"\n ", "end": 3191, "score": 0.9998995065689087, "start": 3170, "tag": "EMAIL", "value": "alicefaux@example.org" }, { "context": "ailto:alicefaux@example.org\"\n \"mailto:bobfake@example.org\"\n \"mailto:frederstaz@example.org\"}\n ", "end": 3233, "score": 0.9999000430107117, "start": 3214, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": "\"mailto:bobfake@example.org\"\n \"mailto:frederstaz@example.org\"}\n (->> valid-input sim-seq (map #(get-", "end": 3278, "score": 0.9998394250869751, "start": 3256, "tag": "EMAIL", "value": "frederstaz@example.org" }, { "context": " :select-agents [\"mbox::mailto:bobfake@example.org\"])]\n (is (every?\n #(or (= % {\"obje", "end": 3646, "score": 0.9995919466018677, "start": 3627, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": "Type\" \"Agent\"\n \"name\" \"Owen Overrider\"\n \"mbox\" \"mailto:owove", "end": 4137, "score": 0.9998623728752136, "start": 4123, "tag": "NAME", "value": "Owen Overrider" }, { "context": "rider\"\n \"mbox\" \"mailto:owoverrider@example.com\"}))\n (map #(get % \"object\") ret)))))\n ", "end": 4205, "score": 0.9999290108680725, "start": 4182, "tag": "EMAIL", "value": "owoverrider@example.com" }, { "context": "is (= #{;; simple personae\n \"mailto:alicefaux@example.org\"\n \"mailto:bobfake@example.org\"\n ", "end": 4587, "score": 0.9999193549156189, "start": 4566, "tag": "EMAIL", "value": "alicefaux@example.org" }, { "context": "lto:alicefaux@example.org\"\n \"mailto:bobfake@example.org\"\n \"mailto:frederstaz@example.org\"\n ", "end": 4631, "score": 0.9999141097068787, "start": 4612, "tag": "EMAIL", "value": "bobfake@example.org" }, { "context": "ailto:bobfake@example.org\"\n \"mailto:frederstaz@example.org\"\n ;; tc3 personae\n \"m", "end": 4678, "score": 0.9999068379402161, "start": 4656, "tag": "EMAIL", "value": "frederstaz@example.org" }, { "context": " ;; tc3 personae\n \"mailto:alice@example.org\"\n \"mailto:bob@example.org\"\n ", "end": 4751, "score": 0.999921977519989, "start": 4734, "tag": "EMAIL", "value": "alice@example.org" }, { "context": "\"mailto:alice@example.org\"\n \"mailto:bob@example.org\"\n \"mailto:fred@example.org\"\n ", "end": 4791, "score": 0.9999197125434875, "start": 4776, "tag": "EMAIL", "value": "bob@example.org" }, { "context": " \"mailto:bob@example.org\"\n \"mailto:fred@example.org\"\n \"mailto:phil@example.org\"\n ", "end": 4832, "score": 0.9999170899391174, "start": 4816, "tag": "EMAIL", "value": "fred@example.org" }, { "context": " \"mailto:fred@example.org\"\n \"mailto:phil@example.org\"\n \"mailto:sally@example.org\"\n ", "end": 4873, "score": 0.9999215006828308, "start": 4857, "tag": "EMAIL", "value": "phil@example.org" }, { "context": " \"mailto:phil@example.org\"\n \"mailto:sally@example.org\"\n \"mailto:steve@example.org\"}\n ", "end": 4915, "score": 0.9998641014099121, "start": 4898, "tag": "EMAIL", "value": "sally@example.org" }, { "context": "\"mailto:sally@example.org\"\n \"mailto:steve@example.org\"}\n (set ids))))))\n", "end": 4957, "score": 0.9998968243598938, "start": 4940, "tag": "EMAIL", "value": "steve@example.org" } ]
src/test/com/yetanalytics/datasim/sim_test.clj
yetanalytics/datasim
12
(ns com.yetanalytics.datasim.sim-test (:require [clojure.test :refer [deftest testing is are]] [com.yetanalytics.datasim.sim :refer [build-skeleton sim-seq]] [com.yetanalytics.datasim.input :as input] [clojure.spec.alpha :as s] [xapi-schema.spec :as xs])) (def valid-input (input/from-location :input :json "dev-resources/input/simple.json")) (deftest build-skeleton-test (testing "given valid input, returns a valid skeleton" (is (s/valid? :com.yetanalytics.datasim.sim/skeleton (build-skeleton valid-input))))) (deftest disjoint-rng-test (testing "Make sure RNGs aren't shared across threads." (let [skeleton (build-skeleton (assoc-in valid-input [:parameters :end] nil))] (are [actor-id] (let [statement-seq (get skeleton actor-id) f1 (future (nth statement-seq 1000)) f2 (future (nth statement-seq 1000))] (= @f1 @f2)) "mbox::mailto:alicefaux@example.org" "mbox::mailto:bobfake@example.org" "mbox::mailto:frederstaz@example.org")))) (deftest xapi-test (testing "sim returns valid xapi statements" (let [skeleton (build-skeleton (assoc-in valid-input [:parameters :end] nil))] (are [actor-id] (s/valid? (s/every ::xs/statement) (get skeleton actor-id)) "mbox::mailto:alicefaux@example.org" "mbox::mailto:bobfake@example.org" "mbox::mailto:frederstaz@example.org")))) (deftest stack-test (testing "that we can iterate for a long time w/o a stack overflow" (is (s/valid? ::xs/statement (-> valid-input (assoc-in [:parameters :end] nil) build-skeleton (get "mbox::mailto:bobfake@example.org") (nth 10000)))))) (deftest sim-seq-test (testing "returns statements" (is (s/valid? (s/every ::xs/statement) (sim-seq valid-input)))) (testing "respects max param" (let [ret (sim-seq (assoc-in valid-input [:parameters :max] 3))] (is (s/valid? (s/every ::xs/statement) ret)) (is (= 3 (count ret))))) (testing "respects from param" (let [[s0 s1 & _] (sim-seq valid-input) [s1' & _] (sim-seq (assoc-in valid-input [:parameters :from] (get s0 "timestamp")))] (is (not= s0 s1')) (is (= s1 s1')))) (testing "respects agent selection" (let [ret (sim-seq (assoc-in valid-input [:parameters :max] 3) ;; specify we only want the given agent(s) :select-agents ["mbox::mailto:bobfake@example.org"])] (is (every? #(= "mailto:bobfake@example.org" (get-in % ["actor" "mbox"])) ret)))) (testing "only actors in personae are generated" (is (= #{"mailto:alicefaux@example.org" "mailto:bobfake@example.org" "mailto:frederstaz@example.org"} (->> valid-input sim-seq (map #(get-in % ["actor" "mbox"])) set)))) (testing "can apply object override" (let [align (input/from-location :alignments :json "dev-resources/alignments/simple_with_overrides.json") ret (sim-seq (assoc valid-input :alignments align) :select-agents ["mbox::mailto:bobfake@example.org"])] (is (every? #(or (= % {"objectType" "Activity" "id" "https://www.whatever.com/activities#course2" "definition" {"name" {"en-US" "Course 2"} "description" {"en-US" "Course Description 2"} "type" "http://adlnet.gov/expapi/activities/course"}}) (= % {"objectType" "Agent" "name" "Owen Overrider" "mbox" "mailto:owoverrider@example.com"})) (map #(get % "object") ret))))) (testing "can apply multiple personae" (let [per (input/from-location :personae :json "dev-resources/personae/tccc_dev.json") ret (sim-seq (update valid-input :personae-array conj per)) ids (map #(get-in % ["actor" "mbox"]) ret)] (is (= #{;; simple personae "mailto:alicefaux@example.org" "mailto:bobfake@example.org" "mailto:frederstaz@example.org" ;; tc3 personae "mailto:alice@example.org" "mailto:bob@example.org" "mailto:fred@example.org" "mailto:phil@example.org" "mailto:sally@example.org" "mailto:steve@example.org"} (set ids))))))
58199
(ns com.yetanalytics.datasim.sim-test (:require [clojure.test :refer [deftest testing is are]] [com.yetanalytics.datasim.sim :refer [build-skeleton sim-seq]] [com.yetanalytics.datasim.input :as input] [clojure.spec.alpha :as s] [xapi-schema.spec :as xs])) (def valid-input (input/from-location :input :json "dev-resources/input/simple.json")) (deftest build-skeleton-test (testing "given valid input, returns a valid skeleton" (is (s/valid? :com.yetanalytics.datasim.sim/skeleton (build-skeleton valid-input))))) (deftest disjoint-rng-test (testing "Make sure RNGs aren't shared across threads." (let [skeleton (build-skeleton (assoc-in valid-input [:parameters :end] nil))] (are [actor-id] (let [statement-seq (get skeleton actor-id) f1 (future (nth statement-seq 1000)) f2 (future (nth statement-seq 1000))] (= @f1 @f2)) "mbox::mailto:<EMAIL>" "mbox::mailto:<EMAIL>" "mbox::mailto:<EMAIL>")))) (deftest xapi-test (testing "sim returns valid xapi statements" (let [skeleton (build-skeleton (assoc-in valid-input [:parameters :end] nil))] (are [actor-id] (s/valid? (s/every ::xs/statement) (get skeleton actor-id)) "mbox::mailto:<EMAIL>" "mbox::mailto:<EMAIL>" "mbox::mailto:<EMAIL>")))) (deftest stack-test (testing "that we can iterate for a long time w/o a stack overflow" (is (s/valid? ::xs/statement (-> valid-input (assoc-in [:parameters :end] nil) build-skeleton (get "mbox::mailto:<EMAIL>") (nth 10000)))))) (deftest sim-seq-test (testing "returns statements" (is (s/valid? (s/every ::xs/statement) (sim-seq valid-input)))) (testing "respects max param" (let [ret (sim-seq (assoc-in valid-input [:parameters :max] 3))] (is (s/valid? (s/every ::xs/statement) ret)) (is (= 3 (count ret))))) (testing "respects from param" (let [[s0 s1 & _] (sim-seq valid-input) [s1' & _] (sim-seq (assoc-in valid-input [:parameters :from] (get s0 "timestamp")))] (is (not= s0 s1')) (is (= s1 s1')))) (testing "respects agent selection" (let [ret (sim-seq (assoc-in valid-input [:parameters :max] 3) ;; specify we only want the given agent(s) :select-agents ["mbox::mailto:<EMAIL>"])] (is (every? #(= "mailto:<EMAIL>" (get-in % ["actor" "mbox"])) ret)))) (testing "only actors in personae are generated" (is (= #{"mailto:<EMAIL>" "mailto:<EMAIL>" "mailto:<EMAIL>"} (->> valid-input sim-seq (map #(get-in % ["actor" "mbox"])) set)))) (testing "can apply object override" (let [align (input/from-location :alignments :json "dev-resources/alignments/simple_with_overrides.json") ret (sim-seq (assoc valid-input :alignments align) :select-agents ["mbox::mailto:<EMAIL>"])] (is (every? #(or (= % {"objectType" "Activity" "id" "https://www.whatever.com/activities#course2" "definition" {"name" {"en-US" "Course 2"} "description" {"en-US" "Course Description 2"} "type" "http://adlnet.gov/expapi/activities/course"}}) (= % {"objectType" "Agent" "name" "<NAME>" "mbox" "mailto:<EMAIL>"})) (map #(get % "object") ret))))) (testing "can apply multiple personae" (let [per (input/from-location :personae :json "dev-resources/personae/tccc_dev.json") ret (sim-seq (update valid-input :personae-array conj per)) ids (map #(get-in % ["actor" "mbox"]) ret)] (is (= #{;; simple personae "mailto:<EMAIL>" "mailto:<EMAIL>" "mailto:<EMAIL>" ;; tc3 personae "mailto:<EMAIL>" "mailto:<EMAIL>" "mailto:<EMAIL>" "mailto:<EMAIL>" "mailto:<EMAIL>" "mailto:<EMAIL>"} (set ids))))))
true
(ns com.yetanalytics.datasim.sim-test (:require [clojure.test :refer [deftest testing is are]] [com.yetanalytics.datasim.sim :refer [build-skeleton sim-seq]] [com.yetanalytics.datasim.input :as input] [clojure.spec.alpha :as s] [xapi-schema.spec :as xs])) (def valid-input (input/from-location :input :json "dev-resources/input/simple.json")) (deftest build-skeleton-test (testing "given valid input, returns a valid skeleton" (is (s/valid? :com.yetanalytics.datasim.sim/skeleton (build-skeleton valid-input))))) (deftest disjoint-rng-test (testing "Make sure RNGs aren't shared across threads." (let [skeleton (build-skeleton (assoc-in valid-input [:parameters :end] nil))] (are [actor-id] (let [statement-seq (get skeleton actor-id) f1 (future (nth statement-seq 1000)) f2 (future (nth statement-seq 1000))] (= @f1 @f2)) "mbox::mailto:PI:EMAIL:<EMAIL>END_PI" "mbox::mailto:PI:EMAIL:<EMAIL>END_PI" "mbox::mailto:PI:EMAIL:<EMAIL>END_PI")))) (deftest xapi-test (testing "sim returns valid xapi statements" (let [skeleton (build-skeleton (assoc-in valid-input [:parameters :end] nil))] (are [actor-id] (s/valid? (s/every ::xs/statement) (get skeleton actor-id)) "mbox::mailto:PI:EMAIL:<EMAIL>END_PI" "mbox::mailto:PI:EMAIL:<EMAIL>END_PI" "mbox::mailto:PI:EMAIL:<EMAIL>END_PI")))) (deftest stack-test (testing "that we can iterate for a long time w/o a stack overflow" (is (s/valid? ::xs/statement (-> valid-input (assoc-in [:parameters :end] nil) build-skeleton (get "mbox::mailto:PI:EMAIL:<EMAIL>END_PI") (nth 10000)))))) (deftest sim-seq-test (testing "returns statements" (is (s/valid? (s/every ::xs/statement) (sim-seq valid-input)))) (testing "respects max param" (let [ret (sim-seq (assoc-in valid-input [:parameters :max] 3))] (is (s/valid? (s/every ::xs/statement) ret)) (is (= 3 (count ret))))) (testing "respects from param" (let [[s0 s1 & _] (sim-seq valid-input) [s1' & _] (sim-seq (assoc-in valid-input [:parameters :from] (get s0 "timestamp")))] (is (not= s0 s1')) (is (= s1 s1')))) (testing "respects agent selection" (let [ret (sim-seq (assoc-in valid-input [:parameters :max] 3) ;; specify we only want the given agent(s) :select-agents ["mbox::mailto:PI:EMAIL:<EMAIL>END_PI"])] (is (every? #(= "mailto:PI:EMAIL:<EMAIL>END_PI" (get-in % ["actor" "mbox"])) ret)))) (testing "only actors in personae are generated" (is (= #{"mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI"} (->> valid-input sim-seq (map #(get-in % ["actor" "mbox"])) set)))) (testing "can apply object override" (let [align (input/from-location :alignments :json "dev-resources/alignments/simple_with_overrides.json") ret (sim-seq (assoc valid-input :alignments align) :select-agents ["mbox::mailto:PI:EMAIL:<EMAIL>END_PI"])] (is (every? #(or (= % {"objectType" "Activity" "id" "https://www.whatever.com/activities#course2" "definition" {"name" {"en-US" "Course 2"} "description" {"en-US" "Course Description 2"} "type" "http://adlnet.gov/expapi/activities/course"}}) (= % {"objectType" "Agent" "name" "PI:NAME:<NAME>END_PI" "mbox" "mailto:PI:EMAIL:<EMAIL>END_PI"})) (map #(get % "object") ret))))) (testing "can apply multiple personae" (let [per (input/from-location :personae :json "dev-resources/personae/tccc_dev.json") ret (sim-seq (update valid-input :personae-array conj per)) ids (map #(get-in % ["actor" "mbox"]) ret)] (is (= #{;; simple personae "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" ;; tc3 personae "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI"} (set ids))))))
[ { "context": "st create-list\n (let [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cret\"})]\n\n ", "end": 356, "score": 0.9979615211486816, "start": 347, "tag": "USERNAME", "value": "Test user" }, { "context": "et [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cret\"})]\n\n (testing \"Create a li", "end": 379, "score": 0.9999194145202637, "start": 366, "tag": "EMAIL", "value": "me@mytest.com" }, { "context": "ame \"Test user\" :email \"me@mytest.com\" :password \"s3cret\"})]\n\n (testing \"Create a list for given user\"\n", "end": 398, "score": 0.9995353817939758, "start": 392, "tag": "PASSWORD", "value": "s3cret" }, { "context": " retrieve-list\n (let [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})]\n\n ", "end": 681, "score": 0.9973140954971313, "start": 672, "tag": "USERNAME", "value": "Test user" }, { "context": "et [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})]\n\n (testing \"Retrieve a ", "end": 704, "score": 0.9998960494995117, "start": 691, "tag": "EMAIL", "value": "me@mytest.com" }, { "context": "ame \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})]\n\n (testing \"Retrieve a list by id\"\n (", "end": 723, "score": 0.9995275735855103, "start": 717, "tag": "PASSWORD", "value": "s3cr3t" }, { "context": "st update-list\n (let [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})]\n\n ", "end": 1064, "score": 0.9961519241333008, "start": 1055, "tag": "USERNAME", "value": "Test user" }, { "context": "et [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})]\n\n (testing \"Modifies ex", "end": 1087, "score": 0.9999176859855652, "start": 1074, "tag": "EMAIL", "value": "me@mytest.com" }, { "context": "ame \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})]\n\n (testing \"Modifies existing list\"\n ", "end": 1106, "score": 0.9995304346084595, "start": 1100, "tag": "PASSWORD", "value": "s3cr3t" }, { "context": "t delete-lists\n (let [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n ", "end": 1522, "score": 0.9970955848693848, "start": 1513, "tag": "USERNAME", "value": "Test user" }, { "context": "et [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n user-id (:id user)]", "end": 1545, "score": 0.9999176859855652, "start": 1532, "tag": "EMAIL", "value": "me@mytest.com" }, { "context": "ame \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n user-id (:id user)]\n (testing \"Decr", "end": 1564, "score": 0.999538242816925, "start": 1558, "tag": "PASSWORD", "value": "s3cr3t" }, { "context": "t add-products\n (let [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n ", "end": 2295, "score": 0.9967097640037537, "start": 2286, "tag": "USERNAME", "value": "Test user" }, { "context": "et [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n my-list (lists/crea", "end": 2318, "score": 0.9999030232429504, "start": 2305, "tag": "EMAIL", "value": "me@mytest.com" }, { "context": "ame \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n my-list (lists/create {:user_id (:id u", "end": 2337, "score": 0.9991961717605591, "start": 2331, "tag": "PASSWORD", "value": "s3cr3t" }, { "context": "emove-products\n (let [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n ", "end": 3706, "score": 0.9981814622879028, "start": 3697, "tag": "USERNAME", "value": "Test user" }, { "context": "et [user (users/create {:name \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n kidneys (products/c", "end": 3729, "score": 0.9999250769615173, "start": 3716, "tag": "EMAIL", "value": "me@mytest.com" }, { "context": "ame \"Test user\" :email \"me@mytest.com\" :password \"s3cr3t\"})\n kidneys (products/create {:title \"Kidn", "end": 3748, "score": 0.999241828918457, "start": 3742, "tag": "PASSWORD", "value": "s3cr3t" } ]
restful-clojure/test/restful_clojure/lists_test.clj
joaobertacchi/restful-clojure
65
(ns restful-clojure.lists-test (:use clojure.test restful-clojure.test-core) (:require [restful-clojure.models.lists :as lists] [restful-clojure.models.products :as products] [restful-clojure.models.users :as users])) (use-fixtures :each with-rollback) (deftest create-list (let [user (users/create {:name "Test user" :email "me@mytest.com" :password "s3cret"})] (testing "Create a list for given user" (let [count-orig (lists/count-lists)] (lists/create {:user_id (:id user) :title "New Test"}) (is (= (inc count-orig) (lists/count-lists))))))) (deftest retrieve-list (let [user (users/create {:name "Test user" :email "me@mytest.com" :password "s3cr3t"})] (testing "Retrieve a list by id" (let [my-list (lists/create {:user_id (:id user) :title "My list"}) found-list (lists/find-by-id (:id my-list))] (is (= "My list" (:title found-list))) (is (= (:id user) (:user_id found-list))))))) (deftest update-list (let [user (users/create {:name "Test user" :email "me@mytest.com" :password "s3cr3t"})] (testing "Modifies existing list" (let [list-orig (lists/create {:user_id (:id user) :title "FP Languages"}) list-id (:id list-orig)] (lists/update-list (assoc list-orig :title "Awesome Languages")) (is (= "Awesome Languages" (:title (lists/find-by-id list-id)))))))) (deftest delete-lists (let [user (users/create {:name "Test user" :email "me@mytest.com" :password "s3cr3t"}) user-id (:id user)] (testing "Decreases list count" (let [listdata (lists/create {:user_id user-id :title "Unimportant things"}) list-count (lists/count-lists)] (lists/delete-list listdata) (is (= (dec list-count) (lists/count-lists))))) (testing "Deleted correct list" (let [list-keep (lists/create {:user_id user-id :title "Stuff to keep"}) list-del (lists/create {:user_id user-id :title "Stuff to delete"})] (lists/delete-list list-del) (is (seq (lists/find-by-id (:id list-keep)))) (is (nil? (lists/find-by-id (:id list-del)))))))) (deftest add-products (let [user (users/create {:name "Test user" :email "me@mytest.com" :password "s3cr3t"}) my-list (lists/create {:user_id (:id user) :title "My list"}) pintos (products/create {:title "Pinto Beans" :description "Yummy beans for burritos"})] (testing "Adds product to existing list" (let [modified-list (lists/add-product my-list (:id pintos))] (is (= [pintos] (:products modified-list))))) (testing "Creates new list with products" (let [listdata (lists/create {:user_id (:id user) :title "Most interesting" :products [pintos]})] (is (= [pintos] (:products listdata))) (is (= [pintos] (:products (lists/find-by-id (:id listdata))))))) (testing "Creates products added with an update" (let [listdata (lists/create {:user_id (:id user) :title "Things to update" :products [pintos]}) coffee (products/create {:title "Coffee Beans" :description "No, not *THAT* Java"}) updated (lists/update-list (update-in listdata [:products] conj coffee))] (is (= [pintos coffee] (:products updated))) (is (= [pintos coffee] (:products (lists/find-by-id (:id listdata))))))))) (deftest remove-products (let [user (users/create {:name "Test user" :email "me@mytest.com" :password "s3cr3t"}) kidneys (products/create {:title "Kidney Beans" :description "Poor Charlie the Unicorn..."}) limas (products/create {:title "Lima Beans" :description "Yuck!"}) my-list (lists/create {:user_id (:id user) :title "My list" :products [kidneys limas]})] (testing "Does not remove a product from the database entirely" (let [fresh-list (lists/create {:user_id (:id user) :title "My list" :products [kidneys limas]})] (lists/remove-product fresh-list (:id kidneys)) (is (not (nil? (products/find-by-id (:id kidneys))))))) (testing "Removes a product from a list" (let [modified-list (lists/remove-product my-list (:id kidneys))] (is (= [limas] (:products modified-list))))) (testing "Removes products absent from an update" (let [coffee (products/create {:title "Coffee Beans" :description "No, not *THAT* Java"}) listdata (lists/create {:user_id (:id user) :title "Things to update" :products [limas coffee]}) updated (lists/update-list (assoc listdata :products [coffee]))] (is (= [coffee] (:products updated))) (is (= [coffee] (:products (lists/find-by-id (:id listdata)))))))))
118503
(ns restful-clojure.lists-test (:use clojure.test restful-clojure.test-core) (:require [restful-clojure.models.lists :as lists] [restful-clojure.models.products :as products] [restful-clojure.models.users :as users])) (use-fixtures :each with-rollback) (deftest create-list (let [user (users/create {:name "Test user" :email "<EMAIL>" :password "<PASSWORD>"})] (testing "Create a list for given user" (let [count-orig (lists/count-lists)] (lists/create {:user_id (:id user) :title "New Test"}) (is (= (inc count-orig) (lists/count-lists))))))) (deftest retrieve-list (let [user (users/create {:name "Test user" :email "<EMAIL>" :password "<PASSWORD>"})] (testing "Retrieve a list by id" (let [my-list (lists/create {:user_id (:id user) :title "My list"}) found-list (lists/find-by-id (:id my-list))] (is (= "My list" (:title found-list))) (is (= (:id user) (:user_id found-list))))))) (deftest update-list (let [user (users/create {:name "Test user" :email "<EMAIL>" :password "<PASSWORD>"})] (testing "Modifies existing list" (let [list-orig (lists/create {:user_id (:id user) :title "FP Languages"}) list-id (:id list-orig)] (lists/update-list (assoc list-orig :title "Awesome Languages")) (is (= "Awesome Languages" (:title (lists/find-by-id list-id)))))))) (deftest delete-lists (let [user (users/create {:name "Test user" :email "<EMAIL>" :password "<PASSWORD>"}) user-id (:id user)] (testing "Decreases list count" (let [listdata (lists/create {:user_id user-id :title "Unimportant things"}) list-count (lists/count-lists)] (lists/delete-list listdata) (is (= (dec list-count) (lists/count-lists))))) (testing "Deleted correct list" (let [list-keep (lists/create {:user_id user-id :title "Stuff to keep"}) list-del (lists/create {:user_id user-id :title "Stuff to delete"})] (lists/delete-list list-del) (is (seq (lists/find-by-id (:id list-keep)))) (is (nil? (lists/find-by-id (:id list-del)))))))) (deftest add-products (let [user (users/create {:name "Test user" :email "<EMAIL>" :password "<PASSWORD>"}) my-list (lists/create {:user_id (:id user) :title "My list"}) pintos (products/create {:title "Pinto Beans" :description "Yummy beans for burritos"})] (testing "Adds product to existing list" (let [modified-list (lists/add-product my-list (:id pintos))] (is (= [pintos] (:products modified-list))))) (testing "Creates new list with products" (let [listdata (lists/create {:user_id (:id user) :title "Most interesting" :products [pintos]})] (is (= [pintos] (:products listdata))) (is (= [pintos] (:products (lists/find-by-id (:id listdata))))))) (testing "Creates products added with an update" (let [listdata (lists/create {:user_id (:id user) :title "Things to update" :products [pintos]}) coffee (products/create {:title "Coffee Beans" :description "No, not *THAT* Java"}) updated (lists/update-list (update-in listdata [:products] conj coffee))] (is (= [pintos coffee] (:products updated))) (is (= [pintos coffee] (:products (lists/find-by-id (:id listdata))))))))) (deftest remove-products (let [user (users/create {:name "Test user" :email "<EMAIL>" :password "<PASSWORD>"}) kidneys (products/create {:title "Kidney Beans" :description "Poor Charlie the Unicorn..."}) limas (products/create {:title "Lima Beans" :description "Yuck!"}) my-list (lists/create {:user_id (:id user) :title "My list" :products [kidneys limas]})] (testing "Does not remove a product from the database entirely" (let [fresh-list (lists/create {:user_id (:id user) :title "My list" :products [kidneys limas]})] (lists/remove-product fresh-list (:id kidneys)) (is (not (nil? (products/find-by-id (:id kidneys))))))) (testing "Removes a product from a list" (let [modified-list (lists/remove-product my-list (:id kidneys))] (is (= [limas] (:products modified-list))))) (testing "Removes products absent from an update" (let [coffee (products/create {:title "Coffee Beans" :description "No, not *THAT* Java"}) listdata (lists/create {:user_id (:id user) :title "Things to update" :products [limas coffee]}) updated (lists/update-list (assoc listdata :products [coffee]))] (is (= [coffee] (:products updated))) (is (= [coffee] (:products (lists/find-by-id (:id listdata)))))))))
true
(ns restful-clojure.lists-test (:use clojure.test restful-clojure.test-core) (:require [restful-clojure.models.lists :as lists] [restful-clojure.models.products :as products] [restful-clojure.models.users :as users])) (use-fixtures :each with-rollback) (deftest create-list (let [user (users/create {:name "Test user" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"})] (testing "Create a list for given user" (let [count-orig (lists/count-lists)] (lists/create {:user_id (:id user) :title "New Test"}) (is (= (inc count-orig) (lists/count-lists))))))) (deftest retrieve-list (let [user (users/create {:name "Test user" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"})] (testing "Retrieve a list by id" (let [my-list (lists/create {:user_id (:id user) :title "My list"}) found-list (lists/find-by-id (:id my-list))] (is (= "My list" (:title found-list))) (is (= (:id user) (:user_id found-list))))))) (deftest update-list (let [user (users/create {:name "Test user" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"})] (testing "Modifies existing list" (let [list-orig (lists/create {:user_id (:id user) :title "FP Languages"}) list-id (:id list-orig)] (lists/update-list (assoc list-orig :title "Awesome Languages")) (is (= "Awesome Languages" (:title (lists/find-by-id list-id)))))))) (deftest delete-lists (let [user (users/create {:name "Test user" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}) user-id (:id user)] (testing "Decreases list count" (let [listdata (lists/create {:user_id user-id :title "Unimportant things"}) list-count (lists/count-lists)] (lists/delete-list listdata) (is (= (dec list-count) (lists/count-lists))))) (testing "Deleted correct list" (let [list-keep (lists/create {:user_id user-id :title "Stuff to keep"}) list-del (lists/create {:user_id user-id :title "Stuff to delete"})] (lists/delete-list list-del) (is (seq (lists/find-by-id (:id list-keep)))) (is (nil? (lists/find-by-id (:id list-del)))))))) (deftest add-products (let [user (users/create {:name "Test user" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}) my-list (lists/create {:user_id (:id user) :title "My list"}) pintos (products/create {:title "Pinto Beans" :description "Yummy beans for burritos"})] (testing "Adds product to existing list" (let [modified-list (lists/add-product my-list (:id pintos))] (is (= [pintos] (:products modified-list))))) (testing "Creates new list with products" (let [listdata (lists/create {:user_id (:id user) :title "Most interesting" :products [pintos]})] (is (= [pintos] (:products listdata))) (is (= [pintos] (:products (lists/find-by-id (:id listdata))))))) (testing "Creates products added with an update" (let [listdata (lists/create {:user_id (:id user) :title "Things to update" :products [pintos]}) coffee (products/create {:title "Coffee Beans" :description "No, not *THAT* Java"}) updated (lists/update-list (update-in listdata [:products] conj coffee))] (is (= [pintos coffee] (:products updated))) (is (= [pintos coffee] (:products (lists/find-by-id (:id listdata))))))))) (deftest remove-products (let [user (users/create {:name "Test user" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}) kidneys (products/create {:title "Kidney Beans" :description "Poor Charlie the Unicorn..."}) limas (products/create {:title "Lima Beans" :description "Yuck!"}) my-list (lists/create {:user_id (:id user) :title "My list" :products [kidneys limas]})] (testing "Does not remove a product from the database entirely" (let [fresh-list (lists/create {:user_id (:id user) :title "My list" :products [kidneys limas]})] (lists/remove-product fresh-list (:id kidneys)) (is (not (nil? (products/find-by-id (:id kidneys))))))) (testing "Removes a product from a list" (let [modified-list (lists/remove-product my-list (:id kidneys))] (is (= [limas] (:products modified-list))))) (testing "Removes products absent from an update" (let [coffee (products/create {:title "Coffee Beans" :description "No, not *THAT* Java"}) listdata (lists/create {:user_id (:id user) :title "Things to update" :products [limas coffee]}) updated (lists/update-list (assoc listdata :products [coffee]))] (is (= [coffee] (:products updated))) (is (= [coffee] (:products (lists/find-by-id (:id listdata)))))))))
[ { "context": ":input {:name \"from\"\n :placeholder \"Lähtösana\"\n :type \"text\"\n :clas", "end": 2176, "score": 0.7536916732788086, "start": 2167, "tag": "NAME", "value": "Lähtösana" }, { "context": " [:input {:name \"to\"\n :placeholder \"Kohdesana\"\n :type \"text\"\n :cla", "end": 2369, "score": 0.7945581674575806, "start": 2364, "tag": "NAME", "value": "ohdes" } ]
src/hauskisgeneraattori/core.cljs
tvirolai/hauskisgeneraattori
0
(ns hauskisgeneraattori.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [reagent.core :as r] [cljs-http.client :as http] [cljs.core.async :refer [<! timeout]] [ajax.core :refer [GET]] [clojure.string :as str])) (def state (r/atom {:from "" :to "" :tracks []})) (defn log [s] (.log js/console (str s))) (defn to-string [item] (str/join " " (vals item))) (defn contains-word? [item word] (str/includes? (str/lower-case (to-string item)) (str/lower-case word))) (defn item-to-string [item] (str (:artist item) ": " (:track item))) (defn edit-item [item to from] (let [istring (item-to-string item)] (-> istring (str/replace from to) (str/replace (str/capitalize from) (str/capitalize to)) (str/replace (str/upper-case from) (str/upper-case to)) (str/replace (str/lower-case from) (str/lower-case to))))) (defn extract-tracks [response] (vec (map (fn [entry] {:artist (:artist entry) :track (:name entry)}) (:track (:trackmatches (:results (:body response))))))) (defn get-tracks! [url from to] (go (let [response (<! (http/get (str url "&track=" from "&limit=300") {:with-credentials? false}))] (reset! state {:from from :to to :tracks (->> (extract-tracks response) (shuffle) (take 100) (filter #(contains-word? % from)))})))) ;; ------------------------- ;; URL (def api "http://ws.audioscrobbler.com/2.0/?method=track.search&api_key=MY_API_KEY&format=json") ;; ------------------------- ;; Views (def form [:div [:form {:on-submit (fn [e] (let [from (.. e -target -elements -from -value) to (.. e -target -elements -to -value)] (.preventDefault e) ;(set-state! from to) (get-tracks! api from to))) :class "form-horizontal"} [:div {:class "form-group"} [:div {:class "col-sm-8"} [:input {:name "from" :placeholder "Lähtösana" :type "text" :class "form-control"}]]] [:div {:class "form-group"} [:div {:class "col-sm-8"} [:input {:name "to" :placeholder "Kohdesana" :type "text" :class "form-control"}]]] [:div [:input {:type "submit" :class "btn btn-default"}]]]]) (defn table [appstate] (let [to (:to @appstate) from (:from @appstate) tracks (:tracks @appstate)] [:table.table.table-striped.table-bordered {:cell-spacing "0" :width "80%"} (when-not (empty? tracks) [:thead>tr [:th "Hauskiksia"]]) (doall (into [:tbody] (for [item tracks] [:tr [:td (edit-item item to from)]])))])) (defn home-page [] [:div [:h2 "Hauskisgeneraattori"] form ;[:h3 (str "From: " (:from @state))] ;[:h3 (str "To: " (:to @state))] ;[:p (str "Hauskaa:" (map edit-item (:tracks @state)))] [:br] [table state]]) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
122598
(ns hauskisgeneraattori.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [reagent.core :as r] [cljs-http.client :as http] [cljs.core.async :refer [<! timeout]] [ajax.core :refer [GET]] [clojure.string :as str])) (def state (r/atom {:from "" :to "" :tracks []})) (defn log [s] (.log js/console (str s))) (defn to-string [item] (str/join " " (vals item))) (defn contains-word? [item word] (str/includes? (str/lower-case (to-string item)) (str/lower-case word))) (defn item-to-string [item] (str (:artist item) ": " (:track item))) (defn edit-item [item to from] (let [istring (item-to-string item)] (-> istring (str/replace from to) (str/replace (str/capitalize from) (str/capitalize to)) (str/replace (str/upper-case from) (str/upper-case to)) (str/replace (str/lower-case from) (str/lower-case to))))) (defn extract-tracks [response] (vec (map (fn [entry] {:artist (:artist entry) :track (:name entry)}) (:track (:trackmatches (:results (:body response))))))) (defn get-tracks! [url from to] (go (let [response (<! (http/get (str url "&track=" from "&limit=300") {:with-credentials? false}))] (reset! state {:from from :to to :tracks (->> (extract-tracks response) (shuffle) (take 100) (filter #(contains-word? % from)))})))) ;; ------------------------- ;; URL (def api "http://ws.audioscrobbler.com/2.0/?method=track.search&api_key=MY_API_KEY&format=json") ;; ------------------------- ;; Views (def form [:div [:form {:on-submit (fn [e] (let [from (.. e -target -elements -from -value) to (.. e -target -elements -to -value)] (.preventDefault e) ;(set-state! from to) (get-tracks! api from to))) :class "form-horizontal"} [:div {:class "form-group"} [:div {:class "col-sm-8"} [:input {:name "from" :placeholder "<NAME>" :type "text" :class "form-control"}]]] [:div {:class "form-group"} [:div {:class "col-sm-8"} [:input {:name "to" :placeholder "K<NAME>ana" :type "text" :class "form-control"}]]] [:div [:input {:type "submit" :class "btn btn-default"}]]]]) (defn table [appstate] (let [to (:to @appstate) from (:from @appstate) tracks (:tracks @appstate)] [:table.table.table-striped.table-bordered {:cell-spacing "0" :width "80%"} (when-not (empty? tracks) [:thead>tr [:th "Hauskiksia"]]) (doall (into [:tbody] (for [item tracks] [:tr [:td (edit-item item to from)]])))])) (defn home-page [] [:div [:h2 "Hauskisgeneraattori"] form ;[:h3 (str "From: " (:from @state))] ;[:h3 (str "To: " (:to @state))] ;[:p (str "Hauskaa:" (map edit-item (:tracks @state)))] [:br] [table state]]) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
true
(ns hauskisgeneraattori.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [reagent.core :as r] [cljs-http.client :as http] [cljs.core.async :refer [<! timeout]] [ajax.core :refer [GET]] [clojure.string :as str])) (def state (r/atom {:from "" :to "" :tracks []})) (defn log [s] (.log js/console (str s))) (defn to-string [item] (str/join " " (vals item))) (defn contains-word? [item word] (str/includes? (str/lower-case (to-string item)) (str/lower-case word))) (defn item-to-string [item] (str (:artist item) ": " (:track item))) (defn edit-item [item to from] (let [istring (item-to-string item)] (-> istring (str/replace from to) (str/replace (str/capitalize from) (str/capitalize to)) (str/replace (str/upper-case from) (str/upper-case to)) (str/replace (str/lower-case from) (str/lower-case to))))) (defn extract-tracks [response] (vec (map (fn [entry] {:artist (:artist entry) :track (:name entry)}) (:track (:trackmatches (:results (:body response))))))) (defn get-tracks! [url from to] (go (let [response (<! (http/get (str url "&track=" from "&limit=300") {:with-credentials? false}))] (reset! state {:from from :to to :tracks (->> (extract-tracks response) (shuffle) (take 100) (filter #(contains-word? % from)))})))) ;; ------------------------- ;; URL (def api "http://ws.audioscrobbler.com/2.0/?method=track.search&api_key=MY_API_KEY&format=json") ;; ------------------------- ;; Views (def form [:div [:form {:on-submit (fn [e] (let [from (.. e -target -elements -from -value) to (.. e -target -elements -to -value)] (.preventDefault e) ;(set-state! from to) (get-tracks! api from to))) :class "form-horizontal"} [:div {:class "form-group"} [:div {:class "col-sm-8"} [:input {:name "from" :placeholder "PI:NAME:<NAME>END_PI" :type "text" :class "form-control"}]]] [:div {:class "form-group"} [:div {:class "col-sm-8"} [:input {:name "to" :placeholder "KPI:NAME:<NAME>END_PIana" :type "text" :class "form-control"}]]] [:div [:input {:type "submit" :class "btn btn-default"}]]]]) (defn table [appstate] (let [to (:to @appstate) from (:from @appstate) tracks (:tracks @appstate)] [:table.table.table-striped.table-bordered {:cell-spacing "0" :width "80%"} (when-not (empty? tracks) [:thead>tr [:th "Hauskiksia"]]) (doall (into [:tbody] (for [item tracks] [:tr [:td (edit-item item to from)]])))])) (defn home-page [] [:div [:h2 "Hauskisgeneraattori"] form ;[:h3 (str "From: " (:from @state))] ;[:h3 (str "To: " (:to @state))] ;[:p (str "Hauskaa:" (map edit-item (:tracks @state)))] [:br] [table state]]) ;; ------------------------- ;; Initialize app (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
[ { "context": ";;; Author: David Goldfarb (deg@degel.com)\n;;; Copyright (c) 2017, David Gol", "end": 26, "score": 0.9998875260353088, "start": 12, "tag": "NAME", "value": "David Goldfarb" }, { "context": ";;; Author: David Goldfarb (deg@degel.com)\n;;; Copyright (c) 2017, David Goldfarb\n\n(ns loca", "end": 41, "score": 0.9999305605888367, "start": 28, "tag": "EMAIL", "value": "deg@degel.com" }, { "context": "d Goldfarb (deg@degel.com)\n;;; Copyright (c) 2017, David Goldfarb\n\n(ns localist.re-frame-firebase.helpers\n (:requi", "end": 81, "score": 0.9998550415039062, "start": 67, "tag": "NAME", "value": "David Goldfarb" } ]
src/cljs/localist/re_frame_firebase/helpers.cljs
jahenderson777/localist
0
;;; Author: David Goldfarb (deg@degel.com) ;;; Copyright (c) 2017, David Goldfarb (ns localist.re-frame-firebase.helpers (:require [clojure.spec.alpha :as s] [iron.re-utils :as re-utils] [iron.utils :as utils] [localist.re-frame-firebase.core :as core])) ;;; Helper functions that straddle the line between this library and Iron ;;; utils. These may move, change, or be abandoned, as I get more comfortable ;;; with them. (defn js->clj-tree [x] (-> (.val x) js->clj clojure.walk/keywordize-keys)) (defn promise-wrapper [promise on-success on-failure] {:pre [(utils/validate (s/nilable :re-frame/vec-or-fn) on-success) (utils/validate (s/nilable :re-frame/vec-or-fn) on-failure)]} (when on-success (.then promise (re-utils/event->fn on-success))) (if on-failure (.catch promise (re-utils/event->fn on-failure)) (.catch promise (core/default-error-handler)))) (defn success-failure-wrapper [on-success on-failure] {:pre [(utils/validate (s/nilable :re-frame/vec-or-fn) on-success) (utils/validate (s/nilable :re-frame/vec-or-fn) on-failure)] :post (fn? %)} (let [on-success (and on-success (re-utils/event->fn on-success)) on-failure (and on-failure (re-utils/event->fn on-failure))] (fn [err] (cond (nil? err) (when on-success (on-success)) on-failure (on-failure err) :else ((core/default-error-handler) err)))))
16651
;;; Author: <NAME> (<EMAIL>) ;;; Copyright (c) 2017, <NAME> (ns localist.re-frame-firebase.helpers (:require [clojure.spec.alpha :as s] [iron.re-utils :as re-utils] [iron.utils :as utils] [localist.re-frame-firebase.core :as core])) ;;; Helper functions that straddle the line between this library and Iron ;;; utils. These may move, change, or be abandoned, as I get more comfortable ;;; with them. (defn js->clj-tree [x] (-> (.val x) js->clj clojure.walk/keywordize-keys)) (defn promise-wrapper [promise on-success on-failure] {:pre [(utils/validate (s/nilable :re-frame/vec-or-fn) on-success) (utils/validate (s/nilable :re-frame/vec-or-fn) on-failure)]} (when on-success (.then promise (re-utils/event->fn on-success))) (if on-failure (.catch promise (re-utils/event->fn on-failure)) (.catch promise (core/default-error-handler)))) (defn success-failure-wrapper [on-success on-failure] {:pre [(utils/validate (s/nilable :re-frame/vec-or-fn) on-success) (utils/validate (s/nilable :re-frame/vec-or-fn) on-failure)] :post (fn? %)} (let [on-success (and on-success (re-utils/event->fn on-success)) on-failure (and on-failure (re-utils/event->fn on-failure))] (fn [err] (cond (nil? err) (when on-success (on-success)) on-failure (on-failure err) :else ((core/default-error-handler) err)))))
true
;;; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ;;; Copyright (c) 2017, PI:NAME:<NAME>END_PI (ns localist.re-frame-firebase.helpers (:require [clojure.spec.alpha :as s] [iron.re-utils :as re-utils] [iron.utils :as utils] [localist.re-frame-firebase.core :as core])) ;;; Helper functions that straddle the line between this library and Iron ;;; utils. These may move, change, or be abandoned, as I get more comfortable ;;; with them. (defn js->clj-tree [x] (-> (.val x) js->clj clojure.walk/keywordize-keys)) (defn promise-wrapper [promise on-success on-failure] {:pre [(utils/validate (s/nilable :re-frame/vec-or-fn) on-success) (utils/validate (s/nilable :re-frame/vec-or-fn) on-failure)]} (when on-success (.then promise (re-utils/event->fn on-success))) (if on-failure (.catch promise (re-utils/event->fn on-failure)) (.catch promise (core/default-error-handler)))) (defn success-failure-wrapper [on-success on-failure] {:pre [(utils/validate (s/nilable :re-frame/vec-or-fn) on-success) (utils/validate (s/nilable :re-frame/vec-or-fn) on-failure)] :post (fn? %)} (let [on-success (and on-success (re-utils/event->fn on-success)) on-failure (and on-failure (re-utils/event->fn on-failure))] (fn [err] (cond (nil? err) (when on-success (on-success)) on-failure (on-failure err) :else ((core/default-error-handler) err)))))
[ { "context": " :user user\n :password password}))\n\n(defn create-user [user]\n (sql/insert! db :u", "end": 381, "score": 0.9990202784538269, "start": 373, "tag": "PASSWORD", "value": "password" } ]
src/blog/models/db.clj
VitaliyHnatyk/web-app
0
(ns blog.models.db (:require [clojure.java.jdbc :as sql])) (defn db-url [host port database] (str "//" host ":" port "/" database)) (let [host "localhost" port 3306 database "blog" user "root" password ""] (def db {:subprotocol "mysql" :subname (db-url host port database) :user user :password password})) (defn create-user [user] (sql/insert! db :users user)) (defn create-comment [comment] (sql/insert! db :comments comment)) (defn get-all-users [] (sql/query db ["select * from users"])) (defn get-user-count [] (sql/query db ["select count(id) as count from users"])) (defn get-active-user [id] (sql/query db ["select * from users where id=? and active=1" id])) (defn get-user [id] (sql/query db ["select * from users where id=?" id])) (defn get-latest-entries [max] (sql/query db ["select entries.*, count(comments.entry) as comments from entries left join comments on (entries.id = comments.entry) group by entries.id order by entries.publishedDate desc limit ?" max])) (defn get-entry [id] (sql/query db ["select * from entries where id=?" id])) (defn get-comments [id] (sql/query db ["select * from comments where entry=?" id])) (defn create-entry [entry] (sql/insert! db :entries entry)) (defn update-entry [id entry] (sql/update! db :entries ["id=?" id] entry)) (defn delete-entry [id] (sql/delete! db :entries ["id=?" id])) (defn delete-user [id] (sql/delete! db :users ["id=?" id])) (defn update-user [user] (sql/update! db :users ["id=?" (:id user)] user))
22278
(ns blog.models.db (:require [clojure.java.jdbc :as sql])) (defn db-url [host port database] (str "//" host ":" port "/" database)) (let [host "localhost" port 3306 database "blog" user "root" password ""] (def db {:subprotocol "mysql" :subname (db-url host port database) :user user :password <PASSWORD>})) (defn create-user [user] (sql/insert! db :users user)) (defn create-comment [comment] (sql/insert! db :comments comment)) (defn get-all-users [] (sql/query db ["select * from users"])) (defn get-user-count [] (sql/query db ["select count(id) as count from users"])) (defn get-active-user [id] (sql/query db ["select * from users where id=? and active=1" id])) (defn get-user [id] (sql/query db ["select * from users where id=?" id])) (defn get-latest-entries [max] (sql/query db ["select entries.*, count(comments.entry) as comments from entries left join comments on (entries.id = comments.entry) group by entries.id order by entries.publishedDate desc limit ?" max])) (defn get-entry [id] (sql/query db ["select * from entries where id=?" id])) (defn get-comments [id] (sql/query db ["select * from comments where entry=?" id])) (defn create-entry [entry] (sql/insert! db :entries entry)) (defn update-entry [id entry] (sql/update! db :entries ["id=?" id] entry)) (defn delete-entry [id] (sql/delete! db :entries ["id=?" id])) (defn delete-user [id] (sql/delete! db :users ["id=?" id])) (defn update-user [user] (sql/update! db :users ["id=?" (:id user)] user))
true
(ns blog.models.db (:require [clojure.java.jdbc :as sql])) (defn db-url [host port database] (str "//" host ":" port "/" database)) (let [host "localhost" port 3306 database "blog" user "root" password ""] (def db {:subprotocol "mysql" :subname (db-url host port database) :user user :password PI:PASSWORD:<PASSWORD>END_PI})) (defn create-user [user] (sql/insert! db :users user)) (defn create-comment [comment] (sql/insert! db :comments comment)) (defn get-all-users [] (sql/query db ["select * from users"])) (defn get-user-count [] (sql/query db ["select count(id) as count from users"])) (defn get-active-user [id] (sql/query db ["select * from users where id=? and active=1" id])) (defn get-user [id] (sql/query db ["select * from users where id=?" id])) (defn get-latest-entries [max] (sql/query db ["select entries.*, count(comments.entry) as comments from entries left join comments on (entries.id = comments.entry) group by entries.id order by entries.publishedDate desc limit ?" max])) (defn get-entry [id] (sql/query db ["select * from entries where id=?" id])) (defn get-comments [id] (sql/query db ["select * from comments where entry=?" id])) (defn create-entry [entry] (sql/insert! db :entries entry)) (defn update-entry [id entry] (sql/update! db :entries ["id=?" id] entry)) (defn delete-entry [id] (sql/delete! db :entries ["id=?" id])) (defn delete-user [id] (sql/delete! db :users ["id=?" id])) (defn update-user [user] (sql/update! db :users ["id=?" (:id user)] user))
[ { "context": "app-state\n (reagent/atom [{:id 1 :first-name \"Jason\" :last-name \"Yates\" :age \"34\"}\n ", "end": 164, "score": 0.9997221231460571, "start": 159, "tag": "NAME", "value": "Jason" }, { "context": "gent/atom [{:id 1 :first-name \"Jason\" :last-name \"Yates\" :age \"34\"}\n {:id 2 :first-nam", "end": 183, "score": 0.999697208404541, "start": 178, "tag": "NAME", "value": "Yates" }, { "context": "age \"34\"}\n {:id 2 :first-name \"Chris\" :last-name \"Wilson\" :age \"33\"}\n ", "end": 241, "score": 0.9997208118438721, "start": 236, "tag": "NAME", "value": "Chris" }, { "context": " {:id 2 :first-name \"Chris\" :last-name \"Wilson\" :age \"33\"}\n {:id 3 :first-nam", "end": 261, "score": 0.9996697902679443, "start": 255, "tag": "NAME", "value": "Wilson" }, { "context": "age \"33\"}\n {:id 3 :first-name \"John\" :last-name \"Lawrence\" :age \"32\"}\n ", "end": 318, "score": 0.999828040599823, "start": 314, "tag": "NAME", "value": "John" }, { "context": " {:id 3 :first-name \"John\" :last-name \"Lawrence\" :age \"32\"}\n {:id 4 :first-nam", "end": 340, "score": 0.9996848106384277, "start": 332, "tag": "NAME", "value": "Lawrence" }, { "context": "age \"32\"}\n {:id 4 :first-name \"Albert\" :last-name \"Voxel\" :age \"67\"}\n ", "end": 399, "score": 0.9997881650924683, "start": 393, "tag": "NAME", "value": "Albert" }, { "context": " {:id 4 :first-name \"Albert\" :last-name \"Voxel\" :age \"67\"}\n {:id 5 :first-nam", "end": 418, "score": 0.9592848420143127, "start": 413, "tag": "NAME", "value": "Voxel" }, { "context": "age \"67\"}\n {:id 5 :first-name \"Zemby\" :last-name \"Alcoe\" :age \"495\"}]))\n\n(defn filter-", "end": 476, "score": 0.9997650980949402, "start": 471, "tag": "NAME", "value": "Zemby" }, { "context": " {:id 5 :first-name \"Zemby\" :last-name \"Alcoe\" :age \"495\"}]))\n\n(defn filter-content\n [filterst", "end": 495, "score": 0.9997107982635498, "start": 490, "tag": "NAME", "value": "Alcoe" } ]
recipes/filter-table/src/cljs/filter_table/core.cljs
yatesj9/reagent-cookbook
1
(ns filter-table.core (:require [reagent.core :as reagent] [clojure.string :as string])) (def app-state (reagent/atom [{:id 1 :first-name "Jason" :last-name "Yates" :age "34"} {:id 2 :first-name "Chris" :last-name "Wilson" :age "33"} {:id 3 :first-name "John" :last-name "Lawrence" :age "32"} {:id 4 :first-name "Albert" :last-name "Voxel" :age "67"} {:id 5 :first-name "Zemby" :last-name "Alcoe" :age "495"}])) (defn filter-content [filterstring] (filter #(re-find (->> (str filterstring) (string/upper-case) (re-pattern)) (string/upper-case (:first-name %))) @app-state)) (defn table [myfilter] [:table {:class "table table-condensed"} [:thead [:tr [:th "First Name"] [:th "Last Name"] [:th "Age"]]] [:tbody (for [{:keys [id first-name last-name age]} (filter-content myfilter)] ^{:key id} [:tr [:td first-name] [:td last-name] [:td age]])]]) (defn search-table [] (let [filter-value (reagent/atom nil)] (fn [] [:div [:input {:type "text" :value @filter-value :on-change #(reset! filter-value (-> % .-target .-value))}] [table @filter-value]]))) (defn home [] [:div.container [search-table]]) (defn ^:export main [] (reagent/render [home] (.getElementById js/document "app")))
52141
(ns filter-table.core (:require [reagent.core :as reagent] [clojure.string :as string])) (def app-state (reagent/atom [{:id 1 :first-name "<NAME>" :last-name "<NAME>" :age "34"} {:id 2 :first-name "<NAME>" :last-name "<NAME>" :age "33"} {:id 3 :first-name "<NAME>" :last-name "<NAME>" :age "32"} {:id 4 :first-name "<NAME>" :last-name "<NAME>" :age "67"} {:id 5 :first-name "<NAME>" :last-name "<NAME>" :age "495"}])) (defn filter-content [filterstring] (filter #(re-find (->> (str filterstring) (string/upper-case) (re-pattern)) (string/upper-case (:first-name %))) @app-state)) (defn table [myfilter] [:table {:class "table table-condensed"} [:thead [:tr [:th "First Name"] [:th "Last Name"] [:th "Age"]]] [:tbody (for [{:keys [id first-name last-name age]} (filter-content myfilter)] ^{:key id} [:tr [:td first-name] [:td last-name] [:td age]])]]) (defn search-table [] (let [filter-value (reagent/atom nil)] (fn [] [:div [:input {:type "text" :value @filter-value :on-change #(reset! filter-value (-> % .-target .-value))}] [table @filter-value]]))) (defn home [] [:div.container [search-table]]) (defn ^:export main [] (reagent/render [home] (.getElementById js/document "app")))
true
(ns filter-table.core (:require [reagent.core :as reagent] [clojure.string :as string])) (def app-state (reagent/atom [{:id 1 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age "34"} {:id 2 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age "33"} {:id 3 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age "32"} {:id 4 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age "67"} {:id 5 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age "495"}])) (defn filter-content [filterstring] (filter #(re-find (->> (str filterstring) (string/upper-case) (re-pattern)) (string/upper-case (:first-name %))) @app-state)) (defn table [myfilter] [:table {:class "table table-condensed"} [:thead [:tr [:th "First Name"] [:th "Last Name"] [:th "Age"]]] [:tbody (for [{:keys [id first-name last-name age]} (filter-content myfilter)] ^{:key id} [:tr [:td first-name] [:td last-name] [:td age]])]]) (defn search-table [] (let [filter-value (reagent/atom nil)] (fn [] [:div [:input {:type "text" :value @filter-value :on-change #(reset! filter-value (-> % .-target .-value))}] [table @filter-value]]))) (defn home [] [:div.container [search-table]]) (defn ^:export main [] (reagent/render [home] (.getElementById js/document "app")))
[ { "context": "_CLIENT_ID\"\n :client-secret \"MyMITREidClientSecret\"\n :authorize-url \"https://au", "end": 1061, "score": 0.9797096252441406, "start": 1040, "tag": "KEY", "value": "MyMITREidClientSecret" } ]
code/test/sixsq/nuvla/server/resources/spec/configuration_template_session_mitreid_test.cljc
nuvla/server
6
(ns sixsq.nuvla.server.resources.spec.configuration-template-session-mitreid-test (:require [clojure.test :refer [deftest]] [sixsq.nuvla.server.resources.configuration-template :as ct] [sixsq.nuvla.server.resources.spec.configuration-template-session-mitreid :as cts-mitreid] [sixsq.nuvla.server.resources.spec.spec-test-utils :as stu])) (def valid-acl {:owners ["group/nuvla-admin"] :view-data ["group/nuvla-anon"]}) (deftest test-configuration-template-schema-check (let [timestamp "1964-08-25T10:00:00Z" root {:id (str ct/resource-type "/session-mitreid-test-instance") :resource-type ct/resource-type :created timestamp :updated timestamp :acl valid-acl :service "session-mitreid" :instance "test-instance" :client-id "FAKE_CLIENT_ID" :client-secret "MyMITREidClientSecret" :authorize-url "https://authorize.mitreid.com/authorize" :token-url "https://token.mitreid.com/token" :user-profile-url "https://userinfo.mitreid.com/api/user/me" :public-key "fake-public-key-value"}] (stu/is-valid ::cts-mitreid/schema root) (stu/is-invalid ::cts-mitreid/schema (assoc root :bad "BAD")) (doseq [k #{:id :resource-type :created :updated :acl :service :instance :client-id :client-secret :authorize-url :token-url :user-profile-url :public-key}] (stu/is-invalid ::cts-mitreid/schema (dissoc root k)))))
26247
(ns sixsq.nuvla.server.resources.spec.configuration-template-session-mitreid-test (:require [clojure.test :refer [deftest]] [sixsq.nuvla.server.resources.configuration-template :as ct] [sixsq.nuvla.server.resources.spec.configuration-template-session-mitreid :as cts-mitreid] [sixsq.nuvla.server.resources.spec.spec-test-utils :as stu])) (def valid-acl {:owners ["group/nuvla-admin"] :view-data ["group/nuvla-anon"]}) (deftest test-configuration-template-schema-check (let [timestamp "1964-08-25T10:00:00Z" root {:id (str ct/resource-type "/session-mitreid-test-instance") :resource-type ct/resource-type :created timestamp :updated timestamp :acl valid-acl :service "session-mitreid" :instance "test-instance" :client-id "FAKE_CLIENT_ID" :client-secret "<KEY>" :authorize-url "https://authorize.mitreid.com/authorize" :token-url "https://token.mitreid.com/token" :user-profile-url "https://userinfo.mitreid.com/api/user/me" :public-key "fake-public-key-value"}] (stu/is-valid ::cts-mitreid/schema root) (stu/is-invalid ::cts-mitreid/schema (assoc root :bad "BAD")) (doseq [k #{:id :resource-type :created :updated :acl :service :instance :client-id :client-secret :authorize-url :token-url :user-profile-url :public-key}] (stu/is-invalid ::cts-mitreid/schema (dissoc root k)))))
true
(ns sixsq.nuvla.server.resources.spec.configuration-template-session-mitreid-test (:require [clojure.test :refer [deftest]] [sixsq.nuvla.server.resources.configuration-template :as ct] [sixsq.nuvla.server.resources.spec.configuration-template-session-mitreid :as cts-mitreid] [sixsq.nuvla.server.resources.spec.spec-test-utils :as stu])) (def valid-acl {:owners ["group/nuvla-admin"] :view-data ["group/nuvla-anon"]}) (deftest test-configuration-template-schema-check (let [timestamp "1964-08-25T10:00:00Z" root {:id (str ct/resource-type "/session-mitreid-test-instance") :resource-type ct/resource-type :created timestamp :updated timestamp :acl valid-acl :service "session-mitreid" :instance "test-instance" :client-id "FAKE_CLIENT_ID" :client-secret "PI:KEY:<KEY>END_PI" :authorize-url "https://authorize.mitreid.com/authorize" :token-url "https://token.mitreid.com/token" :user-profile-url "https://userinfo.mitreid.com/api/user/me" :public-key "fake-public-key-value"}] (stu/is-valid ::cts-mitreid/schema root) (stu/is-invalid ::cts-mitreid/schema (assoc root :bad "BAD")) (doseq [k #{:id :resource-type :created :updated :acl :service :instance :client-id :client-secret :authorize-url :token-url :user-profile-url :public-key}] (stu/is-invalid ::cts-mitreid/schema (dissoc root k)))))
[ { "context": "ef samples (h/gen-samples num-samples))\n\n(def p1 \"Doe John Male Green 1/1/1995\")\n(def p2 \"Doe Jane Female Blue", "end": 481, "score": 0.977908194065094, "start": 471, "tag": "NAME", "value": "Doe John M" }, { "context": "\n(def p1 \"Doe John Male Green 1/1/1995\")\n(def p2 \"Doe Jane Female Blue 2/9/1993\")\n(def p3 \"Brin Frin Female ", "end": 519, "score": 0.9995496273040771, "start": 511, "tag": "NAME", "value": "Doe Jane" }, { "context": "(def p2 \"Doe Jane Female Blue 2/9/1993\")\n(def p3 \"Brin Frin Female Orange 2/9/1993\")\n(def by-dob (join \\newli", "end": 561, "score": 0.9997641444206238, "start": 552, "tag": "NAME", "value": "Brin Frin" } ]
test/sorted/core_test.clj
gekkoe/sorted
0
(ns sorted.core-test (:require [clojure.spec.alpha :as s] [clojure.string :refer [join]] [clojure.test :refer :all] [sorted.core :as c] [sorted.helpers :as h] [sorted.people :as ppl] [sorted.person :as p])) (def num-tests 1000) ; Increase this to run slower but more exhaustive tests. (def checks? (h/checks? num-tests)) (def num-samples 1000) (def samples (h/gen-samples num-samples)) (def p1 "Doe John Male Green 1/1/1995") (def p2 "Doe Jane Female Blue 2/9/1993") (def p3 "Brin Frin Female Orange 2/9/1993") (def by-dob (join \newline [p3 p2 p1])) (def unsorted-strs (join \newline [p1 p2 p3])) (def person1 (p/str->person p1)) (def person2 (p/str->person p2)) (def person3 (p/str->person p3)) (def unsorted-ps [person1 person2 person3]) (def usage-summary (str "sorted - A simple program for sorting people.\n\nUsage: sorted " "[options] file1 file2 file3 ...\n\nOptions:\n -d, --dob " " Sort output by date of birth, ascending.\n -g, --gender " "Sort by gender, female first, then by last name ascending.\n " "-h, --help Prints this help text...\n -l, --last " "Sort output by last name, descending.\n -p, --port PORT Port number. " "If not specified, doesn't start server.\n\nThis program can support " "more than 3 files if desired, but at least one must be provided.\n")) (defn usage? [r] (= usage-summary (::c/exit-msg r))) (defn exit-inst? [r] (s/valid? ::c/exit-instructions r)) (defn actions? [r] (s/valid? ::c/actions r)) (s/def ::non-option (s/and string? #(not (.contains ^String % "-")))) (s/def ::args (s/* string?)) (defn help-args "Generate arg collection containing at least one -h flag." [] (map shuffle (map #(conj % "-h") (samples ::args)))) (deftest usage-test (testing "Conforms to spec." (is (checks? 'sorted.core/usage)))) (deftest error-msg-test (testing "Conforms to spec." (is (checks? 'sorted.core/error-msg)))) (deftest validate-args-test (testing "Conforms to spec." (is (checks? 'sorted.core/validate-args))) (testing (str "When help flag passed, returns exit instructions " "regardless of other args") (is (every? true? (map exit-inst? (map c/validate-args (help-args))))) (let [result (c/validate-args ["--help"])] (testing "which contains the expected message" (is (usage? result))) (testing "which contains a :sorted.core/ok? key with the value true" (is (= true (::c/ok? result)))))) (testing (str "When no help flag is passed but passed bad args, returns" "exit instructions") (let [result (c/validate-args ["-NotGood"])] (is (exit-inst? result)) (testing "which contains the expected message" (is (= (str "The following errors occurred while parsing your " "command:\n\nUnknown option: \"-N\"\nUnknown option: " "\"-o\"\nUnknown option: \"-t\"\nUnknown option: " "\"-G\"\nUnknown option: \"-o\"\nUnknown option: " "\"-o\"\n\n" usage-summary) (::c/exit-msg result)))))) (testing "When given too many sort options, returns exit instructions" (let [result (c/validate-args ["-d" "--last" "somefile" "anotherfile"])] (is (exit-inst? result)) (testing "containing the expected message" (is (= "Please select no more than one sort option." (::c/exit-msg result)))))) (testing "When no options or files are passed, returns an exit message" (let [result (c/validate-args [])] (is (s/valid? ::c/exit-instructions result)) (testing "which contains the expected message" (is (usage? result))))) (testing "When passed non-help options but no files, returns an exit message" (let [result (c/validate-args ["-d" "-p2000"])] (is (exit-inst? result)) (testing "containing the expected message" (is (= "Please provide at least one file with person records in it." (::c/exit-msg result)))))) (testing (str "When passed a port, file(s), no errors, and no other options " "returns :sorted.core/actions") (let [result (c/validate-args ["-p2000" "somefile" "anotherfile"])] (is (actions? result)) (testing "containing the expected :sorted.core/port" (is (= 2000 (::c/port result)))) (testing "containing the expected file(s)" (is (= ["somefile" "anotherfile"] (::c/files result)))))) (testing (str "When passed zero or more valid options, one or more file(s), " "no errors, no help flag, and no port, returns a" ":sorted.core/actions") (let [result (c/validate-args ["--gender" "somefile"])] (is (actions? result)) (testing "containing the expected file(s)" (is (= ["somefile"] (::c/files result)))) (testing "containing the expected sort-kw" (is (= ::p/gender (::c/sort-kw result))))))) (deftest sorted-people-str-test (testing "Conforms to spec" (checks? 'sorted.core/sorted-people-str)) (with-redefs [ppl/people (atom unsorted-ps)] (testing "Returns the expected string when passed a valid sort-kw" (is (= by-dob (c/sorted-people-str ::p/dob)))) (testing "Returns unsorted list when passed invalid sort-kw" (is (= unsorted-strs (c/sorted-people-str ::made-up-kw))))))
110893
(ns sorted.core-test (:require [clojure.spec.alpha :as s] [clojure.string :refer [join]] [clojure.test :refer :all] [sorted.core :as c] [sorted.helpers :as h] [sorted.people :as ppl] [sorted.person :as p])) (def num-tests 1000) ; Increase this to run slower but more exhaustive tests. (def checks? (h/checks? num-tests)) (def num-samples 1000) (def samples (h/gen-samples num-samples)) (def p1 "<NAME>ale Green 1/1/1995") (def p2 "<NAME> Female Blue 2/9/1993") (def p3 "<NAME> Female Orange 2/9/1993") (def by-dob (join \newline [p3 p2 p1])) (def unsorted-strs (join \newline [p1 p2 p3])) (def person1 (p/str->person p1)) (def person2 (p/str->person p2)) (def person3 (p/str->person p3)) (def unsorted-ps [person1 person2 person3]) (def usage-summary (str "sorted - A simple program for sorting people.\n\nUsage: sorted " "[options] file1 file2 file3 ...\n\nOptions:\n -d, --dob " " Sort output by date of birth, ascending.\n -g, --gender " "Sort by gender, female first, then by last name ascending.\n " "-h, --help Prints this help text...\n -l, --last " "Sort output by last name, descending.\n -p, --port PORT Port number. " "If not specified, doesn't start server.\n\nThis program can support " "more than 3 files if desired, but at least one must be provided.\n")) (defn usage? [r] (= usage-summary (::c/exit-msg r))) (defn exit-inst? [r] (s/valid? ::c/exit-instructions r)) (defn actions? [r] (s/valid? ::c/actions r)) (s/def ::non-option (s/and string? #(not (.contains ^String % "-")))) (s/def ::args (s/* string?)) (defn help-args "Generate arg collection containing at least one -h flag." [] (map shuffle (map #(conj % "-h") (samples ::args)))) (deftest usage-test (testing "Conforms to spec." (is (checks? 'sorted.core/usage)))) (deftest error-msg-test (testing "Conforms to spec." (is (checks? 'sorted.core/error-msg)))) (deftest validate-args-test (testing "Conforms to spec." (is (checks? 'sorted.core/validate-args))) (testing (str "When help flag passed, returns exit instructions " "regardless of other args") (is (every? true? (map exit-inst? (map c/validate-args (help-args))))) (let [result (c/validate-args ["--help"])] (testing "which contains the expected message" (is (usage? result))) (testing "which contains a :sorted.core/ok? key with the value true" (is (= true (::c/ok? result)))))) (testing (str "When no help flag is passed but passed bad args, returns" "exit instructions") (let [result (c/validate-args ["-NotGood"])] (is (exit-inst? result)) (testing "which contains the expected message" (is (= (str "The following errors occurred while parsing your " "command:\n\nUnknown option: \"-N\"\nUnknown option: " "\"-o\"\nUnknown option: \"-t\"\nUnknown option: " "\"-G\"\nUnknown option: \"-o\"\nUnknown option: " "\"-o\"\n\n" usage-summary) (::c/exit-msg result)))))) (testing "When given too many sort options, returns exit instructions" (let [result (c/validate-args ["-d" "--last" "somefile" "anotherfile"])] (is (exit-inst? result)) (testing "containing the expected message" (is (= "Please select no more than one sort option." (::c/exit-msg result)))))) (testing "When no options or files are passed, returns an exit message" (let [result (c/validate-args [])] (is (s/valid? ::c/exit-instructions result)) (testing "which contains the expected message" (is (usage? result))))) (testing "When passed non-help options but no files, returns an exit message" (let [result (c/validate-args ["-d" "-p2000"])] (is (exit-inst? result)) (testing "containing the expected message" (is (= "Please provide at least one file with person records in it." (::c/exit-msg result)))))) (testing (str "When passed a port, file(s), no errors, and no other options " "returns :sorted.core/actions") (let [result (c/validate-args ["-p2000" "somefile" "anotherfile"])] (is (actions? result)) (testing "containing the expected :sorted.core/port" (is (= 2000 (::c/port result)))) (testing "containing the expected file(s)" (is (= ["somefile" "anotherfile"] (::c/files result)))))) (testing (str "When passed zero or more valid options, one or more file(s), " "no errors, no help flag, and no port, returns a" ":sorted.core/actions") (let [result (c/validate-args ["--gender" "somefile"])] (is (actions? result)) (testing "containing the expected file(s)" (is (= ["somefile"] (::c/files result)))) (testing "containing the expected sort-kw" (is (= ::p/gender (::c/sort-kw result))))))) (deftest sorted-people-str-test (testing "Conforms to spec" (checks? 'sorted.core/sorted-people-str)) (with-redefs [ppl/people (atom unsorted-ps)] (testing "Returns the expected string when passed a valid sort-kw" (is (= by-dob (c/sorted-people-str ::p/dob)))) (testing "Returns unsorted list when passed invalid sort-kw" (is (= unsorted-strs (c/sorted-people-str ::made-up-kw))))))
true
(ns sorted.core-test (:require [clojure.spec.alpha :as s] [clojure.string :refer [join]] [clojure.test :refer :all] [sorted.core :as c] [sorted.helpers :as h] [sorted.people :as ppl] [sorted.person :as p])) (def num-tests 1000) ; Increase this to run slower but more exhaustive tests. (def checks? (h/checks? num-tests)) (def num-samples 1000) (def samples (h/gen-samples num-samples)) (def p1 "PI:NAME:<NAME>END_PIale Green 1/1/1995") (def p2 "PI:NAME:<NAME>END_PI Female Blue 2/9/1993") (def p3 "PI:NAME:<NAME>END_PI Female Orange 2/9/1993") (def by-dob (join \newline [p3 p2 p1])) (def unsorted-strs (join \newline [p1 p2 p3])) (def person1 (p/str->person p1)) (def person2 (p/str->person p2)) (def person3 (p/str->person p3)) (def unsorted-ps [person1 person2 person3]) (def usage-summary (str "sorted - A simple program for sorting people.\n\nUsage: sorted " "[options] file1 file2 file3 ...\n\nOptions:\n -d, --dob " " Sort output by date of birth, ascending.\n -g, --gender " "Sort by gender, female first, then by last name ascending.\n " "-h, --help Prints this help text...\n -l, --last " "Sort output by last name, descending.\n -p, --port PORT Port number. " "If not specified, doesn't start server.\n\nThis program can support " "more than 3 files if desired, but at least one must be provided.\n")) (defn usage? [r] (= usage-summary (::c/exit-msg r))) (defn exit-inst? [r] (s/valid? ::c/exit-instructions r)) (defn actions? [r] (s/valid? ::c/actions r)) (s/def ::non-option (s/and string? #(not (.contains ^String % "-")))) (s/def ::args (s/* string?)) (defn help-args "Generate arg collection containing at least one -h flag." [] (map shuffle (map #(conj % "-h") (samples ::args)))) (deftest usage-test (testing "Conforms to spec." (is (checks? 'sorted.core/usage)))) (deftest error-msg-test (testing "Conforms to spec." (is (checks? 'sorted.core/error-msg)))) (deftest validate-args-test (testing "Conforms to spec." (is (checks? 'sorted.core/validate-args))) (testing (str "When help flag passed, returns exit instructions " "regardless of other args") (is (every? true? (map exit-inst? (map c/validate-args (help-args))))) (let [result (c/validate-args ["--help"])] (testing "which contains the expected message" (is (usage? result))) (testing "which contains a :sorted.core/ok? key with the value true" (is (= true (::c/ok? result)))))) (testing (str "When no help flag is passed but passed bad args, returns" "exit instructions") (let [result (c/validate-args ["-NotGood"])] (is (exit-inst? result)) (testing "which contains the expected message" (is (= (str "The following errors occurred while parsing your " "command:\n\nUnknown option: \"-N\"\nUnknown option: " "\"-o\"\nUnknown option: \"-t\"\nUnknown option: " "\"-G\"\nUnknown option: \"-o\"\nUnknown option: " "\"-o\"\n\n" usage-summary) (::c/exit-msg result)))))) (testing "When given too many sort options, returns exit instructions" (let [result (c/validate-args ["-d" "--last" "somefile" "anotherfile"])] (is (exit-inst? result)) (testing "containing the expected message" (is (= "Please select no more than one sort option." (::c/exit-msg result)))))) (testing "When no options or files are passed, returns an exit message" (let [result (c/validate-args [])] (is (s/valid? ::c/exit-instructions result)) (testing "which contains the expected message" (is (usage? result))))) (testing "When passed non-help options but no files, returns an exit message" (let [result (c/validate-args ["-d" "-p2000"])] (is (exit-inst? result)) (testing "containing the expected message" (is (= "Please provide at least one file with person records in it." (::c/exit-msg result)))))) (testing (str "When passed a port, file(s), no errors, and no other options " "returns :sorted.core/actions") (let [result (c/validate-args ["-p2000" "somefile" "anotherfile"])] (is (actions? result)) (testing "containing the expected :sorted.core/port" (is (= 2000 (::c/port result)))) (testing "containing the expected file(s)" (is (= ["somefile" "anotherfile"] (::c/files result)))))) (testing (str "When passed zero or more valid options, one or more file(s), " "no errors, no help flag, and no port, returns a" ":sorted.core/actions") (let [result (c/validate-args ["--gender" "somefile"])] (is (actions? result)) (testing "containing the expected file(s)" (is (= ["somefile"] (::c/files result)))) (testing "containing the expected sort-kw" (is (= ::p/gender (::c/sort-kw result))))))) (deftest sorted-people-str-test (testing "Conforms to spec" (checks? 'sorted.core/sorted-people-str)) (with-redefs [ppl/people (atom unsorted-ps)] (testing "Returns the expected string when passed a valid sort-kw" (is (= by-dob (c/sorted-people-str ::p/dob)))) (testing "Returns unsorted list when passed invalid sort-kw" (is (= unsorted-strs (c/sorted-people-str ::made-up-kw))))))
[ { "context": "herer-id 123456,\n :rarity \"Common\",\n :artist \"Stabby Stanley\",\n :name \"Uslar\",\n :typelist \"Creature — Bear", "end": 7973, "score": 0.9998337030410767, "start": 7959, "tag": "NAME", "value": "Stabby Stanley" }, { "context": " \"Common\",\n :artist \"Stabby Stanley\",\n :name \"Uslar\",\n :typelist \"Creature — Bear Knight\",\n :expa", "end": 7991, "score": 0.998857319355011, "start": 7986, "tag": "NAME", "value": "Uslar" } ]
src/loa/gatherer/card_details.clj
karmag/loa
4
(ns loa.gatherer.card-details (:require (loa.gatherer (common :as common-)) (loa.util (xml :as xml-)))) (declare translate-image-string) ;;-------------------------------------------------- ;; helpers (defn- get-text [xml] (-> (xml-/xml-> (xml-/from-xml xml) xml-/text) first .trim)) (def ^:private alt->letter {"Tap" "T" "Untap" "Q" "White" "W" "Black" "B" "Blue" "U" "Green" "G" "Red" "R" "Snow" "S" "[chaos]" "C" "Variable Colorless" "X" "Black or Green" "B/G" "Black or Red" "B/R" "Blue or Red" "U/R" "Green or Blue" "G/U" "Green or White" "G/W" "Red or White" "R/W" "White or Black" "W/B" "Red or Green" "R/G" "Blue or Black" "U/B" "White or Blue" "W/U" "Two or Black" "2/B" "Two or Blue" "2/U" "Two or Green" "2/G" "Two or Red" "2/R" "Two or White" "2/W" "Phyrexian" "P" "Phyrexian Black" "P/B" "Phyrexian Blue" "P/U" "Phyrexian Green" "P/G" "Phyrexian Red" "P/R" "Phyrexian White" "P/W"}) (defn- translate-image "Converts an image tag into its corresponding text equivalent." [xml] (let [alt (-> xml :attrs :alt) int? (try (Integer/parseInt alt) true (catch NumberFormatException e)) value (if int? alt (alt->letter alt))] (if value (format "{%s}" value) (throw (Exception. (format "Unknown image alt value: '%s'" (str alt))))))) (defn- translate-tag [xml] (case (:tag xml) :img (translate-image xml) :i (translate-image-string xml))) (defn- cleanup-spaces "When translating images to text it's not quite possible to know within that limited context if there should be surronding whitespace or not. This method should be applied after such transformation has taken place." [text] (-> text (.replaceAll "} ([:,.{])" "}$1") (.replaceAll "([\"(]) \\{" "$1{") (.replaceAll " ' " " '") (.replaceAll " ‘ " " ‘"))) (defn- translate-image-string [xml] (->> (:content xml) (map #(if (string? %) % (translate-tag %))) (map (memfn trim)) (interpose " ") (apply str) cleanup-spaces)) (defn- cleanup-rulelist [xml] (let [rules-xml (xml-/transform xml (xml-/search (xml-/attr= :class "cardtextbox")))] (doall (->> rules-xml (map translate-image-string) (remove empty?))))) (defn- cleanup-all-sets [xml] (let [sets (xml-/transform xml (xml-/search :a)) href [:attrs :href] name [:content 0 :attrs :alt]] (reduce #(assoc %1 (common-/href->gatherer-id (get-in %2 href)) (get-in %2 name)) nil sets))) ;;-------------------------------------------------- ;; data cleanup (defmulti cleanup-value (fn [key value] key)) (defmethod cleanup-value "Community Rating:" [name value]) (defmethod cleanup-value "Converted Mana Cost:" [name value]) (defmethod cleanup-value "Watermark:" [name value]) (defmethod cleanup-value "Card Name:" [name value] [:name (get-text value)]) (defmethod cleanup-value "Types:" [name value] [:typelist (get-text value)]) (defmethod cleanup-value "Mana Cost:" [name value] [:cost (translate-image-string value)]) (defmethod cleanup-value "Card Text:" [name value] [:rulelist (cleanup-rulelist value)]) (defmethod cleanup-value "Flavor Text:" [name value] [:flavor (first (xml-/transform value (xml-/search :i) xml-/text))]) (defmethod cleanup-value "P/T:" [name value] [:pt (get-text value)]) (defmethod cleanup-value "Expansion:" [name value] [:expansion (get-text value)]) (defmethod cleanup-value "Rarity:" [name value] [:rarity (get-text value)]) (defmethod cleanup-value "Color Indicator:" [name value] [:color-indicator (get-text value)]) (defmethod cleanup-value "All Sets:" [name value] [:sets (cleanup-all-sets value)]) (defmethod cleanup-value "Other Sets:" [name value] (cleanup-value "All Sets:" value)) (defmethod cleanup-value "Card Number:" [name value] [:number (get-text value)]) (defmethod cleanup-value "Artist:" [name value] [:artist (get-text value)]) (defmethod cleanup-value "Hand/Life:" [name value] [:hand-life (get-text value)]) (defmethod cleanup-value "Loyalty:" [name value] [:loyalty (get-text value)]) (defn- cleanup-row [[key value]] (let [key (-> key xml-/from-xml xml-/text .trim)] (cleanup-value key value))) ;;-------------------------------------------------- ;; data extraction (defn- get-grids [page] (let [grids (xml-/xml-> (xml-/from-html page) (xml-/search (xml-/attr= :class "rightCol")) xml-/node) [_ fst-name snd-name] (re-find #"SubContentHeader_subtitleDisplay\"[^>]*>([^/]*)//([^<]*)<" page) actual-fst-name (when fst-name (first (xml-/transform (first grids) (xml-/search (xml-/re-attr= :id #".*SubContent_.*nameRow")) (xml-/search (xml-/re-attr= :class #"value")) xml-/text)))] (if (not= (.trim (or fst-name "")) (.trim (or actual-fst-name ""))) (reverse grids) grids))) (defn- get-rows [card-grid] (let [items (xml-/transform card-grid (xml-/search (xml-/re-attr= :id #".*SubContent_.*Row")) (xml-/search (xml-/re-attr= :class #"label|value")))] (partition 2 items))) (defn- combine-grids [grids] (case (count grids) 1 (first grids) 2 (assoc (first grids) :multi (second grids)))) (defn- get-gatherer-id [page] (-> (xml-/xml1-> (xml-/from-html page) (xml-/search (xml-/attr= :id "cardTextSwitchLink1")) xml-/node) :attrs :href common-/href->gatherer-id)) ;;-------------------------------------------------- ;; interface (defn find-details [page] (let [details (->> (get-grids page) (map get-rows) (map (partial map cleanup-row)) (map #(reduce (fn [m [k v]] (if k (assoc m k v) m)) nil %)) combine-grids)] (assoc details :gatherer-id (get-gatherer-id page)))) (defn find-print-details [page] (let [base (select-keys (find-details page) [:name :typelist :rulelist :flavor :multi])] (if (:multi base) (update-in base [:multi] select-keys [:name :typelist :rulelist :flavor]) base))) (defn find-set-codes [page] (->> (re-seq #"Image.ashx?[^>]*set=(\w+)[^>]*alt=\"([^\"]+) \([^)\"]*\)" page) (map (fn [[_ code name]] [(-> (.trim name) (.replaceAll "&quot;" "\"") (.replaceAll "&apos;" "'")) code])) (reduce (fn [m [name code]] (assoc m name code)) nil))) (defn find-double-card-information "Returns information about the other parts of the card if any." [name page] ;; TODO not needed anymore? #_(when-let [[_ fst snd] (re-find #"SubContentHeader_subtitleDisplay\"[^>]*>([^/]*)//([^<]*)<" page)] (let [fst (.trim fst) snd (.trim snd) re (re-pattern (format "part=([A-Za-z]+)[^>]+multiverseid=(\\d+)[^<]*%s // %s" fst snd)) [_ part gatherer-id] (re-find re page) gatherer-id (when gatherer-id (Integer/parseInt gatherer-id))] {:fst fst :snd snd :link {:part part :gatherer-id gatherer-id}}))) (comment {:gatherer-id 123456, :rarity "Common", :artist "Stabby Stanley", :name "Uslar", :typelist "Creature — Bear Knight", :expansion "Magic 2050", :sets {123 "Portal (Common)", 456 "Magic 2050 (Common)", 789 "Duel Decks: Bears vs. Fungus (Common)"}, :pt "2 / 2", :flavor "He ate the world, his paws, his pals. But mostly he just ate.", :cost "{G}", :number "235", :rulelist ("Haste","{T}: Uslar deals 10 damage to everything.")} ;; Additional data {:loyalty "5", :hand-life "(Hand Modifier: +3 , Life Modifier: -4)" :multi <card> ;; :multi-type :transform :color-indicator "Green"})
102598
(ns loa.gatherer.card-details (:require (loa.gatherer (common :as common-)) (loa.util (xml :as xml-)))) (declare translate-image-string) ;;-------------------------------------------------- ;; helpers (defn- get-text [xml] (-> (xml-/xml-> (xml-/from-xml xml) xml-/text) first .trim)) (def ^:private alt->letter {"Tap" "T" "Untap" "Q" "White" "W" "Black" "B" "Blue" "U" "Green" "G" "Red" "R" "Snow" "S" "[chaos]" "C" "Variable Colorless" "X" "Black or Green" "B/G" "Black or Red" "B/R" "Blue or Red" "U/R" "Green or Blue" "G/U" "Green or White" "G/W" "Red or White" "R/W" "White or Black" "W/B" "Red or Green" "R/G" "Blue or Black" "U/B" "White or Blue" "W/U" "Two or Black" "2/B" "Two or Blue" "2/U" "Two or Green" "2/G" "Two or Red" "2/R" "Two or White" "2/W" "Phyrexian" "P" "Phyrexian Black" "P/B" "Phyrexian Blue" "P/U" "Phyrexian Green" "P/G" "Phyrexian Red" "P/R" "Phyrexian White" "P/W"}) (defn- translate-image "Converts an image tag into its corresponding text equivalent." [xml] (let [alt (-> xml :attrs :alt) int? (try (Integer/parseInt alt) true (catch NumberFormatException e)) value (if int? alt (alt->letter alt))] (if value (format "{%s}" value) (throw (Exception. (format "Unknown image alt value: '%s'" (str alt))))))) (defn- translate-tag [xml] (case (:tag xml) :img (translate-image xml) :i (translate-image-string xml))) (defn- cleanup-spaces "When translating images to text it's not quite possible to know within that limited context if there should be surronding whitespace or not. This method should be applied after such transformation has taken place." [text] (-> text (.replaceAll "} ([:,.{])" "}$1") (.replaceAll "([\"(]) \\{" "$1{") (.replaceAll " ' " " '") (.replaceAll " ‘ " " ‘"))) (defn- translate-image-string [xml] (->> (:content xml) (map #(if (string? %) % (translate-tag %))) (map (memfn trim)) (interpose " ") (apply str) cleanup-spaces)) (defn- cleanup-rulelist [xml] (let [rules-xml (xml-/transform xml (xml-/search (xml-/attr= :class "cardtextbox")))] (doall (->> rules-xml (map translate-image-string) (remove empty?))))) (defn- cleanup-all-sets [xml] (let [sets (xml-/transform xml (xml-/search :a)) href [:attrs :href] name [:content 0 :attrs :alt]] (reduce #(assoc %1 (common-/href->gatherer-id (get-in %2 href)) (get-in %2 name)) nil sets))) ;;-------------------------------------------------- ;; data cleanup (defmulti cleanup-value (fn [key value] key)) (defmethod cleanup-value "Community Rating:" [name value]) (defmethod cleanup-value "Converted Mana Cost:" [name value]) (defmethod cleanup-value "Watermark:" [name value]) (defmethod cleanup-value "Card Name:" [name value] [:name (get-text value)]) (defmethod cleanup-value "Types:" [name value] [:typelist (get-text value)]) (defmethod cleanup-value "Mana Cost:" [name value] [:cost (translate-image-string value)]) (defmethod cleanup-value "Card Text:" [name value] [:rulelist (cleanup-rulelist value)]) (defmethod cleanup-value "Flavor Text:" [name value] [:flavor (first (xml-/transform value (xml-/search :i) xml-/text))]) (defmethod cleanup-value "P/T:" [name value] [:pt (get-text value)]) (defmethod cleanup-value "Expansion:" [name value] [:expansion (get-text value)]) (defmethod cleanup-value "Rarity:" [name value] [:rarity (get-text value)]) (defmethod cleanup-value "Color Indicator:" [name value] [:color-indicator (get-text value)]) (defmethod cleanup-value "All Sets:" [name value] [:sets (cleanup-all-sets value)]) (defmethod cleanup-value "Other Sets:" [name value] (cleanup-value "All Sets:" value)) (defmethod cleanup-value "Card Number:" [name value] [:number (get-text value)]) (defmethod cleanup-value "Artist:" [name value] [:artist (get-text value)]) (defmethod cleanup-value "Hand/Life:" [name value] [:hand-life (get-text value)]) (defmethod cleanup-value "Loyalty:" [name value] [:loyalty (get-text value)]) (defn- cleanup-row [[key value]] (let [key (-> key xml-/from-xml xml-/text .trim)] (cleanup-value key value))) ;;-------------------------------------------------- ;; data extraction (defn- get-grids [page] (let [grids (xml-/xml-> (xml-/from-html page) (xml-/search (xml-/attr= :class "rightCol")) xml-/node) [_ fst-name snd-name] (re-find #"SubContentHeader_subtitleDisplay\"[^>]*>([^/]*)//([^<]*)<" page) actual-fst-name (when fst-name (first (xml-/transform (first grids) (xml-/search (xml-/re-attr= :id #".*SubContent_.*nameRow")) (xml-/search (xml-/re-attr= :class #"value")) xml-/text)))] (if (not= (.trim (or fst-name "")) (.trim (or actual-fst-name ""))) (reverse grids) grids))) (defn- get-rows [card-grid] (let [items (xml-/transform card-grid (xml-/search (xml-/re-attr= :id #".*SubContent_.*Row")) (xml-/search (xml-/re-attr= :class #"label|value")))] (partition 2 items))) (defn- combine-grids [grids] (case (count grids) 1 (first grids) 2 (assoc (first grids) :multi (second grids)))) (defn- get-gatherer-id [page] (-> (xml-/xml1-> (xml-/from-html page) (xml-/search (xml-/attr= :id "cardTextSwitchLink1")) xml-/node) :attrs :href common-/href->gatherer-id)) ;;-------------------------------------------------- ;; interface (defn find-details [page] (let [details (->> (get-grids page) (map get-rows) (map (partial map cleanup-row)) (map #(reduce (fn [m [k v]] (if k (assoc m k v) m)) nil %)) combine-grids)] (assoc details :gatherer-id (get-gatherer-id page)))) (defn find-print-details [page] (let [base (select-keys (find-details page) [:name :typelist :rulelist :flavor :multi])] (if (:multi base) (update-in base [:multi] select-keys [:name :typelist :rulelist :flavor]) base))) (defn find-set-codes [page] (->> (re-seq #"Image.ashx?[^>]*set=(\w+)[^>]*alt=\"([^\"]+) \([^)\"]*\)" page) (map (fn [[_ code name]] [(-> (.trim name) (.replaceAll "&quot;" "\"") (.replaceAll "&apos;" "'")) code])) (reduce (fn [m [name code]] (assoc m name code)) nil))) (defn find-double-card-information "Returns information about the other parts of the card if any." [name page] ;; TODO not needed anymore? #_(when-let [[_ fst snd] (re-find #"SubContentHeader_subtitleDisplay\"[^>]*>([^/]*)//([^<]*)<" page)] (let [fst (.trim fst) snd (.trim snd) re (re-pattern (format "part=([A-Za-z]+)[^>]+multiverseid=(\\d+)[^<]*%s // %s" fst snd)) [_ part gatherer-id] (re-find re page) gatherer-id (when gatherer-id (Integer/parseInt gatherer-id))] {:fst fst :snd snd :link {:part part :gatherer-id gatherer-id}}))) (comment {:gatherer-id 123456, :rarity "Common", :artist "<NAME>", :name "<NAME>", :typelist "Creature — Bear Knight", :expansion "Magic 2050", :sets {123 "Portal (Common)", 456 "Magic 2050 (Common)", 789 "Duel Decks: Bears vs. Fungus (Common)"}, :pt "2 / 2", :flavor "He ate the world, his paws, his pals. But mostly he just ate.", :cost "{G}", :number "235", :rulelist ("Haste","{T}: Uslar deals 10 damage to everything.")} ;; Additional data {:loyalty "5", :hand-life "(Hand Modifier: +3 , Life Modifier: -4)" :multi <card> ;; :multi-type :transform :color-indicator "Green"})
true
(ns loa.gatherer.card-details (:require (loa.gatherer (common :as common-)) (loa.util (xml :as xml-)))) (declare translate-image-string) ;;-------------------------------------------------- ;; helpers (defn- get-text [xml] (-> (xml-/xml-> (xml-/from-xml xml) xml-/text) first .trim)) (def ^:private alt->letter {"Tap" "T" "Untap" "Q" "White" "W" "Black" "B" "Blue" "U" "Green" "G" "Red" "R" "Snow" "S" "[chaos]" "C" "Variable Colorless" "X" "Black or Green" "B/G" "Black or Red" "B/R" "Blue or Red" "U/R" "Green or Blue" "G/U" "Green or White" "G/W" "Red or White" "R/W" "White or Black" "W/B" "Red or Green" "R/G" "Blue or Black" "U/B" "White or Blue" "W/U" "Two or Black" "2/B" "Two or Blue" "2/U" "Two or Green" "2/G" "Two or Red" "2/R" "Two or White" "2/W" "Phyrexian" "P" "Phyrexian Black" "P/B" "Phyrexian Blue" "P/U" "Phyrexian Green" "P/G" "Phyrexian Red" "P/R" "Phyrexian White" "P/W"}) (defn- translate-image "Converts an image tag into its corresponding text equivalent." [xml] (let [alt (-> xml :attrs :alt) int? (try (Integer/parseInt alt) true (catch NumberFormatException e)) value (if int? alt (alt->letter alt))] (if value (format "{%s}" value) (throw (Exception. (format "Unknown image alt value: '%s'" (str alt))))))) (defn- translate-tag [xml] (case (:tag xml) :img (translate-image xml) :i (translate-image-string xml))) (defn- cleanup-spaces "When translating images to text it's not quite possible to know within that limited context if there should be surronding whitespace or not. This method should be applied after such transformation has taken place." [text] (-> text (.replaceAll "} ([:,.{])" "}$1") (.replaceAll "([\"(]) \\{" "$1{") (.replaceAll " ' " " '") (.replaceAll " ‘ " " ‘"))) (defn- translate-image-string [xml] (->> (:content xml) (map #(if (string? %) % (translate-tag %))) (map (memfn trim)) (interpose " ") (apply str) cleanup-spaces)) (defn- cleanup-rulelist [xml] (let [rules-xml (xml-/transform xml (xml-/search (xml-/attr= :class "cardtextbox")))] (doall (->> rules-xml (map translate-image-string) (remove empty?))))) (defn- cleanup-all-sets [xml] (let [sets (xml-/transform xml (xml-/search :a)) href [:attrs :href] name [:content 0 :attrs :alt]] (reduce #(assoc %1 (common-/href->gatherer-id (get-in %2 href)) (get-in %2 name)) nil sets))) ;;-------------------------------------------------- ;; data cleanup (defmulti cleanup-value (fn [key value] key)) (defmethod cleanup-value "Community Rating:" [name value]) (defmethod cleanup-value "Converted Mana Cost:" [name value]) (defmethod cleanup-value "Watermark:" [name value]) (defmethod cleanup-value "Card Name:" [name value] [:name (get-text value)]) (defmethod cleanup-value "Types:" [name value] [:typelist (get-text value)]) (defmethod cleanup-value "Mana Cost:" [name value] [:cost (translate-image-string value)]) (defmethod cleanup-value "Card Text:" [name value] [:rulelist (cleanup-rulelist value)]) (defmethod cleanup-value "Flavor Text:" [name value] [:flavor (first (xml-/transform value (xml-/search :i) xml-/text))]) (defmethod cleanup-value "P/T:" [name value] [:pt (get-text value)]) (defmethod cleanup-value "Expansion:" [name value] [:expansion (get-text value)]) (defmethod cleanup-value "Rarity:" [name value] [:rarity (get-text value)]) (defmethod cleanup-value "Color Indicator:" [name value] [:color-indicator (get-text value)]) (defmethod cleanup-value "All Sets:" [name value] [:sets (cleanup-all-sets value)]) (defmethod cleanup-value "Other Sets:" [name value] (cleanup-value "All Sets:" value)) (defmethod cleanup-value "Card Number:" [name value] [:number (get-text value)]) (defmethod cleanup-value "Artist:" [name value] [:artist (get-text value)]) (defmethod cleanup-value "Hand/Life:" [name value] [:hand-life (get-text value)]) (defmethod cleanup-value "Loyalty:" [name value] [:loyalty (get-text value)]) (defn- cleanup-row [[key value]] (let [key (-> key xml-/from-xml xml-/text .trim)] (cleanup-value key value))) ;;-------------------------------------------------- ;; data extraction (defn- get-grids [page] (let [grids (xml-/xml-> (xml-/from-html page) (xml-/search (xml-/attr= :class "rightCol")) xml-/node) [_ fst-name snd-name] (re-find #"SubContentHeader_subtitleDisplay\"[^>]*>([^/]*)//([^<]*)<" page) actual-fst-name (when fst-name (first (xml-/transform (first grids) (xml-/search (xml-/re-attr= :id #".*SubContent_.*nameRow")) (xml-/search (xml-/re-attr= :class #"value")) xml-/text)))] (if (not= (.trim (or fst-name "")) (.trim (or actual-fst-name ""))) (reverse grids) grids))) (defn- get-rows [card-grid] (let [items (xml-/transform card-grid (xml-/search (xml-/re-attr= :id #".*SubContent_.*Row")) (xml-/search (xml-/re-attr= :class #"label|value")))] (partition 2 items))) (defn- combine-grids [grids] (case (count grids) 1 (first grids) 2 (assoc (first grids) :multi (second grids)))) (defn- get-gatherer-id [page] (-> (xml-/xml1-> (xml-/from-html page) (xml-/search (xml-/attr= :id "cardTextSwitchLink1")) xml-/node) :attrs :href common-/href->gatherer-id)) ;;-------------------------------------------------- ;; interface (defn find-details [page] (let [details (->> (get-grids page) (map get-rows) (map (partial map cleanup-row)) (map #(reduce (fn [m [k v]] (if k (assoc m k v) m)) nil %)) combine-grids)] (assoc details :gatherer-id (get-gatherer-id page)))) (defn find-print-details [page] (let [base (select-keys (find-details page) [:name :typelist :rulelist :flavor :multi])] (if (:multi base) (update-in base [:multi] select-keys [:name :typelist :rulelist :flavor]) base))) (defn find-set-codes [page] (->> (re-seq #"Image.ashx?[^>]*set=(\w+)[^>]*alt=\"([^\"]+) \([^)\"]*\)" page) (map (fn [[_ code name]] [(-> (.trim name) (.replaceAll "&quot;" "\"") (.replaceAll "&apos;" "'")) code])) (reduce (fn [m [name code]] (assoc m name code)) nil))) (defn find-double-card-information "Returns information about the other parts of the card if any." [name page] ;; TODO not needed anymore? #_(when-let [[_ fst snd] (re-find #"SubContentHeader_subtitleDisplay\"[^>]*>([^/]*)//([^<]*)<" page)] (let [fst (.trim fst) snd (.trim snd) re (re-pattern (format "part=([A-Za-z]+)[^>]+multiverseid=(\\d+)[^<]*%s // %s" fst snd)) [_ part gatherer-id] (re-find re page) gatherer-id (when gatherer-id (Integer/parseInt gatherer-id))] {:fst fst :snd snd :link {:part part :gatherer-id gatherer-id}}))) (comment {:gatherer-id 123456, :rarity "Common", :artist "PI:NAME:<NAME>END_PI", :name "PI:NAME:<NAME>END_PI", :typelist "Creature — Bear Knight", :expansion "Magic 2050", :sets {123 "Portal (Common)", 456 "Magic 2050 (Common)", 789 "Duel Decks: Bears vs. Fungus (Common)"}, :pt "2 / 2", :flavor "He ate the world, his paws, his pals. But mostly he just ate.", :cost "{G}", :number "235", :rulelist ("Haste","{T}: Uslar deals 10 damage to everything.")} ;; Additional data {:loyalty "5", :hand-life "(Hand Modifier: +3 , Life Modifier: -4)" :multi <card> ;; :multi-type :transform :color-indicator "Green"})
[ { "context": " uri,\n :user user,\n :password password,\n :db db\n :destroy-fn #(.close ", "end": 1344, "score": 0.9992249011993408, "start": 1336, "tag": "PASSWORD", "value": "password" } ]
src/neo4j_clj/core.clj
cloojure/neo4j-clj
85
(ns neo4j-clj.core "This namespace contains the logic to connect to Neo4j instances, create and run queries as well as creating an in-memory database for testing." (:require [neo4j-clj.compatibility :refer [neo4j->clj clj->neo4j]]) (:import (org.neo4j.driver GraphDatabase AuthTokens Config AuthToken Driver Session) (org.neo4j.driver.exceptions TransientException) (java.net URI) (org.neo4j.driver.internal.logging ConsoleLogging) (java.util.logging Level))) ;; Connecting to dbs (defn config [options] (let [logging (:logging options (ConsoleLogging. Level/CONFIG))] (-> (Config/builder) (.withLogging logging) (.build)))) (defn connect "Returns a connection map from an url. Uses BOLT as the only communication protocol. You can connect using a url or a url, user, password combination. Either way, you can optioninally pass a map of options: `:logging` - a Neo4j logging configuration, e.g. (ConsoleLogging. Level/FINEST)" ([^URI uri user password] (connect uri user password nil)) ([^URI uri user password options] (let [^AuthToken auth (AuthTokens/basic user password) ^Config config (config options) db (GraphDatabase/driver uri auth config)] {:url uri, :user user, :password password, :db db :destroy-fn #(.close db)})) ([^URI uri] (connect uri nil)) ([^URI uri options] (let [^Config config (config options) db (GraphDatabase/driver uri, config)] {:url uri, :db db, :destroy-fn #(.close db)}))) (defn disconnect [db] "Disconnect a connection" ((:destroy-fn db))) (defn ^{:deprecated "4.0.2"} create-in-memory-connection "To make the local db visible under the same interface/map as remote databases, we connect to the local url. To be able to shutdown the local db, we merge a destroy function into the map that can be called after testing. _All_ data will be wiped after shutting down the db! Deprecated: Please use `neo4j-clj.in-memory/create-in-memory-connection` directly." [] (try (require 'neo4j-clj.in-memory) (when-let [in-mem (find-ns 'neo4j-clj.in-memory)] ((ns-resolve in-mem 'create-in-memory-connection))) (catch Throwable t (throw (ex-info "Sorry, unable to create an in-memory Neo4j instance. Did you include neo4j-harness to your classpath, e.g. as a test dependency to your project?" {} t))))) ;; Sessions and transactions (defn get-session [^Driver connection] (.session (:db connection))) (defn- make-success-transaction [tx] (proxy [org.neo4j.driver.Transaction] [] (run ([q] (.run tx q)) ([q p] (.run tx q p))) (commit [] (.commit tx)) (rollback [] (.rollback tx)) ;; We only want to auto-success to ensure persistence (close [] (.commit tx) (.close tx)))) (defn get-transaction [^Session session] (make-success-transaction (.beginTransaction session))) ;; Executing cypher queries (defn execute ([sess query params] (neo4j->clj (.run sess query (clj->neo4j params)))) ([sess query] (neo4j->clj (.run sess query)))) (defn create-query "Convenience function. Takes a cypher query as input, returns a function that takes a session (and parameter as a map, optionally) and return the query result as a map." [cypher] (fn ([sess] (execute sess cypher)) ([sess params] (execute sess cypher params)))) (defmacro defquery "Shortcut macro to define a named query." [name ^String query] `(def ~name (create-query ~query))) (defn retry-times [times body] (let [res (try {:result (body)} (catch TransientException e# (if (zero? times) (throw e#) {:exception e#})))] (if (:exception res) (recur (dec times) body) (:result res)))) (defmacro with-transaction [connection tx & body] `(with-open [~tx (get-transaction (get-session ~connection))] ~@body)) (defmacro with-retry [[connection tx & {:keys [max-times] :or {max-times 1000}}] & body] `(retry-times ~max-times (fn [] (with-transaction ~connection ~tx ~@body))))
49797
(ns neo4j-clj.core "This namespace contains the logic to connect to Neo4j instances, create and run queries as well as creating an in-memory database for testing." (:require [neo4j-clj.compatibility :refer [neo4j->clj clj->neo4j]]) (:import (org.neo4j.driver GraphDatabase AuthTokens Config AuthToken Driver Session) (org.neo4j.driver.exceptions TransientException) (java.net URI) (org.neo4j.driver.internal.logging ConsoleLogging) (java.util.logging Level))) ;; Connecting to dbs (defn config [options] (let [logging (:logging options (ConsoleLogging. Level/CONFIG))] (-> (Config/builder) (.withLogging logging) (.build)))) (defn connect "Returns a connection map from an url. Uses BOLT as the only communication protocol. You can connect using a url or a url, user, password combination. Either way, you can optioninally pass a map of options: `:logging` - a Neo4j logging configuration, e.g. (ConsoleLogging. Level/FINEST)" ([^URI uri user password] (connect uri user password nil)) ([^URI uri user password options] (let [^AuthToken auth (AuthTokens/basic user password) ^Config config (config options) db (GraphDatabase/driver uri auth config)] {:url uri, :user user, :password <PASSWORD>, :db db :destroy-fn #(.close db)})) ([^URI uri] (connect uri nil)) ([^URI uri options] (let [^Config config (config options) db (GraphDatabase/driver uri, config)] {:url uri, :db db, :destroy-fn #(.close db)}))) (defn disconnect [db] "Disconnect a connection" ((:destroy-fn db))) (defn ^{:deprecated "4.0.2"} create-in-memory-connection "To make the local db visible under the same interface/map as remote databases, we connect to the local url. To be able to shutdown the local db, we merge a destroy function into the map that can be called after testing. _All_ data will be wiped after shutting down the db! Deprecated: Please use `neo4j-clj.in-memory/create-in-memory-connection` directly." [] (try (require 'neo4j-clj.in-memory) (when-let [in-mem (find-ns 'neo4j-clj.in-memory)] ((ns-resolve in-mem 'create-in-memory-connection))) (catch Throwable t (throw (ex-info "Sorry, unable to create an in-memory Neo4j instance. Did you include neo4j-harness to your classpath, e.g. as a test dependency to your project?" {} t))))) ;; Sessions and transactions (defn get-session [^Driver connection] (.session (:db connection))) (defn- make-success-transaction [tx] (proxy [org.neo4j.driver.Transaction] [] (run ([q] (.run tx q)) ([q p] (.run tx q p))) (commit [] (.commit tx)) (rollback [] (.rollback tx)) ;; We only want to auto-success to ensure persistence (close [] (.commit tx) (.close tx)))) (defn get-transaction [^Session session] (make-success-transaction (.beginTransaction session))) ;; Executing cypher queries (defn execute ([sess query params] (neo4j->clj (.run sess query (clj->neo4j params)))) ([sess query] (neo4j->clj (.run sess query)))) (defn create-query "Convenience function. Takes a cypher query as input, returns a function that takes a session (and parameter as a map, optionally) and return the query result as a map." [cypher] (fn ([sess] (execute sess cypher)) ([sess params] (execute sess cypher params)))) (defmacro defquery "Shortcut macro to define a named query." [name ^String query] `(def ~name (create-query ~query))) (defn retry-times [times body] (let [res (try {:result (body)} (catch TransientException e# (if (zero? times) (throw e#) {:exception e#})))] (if (:exception res) (recur (dec times) body) (:result res)))) (defmacro with-transaction [connection tx & body] `(with-open [~tx (get-transaction (get-session ~connection))] ~@body)) (defmacro with-retry [[connection tx & {:keys [max-times] :or {max-times 1000}}] & body] `(retry-times ~max-times (fn [] (with-transaction ~connection ~tx ~@body))))
true
(ns neo4j-clj.core "This namespace contains the logic to connect to Neo4j instances, create and run queries as well as creating an in-memory database for testing." (:require [neo4j-clj.compatibility :refer [neo4j->clj clj->neo4j]]) (:import (org.neo4j.driver GraphDatabase AuthTokens Config AuthToken Driver Session) (org.neo4j.driver.exceptions TransientException) (java.net URI) (org.neo4j.driver.internal.logging ConsoleLogging) (java.util.logging Level))) ;; Connecting to dbs (defn config [options] (let [logging (:logging options (ConsoleLogging. Level/CONFIG))] (-> (Config/builder) (.withLogging logging) (.build)))) (defn connect "Returns a connection map from an url. Uses BOLT as the only communication protocol. You can connect using a url or a url, user, password combination. Either way, you can optioninally pass a map of options: `:logging` - a Neo4j logging configuration, e.g. (ConsoleLogging. Level/FINEST)" ([^URI uri user password] (connect uri user password nil)) ([^URI uri user password options] (let [^AuthToken auth (AuthTokens/basic user password) ^Config config (config options) db (GraphDatabase/driver uri auth config)] {:url uri, :user user, :password PI:PASSWORD:<PASSWORD>END_PI, :db db :destroy-fn #(.close db)})) ([^URI uri] (connect uri nil)) ([^URI uri options] (let [^Config config (config options) db (GraphDatabase/driver uri, config)] {:url uri, :db db, :destroy-fn #(.close db)}))) (defn disconnect [db] "Disconnect a connection" ((:destroy-fn db))) (defn ^{:deprecated "4.0.2"} create-in-memory-connection "To make the local db visible under the same interface/map as remote databases, we connect to the local url. To be able to shutdown the local db, we merge a destroy function into the map that can be called after testing. _All_ data will be wiped after shutting down the db! Deprecated: Please use `neo4j-clj.in-memory/create-in-memory-connection` directly." [] (try (require 'neo4j-clj.in-memory) (when-let [in-mem (find-ns 'neo4j-clj.in-memory)] ((ns-resolve in-mem 'create-in-memory-connection))) (catch Throwable t (throw (ex-info "Sorry, unable to create an in-memory Neo4j instance. Did you include neo4j-harness to your classpath, e.g. as a test dependency to your project?" {} t))))) ;; Sessions and transactions (defn get-session [^Driver connection] (.session (:db connection))) (defn- make-success-transaction [tx] (proxy [org.neo4j.driver.Transaction] [] (run ([q] (.run tx q)) ([q p] (.run tx q p))) (commit [] (.commit tx)) (rollback [] (.rollback tx)) ;; We only want to auto-success to ensure persistence (close [] (.commit tx) (.close tx)))) (defn get-transaction [^Session session] (make-success-transaction (.beginTransaction session))) ;; Executing cypher queries (defn execute ([sess query params] (neo4j->clj (.run sess query (clj->neo4j params)))) ([sess query] (neo4j->clj (.run sess query)))) (defn create-query "Convenience function. Takes a cypher query as input, returns a function that takes a session (and parameter as a map, optionally) and return the query result as a map." [cypher] (fn ([sess] (execute sess cypher)) ([sess params] (execute sess cypher params)))) (defmacro defquery "Shortcut macro to define a named query." [name ^String query] `(def ~name (create-query ~query))) (defn retry-times [times body] (let [res (try {:result (body)} (catch TransientException e# (if (zero? times) (throw e#) {:exception e#})))] (if (:exception res) (recur (dec times) body) (:result res)))) (defmacro with-transaction [connection tx & body] `(with-open [~tx (get-transaction (get-session ~connection))] ~@body)) (defmacro with-retry [[connection tx & {:keys [max-times] :or {max-times 1000}}] & body] `(retry-times ~max-times (fn [] (with-transaction ~connection ~tx ~@body))))
[ { "context": "run --rm --name crux-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -p 3306:3306 -d mysql:8.0.21\n ;; mariadb -h ", "end": 2038, "score": 0.9991905093193054, "start": 2026, "tag": "PASSWORD", "value": "my-secret-pw" }, { "context": " -p 3306:3306 -d mysql:8.0.21\n ;; mariadb -h 127.0.0.1 -u root -p\n ;; CREATE DATABASE cruxtest;\n ", "end": 2097, "score": 0.9997336864471436, "start": 2088, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "pts {:dbname \"cruxtest\", :user \"root\", :password \"my-secret-pw\"} f))\n\n #_(when (.exists (clojure.java.io/file \"", "end": 2225, "score": 0.9994739294052124, "start": 2213, "tag": "PASSWORD", "value": "my-secret-pw" }, { "context": "ame crux-mssql -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=yourStrong(!)Password' -e 'MSSQL_PID=Express' -p 1433:1433 -", "end": 2546, "score": 0.9969062805175781, "start": 2536, "tag": "PASSWORD", "value": "yourStrong" }, { "context": "ql -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=yourStrong(!)Password' -e 'MSSQL_PID=Express' -p 1433:1433 -d mcr.micro", "end": 2557, "score": 0.990973711013794, "start": 2549, "tag": "PASSWORD", "value": "Password" }, { "context": "a\"\n :password \"yourStrong(!)Password\"}}\n f)))\n", "end": 2875, "score": 0.9990049600601196, "start": 2854, "tag": "PASSWORD", "value": "yourStrong(!)Password" } ]
crux-test/src/crux/fixtures/jdbc.clj
coyotesqrl/crux
0
(ns crux.fixtures.jdbc (:require [clojure.java.io :as io] [crux.fixtures :as fix] [crux.jdbc :as j] [clojure.test :as t]) (:import com.opentable.db.postgres.embedded.EmbeddedPostgres)) (defn- with-jdbc-opts [{:keys [pool-opts dialect db-spec]} f] (fix/with-opts {::j/connection-pool {:pool-opts pool-opts, :dialect dialect, :db-spec db-spec} :crux/tx-log {:crux/module `j/->tx-log :connection-pool ::j/connection-pool} :crux/document-store {:crux/module `j/->document-store, :connection-pool ::j/connection-pool}} f)) (defn with-h2-opts [f] (fix/with-tmp-dirs #{db-dir} (with-jdbc-opts {:dialect 'crux.jdbc.h2/->dialect :db-spec {:dbname (str (io/file db-dir "cruxtest"))}} f))) (defn with-sqlite-opts [f] (fix/with-tmp-dirs #{db-dir} (with-jdbc-opts {:dialect 'crux.jdbc.sqlite/->dialect :db-spec {:dbname (str (io/file db-dir "cruxtest"))}} f))) (defn with-mssql-opts [{:keys [db-spec pool-opts]} f] (with-jdbc-opts {:dialect 'crux.jdbc.mssql/->dialect :pool-opts pool-opts :db-spec db-spec} f)) (defn with-mysql-opts [db-spec f] (with-jdbc-opts {:dialect 'crux.jdbc.mysql/->dialect :db-spec db-spec} f)) (defn with-embedded-postgres [f] (with-open [pg (.start (EmbeddedPostgres/builder))] (with-jdbc-opts {:dialect 'crux.jdbc.psql/->dialect :db-spec {:port (.getPort pg) :dbname "postgres" :user "postgres"}} f))) (defn with-each-jdbc-node [f] (t/testing "H2 Database" (with-h2-opts f)) (t/testing "SQLite Database" (with-sqlite-opts f)) (t/testing "Postgresql Database" (with-embedded-postgres f)) ;; Optional: #_(t/testing "MySQL Database" ;; docker run --rm --name crux-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -p 3306:3306 -d mysql:8.0.21 ;; mariadb -h 127.0.0.1 -u root -p ;; CREATE DATABASE cruxtest; (with-mysql-opts {:dbname "cruxtest", :user "root", :password "my-secret-pw"} f)) #_(when (.exists (clojure.java.io/file ".testing-oracle.edn")) (t/testing "Oracle Database" (with-jdbc-node "oracle" f (read-string (slurp ".testing-oracle.edn"))))) #_(t/testing "MSSQL Database" ;; docker run --rm --name crux-mssql -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=yourStrong(!)Password' -e 'MSSQL_PID=Express' -p 1433:1433 -d mcr.microsoft.com/mssql/server:2017-latest-ubuntu ;; mssql-cli ;; CREATE DATABASE cruxtest; (with-mssql-opts {:db-spec {:dbname "cruxtest"} :pool-opts {:username "sa" :password "yourStrong(!)Password"}} f)))
112555
(ns crux.fixtures.jdbc (:require [clojure.java.io :as io] [crux.fixtures :as fix] [crux.jdbc :as j] [clojure.test :as t]) (:import com.opentable.db.postgres.embedded.EmbeddedPostgres)) (defn- with-jdbc-opts [{:keys [pool-opts dialect db-spec]} f] (fix/with-opts {::j/connection-pool {:pool-opts pool-opts, :dialect dialect, :db-spec db-spec} :crux/tx-log {:crux/module `j/->tx-log :connection-pool ::j/connection-pool} :crux/document-store {:crux/module `j/->document-store, :connection-pool ::j/connection-pool}} f)) (defn with-h2-opts [f] (fix/with-tmp-dirs #{db-dir} (with-jdbc-opts {:dialect 'crux.jdbc.h2/->dialect :db-spec {:dbname (str (io/file db-dir "cruxtest"))}} f))) (defn with-sqlite-opts [f] (fix/with-tmp-dirs #{db-dir} (with-jdbc-opts {:dialect 'crux.jdbc.sqlite/->dialect :db-spec {:dbname (str (io/file db-dir "cruxtest"))}} f))) (defn with-mssql-opts [{:keys [db-spec pool-opts]} f] (with-jdbc-opts {:dialect 'crux.jdbc.mssql/->dialect :pool-opts pool-opts :db-spec db-spec} f)) (defn with-mysql-opts [db-spec f] (with-jdbc-opts {:dialect 'crux.jdbc.mysql/->dialect :db-spec db-spec} f)) (defn with-embedded-postgres [f] (with-open [pg (.start (EmbeddedPostgres/builder))] (with-jdbc-opts {:dialect 'crux.jdbc.psql/->dialect :db-spec {:port (.getPort pg) :dbname "postgres" :user "postgres"}} f))) (defn with-each-jdbc-node [f] (t/testing "H2 Database" (with-h2-opts f)) (t/testing "SQLite Database" (with-sqlite-opts f)) (t/testing "Postgresql Database" (with-embedded-postgres f)) ;; Optional: #_(t/testing "MySQL Database" ;; docker run --rm --name crux-mysql -e MYSQL_ROOT_PASSWORD=<PASSWORD> -p 3306:3306 -d mysql:8.0.21 ;; mariadb -h 127.0.0.1 -u root -p ;; CREATE DATABASE cruxtest; (with-mysql-opts {:dbname "cruxtest", :user "root", :password "<PASSWORD>"} f)) #_(when (.exists (clojure.java.io/file ".testing-oracle.edn")) (t/testing "Oracle Database" (with-jdbc-node "oracle" f (read-string (slurp ".testing-oracle.edn"))))) #_(t/testing "MSSQL Database" ;; docker run --rm --name crux-mssql -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=<PASSWORD>(!)<PASSWORD>' -e 'MSSQL_PID=Express' -p 1433:1433 -d mcr.microsoft.com/mssql/server:2017-latest-ubuntu ;; mssql-cli ;; CREATE DATABASE cruxtest; (with-mssql-opts {:db-spec {:dbname "cruxtest"} :pool-opts {:username "sa" :password "<PASSWORD>"}} f)))
true
(ns crux.fixtures.jdbc (:require [clojure.java.io :as io] [crux.fixtures :as fix] [crux.jdbc :as j] [clojure.test :as t]) (:import com.opentable.db.postgres.embedded.EmbeddedPostgres)) (defn- with-jdbc-opts [{:keys [pool-opts dialect db-spec]} f] (fix/with-opts {::j/connection-pool {:pool-opts pool-opts, :dialect dialect, :db-spec db-spec} :crux/tx-log {:crux/module `j/->tx-log :connection-pool ::j/connection-pool} :crux/document-store {:crux/module `j/->document-store, :connection-pool ::j/connection-pool}} f)) (defn with-h2-opts [f] (fix/with-tmp-dirs #{db-dir} (with-jdbc-opts {:dialect 'crux.jdbc.h2/->dialect :db-spec {:dbname (str (io/file db-dir "cruxtest"))}} f))) (defn with-sqlite-opts [f] (fix/with-tmp-dirs #{db-dir} (with-jdbc-opts {:dialect 'crux.jdbc.sqlite/->dialect :db-spec {:dbname (str (io/file db-dir "cruxtest"))}} f))) (defn with-mssql-opts [{:keys [db-spec pool-opts]} f] (with-jdbc-opts {:dialect 'crux.jdbc.mssql/->dialect :pool-opts pool-opts :db-spec db-spec} f)) (defn with-mysql-opts [db-spec f] (with-jdbc-opts {:dialect 'crux.jdbc.mysql/->dialect :db-spec db-spec} f)) (defn with-embedded-postgres [f] (with-open [pg (.start (EmbeddedPostgres/builder))] (with-jdbc-opts {:dialect 'crux.jdbc.psql/->dialect :db-spec {:port (.getPort pg) :dbname "postgres" :user "postgres"}} f))) (defn with-each-jdbc-node [f] (t/testing "H2 Database" (with-h2-opts f)) (t/testing "SQLite Database" (with-sqlite-opts f)) (t/testing "Postgresql Database" (with-embedded-postgres f)) ;; Optional: #_(t/testing "MySQL Database" ;; docker run --rm --name crux-mysql -e MYSQL_ROOT_PASSWORD=PI:PASSWORD:<PASSWORD>END_PI -p 3306:3306 -d mysql:8.0.21 ;; mariadb -h 127.0.0.1 -u root -p ;; CREATE DATABASE cruxtest; (with-mysql-opts {:dbname "cruxtest", :user "root", :password "PI:PASSWORD:<PASSWORD>END_PI"} f)) #_(when (.exists (clojure.java.io/file ".testing-oracle.edn")) (t/testing "Oracle Database" (with-jdbc-node "oracle" f (read-string (slurp ".testing-oracle.edn"))))) #_(t/testing "MSSQL Database" ;; docker run --rm --name crux-mssql -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=PI:PASSWORD:<PASSWORD>END_PI(!)PI:PASSWORD:<PASSWORD>END_PI' -e 'MSSQL_PID=Express' -p 1433:1433 -d mcr.microsoft.com/mssql/server:2017-latest-ubuntu ;; mssql-cli ;; CREATE DATABASE cruxtest; (with-mssql-opts {:db-spec {:dbname "cruxtest"} :pool-opts {:username "sa" :password "PI:PASSWORD:<PASSWORD>END_PI"}} f)))
[ { "context": "ring butter\"\n :resource-id \"rafik\"\n :duration 5\n ", "end": 424, "score": 0.8051007986068726, "start": 419, "tag": "NAME", "value": "rafik" }, { "context": "er on bread\"\n :resource-id \"salma\"\n :duration 3\n ", "end": 636, "score": 0.8515286445617676, "start": 631, "tag": "NAME", "value": "salma" }, { "context": " \"Eat toast\"\n :resource-id \"rafik\"\n :duration 4\n ", "end": 841, "score": 0.6757130026817322, "start": 836, "tag": "NAME", "value": "rafik" }, { "context": " \"Eat toast\"\n :resource-id \"salma\"\n :duration 4\n ", "end": 1044, "score": 0.9807940721511841, "start": 1039, "tag": "NAME", "value": "salma" }, { "context": "name \"task 2\"\n :resource-id \"rafik\"\n :duration 5\n ", "end": 2166, "score": 0.5853208303451538, "start": 2161, "tag": "NAME", "value": "rafik" } ]
test/milestones/dyna_scheduler_test.clj
vinity/milestones
63
(ns milestones.dyna-scheduler-test (:require [milestones.dyna-scheduler :refer :all] [clojure.test :refer :all])) (def correct-tasks {1 {:task-name "Bring bread" :resource-id "mehdi" :duration 5 :priority 1 :predecessors []} 2 {:task-name "Bring butter" :resource-id "rafik" :duration 5 :priority 1 :predecessors []} 3 {:task-name "Put butter on bread" :resource-id "salma" :duration 3 :priority 1 :predecessors [1 2]} 4 {:task-name "Eat toast" :resource-id "rafik" :duration 4 :priority 1 :predecessors [3]} 5 {:task-name "Eat toast" :resource-id "salma" :duration 4 :priority 1 :predecessors [3]} ;; now some milestones 6 {:task-name "Toasts ready" :is-milestone true :predecessors [3]}}) (def correct-tasks-schedule (schedule correct-tasks [:priority])) ;; test if correct-tasks-schedule :errors is nil (deftest correct-tasks-pass (testing "Correct tasks have no error.") (is (= true (nil? (:error correct-tasks-schedule))))) ;; test if task 6 is scheduled after 3 (deftest tasks-are-correctly-scheduled) (testing "test if task 6 is scheduled after 3") (is (= true (> (get-in correct-tasks-schedule [:result 6 :begin] ) (get-in correct-tasks-schedule [:result 3 :begin] )))) ;; Detecting cycles (def cyclic-tasks {1 {:task-name "task 1" :resource-id "mehdi" :duration 5 :priority 1 :predecessors [3]} 2 {:task-name "task 2" :resource-id "rafik" :duration 5 :priority 1 :predecessors [1]} 3 {:task-name "task 3" :resource-id "salma" :duration 3 :priority 1 :predecessors [2]}}) (deftest has-cycle-errors (testing "Detect cycles in tasks definition graphs.") (is (= [[2 3 1]] (get-in (schedule cyclic-tasks [:priority]) [:errors :tasks-cycles])))) ;; task 3 has no resource but is no milestone, ;; task 1 is a milestone, so only task 3 should be reported (def tasks-w-no-resource {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors []} 1 {:task-name "milestone 1" :duration 3 :priority 1 :is-milestone true :predecessors [3]}}) (deftest verify-resources-for-tasks (testing " task 3 has no resource but is no milestone,task 1 is a milestone, so only task 3 should be reported") (is (= [3] (get-in (schedule tasks-w-no-resource [:priority]) [:errors :tasks-w-no-resources])))) ;; some tasks with inexisting predecessors (def tasks-w-predecessors-errors {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors [17]} 1 {:task-name "task 1" :duration 3 :priority 1 :predecessors []}}) (deftest tasks-inexistent-preds (testing "Some tasks with inexisting predecessors") (is (= {3 [17]} (get-in (schedule tasks-w-predecessors-errors [:priority]) [:errors :tasks-w-predecessors-errors])))) ;; Some tasks that do not contain the ordering field (def tasks-w-reordering-errors {3 {:task-name "task 3" :duration 3 :predecessors []} 1 {:task-name "task 1" :duration 3 :priority 1 :predecessors [3]}}) (deftest tatks-reordering-issues (testing "Some tasks that do not contain the ordering field") (is (= {3 [:priority]} (get-in (schedule tasks-w-reordering-errors [:priority]) [:errors :reordering-errors])))) ;; Milestones with no predecessors errors (def milestones-w-no-predecessors {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors []} 1 {:task-name "milestone 1" :duration 3 :priority 1 :is-milestone true :predecessors []}}) (deftest tasks-w-no-preds (testing "Some tasks that do not contain the ordering field") (is (= [1] (get-in (schedule milestones-w-no-predecessors [:priority]) [:errors :milestones-w-no-predecessors]))))
11752
(ns milestones.dyna-scheduler-test (:require [milestones.dyna-scheduler :refer :all] [clojure.test :refer :all])) (def correct-tasks {1 {:task-name "Bring bread" :resource-id "mehdi" :duration 5 :priority 1 :predecessors []} 2 {:task-name "Bring butter" :resource-id "<NAME>" :duration 5 :priority 1 :predecessors []} 3 {:task-name "Put butter on bread" :resource-id "<NAME>" :duration 3 :priority 1 :predecessors [1 2]} 4 {:task-name "Eat toast" :resource-id "<NAME>" :duration 4 :priority 1 :predecessors [3]} 5 {:task-name "Eat toast" :resource-id "<NAME>" :duration 4 :priority 1 :predecessors [3]} ;; now some milestones 6 {:task-name "Toasts ready" :is-milestone true :predecessors [3]}}) (def correct-tasks-schedule (schedule correct-tasks [:priority])) ;; test if correct-tasks-schedule :errors is nil (deftest correct-tasks-pass (testing "Correct tasks have no error.") (is (= true (nil? (:error correct-tasks-schedule))))) ;; test if task 6 is scheduled after 3 (deftest tasks-are-correctly-scheduled) (testing "test if task 6 is scheduled after 3") (is (= true (> (get-in correct-tasks-schedule [:result 6 :begin] ) (get-in correct-tasks-schedule [:result 3 :begin] )))) ;; Detecting cycles (def cyclic-tasks {1 {:task-name "task 1" :resource-id "mehdi" :duration 5 :priority 1 :predecessors [3]} 2 {:task-name "task 2" :resource-id "<NAME>" :duration 5 :priority 1 :predecessors [1]} 3 {:task-name "task 3" :resource-id "salma" :duration 3 :priority 1 :predecessors [2]}}) (deftest has-cycle-errors (testing "Detect cycles in tasks definition graphs.") (is (= [[2 3 1]] (get-in (schedule cyclic-tasks [:priority]) [:errors :tasks-cycles])))) ;; task 3 has no resource but is no milestone, ;; task 1 is a milestone, so only task 3 should be reported (def tasks-w-no-resource {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors []} 1 {:task-name "milestone 1" :duration 3 :priority 1 :is-milestone true :predecessors [3]}}) (deftest verify-resources-for-tasks (testing " task 3 has no resource but is no milestone,task 1 is a milestone, so only task 3 should be reported") (is (= [3] (get-in (schedule tasks-w-no-resource [:priority]) [:errors :tasks-w-no-resources])))) ;; some tasks with inexisting predecessors (def tasks-w-predecessors-errors {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors [17]} 1 {:task-name "task 1" :duration 3 :priority 1 :predecessors []}}) (deftest tasks-inexistent-preds (testing "Some tasks with inexisting predecessors") (is (= {3 [17]} (get-in (schedule tasks-w-predecessors-errors [:priority]) [:errors :tasks-w-predecessors-errors])))) ;; Some tasks that do not contain the ordering field (def tasks-w-reordering-errors {3 {:task-name "task 3" :duration 3 :predecessors []} 1 {:task-name "task 1" :duration 3 :priority 1 :predecessors [3]}}) (deftest tatks-reordering-issues (testing "Some tasks that do not contain the ordering field") (is (= {3 [:priority]} (get-in (schedule tasks-w-reordering-errors [:priority]) [:errors :reordering-errors])))) ;; Milestones with no predecessors errors (def milestones-w-no-predecessors {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors []} 1 {:task-name "milestone 1" :duration 3 :priority 1 :is-milestone true :predecessors []}}) (deftest tasks-w-no-preds (testing "Some tasks that do not contain the ordering field") (is (= [1] (get-in (schedule milestones-w-no-predecessors [:priority]) [:errors :milestones-w-no-predecessors]))))
true
(ns milestones.dyna-scheduler-test (:require [milestones.dyna-scheduler :refer :all] [clojure.test :refer :all])) (def correct-tasks {1 {:task-name "Bring bread" :resource-id "mehdi" :duration 5 :priority 1 :predecessors []} 2 {:task-name "Bring butter" :resource-id "PI:NAME:<NAME>END_PI" :duration 5 :priority 1 :predecessors []} 3 {:task-name "Put butter on bread" :resource-id "PI:NAME:<NAME>END_PI" :duration 3 :priority 1 :predecessors [1 2]} 4 {:task-name "Eat toast" :resource-id "PI:NAME:<NAME>END_PI" :duration 4 :priority 1 :predecessors [3]} 5 {:task-name "Eat toast" :resource-id "PI:NAME:<NAME>END_PI" :duration 4 :priority 1 :predecessors [3]} ;; now some milestones 6 {:task-name "Toasts ready" :is-milestone true :predecessors [3]}}) (def correct-tasks-schedule (schedule correct-tasks [:priority])) ;; test if correct-tasks-schedule :errors is nil (deftest correct-tasks-pass (testing "Correct tasks have no error.") (is (= true (nil? (:error correct-tasks-schedule))))) ;; test if task 6 is scheduled after 3 (deftest tasks-are-correctly-scheduled) (testing "test if task 6 is scheduled after 3") (is (= true (> (get-in correct-tasks-schedule [:result 6 :begin] ) (get-in correct-tasks-schedule [:result 3 :begin] )))) ;; Detecting cycles (def cyclic-tasks {1 {:task-name "task 1" :resource-id "mehdi" :duration 5 :priority 1 :predecessors [3]} 2 {:task-name "task 2" :resource-id "PI:NAME:<NAME>END_PI" :duration 5 :priority 1 :predecessors [1]} 3 {:task-name "task 3" :resource-id "salma" :duration 3 :priority 1 :predecessors [2]}}) (deftest has-cycle-errors (testing "Detect cycles in tasks definition graphs.") (is (= [[2 3 1]] (get-in (schedule cyclic-tasks [:priority]) [:errors :tasks-cycles])))) ;; task 3 has no resource but is no milestone, ;; task 1 is a milestone, so only task 3 should be reported (def tasks-w-no-resource {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors []} 1 {:task-name "milestone 1" :duration 3 :priority 1 :is-milestone true :predecessors [3]}}) (deftest verify-resources-for-tasks (testing " task 3 has no resource but is no milestone,task 1 is a milestone, so only task 3 should be reported") (is (= [3] (get-in (schedule tasks-w-no-resource [:priority]) [:errors :tasks-w-no-resources])))) ;; some tasks with inexisting predecessors (def tasks-w-predecessors-errors {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors [17]} 1 {:task-name "task 1" :duration 3 :priority 1 :predecessors []}}) (deftest tasks-inexistent-preds (testing "Some tasks with inexisting predecessors") (is (= {3 [17]} (get-in (schedule tasks-w-predecessors-errors [:priority]) [:errors :tasks-w-predecessors-errors])))) ;; Some tasks that do not contain the ordering field (def tasks-w-reordering-errors {3 {:task-name "task 3" :duration 3 :predecessors []} 1 {:task-name "task 1" :duration 3 :priority 1 :predecessors [3]}}) (deftest tatks-reordering-issues (testing "Some tasks that do not contain the ordering field") (is (= {3 [:priority]} (get-in (schedule tasks-w-reordering-errors [:priority]) [:errors :reordering-errors])))) ;; Milestones with no predecessors errors (def milestones-w-no-predecessors {3 {:task-name "task 3" :duration 3 :priority 1 :predecessors []} 1 {:task-name "milestone 1" :duration 3 :priority 1 :is-milestone true :predecessors []}}) (deftest tasks-w-no-preds (testing "Some tasks that do not contain the ordering field") (is (= [1] (get-in (schedule milestones-w-no-predecessors [:priority]) [:errors :milestones-w-no-predecessors]))))
[ { "context": "-reset.ba.bg-transparent {:name \"password\" :type \"password\"}]]\n [:div.mt3\n [:input.b.", "end": 3939, "score": 0.822975754737854, "start": 3931, "tag": "PASSWORD", "value": "password" }, { "context": " moment Chili Dog Night is \"\n (person \"Alex Sanchez\")\n \", \"\n (person \"Jason Aum", "end": 7105, "score": 0.9998400211334229, "start": 7093, "tag": "NAME", "value": "Alex Sanchez" }, { "context": "x Sanchez\")\n \", \"\n (person \"Jason Aumann\")\n \", \"\n (person \"Greg Ryan", "end": 7158, "score": 0.9998234510421753, "start": 7146, "tag": "NAME", "value": "Jason Aumann" }, { "context": "on Aumann\")\n \", \"\n (person \"Greg Ryan\")\n \", \"\n (person \"Jacob Dob", "end": 7208, "score": 0.9998670816421509, "start": 7199, "tag": "NAME", "value": "Greg Ryan" }, { "context": "Greg Ryan\")\n \", \"\n (person \"Jacob Dobner\")\n \", \"\n (person \"Matt Beck", "end": 7261, "score": 0.9998257756233215, "start": 7249, "tag": "NAME", "value": "Jacob Dobner" }, { "context": "ob Dobner\")\n \", \"\n (person \"Matt Beck\")\n \", \"\n (person \"Colin Tea", "end": 7311, "score": 0.9998446106910706, "start": 7302, "tag": "NAME", "value": "Matt Beck" }, { "context": "Matt Beck\")\n \", \"\n (person \"Colin Teal\")\n \", and Kaia. They all hail from Sea", "end": 7362, "score": 0.9998648762702942, "start": 7352, "tag": "NAME", "value": "Colin Teal" }, { "context": "\", and \"\n (link-to \"https://github.com/pandeiro/boot-http\" \"boot-http\")\n \"). Hypertext", "end": 8323, "score": 0.8992353081703186, "start": 8315, "tag": "USERNAME", "value": "pandeiro" }, { "context": "ed via \"\n (link-to \"https://github.com/yogthos/clj-rss\" \"clj-rss\")\n \".\"])\n ", "end": 8742, "score": 0.9660534858703613, "start": 8735, "tag": "USERNAME", "value": "yogthos" }, { "context": "red on \"\n (link-to \"https://github.com/chili-dog-night/site\" \"GitHub\")\n \".\"])]))\n\n(defn ratin", "end": 9148, "score": 0.9853437542915344, "start": 9133, "tag": "USERNAME", "value": "chili-dog-night" } ]
src/clj/chili_dog_night/views.clj
chili-dog-night/site
0
(ns chili-dog-night.views (:require [hiccup.page :as h] [hiccup.element :as el] [clj-rss.core :as rss] [clj-time.core :as t] [clj-time.coerce :as c] [clj-time.format :as f] [clojure.string :as str])) (defn link-to [url text] (el/link-to {:class "link blue underline-hover"} url text)) (defn headline [text] [:h2.f2.f-subheadline-ns.lh-title.mb4.mt0 text]) (defn p ([] [:p.f4.f3-ns.measure.lh-copy]) ([body] (into (p) body))) (defn header [] [:header.db.dt-l.w-100.border-box.pa3.ph5-l {:role "banner"} [:h1.db.dtc-l.v-mid.w-100.w-25-l.tc.tl-l.mb2.mb0-l (el/link-to {:class "link dark-gray underline-hover"} "/" "Chili Dog Night")] [:nav.db.dtc-l.v-mid.w-100.w-75-l.tc.tr-l (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/ratings" "Ratings") (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/make-movies-great-again" "Make Movies Great Again") (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/about" "About") (el/link-to {:class "link underline-hover blue f6 f5-l dib"} "/colophon" "Colophon")]]) (defn footer [] [:footer.ph3.ph5-ns{:role "contentinfo"} [:p "©&nbsp;2016-2018 Chili Dog Night Productions"]]) (defn common [title head body] (h/html5 {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (h/include-css "//unpkg.com/tachyons@4.7.0/css/tachyons.min.css") [:title (str title " | " "Chili Dog Night")] [:link {:rel "alternate" :type "application/rss+xml" :href "/rss" :title "Chili Dog Night"}] head] [:body.w-100.sans-serif (header) [:main body] (footer)])) (defn film-citation [film] [:cite {:itemscope "" :itemtype "http://schema.org/Movie"} [:meta {:itemprop "name" :content (:title film)}] (link-to (:uri film) (str/replace (:title film) #"\s" "&nbsp;"))]) (defn person [name] [:span {:itemscope "" :itemtype "http://schema.org/Person"} [:span {:itemprop "name"} name]]) (defn comma-separate-str [coll] (if (nil? coll) "nothing" (if (= (count coll) 1) (first coll) (str (reduce #(str % ", " %2) (drop-last coll)) ", and " (last coll))))) (defn comma-separate [coll] (if (= (count coll) 1) coll (reduce into (concat (map #(vec [% ", "]) (drop-last 2 coll)) (reduce #(vec [[ % ", and "] [%2]]) (take-last 2 coll)))))) (defn gathering-partial [data] [:section (headline (:synopsis data)) (reduce into (p) [(comma-separate (map person (sort (:attendees data)))) " experienced " (comma-separate (map film-citation (:media data))) ". They ate " (comma-separate-str (:food data)) "."]) (when-not (nil? (:notes data)) [:div (p "This is what they discussed during, and between films:") (into [:p.f4.f3-ns.lh-copy] (:notes data))])]) (defn login [] (common "Login" [:meta {:name "description" :content "Login"}] [:section.pa3.pa5-ns (headline "Login") [:form.measure {:method "post" :action "/login"} [:div.mt3 [:label.db.fw6.lh-copy.f6 {:for "email"} "Email address"] [:input.b.pa2.input-reset.ba.bg-transparent {:name "email" :type "text"}]] [:div.mt3 [:label.db.fw6.lh-copy.f6 {:for "password"} "Password"] [:input.b.pa2.input-reset.ba.bg-transparent {:name "password" :type "password"}]] [:div.mt3 [:input.b.ph3.pv2.input-reset.ba.b--black.bg-transparent.grow.pointer.f6.dib {:type "submit" :value "Login"}]]]])) (defn not-found [] (common "404" [:meta {:name "description" :content "You look lost."}] [:section.pa3.pa5-ns (headline 404) (p "The resource you requested was not found.")])) (defn previously [data] (when-not (nil? data) (p [(link-to (str "/" (if (:themes data) "make-movies-great-again" "gatherings") "/" (:date data)) "Previously...")]))) (defn home ([latest] (home latest nil)) ([latest previous] (common "Our cinematic torture chamber." [:meta {:name "description" :content "This is the story of a friendship forged in food, film, and fear. It is pain, but it is also laughter. This is Chili Dog Night."}] [:article.pa3.pa5-ns (gathering-partial latest) (previously previous)]))) (defn gathering ([latest] (gathering latest nil)) ([latest previous] (common (:date latest) [:meta {:name "description" :content (:synopsis latest)}] [:article.pa3.pa5-ns (gathering-partial latest) (previously previous)]))) (defn admin [a b] (common "Behind the Scenes" nil [:div [:section.pa3.pa5-ns {:id "app"} (headline "Which is worse?") [:form {:action "/api/media/vote" :method "post"} [:div.mt3 [:input {:type "radio" :name "selected-media-id" :value (:id a) :checked true}] [:label.pl3 (:title a)]] [:div.mt3 [:input {:type "radio" :name "selected-media-id" :value (:id b)}] [:label.pl3 (:title b)]] [:input {:type "hidden" :name "media-a-id" :value (:id a)}] [:input {:type "hidden" :name "media-b-id" :value (:id b)}] [:div.mt3 [:input.b.ph3.pv2.input-reset.ba.b--black.bg-transparent.grow.pointer.f6.dib {:type "submit" :value "I've made my decision"}]]]]])) (defn about [] (common "About" [:meta {:name "description" :content "Somehow we got the part. Don't ask. This is Chili Dog Night."}] [:section.pa3.pa5-ns (headline "About") (p ["Chili Dog Night is a celebration of the worst kinds of moving images " "experienced in tandem with relatively unhealthy foods. " "The primary objective is to deconstruct and ridicule movies that don't have an " "excuse for their bad behavior. While the occasional obvious choice is " "consumed the real focus, and most infuriatingly painful kind of movie, is mainstream mediocrity."]) (p ["As of this moment Chili Dog Night is " (person "Alex Sanchez") ", " (person "Jason Aumann") ", " (person "Greg Ryan") ", " (person "Jacob Dobner") ", " (person "Matt Beck") ", " (person "Colin Teal") ", and Kaia. They all hail from Seattle, and are slowly losing their minds one film at a time."])])) (defn colophon [] (common "Colophon" [:meta {:name "description" :content "We made it good with a beginning, middle, and end. This is Chili Dog Night."}] [:section.pa3.pa5-ns (headline "Colophon") (p ["This website was made possible by " (link-to "http://clojure.org/" "Clojure") " and " (link-to "https://github.com/clojure/clojurescript" "ClojureScript") ". Compilation of the application is facilitated by " (link-to "http://boot-clj.com/" "Boot") " and its myriad friends (e.g., " (link-to "https://github.com/adzerk-oss/boot-cljs" "boot-cljs") ", " (link-to "https://github.com/adzerk-oss/boot-reload" "boot-reload") ", and " (link-to "https://github.com/pandeiro/boot-http" "boot-http") "). Hypertext Markup Language (HTML) is generated via " (link-to "https://github.com/weavejester/hiccup" "Hiccup") ", and the Cascading Style Sheets (CSS) are grown with help from " (link-to "http://tachyons.io/" "Tachyons") ". The Really Simple Syndication (RSS) feed is created via " (link-to "https://github.com/yogthos/clj-rss" "clj-rss") "."]) (p ["The domain name was purchased through " (link-to "https://www.namecheap.com/" "NameCheap") ". Hosting of the application is provided by " (link-to "https://www.heroku.com" "Heroku") ". The project source code is publicly available and stored on " (link-to "https://github.com/chili-dog-night/site" "GitHub") "."])])) (defn ratings [media] (common "Ratings" [:meta {:name "description" :content "The films we have suffered through from worst to less worse."}] [:section.pa3.pa5-ns (headline "Ratings") (p ["The order below has been determined via random head to head voting. Each film is given an initial base rating that is updated per the " (link-to "https://en.wikipedia.org/wiki/Elo_rating_system" "Elo rating system") ". Adjustments to the ratings of winner and loser are based on the expected result versus the actual result for any given dual."]) (p "The films are ordered from worst to least worst (best).") [:ol.f4.f3-ns.lh-copy (map #(vec [:li (film-citation %)]) media)]])) (defn str->date [str] (c/to-date (f/parse (f/formatter "yyyy/MM/dd") str))) (defn rss-feed-item [item] (let [date (:date item)] {:title date :pubDate (str->date date) :description (:synopsis item) :link (str "http://www.chilidognight.com/gatherings/" date)})) (defn rss-feed [items] (rss/channel-xml {:title "Chili Dog Night" :language "en-us" :pubDate (c/to-date (t/today-at 12 00)) :lastBuildDate (str->date (:date (first items))) :docs "http://blogs.law.harvard.edu/tech/rss" :link "http://www.chilidognight.com" :copyright "Copyright 2016, Chili Dog Night Productions" :description "The latest gatherings from your friends at Chili Dog Night."} (map rss-feed-item items)))
88522
(ns chili-dog-night.views (:require [hiccup.page :as h] [hiccup.element :as el] [clj-rss.core :as rss] [clj-time.core :as t] [clj-time.coerce :as c] [clj-time.format :as f] [clojure.string :as str])) (defn link-to [url text] (el/link-to {:class "link blue underline-hover"} url text)) (defn headline [text] [:h2.f2.f-subheadline-ns.lh-title.mb4.mt0 text]) (defn p ([] [:p.f4.f3-ns.measure.lh-copy]) ([body] (into (p) body))) (defn header [] [:header.db.dt-l.w-100.border-box.pa3.ph5-l {:role "banner"} [:h1.db.dtc-l.v-mid.w-100.w-25-l.tc.tl-l.mb2.mb0-l (el/link-to {:class "link dark-gray underline-hover"} "/" "Chili Dog Night")] [:nav.db.dtc-l.v-mid.w-100.w-75-l.tc.tr-l (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/ratings" "Ratings") (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/make-movies-great-again" "Make Movies Great Again") (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/about" "About") (el/link-to {:class "link underline-hover blue f6 f5-l dib"} "/colophon" "Colophon")]]) (defn footer [] [:footer.ph3.ph5-ns{:role "contentinfo"} [:p "©&nbsp;2016-2018 Chili Dog Night Productions"]]) (defn common [title head body] (h/html5 {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (h/include-css "//unpkg.com/tachyons@4.7.0/css/tachyons.min.css") [:title (str title " | " "Chili Dog Night")] [:link {:rel "alternate" :type "application/rss+xml" :href "/rss" :title "Chili Dog Night"}] head] [:body.w-100.sans-serif (header) [:main body] (footer)])) (defn film-citation [film] [:cite {:itemscope "" :itemtype "http://schema.org/Movie"} [:meta {:itemprop "name" :content (:title film)}] (link-to (:uri film) (str/replace (:title film) #"\s" "&nbsp;"))]) (defn person [name] [:span {:itemscope "" :itemtype "http://schema.org/Person"} [:span {:itemprop "name"} name]]) (defn comma-separate-str [coll] (if (nil? coll) "nothing" (if (= (count coll) 1) (first coll) (str (reduce #(str % ", " %2) (drop-last coll)) ", and " (last coll))))) (defn comma-separate [coll] (if (= (count coll) 1) coll (reduce into (concat (map #(vec [% ", "]) (drop-last 2 coll)) (reduce #(vec [[ % ", and "] [%2]]) (take-last 2 coll)))))) (defn gathering-partial [data] [:section (headline (:synopsis data)) (reduce into (p) [(comma-separate (map person (sort (:attendees data)))) " experienced " (comma-separate (map film-citation (:media data))) ". They ate " (comma-separate-str (:food data)) "."]) (when-not (nil? (:notes data)) [:div (p "This is what they discussed during, and between films:") (into [:p.f4.f3-ns.lh-copy] (:notes data))])]) (defn login [] (common "Login" [:meta {:name "description" :content "Login"}] [:section.pa3.pa5-ns (headline "Login") [:form.measure {:method "post" :action "/login"} [:div.mt3 [:label.db.fw6.lh-copy.f6 {:for "email"} "Email address"] [:input.b.pa2.input-reset.ba.bg-transparent {:name "email" :type "text"}]] [:div.mt3 [:label.db.fw6.lh-copy.f6 {:for "password"} "Password"] [:input.b.pa2.input-reset.ba.bg-transparent {:name "password" :type "<PASSWORD>"}]] [:div.mt3 [:input.b.ph3.pv2.input-reset.ba.b--black.bg-transparent.grow.pointer.f6.dib {:type "submit" :value "Login"}]]]])) (defn not-found [] (common "404" [:meta {:name "description" :content "You look lost."}] [:section.pa3.pa5-ns (headline 404) (p "The resource you requested was not found.")])) (defn previously [data] (when-not (nil? data) (p [(link-to (str "/" (if (:themes data) "make-movies-great-again" "gatherings") "/" (:date data)) "Previously...")]))) (defn home ([latest] (home latest nil)) ([latest previous] (common "Our cinematic torture chamber." [:meta {:name "description" :content "This is the story of a friendship forged in food, film, and fear. It is pain, but it is also laughter. This is Chili Dog Night."}] [:article.pa3.pa5-ns (gathering-partial latest) (previously previous)]))) (defn gathering ([latest] (gathering latest nil)) ([latest previous] (common (:date latest) [:meta {:name "description" :content (:synopsis latest)}] [:article.pa3.pa5-ns (gathering-partial latest) (previously previous)]))) (defn admin [a b] (common "Behind the Scenes" nil [:div [:section.pa3.pa5-ns {:id "app"} (headline "Which is worse?") [:form {:action "/api/media/vote" :method "post"} [:div.mt3 [:input {:type "radio" :name "selected-media-id" :value (:id a) :checked true}] [:label.pl3 (:title a)]] [:div.mt3 [:input {:type "radio" :name "selected-media-id" :value (:id b)}] [:label.pl3 (:title b)]] [:input {:type "hidden" :name "media-a-id" :value (:id a)}] [:input {:type "hidden" :name "media-b-id" :value (:id b)}] [:div.mt3 [:input.b.ph3.pv2.input-reset.ba.b--black.bg-transparent.grow.pointer.f6.dib {:type "submit" :value "I've made my decision"}]]]]])) (defn about [] (common "About" [:meta {:name "description" :content "Somehow we got the part. Don't ask. This is Chili Dog Night."}] [:section.pa3.pa5-ns (headline "About") (p ["Chili Dog Night is a celebration of the worst kinds of moving images " "experienced in tandem with relatively unhealthy foods. " "The primary objective is to deconstruct and ridicule movies that don't have an " "excuse for their bad behavior. While the occasional obvious choice is " "consumed the real focus, and most infuriatingly painful kind of movie, is mainstream mediocrity."]) (p ["As of this moment Chili Dog Night is " (person "<NAME>") ", " (person "<NAME>") ", " (person "<NAME>") ", " (person "<NAME>") ", " (person "<NAME>") ", " (person "<NAME>") ", and Kaia. They all hail from Seattle, and are slowly losing their minds one film at a time."])])) (defn colophon [] (common "Colophon" [:meta {:name "description" :content "We made it good with a beginning, middle, and end. This is Chili Dog Night."}] [:section.pa3.pa5-ns (headline "Colophon") (p ["This website was made possible by " (link-to "http://clojure.org/" "Clojure") " and " (link-to "https://github.com/clojure/clojurescript" "ClojureScript") ". Compilation of the application is facilitated by " (link-to "http://boot-clj.com/" "Boot") " and its myriad friends (e.g., " (link-to "https://github.com/adzerk-oss/boot-cljs" "boot-cljs") ", " (link-to "https://github.com/adzerk-oss/boot-reload" "boot-reload") ", and " (link-to "https://github.com/pandeiro/boot-http" "boot-http") "). Hypertext Markup Language (HTML) is generated via " (link-to "https://github.com/weavejester/hiccup" "Hiccup") ", and the Cascading Style Sheets (CSS) are grown with help from " (link-to "http://tachyons.io/" "Tachyons") ". The Really Simple Syndication (RSS) feed is created via " (link-to "https://github.com/yogthos/clj-rss" "clj-rss") "."]) (p ["The domain name was purchased through " (link-to "https://www.namecheap.com/" "NameCheap") ". Hosting of the application is provided by " (link-to "https://www.heroku.com" "Heroku") ". The project source code is publicly available and stored on " (link-to "https://github.com/chili-dog-night/site" "GitHub") "."])])) (defn ratings [media] (common "Ratings" [:meta {:name "description" :content "The films we have suffered through from worst to less worse."}] [:section.pa3.pa5-ns (headline "Ratings") (p ["The order below has been determined via random head to head voting. Each film is given an initial base rating that is updated per the " (link-to "https://en.wikipedia.org/wiki/Elo_rating_system" "Elo rating system") ". Adjustments to the ratings of winner and loser are based on the expected result versus the actual result for any given dual."]) (p "The films are ordered from worst to least worst (best).") [:ol.f4.f3-ns.lh-copy (map #(vec [:li (film-citation %)]) media)]])) (defn str->date [str] (c/to-date (f/parse (f/formatter "yyyy/MM/dd") str))) (defn rss-feed-item [item] (let [date (:date item)] {:title date :pubDate (str->date date) :description (:synopsis item) :link (str "http://www.chilidognight.com/gatherings/" date)})) (defn rss-feed [items] (rss/channel-xml {:title "Chili Dog Night" :language "en-us" :pubDate (c/to-date (t/today-at 12 00)) :lastBuildDate (str->date (:date (first items))) :docs "http://blogs.law.harvard.edu/tech/rss" :link "http://www.chilidognight.com" :copyright "Copyright 2016, Chili Dog Night Productions" :description "The latest gatherings from your friends at Chili Dog Night."} (map rss-feed-item items)))
true
(ns chili-dog-night.views (:require [hiccup.page :as h] [hiccup.element :as el] [clj-rss.core :as rss] [clj-time.core :as t] [clj-time.coerce :as c] [clj-time.format :as f] [clojure.string :as str])) (defn link-to [url text] (el/link-to {:class "link blue underline-hover"} url text)) (defn headline [text] [:h2.f2.f-subheadline-ns.lh-title.mb4.mt0 text]) (defn p ([] [:p.f4.f3-ns.measure.lh-copy]) ([body] (into (p) body))) (defn header [] [:header.db.dt-l.w-100.border-box.pa3.ph5-l {:role "banner"} [:h1.db.dtc-l.v-mid.w-100.w-25-l.tc.tl-l.mb2.mb0-l (el/link-to {:class "link dark-gray underline-hover"} "/" "Chili Dog Night")] [:nav.db.dtc-l.v-mid.w-100.w-75-l.tc.tr-l (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/ratings" "Ratings") (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/make-movies-great-again" "Make Movies Great Again") (el/link-to {:class "link underline-hover blue f6 f5-l dib mr3 mr4-l"} "/about" "About") (el/link-to {:class "link underline-hover blue f6 f5-l dib"} "/colophon" "Colophon")]]) (defn footer [] [:footer.ph3.ph5-ns{:role "contentinfo"} [:p "©&nbsp;2016-2018 Chili Dog Night Productions"]]) (defn common [title head body] (h/html5 {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (h/include-css "//unpkg.com/tachyons@4.7.0/css/tachyons.min.css") [:title (str title " | " "Chili Dog Night")] [:link {:rel "alternate" :type "application/rss+xml" :href "/rss" :title "Chili Dog Night"}] head] [:body.w-100.sans-serif (header) [:main body] (footer)])) (defn film-citation [film] [:cite {:itemscope "" :itemtype "http://schema.org/Movie"} [:meta {:itemprop "name" :content (:title film)}] (link-to (:uri film) (str/replace (:title film) #"\s" "&nbsp;"))]) (defn person [name] [:span {:itemscope "" :itemtype "http://schema.org/Person"} [:span {:itemprop "name"} name]]) (defn comma-separate-str [coll] (if (nil? coll) "nothing" (if (= (count coll) 1) (first coll) (str (reduce #(str % ", " %2) (drop-last coll)) ", and " (last coll))))) (defn comma-separate [coll] (if (= (count coll) 1) coll (reduce into (concat (map #(vec [% ", "]) (drop-last 2 coll)) (reduce #(vec [[ % ", and "] [%2]]) (take-last 2 coll)))))) (defn gathering-partial [data] [:section (headline (:synopsis data)) (reduce into (p) [(comma-separate (map person (sort (:attendees data)))) " experienced " (comma-separate (map film-citation (:media data))) ". They ate " (comma-separate-str (:food data)) "."]) (when-not (nil? (:notes data)) [:div (p "This is what they discussed during, and between films:") (into [:p.f4.f3-ns.lh-copy] (:notes data))])]) (defn login [] (common "Login" [:meta {:name "description" :content "Login"}] [:section.pa3.pa5-ns (headline "Login") [:form.measure {:method "post" :action "/login"} [:div.mt3 [:label.db.fw6.lh-copy.f6 {:for "email"} "Email address"] [:input.b.pa2.input-reset.ba.bg-transparent {:name "email" :type "text"}]] [:div.mt3 [:label.db.fw6.lh-copy.f6 {:for "password"} "Password"] [:input.b.pa2.input-reset.ba.bg-transparent {:name "password" :type "PI:PASSWORD:<PASSWORD>END_PI"}]] [:div.mt3 [:input.b.ph3.pv2.input-reset.ba.b--black.bg-transparent.grow.pointer.f6.dib {:type "submit" :value "Login"}]]]])) (defn not-found [] (common "404" [:meta {:name "description" :content "You look lost."}] [:section.pa3.pa5-ns (headline 404) (p "The resource you requested was not found.")])) (defn previously [data] (when-not (nil? data) (p [(link-to (str "/" (if (:themes data) "make-movies-great-again" "gatherings") "/" (:date data)) "Previously...")]))) (defn home ([latest] (home latest nil)) ([latest previous] (common "Our cinematic torture chamber." [:meta {:name "description" :content "This is the story of a friendship forged in food, film, and fear. It is pain, but it is also laughter. This is Chili Dog Night."}] [:article.pa3.pa5-ns (gathering-partial latest) (previously previous)]))) (defn gathering ([latest] (gathering latest nil)) ([latest previous] (common (:date latest) [:meta {:name "description" :content (:synopsis latest)}] [:article.pa3.pa5-ns (gathering-partial latest) (previously previous)]))) (defn admin [a b] (common "Behind the Scenes" nil [:div [:section.pa3.pa5-ns {:id "app"} (headline "Which is worse?") [:form {:action "/api/media/vote" :method "post"} [:div.mt3 [:input {:type "radio" :name "selected-media-id" :value (:id a) :checked true}] [:label.pl3 (:title a)]] [:div.mt3 [:input {:type "radio" :name "selected-media-id" :value (:id b)}] [:label.pl3 (:title b)]] [:input {:type "hidden" :name "media-a-id" :value (:id a)}] [:input {:type "hidden" :name "media-b-id" :value (:id b)}] [:div.mt3 [:input.b.ph3.pv2.input-reset.ba.b--black.bg-transparent.grow.pointer.f6.dib {:type "submit" :value "I've made my decision"}]]]]])) (defn about [] (common "About" [:meta {:name "description" :content "Somehow we got the part. Don't ask. This is Chili Dog Night."}] [:section.pa3.pa5-ns (headline "About") (p ["Chili Dog Night is a celebration of the worst kinds of moving images " "experienced in tandem with relatively unhealthy foods. " "The primary objective is to deconstruct and ridicule movies that don't have an " "excuse for their bad behavior. While the occasional obvious choice is " "consumed the real focus, and most infuriatingly painful kind of movie, is mainstream mediocrity."]) (p ["As of this moment Chili Dog Night is " (person "PI:NAME:<NAME>END_PI") ", " (person "PI:NAME:<NAME>END_PI") ", " (person "PI:NAME:<NAME>END_PI") ", " (person "PI:NAME:<NAME>END_PI") ", " (person "PI:NAME:<NAME>END_PI") ", " (person "PI:NAME:<NAME>END_PI") ", and Kaia. They all hail from Seattle, and are slowly losing their minds one film at a time."])])) (defn colophon [] (common "Colophon" [:meta {:name "description" :content "We made it good with a beginning, middle, and end. This is Chili Dog Night."}] [:section.pa3.pa5-ns (headline "Colophon") (p ["This website was made possible by " (link-to "http://clojure.org/" "Clojure") " and " (link-to "https://github.com/clojure/clojurescript" "ClojureScript") ". Compilation of the application is facilitated by " (link-to "http://boot-clj.com/" "Boot") " and its myriad friends (e.g., " (link-to "https://github.com/adzerk-oss/boot-cljs" "boot-cljs") ", " (link-to "https://github.com/adzerk-oss/boot-reload" "boot-reload") ", and " (link-to "https://github.com/pandeiro/boot-http" "boot-http") "). Hypertext Markup Language (HTML) is generated via " (link-to "https://github.com/weavejester/hiccup" "Hiccup") ", and the Cascading Style Sheets (CSS) are grown with help from " (link-to "http://tachyons.io/" "Tachyons") ". The Really Simple Syndication (RSS) feed is created via " (link-to "https://github.com/yogthos/clj-rss" "clj-rss") "."]) (p ["The domain name was purchased through " (link-to "https://www.namecheap.com/" "NameCheap") ". Hosting of the application is provided by " (link-to "https://www.heroku.com" "Heroku") ". The project source code is publicly available and stored on " (link-to "https://github.com/chili-dog-night/site" "GitHub") "."])])) (defn ratings [media] (common "Ratings" [:meta {:name "description" :content "The films we have suffered through from worst to less worse."}] [:section.pa3.pa5-ns (headline "Ratings") (p ["The order below has been determined via random head to head voting. Each film is given an initial base rating that is updated per the " (link-to "https://en.wikipedia.org/wiki/Elo_rating_system" "Elo rating system") ". Adjustments to the ratings of winner and loser are based on the expected result versus the actual result for any given dual."]) (p "The films are ordered from worst to least worst (best).") [:ol.f4.f3-ns.lh-copy (map #(vec [:li (film-citation %)]) media)]])) (defn str->date [str] (c/to-date (f/parse (f/formatter "yyyy/MM/dd") str))) (defn rss-feed-item [item] (let [date (:date item)] {:title date :pubDate (str->date date) :description (:synopsis item) :link (str "http://www.chilidognight.com/gatherings/" date)})) (defn rss-feed [items] (rss/channel-xml {:title "Chili Dog Night" :language "en-us" :pubDate (c/to-date (t/today-at 12 00)) :lastBuildDate (str->date (:date (first items))) :docs "http://blogs.law.harvard.edu/tech/rss" :link "http://www.chilidognight.com" :copyright "Copyright 2016, Chili Dog Night Productions" :description "The latest gatherings from your friends at Chili Dog Night."} (map rss-feed-item items)))
[ { "context": "abase \"cggdb\"\n :username \"cgg_role\"\n :password \"lacinia\"\n ", "end": 408, "score": 0.9954491853713989, "start": 400, "tag": "USERNAME", "value": "cgg_role" }, { "context": "me \"cgg_role\"\n :password \"lacinia\"\n ;; Host port mapped to ", "end": 453, "score": 0.9987871050834656, "start": 446, "tag": "PASSWORD", "value": "lacinia" } ]
src/clojure_game_geek/db.clj
hlship/clojure-game-geek
0
(ns clojure-game-geek.db (:require [com.stuartsierra.component :as component] [postgres.async :refer [open-db query! close-db!]] [clojure.core.async :refer [<!!]])) (defrecord ClojureGameGeekDb [conn] component/Lifecycle (start [this] (assoc this :conn (open-db {:hostname "localhost" :database "cggdb" :username "cgg_role" :password "lacinia" ;; Host port mapped to 5432 in the container :port 25432}))) (stop [this] (close-db! conn) (assoc this :conn nil))) (defn new-db [] {:db (map->ClojureGameGeekDb {})}) (defn ^:private take! "Takes a value from a channel and rethrows an exception if that is the conveyed value." [ch] (let [v (<!! ch)] (if (instance? Throwable v) (throw v) v))) (defn find-game-by-id [component game-id] (-> (query! (:conn component) ["select game_id, name, summary, min_players, max_players, created_at, updated_at from board_game where game_id = $1" game-id]) take! first)) (defn find-member-by-id [component member-id] (->> component :db deref :members (filter #(= member-id (:id %))) first)) (defn list-designers-for-game [component game-id] (let [designers (:designers (find-game-by-id component game-id))] (->> component :db deref :designers (filter #(contains? designers (:id %)))))) (defn list-games-for-designer [component designer-id] (->> component :db deref :games (filter #(-> % :designers (contains? designer-id))))) (defn list-ratings-for-game [component game-id] (->> component :db deref :ratings (filter #(= game-id (:game_id %))))) (defn list-ratings-for-member [component member-id] (->> component :db deref :ratings (filter #(= member-id (:member_id %))))) (defn ^:private apply-game-rating [game-ratings game-id member-id rating] (->> game-ratings (remove #(and (= game-id (:game_id %)) (= member-id (:member_id %)))) (cons {:game_id game-id :member_id member-id :rating rating}))) (defn upsert-game-rating "Adds a new game rating, or changes the value of an existing game rating." [db game-id member-id rating] (-> db :db (swap! update :ratings apply-game-rating game-id member-id rating)))
103570
(ns clojure-game-geek.db (:require [com.stuartsierra.component :as component] [postgres.async :refer [open-db query! close-db!]] [clojure.core.async :refer [<!!]])) (defrecord ClojureGameGeekDb [conn] component/Lifecycle (start [this] (assoc this :conn (open-db {:hostname "localhost" :database "cggdb" :username "cgg_role" :password "<PASSWORD>" ;; Host port mapped to 5432 in the container :port 25432}))) (stop [this] (close-db! conn) (assoc this :conn nil))) (defn new-db [] {:db (map->ClojureGameGeekDb {})}) (defn ^:private take! "Takes a value from a channel and rethrows an exception if that is the conveyed value." [ch] (let [v (<!! ch)] (if (instance? Throwable v) (throw v) v))) (defn find-game-by-id [component game-id] (-> (query! (:conn component) ["select game_id, name, summary, min_players, max_players, created_at, updated_at from board_game where game_id = $1" game-id]) take! first)) (defn find-member-by-id [component member-id] (->> component :db deref :members (filter #(= member-id (:id %))) first)) (defn list-designers-for-game [component game-id] (let [designers (:designers (find-game-by-id component game-id))] (->> component :db deref :designers (filter #(contains? designers (:id %)))))) (defn list-games-for-designer [component designer-id] (->> component :db deref :games (filter #(-> % :designers (contains? designer-id))))) (defn list-ratings-for-game [component game-id] (->> component :db deref :ratings (filter #(= game-id (:game_id %))))) (defn list-ratings-for-member [component member-id] (->> component :db deref :ratings (filter #(= member-id (:member_id %))))) (defn ^:private apply-game-rating [game-ratings game-id member-id rating] (->> game-ratings (remove #(and (= game-id (:game_id %)) (= member-id (:member_id %)))) (cons {:game_id game-id :member_id member-id :rating rating}))) (defn upsert-game-rating "Adds a new game rating, or changes the value of an existing game rating." [db game-id member-id rating] (-> db :db (swap! update :ratings apply-game-rating game-id member-id rating)))
true
(ns clojure-game-geek.db (:require [com.stuartsierra.component :as component] [postgres.async :refer [open-db query! close-db!]] [clojure.core.async :refer [<!!]])) (defrecord ClojureGameGeekDb [conn] component/Lifecycle (start [this] (assoc this :conn (open-db {:hostname "localhost" :database "cggdb" :username "cgg_role" :password "PI:PASSWORD:<PASSWORD>END_PI" ;; Host port mapped to 5432 in the container :port 25432}))) (stop [this] (close-db! conn) (assoc this :conn nil))) (defn new-db [] {:db (map->ClojureGameGeekDb {})}) (defn ^:private take! "Takes a value from a channel and rethrows an exception if that is the conveyed value." [ch] (let [v (<!! ch)] (if (instance? Throwable v) (throw v) v))) (defn find-game-by-id [component game-id] (-> (query! (:conn component) ["select game_id, name, summary, min_players, max_players, created_at, updated_at from board_game where game_id = $1" game-id]) take! first)) (defn find-member-by-id [component member-id] (->> component :db deref :members (filter #(= member-id (:id %))) first)) (defn list-designers-for-game [component game-id] (let [designers (:designers (find-game-by-id component game-id))] (->> component :db deref :designers (filter #(contains? designers (:id %)))))) (defn list-games-for-designer [component designer-id] (->> component :db deref :games (filter #(-> % :designers (contains? designer-id))))) (defn list-ratings-for-game [component game-id] (->> component :db deref :ratings (filter #(= game-id (:game_id %))))) (defn list-ratings-for-member [component member-id] (->> component :db deref :ratings (filter #(= member-id (:member_id %))))) (defn ^:private apply-game-rating [game-ratings game-id member-id rating] (->> game-ratings (remove #(and (= game-id (:game_id %)) (= member-id (:member_id %)))) (cons {:game_id game-id :member_id member-id :rating rating}))) (defn upsert-game-rating "Adds a new game rating, or changes the value of an existing game rating." [db game-id member-id rating] (-> db :db (swap! update :ratings apply-game-rating game-id member-id rating)))
[ { "context": "an be [found on\n;; GitHub](https://www.github.com/tombooth/painting-in-clojure).\n;; Below is an example of w", "end": 291, "score": 0.9982208609580994, "start": 283, "tag": "USERNAME", "value": "tombooth" }, { "context": ";; <button id=\"fill\">Fill canvas</button>\n\n\n\n;; ## Jackson Pollock\n\n;; He was an abstract artist who lived through t", "end": 592, "score": 0.9992160797119141, "start": 577, "tag": "NAME", "value": "Jackson Pollock" }, { "context": "called say-hello that when called `(say-hello\n;; \"James\")` it will return the string \"Hello James\".\n\n;; W", "end": 4956, "score": 0.9991738200187683, "start": 4951, "tag": "NAME", "value": "James" }, { "context": "ello\n;; \"James\")` it will return the string \"Hello James\".\n\n;; We are going to cover a common functional i", "end": 4998, "score": 0.9994945526123047, "start": 4993, "tag": "NAME", "value": "James" }, { "context": "l together\n\n;; I've pulled a bunch of colours that Pollock used in his seminal\n;; work \"Number 8\" so that ea", "end": 23276, "score": 0.9919189810752869, "start": 23269, "tag": "NAME", "value": "Pollock" }, { "context": "he above functions into something\n;; the resembles Jackson Pollock applying paint to a canvas. We start\n;; with a po", "end": 23700, "score": 0.9919853806495667, "start": 23685, "tag": "NAME", "value": "Jackson Pollock" } ]
src/uk/co/tombooth/pollock.cljs
tombooth/painting-in-clojure
20
(ns uk.co.tombooth.pollock (:require [quil.core :as q :include-macros true])) ;; --- ;; title: Painting in Clojure ;; ... ;; Learning Clojure by building a digital Jackson Pollock. This ;; article and the source code backing it can be [found on ;; GitHub](https://www.github.com/tombooth/painting-in-clojure). ;; Below is an example of what we will be building, running the code ;; found in this page. ;; <canvas id="pollock" style="width: 100%; border: 5px solid #eee"></canvas> ;; <button id="add">Add stroke</button> ;; <button id="fill">Fill canvas</button> ;; ## Jackson Pollock ;; He was an abstract artist who lived through the first half of the ;; 20th century and is most famous for his drip paintings. This style ;; of painting involves him using sticks brushes, sticks and cans to ;; apply paint to the canvas with the motion of his gestures causing ;; the artworks to come alive. You can get a good idea of how this ;; comes together from [this youtube video](https://www.youtube.com/watch?v=7bICqvmKL5s). ;; ## Setting the scene ;; We want to define some facts about the space that our digital ;; Pollock will work in. These facts will not change over the ;; execution of our model and fit Clojure's preference for ;; immutability perfectly. For those who have not come across the idea ;; of mutability before it is simply whether something can be changed ;; in place. In most languages if you set the label `some_number` to ;; equal `5`, further on you can increment the value of `some_number` to ;; `6` or even `7`. In Clojure if you tried to increment `some_number` ;; you would get a new value rather than changing `some_number`. ;; Clojure will let us define facts using one of the following value types: ;; ;; - A number. This could be `5` an integer, `3/2` a ratio/fraction ;; or `3.14` a floating point number; ;; - A string, represented as a sequence of characters, for example ;; `"Hello world!"`; ;; - A keyword, which are very similar to strings in appearance ;; except they are preceded by a colon e.g. `:an-identifier`. As ;; alluded to in the example they are usually used for identifiers or ;; labels and do not allow spaces. ;; - A list `(...)`, this is a way of grouping values into a ;; collection with an explicit order. You may notice all of ;; the code written takes for ;; form of lists. By default if you have written `(...)` Clojure ;; will assume the first item is a function and the rest are ;; arguments to be passed in. In order for the list not to be ;; executed you should prefix it with a `'`; ;; - A vector `[...]`, which is a lot like a list except that they are optimised for ;; appending to the end of the sequence rather than to the front; ;; - A set `#{...}`. If you are not particularly bothered by the order of ;; the values stored in your collection then you can use a set; ;; - Lastly there are maps `{...}`, these store pairs of values ;; where the first is a key and the second is a value. ;; If you would like to learn more about the basic types in Clojure, I ;; suggest you read [this great blog ;; post](http://aphyr.com/posts/302-clojure-from-the-ground-up-basic-types) ;; by Aphyr. ;; The most important fact about the space is its size. We will use ;; metres to measure the size only converting to pixels when we need ;; to draw to the screen. We are going to define size as a vector ;; containing its width, height and depth. (def space [8 ;; width 5 ;; height 6]) ;; depth ;; We need to know the gravity of the space so it can influence the ;; flow of paint as it leaves the brush. This will be defined as a ;; vector that represents acceleration influenced by gravity. (def gravity [0 -9.8 0]) ;; Lastly, we need to know the normal of the surface of the canvas that ;; the paint will impact with. This will be used to dictate how paint ;; acts when it spatters from the impact with the canvas. (def canvas-normal [0 1 0]) ;; ## Starting points and projection ;; Our digital Pollock is going to start a stroke of the brush by ;; picking a random point in space. This point will then be projected ;; to find where it impacts with the canvas. ;; In order to generate a random point inside of the space we need to ;; define a function that each time it is called will emit a vector ;; containing the position of the point. Function values can be ;; created by calling `(fn [...] ...)` with the first vector being the ;; arguments the function should receive and any follow items in the ;; list are the body of the function and executed with the arguments ;; bound. Rather than calling `(def name (fn ...))` Clojure has provided a ;; shortcut function `(defn name [...] ...)`. An example of a defined ;; function is `(defn say-hello [name] (str "Hello " name))`, this ;; creates a function called say-hello that when called `(say-hello ;; "James")` it will return the string "Hello James". ;; We are going to cover a common functional idiom when dealing with ;; lists to change the dimensions of the space above into a random ;; point inside that space. To do this we want to iterate over each ;; dimension of the size of space, generate a random number between 0 ;; and the magnitude of each dimension and then return the resultant ;; list of random numbers as a list. To generate a random number in ;; Clojure we can use the `(rand)` function, which will return a ;; random number between 0 (inclusive) and 1 (exclusive). The rand ;; function can take an optional parameter `(rand 100), this will ;; define the bounds of the number generated to 0 and 100. ;; The function map `(map [fn] [sequence])` will iterate through the ;; sequence executing the function with the current value of the ;; sequence as its first parameter, the values returned from the ;; function will be stored in a list the same length as the sequence ;; and returned by the function. ;; We can now define a random point inside of space as follows (defn starting-point [] (map rand space)) ;; Now that we can generate a random point in space we want to project ;; this to the canvas. We are going to use [Newtonian equations of ;; motion](https://en.wikipedia.org/wiki/Equations_of_motion), ;; we know the position, velocity and acceleration of the ;; point and we want to know what the position and velocity are when y ;; is 0. In order to work out final positions we need to know the ;; total time the point spent falling, we can do this using the y ;; position as we know that the final position should be 0. ;; To work out the time it takes for the point to reach the canvas we ;; will solve the following equation for t: ;; ;; - $r$ = final displacement, ;; - $r_{0}$ = initial displacement, ;; - $v_{0}$ = initial velocity, ;; - $a$ = acceleration, ;; - $t$ = time. ;; ;; $r = r_{0} + v_{0} * t + \frac{at^2}{2}$ ;; ;; This rearranges to: ;; ;; $at^2 + 2v_{0}t + 2r_{0} - 2r = 0$ ;; ;; We can solve this using the Quadratic Equation, but this will yield ;; us two results. In general we can say that we are interested in the ;; result with the maximum value. ;; ;; In the next block of code you can see an example of call out to Java(Script). ;; Clojure doesn't have an in-built square root function, so we are calling out ;; to the Java(Script) version. A function named in the form `foo/bar` means ;; it will call the function `bar` in the namespace `foo`. You might ;; be wondering, what is a namespace?. ;; All good languages need a way to ;; bundle up code that is related, so that it can be reused and ;; accessed only when needed. Clojure's take on this is to provide ;; namespaces. Every Clojure source file will declare its namespace at ;; the top of the file so that other files can reference it, extract ;; values and use functions. Given that Clojure is a hosted language ;; its namespace will related to packages in Java and Google Closure ;; Library namespaces in Javascript. ;; When hosted on Java all of java.util.* is automatically imported ;; and on JavaScript assorted core and Google Closure Library modules ;; are imported. Both of these languages provide us with a Math ;; namespace which contains a `sqrt` function. ;; If you want to learn more about Clojure -> Java(Script) interop ;; then have a read [of this article](http://clojure-doc.org/articles/language/interop.html). (defn time-to-canvas [position velocity acceleration] (let [a acceleration b (* 2 velocity) c (* 2 position) discriminant (- (* b b) (* 4 a c)) minus-b (- 0 b) add-sqrt (/ (+ minus-b (Math/sqrt discriminant)) (* 2 a)) minus-sqrt (/ (- minus-b (Math/sqrt discriminant)) (* 2 a))] (max add-sqrt minus-sqrt))) ;; We can now calculate the time to impact but we want the final position and ;; velocity. For position we can use the same function that we ;; rearranged above to derive the time. (defn position-at [time initial-position initial-velocity acceleration] (+ initial-position (* initial-velocity time) (/ (* acceleration time time) 2))) ;; For velocity we can use another equation of motion: ;; ;; $v = at + v_{0}$ (defn velocity-at [time initial-velocity acceleration] (+ (* acceleration time) initial-velocity)) ;; These functions we just implemented can be joined up so that, given ;; an initial position and velocity we can return the final position and ;; velocity. This function doesn't explicitly ask for the acceleration ;; acting on the paint, it assumes only gravity is acting using the ;; constant defined earlier on. (defn project-point [position velocity] (let [[i j k] position [vi vj vk] velocity [ai aj ak] gravity time (time-to-canvas j vj aj) projected-position [(position-at time i vi ai) 0 ;; we don't need to calculate as it ;; should be 0, on the canvas (position-at time k vk ak)] projected-velocity [(velocity-at time vi ai) (velocity-at time vj aj) (velocity-at time vk ak)]] [projected-position projected-velocity])) ;; ## Paint splatter ;; An important aspect of Pollocks painting is the splatter of the ;; paint hitting the canvas and what this adds to the images. We are ;; going to add a simple splatter model based of the velocity at ;; impact we calculated in the last part. ;; Not all paint that hits the canvas will splatter, so we need to ;; work out the impact force of the paint and use this as a cutoff for ;; whether the paint should splatter. ;; We will work out the impact force of the paint by taking the ;; velocity at impact and calculating the force required to reduce ;; that velocity to 0 over a set impact distance. (def impact-distance 0.05) ;; We can now use the work-energy principle ;; (https://en.wikipedia.org/wiki/Work_(physics)#Work_and_energy) to ;; calculate the impact force. On one side of the equation we will ;; have the forces at play and the other the energy: ;; - $F_{i}$ = impact force, ;; - d = impact distance, ;; - m = mass, ;; - g = gravity, ;; - v = velocity at impact. ;; $-F_{i}d + mgd = 0 - \frac{1}{2}mv^2$ ;; This equation can be rearranged to: ;; $F_{i} = mg + \frac{mv^2}{2d}$ ;; For simplicity of code we are just going to consider the y axis as ;; this is the most important when it comes to working out the impact ;; force of the paint into the canvas. The above equation can ;; therefore be expressed as: (defn impact-force [mass velocity] (let [y-gravity (second gravity) y-velocity (second velocity)] (+ (* mass y-gravity) (/ (* mass y-velocity y-velocity) (* 2 impact-distance))))) ;; Based of this function to calculate the impact force we can define ;; a predicate that will tell us whether paint should splatter based ;; off its mass and velocity. It is idiomatic in Clojure to end ;; predicates with a `?`. We are going to add some randomness to this ;; function so that we don't necessarily just get a uniform line of ;; points. Also defined is a minimum force for us to consider whether ;; some paint could splatter. (def min-impact-force-for-splatter 30) (defn does-impact-splatter? [mass velocity] (and (> (impact-force mass velocity) min-impact-force-for-splatter) (> (rand) 0.8))) ;; If an impact splatters then we will need to bounce its velocity ;; vector as this is the direction it will leave its current position. ;; The equation to bounce a vector, $V$, off a plane with normal, $N$, is: ;; ;; - $N$ is the normal vector of the plane ;; - $V$ = the incoming vector ;; - $B$ is the outgoing, bounced, vector ;; ;; $B = V - (2 * (V.N) * N)$ ;; ;; You can find out a bit more about the derivation on this [Wolfram ;; page](http://mathworld.wolfram.com/Reflection.html). ;; We are missing a few of the required vector operations used in this ;; equation so we should define some more functions before trying to ;; implement it. The first is the vector dot product, this is defined ;; as the sum of the multiples of each dimension. Otherwise we need ;; subtraction of two vectors and a function to multiply a vector by ;; a constant. (defn dot-product [vector1 vector2] (reduce + (map * vector1 vector2))) (defn vector-subtraction [vector1 vector2] (map - vector1 vector2)) ;; This function will introduce a shorthand for defining functions ;; that is very useful in combination with functions like `map` and ;; `reduce`. Rather than writing `(fn [args...] body)` you can use ;; `#(body)` and if you want access to the arguments use `%n` where ;; `n` is the position of the argument. If you are only expecting one ;; argument then you can use just `%` on its own. (defn vector-multiply-by-constant [vector constant] (map #(* % constant) vector)) ;; Using the above functions we can now implement the vector bouncing ;; equation. I have pulled $(2 * (V.N) * N)$ out into a variable ;; called extreme for clarity. (defn bounce-vector [vector normal] (let [vector-dot-normal (dot-product vector normal) extreme (vector-multiply-by-constant normal (* 2 vector-dot-normal))] (vector-subtraction vector extreme))) ;; When an impact splatters it will only take a fraction of the ;; velocity, otherwise know as being an inelastic rather than elastic ;; collision. We can define a constant that will be ;; used to reduce the total velocity of the bounced vector to reflect ;; this elasticity. (def splatter-dampening-constant 0.7) (defn splatter-vector [velocity] (let [bounced-vector (bounce-vector velocity canvas-normal)] (vector-multiply-by-constant bounced-vector splatter-dampening-constant))) ;; ## Paths vs Points ;; All of the gestures Pollock makes are fluid paths, even if the ;; velocity along the path might be rather erratic. We now need to ;; work out how to generate a path of points that we can then use the ;; code we have written above to project and splatter. ;; A [Bezier curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) ;; is a commonly used curve for generating a smooth curve that can be ;; scaled indefinitely allowing us to have as many points along our ;; path as we care to calculate. ;; Bezier curves are defined by an list of control points, so we need ;; to be able to generate a potential unbounded list of random control ;; points that should give use limitless different paths to paint with. ;; In order to generate a list of control points we will need to be ;; able to: ;; - get a random number between two points for distance and steps, ;; - get a random unit vector for the initial direction of the generation, ;; - add vectors together to move between our control points. (defn random-between [lower-bound upper-bound] (+ lower-bound (rand (- upper-bound lower-bound)))) ;; Below is an algorithm that will give well distributed random unit ;; vectors. It was ported from code found [in GameDev the ;; forums](http://www.gamedev.net/topic/499972-generate-a-random-unit-vector/#entry4261773). (defn random-unit-vector [] (let [asimuth (* (rand) 2 Math/PI) k (- (rand 2) 1) a (Math/sqrt (- 1 (* k k))) i (* (Math/cos asimuth) a) j (* (Math/sin asimuth) a)] [i j k])) (defn vector-add [vector1 vector2] (map + vector1 vector2)) ;; Now that we have a random direction in which to move we need to ;; generate an unbounded path that will move in that direction, but ;; randomise the position of each point within provided bounds. ;; Firstly, we can define a function that will generate a random ;; vector inside of lower and upper bounds that can be combined with ;; the non-randomised position to provide a randomised path. (defn random-vector-between [lower upper] [(random-between lower upper) (random-between lower upper) (random-between lower upper)]) ;; In order to provide an unbounded path we can use a lazy sequence. ;; This function returns a value that is somewhat akin to list that ;; never ends. Every time you try to look at the next value in the list ;; it will generate one just in time for you to see no end. ;; In this function the first value returned should always be the ;; initial starting position, each following value should be a step ;; along the path. You can see this below, it returns the position ;; argument cons'd with another iteration of random-path with the ;; position randomised. (defn random-path [position step-vector bounds] (cons position (lazy-seq (random-path (vector-add (vector-add position step-vector) (random-vector-between (- 0 bounds) bounds)) step-vector bounds)))) ;; We can now use this random-path lazy sequence to generate a list of ;; control points given an initial starting point and some bounding ;; variables. The distance, step and variation allow us to request long ;; winding paths or short flicks. (defn control-points [position min-distance max-distance min-steps max-steps variation] (let [direction (random-unit-vector) distance (random-between min-distance max-distance) steps (random-between min-steps max-steps) step-vector (vector-multiply-by-constant direction (/ distance steps)) random-positions (take steps (random-path position step-vector variation)) end-position (vector-add position (vector-multiply-by-constant step-vector steps))] (conj (vec random-positions) end-position))) ;; In order to turn this list of control points into a list of points ;; that represent a path we need an algorithm. The most commonly used ;; is a recursive algorithm proved by De Casteljau. There is a [great ;; video on YouTube](https://www.youtube.com/watch?v=YATikPP2q70) ;; explaining this algorithm that I recommend you watch. ;; At the core of the algorithm is an equation that will return a ;; point along a line weighted by a variable, $t$ which dictates how ;; close it is to each end of the line: ;; $P = (1 - t)P_{0} + tP_{1}$ ;; For example, if a line runs ;; from $P_{0}$ to $P_{1}$ and $t$ is 0 then the outputted point with ;; be equal to $P_{0}$ and if it is 1 then $P_{1}$. ;; De Casteljau's algorithm recursively creates a new set of points by ;; using the above equation for a fixed $t$ against all the lines ;; created by the control points. It does this until there is just a ;; single point, this is a point on the bezier curve. It $t$ from 0 to ;; 1 and for each step gets a point along the curve. (defn recur-relation [t a b] (+ (* t b) (* a (- 1 t)))) (defn for-component [t component-vals] (if (= (count component-vals) 1) (first component-vals) (for-component t (map #(recur-relation t %1 %2) component-vals (rest component-vals))))) (defn for-t [t components] (map #(for-component t %) components)) (defn de-casteljau [control-points step-amount] (let [x-vals (map first control-points) y-vals (map second control-points) z-vals (map #(nth % 2) control-points) points (map #(for-t % [x-vals y-vals z-vals]) (range 0 1 step-amount))] points)) ;; This can generate paths that go below the canvas, we should set ;; these to 0 as it is the equivalent of painting on the canvas (defn ensure-above-canvas [path] (map (fn [[i j k]] [i (if (< j 0) 0 j) k]) path)) ;; ## Motion, going through the paces ;; All the points along the generated path should have an associated ;; velocity. To start with we can generate a linear velocity along the ;; path, given a randomised total time to traverse the path and the ;; total length of the path. ;; In order to calculate the length of the paths, we will want to do ;; something similar to a map but with pairs of values. Using this we ;; can take two points, calculate the distance between them and then ;; sum all the distances (defn map-2 [f coll] (when-let [s (seq coll)] (let [s1 (first s) s2 (second s)] (if (not (nil? s2)) (cons (f (first s) (second s)) (map-2 f (rest s))))))) ;; in order to find the distance between two points we need subtract ;; the two vectors, square and sum the resultant dimensions and then ;; take the root. (https://en.wikipedia.org/wiki/Euclidean_distance) (defn vector-multiply [vector1 vector2] (map * vector1 vector2)) (defn distance-between-points [point1 point2] (let [difference-vector (vector-subtraction point1 point2) summed-vector (reduce + (vector-multiply difference-vector difference-vector))] (Math/sqrt summed-vector))) (defn path-length [path] (reduce + (map-2 distance-between-points path))) (defn vector-divide-by-const [vector const] (map #(/ % const) vector)) (defn velocity-between [point1 point2 total-time total-distance] (let [difference-vector (vector-subtraction point1 point2) time-between (* total-time (/ (distance-between-points point1 point2) total-distance))] (vector-divide-by-const difference-vector time-between))) ;; This calculation will leave off the last points velocity, we can just set it to 0 (defn path-velocities [path total-time] (let [total-distance (path-length path) number-of-points (count path)] (conj (vec (map-2 #(velocity-between %1 %2 total-time total-distance) path)) [0 0 0]))) ;; As well as the velocity at each point along the path, we also need ;; how much paint there is falling. Again to keep life simple we are ;; going to model this as a linear flow along the path with there ;; always being no paint left. (defn path-masses [path initial-mass] (let [number-of-points (count path) step (- 0 (/ initial-mass number-of-points))] (take number-of-points (range initial-mass 0 step)))) ;; ## Putting it all together ;; I've pulled a bunch of colours that Pollock used in his seminal ;; work "Number 8" so that each flick of paint can be rendered in a ;; random colour out of this palette (def canvas-colour [142 141 93]) (def paint-colours [[232 51 1] [248 179 10] [247 239 189] [29 16 8]]) (defn pick-a-colour [] (nth paint-colours (rand-int (count paint-colours)))) ;; Now we need to assemble all of the above functions into something ;; the resembles Jackson Pollock applying paint to a canvas. We start ;; with a point, project a path, work out masses and velocities, ;; project and then splatter. This is all then packaged up with a ;; colour for drawing onto our canvas. (defn fling-paint [] (let [position (starting-point) total-time (random-between 1 5) path (ensure-above-canvas (de-casteljau (control-points position 0.1 2 3 15 0.4) 0.01)) velocities (path-velocities path total-time) masses (path-masses path (random-between 0.1 1)) projected-path (map #(project-point %1 %2) path velocities) splatter (map (fn [[position velocity] mass] (if (does-impact-splatter? mass velocity) [position (splatter-vector velocity) (* mass splatter-dampening-constant)] nil)) projected-path masses) projected-splatter (map (fn [[position velocity mass :as point]] (if (nil? point) nil (conj (vec (project-point position velocity)) mass))) splatter)] {:colour (pick-a-colour) :air-path path :canvas-path (map #(conj %1 %2) projected-path masses) :splatter (filter #(not-any? nil? %) (partition-by nil? projected-splatter))})) ;; ## Rendering the canvas ;; We need to know the available size for the outputted image to fit ;; in. To work this out we are going to have to interface with ;; JavaScript directly. Luckily ClojureScript makes this very easy ;; using the `js` namespace. (def image-width (.-clientWidth (.querySelector js/document "#pollock"))) ;; Now we have the width of the image we can use the dimensions of the ;; space to work out the pixel size of the image and how to convert ;; between metres and pixels. (def pixels-in-a-metre (let [[width _ _] space] (/ image-width width))) (defn metres-to-pixels [metres] (Math/floor (* metres pixels-in-a-metre))) ;; We can now use this function to work out the size the sketch should ;; be and how to convert a position in metres over to a position to be ;; drawn in the image. (def sketch-size (let [[width _ height] space] [(metres-to-pixels width) (metres-to-pixels height)])) (defn position-to-pixel [[i j k]] [(metres-to-pixels i) (metres-to-pixels k)]) ;; Now the dimensions of the image our calculated we can use Quil to ;; define the sketch that we will draw into. We also need to define a ;; function that will initialise the image into the state we want it. ;; This function will be run when the sketch is defined. (defn setup-image [] (apply q/background canvas-colour) (q/fill 0)) (q/defsketch pollock :setup setup-image :host "pollock" ;; the id of the <canvas> element :size sketch-size) ;; To draw the trails of paint across the canvas we need draw a path ;; following the defined positions, which takes into account the ;; amount of paint at each position and uses this to set with width of ;; the path. In order to do this cleanly in Quil we need to consider ;; the path as pairs of positions that we shall draw paths between ;; using the initial paint amount as the stroke-weight. This allows ;; for a smooth decrease in the width of the path. (defn mass-to-weight [mass] (* 50 mass)) (defn draw-path [path] (doall (map-2 (fn [[position1 _ mass] [position2 _ _]] (q/stroke-weight (mass-to-weight mass)) (apply q/line (concat (position-to-pixel position1) (position-to-pixel position2)))) path))) ;; For splatter we are just going to draw a point that has a stroke-weight ;; proportional to the amount of paint. (defn draw-splats [path] (doall (map (fn [[position _ mass]] (q/stroke-weight (mass-to-weight mass)) (apply q/point (position-to-pixel position))) path))) ;; Now that we can render the result of flinging some paint around we ;; need a function that will fling the paint and render the result. (defn fling-and-render [& any] (q/with-sketch (q/get-sketch-by-id "pollock") (let [{:keys [colour canvas-path splatter]} (fling-paint)] (q/stroke (apply q/color colour)) (draw-path canvas-path) (doall (map draw-splats splatter))))) ;; Lastly, we shall attach to the buttons and cause our image to come ;; to life. (.addEventListener (.querySelector js/document "#add") "click" fling-and-render) (def interval-ref (atom nil)) (def fill-count (atom 0)) (.addEventListener (.querySelector js/document "#fill") "click" (fn [e] (reset! interval-ref (js/setInterval (fn [] (if (> @fill-count 500) (js/clearInterval @interval-ref) (do (fling-and-render) (swap! fill-count inc)))) 100))))
108482
(ns uk.co.tombooth.pollock (:require [quil.core :as q :include-macros true])) ;; --- ;; title: Painting in Clojure ;; ... ;; Learning Clojure by building a digital Jackson Pollock. This ;; article and the source code backing it can be [found on ;; GitHub](https://www.github.com/tombooth/painting-in-clojure). ;; Below is an example of what we will be building, running the code ;; found in this page. ;; <canvas id="pollock" style="width: 100%; border: 5px solid #eee"></canvas> ;; <button id="add">Add stroke</button> ;; <button id="fill">Fill canvas</button> ;; ## <NAME> ;; He was an abstract artist who lived through the first half of the ;; 20th century and is most famous for his drip paintings. This style ;; of painting involves him using sticks brushes, sticks and cans to ;; apply paint to the canvas with the motion of his gestures causing ;; the artworks to come alive. You can get a good idea of how this ;; comes together from [this youtube video](https://www.youtube.com/watch?v=7bICqvmKL5s). ;; ## Setting the scene ;; We want to define some facts about the space that our digital ;; Pollock will work in. These facts will not change over the ;; execution of our model and fit Clojure's preference for ;; immutability perfectly. For those who have not come across the idea ;; of mutability before it is simply whether something can be changed ;; in place. In most languages if you set the label `some_number` to ;; equal `5`, further on you can increment the value of `some_number` to ;; `6` or even `7`. In Clojure if you tried to increment `some_number` ;; you would get a new value rather than changing `some_number`. ;; Clojure will let us define facts using one of the following value types: ;; ;; - A number. This could be `5` an integer, `3/2` a ratio/fraction ;; or `3.14` a floating point number; ;; - A string, represented as a sequence of characters, for example ;; `"Hello world!"`; ;; - A keyword, which are very similar to strings in appearance ;; except they are preceded by a colon e.g. `:an-identifier`. As ;; alluded to in the example they are usually used for identifiers or ;; labels and do not allow spaces. ;; - A list `(...)`, this is a way of grouping values into a ;; collection with an explicit order. You may notice all of ;; the code written takes for ;; form of lists. By default if you have written `(...)` Clojure ;; will assume the first item is a function and the rest are ;; arguments to be passed in. In order for the list not to be ;; executed you should prefix it with a `'`; ;; - A vector `[...]`, which is a lot like a list except that they are optimised for ;; appending to the end of the sequence rather than to the front; ;; - A set `#{...}`. If you are not particularly bothered by the order of ;; the values stored in your collection then you can use a set; ;; - Lastly there are maps `{...}`, these store pairs of values ;; where the first is a key and the second is a value. ;; If you would like to learn more about the basic types in Clojure, I ;; suggest you read [this great blog ;; post](http://aphyr.com/posts/302-clojure-from-the-ground-up-basic-types) ;; by Aphyr. ;; The most important fact about the space is its size. We will use ;; metres to measure the size only converting to pixels when we need ;; to draw to the screen. We are going to define size as a vector ;; containing its width, height and depth. (def space [8 ;; width 5 ;; height 6]) ;; depth ;; We need to know the gravity of the space so it can influence the ;; flow of paint as it leaves the brush. This will be defined as a ;; vector that represents acceleration influenced by gravity. (def gravity [0 -9.8 0]) ;; Lastly, we need to know the normal of the surface of the canvas that ;; the paint will impact with. This will be used to dictate how paint ;; acts when it spatters from the impact with the canvas. (def canvas-normal [0 1 0]) ;; ## Starting points and projection ;; Our digital Pollock is going to start a stroke of the brush by ;; picking a random point in space. This point will then be projected ;; to find where it impacts with the canvas. ;; In order to generate a random point inside of the space we need to ;; define a function that each time it is called will emit a vector ;; containing the position of the point. Function values can be ;; created by calling `(fn [...] ...)` with the first vector being the ;; arguments the function should receive and any follow items in the ;; list are the body of the function and executed with the arguments ;; bound. Rather than calling `(def name (fn ...))` Clojure has provided a ;; shortcut function `(defn name [...] ...)`. An example of a defined ;; function is `(defn say-hello [name] (str "Hello " name))`, this ;; creates a function called say-hello that when called `(say-hello ;; "<NAME>")` it will return the string "Hello <NAME>". ;; We are going to cover a common functional idiom when dealing with ;; lists to change the dimensions of the space above into a random ;; point inside that space. To do this we want to iterate over each ;; dimension of the size of space, generate a random number between 0 ;; and the magnitude of each dimension and then return the resultant ;; list of random numbers as a list. To generate a random number in ;; Clojure we can use the `(rand)` function, which will return a ;; random number between 0 (inclusive) and 1 (exclusive). The rand ;; function can take an optional parameter `(rand 100), this will ;; define the bounds of the number generated to 0 and 100. ;; The function map `(map [fn] [sequence])` will iterate through the ;; sequence executing the function with the current value of the ;; sequence as its first parameter, the values returned from the ;; function will be stored in a list the same length as the sequence ;; and returned by the function. ;; We can now define a random point inside of space as follows (defn starting-point [] (map rand space)) ;; Now that we can generate a random point in space we want to project ;; this to the canvas. We are going to use [Newtonian equations of ;; motion](https://en.wikipedia.org/wiki/Equations_of_motion), ;; we know the position, velocity and acceleration of the ;; point and we want to know what the position and velocity are when y ;; is 0. In order to work out final positions we need to know the ;; total time the point spent falling, we can do this using the y ;; position as we know that the final position should be 0. ;; To work out the time it takes for the point to reach the canvas we ;; will solve the following equation for t: ;; ;; - $r$ = final displacement, ;; - $r_{0}$ = initial displacement, ;; - $v_{0}$ = initial velocity, ;; - $a$ = acceleration, ;; - $t$ = time. ;; ;; $r = r_{0} + v_{0} * t + \frac{at^2}{2}$ ;; ;; This rearranges to: ;; ;; $at^2 + 2v_{0}t + 2r_{0} - 2r = 0$ ;; ;; We can solve this using the Quadratic Equation, but this will yield ;; us two results. In general we can say that we are interested in the ;; result with the maximum value. ;; ;; In the next block of code you can see an example of call out to Java(Script). ;; Clojure doesn't have an in-built square root function, so we are calling out ;; to the Java(Script) version. A function named in the form `foo/bar` means ;; it will call the function `bar` in the namespace `foo`. You might ;; be wondering, what is a namespace?. ;; All good languages need a way to ;; bundle up code that is related, so that it can be reused and ;; accessed only when needed. Clojure's take on this is to provide ;; namespaces. Every Clojure source file will declare its namespace at ;; the top of the file so that other files can reference it, extract ;; values and use functions. Given that Clojure is a hosted language ;; its namespace will related to packages in Java and Google Closure ;; Library namespaces in Javascript. ;; When hosted on Java all of java.util.* is automatically imported ;; and on JavaScript assorted core and Google Closure Library modules ;; are imported. Both of these languages provide us with a Math ;; namespace which contains a `sqrt` function. ;; If you want to learn more about Clojure -> Java(Script) interop ;; then have a read [of this article](http://clojure-doc.org/articles/language/interop.html). (defn time-to-canvas [position velocity acceleration] (let [a acceleration b (* 2 velocity) c (* 2 position) discriminant (- (* b b) (* 4 a c)) minus-b (- 0 b) add-sqrt (/ (+ minus-b (Math/sqrt discriminant)) (* 2 a)) minus-sqrt (/ (- minus-b (Math/sqrt discriminant)) (* 2 a))] (max add-sqrt minus-sqrt))) ;; We can now calculate the time to impact but we want the final position and ;; velocity. For position we can use the same function that we ;; rearranged above to derive the time. (defn position-at [time initial-position initial-velocity acceleration] (+ initial-position (* initial-velocity time) (/ (* acceleration time time) 2))) ;; For velocity we can use another equation of motion: ;; ;; $v = at + v_{0}$ (defn velocity-at [time initial-velocity acceleration] (+ (* acceleration time) initial-velocity)) ;; These functions we just implemented can be joined up so that, given ;; an initial position and velocity we can return the final position and ;; velocity. This function doesn't explicitly ask for the acceleration ;; acting on the paint, it assumes only gravity is acting using the ;; constant defined earlier on. (defn project-point [position velocity] (let [[i j k] position [vi vj vk] velocity [ai aj ak] gravity time (time-to-canvas j vj aj) projected-position [(position-at time i vi ai) 0 ;; we don't need to calculate as it ;; should be 0, on the canvas (position-at time k vk ak)] projected-velocity [(velocity-at time vi ai) (velocity-at time vj aj) (velocity-at time vk ak)]] [projected-position projected-velocity])) ;; ## Paint splatter ;; An important aspect of Pollocks painting is the splatter of the ;; paint hitting the canvas and what this adds to the images. We are ;; going to add a simple splatter model based of the velocity at ;; impact we calculated in the last part. ;; Not all paint that hits the canvas will splatter, so we need to ;; work out the impact force of the paint and use this as a cutoff for ;; whether the paint should splatter. ;; We will work out the impact force of the paint by taking the ;; velocity at impact and calculating the force required to reduce ;; that velocity to 0 over a set impact distance. (def impact-distance 0.05) ;; We can now use the work-energy principle ;; (https://en.wikipedia.org/wiki/Work_(physics)#Work_and_energy) to ;; calculate the impact force. On one side of the equation we will ;; have the forces at play and the other the energy: ;; - $F_{i}$ = impact force, ;; - d = impact distance, ;; - m = mass, ;; - g = gravity, ;; - v = velocity at impact. ;; $-F_{i}d + mgd = 0 - \frac{1}{2}mv^2$ ;; This equation can be rearranged to: ;; $F_{i} = mg + \frac{mv^2}{2d}$ ;; For simplicity of code we are just going to consider the y axis as ;; this is the most important when it comes to working out the impact ;; force of the paint into the canvas. The above equation can ;; therefore be expressed as: (defn impact-force [mass velocity] (let [y-gravity (second gravity) y-velocity (second velocity)] (+ (* mass y-gravity) (/ (* mass y-velocity y-velocity) (* 2 impact-distance))))) ;; Based of this function to calculate the impact force we can define ;; a predicate that will tell us whether paint should splatter based ;; off its mass and velocity. It is idiomatic in Clojure to end ;; predicates with a `?`. We are going to add some randomness to this ;; function so that we don't necessarily just get a uniform line of ;; points. Also defined is a minimum force for us to consider whether ;; some paint could splatter. (def min-impact-force-for-splatter 30) (defn does-impact-splatter? [mass velocity] (and (> (impact-force mass velocity) min-impact-force-for-splatter) (> (rand) 0.8))) ;; If an impact splatters then we will need to bounce its velocity ;; vector as this is the direction it will leave its current position. ;; The equation to bounce a vector, $V$, off a plane with normal, $N$, is: ;; ;; - $N$ is the normal vector of the plane ;; - $V$ = the incoming vector ;; - $B$ is the outgoing, bounced, vector ;; ;; $B = V - (2 * (V.N) * N)$ ;; ;; You can find out a bit more about the derivation on this [Wolfram ;; page](http://mathworld.wolfram.com/Reflection.html). ;; We are missing a few of the required vector operations used in this ;; equation so we should define some more functions before trying to ;; implement it. The first is the vector dot product, this is defined ;; as the sum of the multiples of each dimension. Otherwise we need ;; subtraction of two vectors and a function to multiply a vector by ;; a constant. (defn dot-product [vector1 vector2] (reduce + (map * vector1 vector2))) (defn vector-subtraction [vector1 vector2] (map - vector1 vector2)) ;; This function will introduce a shorthand for defining functions ;; that is very useful in combination with functions like `map` and ;; `reduce`. Rather than writing `(fn [args...] body)` you can use ;; `#(body)` and if you want access to the arguments use `%n` where ;; `n` is the position of the argument. If you are only expecting one ;; argument then you can use just `%` on its own. (defn vector-multiply-by-constant [vector constant] (map #(* % constant) vector)) ;; Using the above functions we can now implement the vector bouncing ;; equation. I have pulled $(2 * (V.N) * N)$ out into a variable ;; called extreme for clarity. (defn bounce-vector [vector normal] (let [vector-dot-normal (dot-product vector normal) extreme (vector-multiply-by-constant normal (* 2 vector-dot-normal))] (vector-subtraction vector extreme))) ;; When an impact splatters it will only take a fraction of the ;; velocity, otherwise know as being an inelastic rather than elastic ;; collision. We can define a constant that will be ;; used to reduce the total velocity of the bounced vector to reflect ;; this elasticity. (def splatter-dampening-constant 0.7) (defn splatter-vector [velocity] (let [bounced-vector (bounce-vector velocity canvas-normal)] (vector-multiply-by-constant bounced-vector splatter-dampening-constant))) ;; ## Paths vs Points ;; All of the gestures Pollock makes are fluid paths, even if the ;; velocity along the path might be rather erratic. We now need to ;; work out how to generate a path of points that we can then use the ;; code we have written above to project and splatter. ;; A [Bezier curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) ;; is a commonly used curve for generating a smooth curve that can be ;; scaled indefinitely allowing us to have as many points along our ;; path as we care to calculate. ;; Bezier curves are defined by an list of control points, so we need ;; to be able to generate a potential unbounded list of random control ;; points that should give use limitless different paths to paint with. ;; In order to generate a list of control points we will need to be ;; able to: ;; - get a random number between two points for distance and steps, ;; - get a random unit vector for the initial direction of the generation, ;; - add vectors together to move between our control points. (defn random-between [lower-bound upper-bound] (+ lower-bound (rand (- upper-bound lower-bound)))) ;; Below is an algorithm that will give well distributed random unit ;; vectors. It was ported from code found [in GameDev the ;; forums](http://www.gamedev.net/topic/499972-generate-a-random-unit-vector/#entry4261773). (defn random-unit-vector [] (let [asimuth (* (rand) 2 Math/PI) k (- (rand 2) 1) a (Math/sqrt (- 1 (* k k))) i (* (Math/cos asimuth) a) j (* (Math/sin asimuth) a)] [i j k])) (defn vector-add [vector1 vector2] (map + vector1 vector2)) ;; Now that we have a random direction in which to move we need to ;; generate an unbounded path that will move in that direction, but ;; randomise the position of each point within provided bounds. ;; Firstly, we can define a function that will generate a random ;; vector inside of lower and upper bounds that can be combined with ;; the non-randomised position to provide a randomised path. (defn random-vector-between [lower upper] [(random-between lower upper) (random-between lower upper) (random-between lower upper)]) ;; In order to provide an unbounded path we can use a lazy sequence. ;; This function returns a value that is somewhat akin to list that ;; never ends. Every time you try to look at the next value in the list ;; it will generate one just in time for you to see no end. ;; In this function the first value returned should always be the ;; initial starting position, each following value should be a step ;; along the path. You can see this below, it returns the position ;; argument cons'd with another iteration of random-path with the ;; position randomised. (defn random-path [position step-vector bounds] (cons position (lazy-seq (random-path (vector-add (vector-add position step-vector) (random-vector-between (- 0 bounds) bounds)) step-vector bounds)))) ;; We can now use this random-path lazy sequence to generate a list of ;; control points given an initial starting point and some bounding ;; variables. The distance, step and variation allow us to request long ;; winding paths or short flicks. (defn control-points [position min-distance max-distance min-steps max-steps variation] (let [direction (random-unit-vector) distance (random-between min-distance max-distance) steps (random-between min-steps max-steps) step-vector (vector-multiply-by-constant direction (/ distance steps)) random-positions (take steps (random-path position step-vector variation)) end-position (vector-add position (vector-multiply-by-constant step-vector steps))] (conj (vec random-positions) end-position))) ;; In order to turn this list of control points into a list of points ;; that represent a path we need an algorithm. The most commonly used ;; is a recursive algorithm proved by De Casteljau. There is a [great ;; video on YouTube](https://www.youtube.com/watch?v=YATikPP2q70) ;; explaining this algorithm that I recommend you watch. ;; At the core of the algorithm is an equation that will return a ;; point along a line weighted by a variable, $t$ which dictates how ;; close it is to each end of the line: ;; $P = (1 - t)P_{0} + tP_{1}$ ;; For example, if a line runs ;; from $P_{0}$ to $P_{1}$ and $t$ is 0 then the outputted point with ;; be equal to $P_{0}$ and if it is 1 then $P_{1}$. ;; De Casteljau's algorithm recursively creates a new set of points by ;; using the above equation for a fixed $t$ against all the lines ;; created by the control points. It does this until there is just a ;; single point, this is a point on the bezier curve. It $t$ from 0 to ;; 1 and for each step gets a point along the curve. (defn recur-relation [t a b] (+ (* t b) (* a (- 1 t)))) (defn for-component [t component-vals] (if (= (count component-vals) 1) (first component-vals) (for-component t (map #(recur-relation t %1 %2) component-vals (rest component-vals))))) (defn for-t [t components] (map #(for-component t %) components)) (defn de-casteljau [control-points step-amount] (let [x-vals (map first control-points) y-vals (map second control-points) z-vals (map #(nth % 2) control-points) points (map #(for-t % [x-vals y-vals z-vals]) (range 0 1 step-amount))] points)) ;; This can generate paths that go below the canvas, we should set ;; these to 0 as it is the equivalent of painting on the canvas (defn ensure-above-canvas [path] (map (fn [[i j k]] [i (if (< j 0) 0 j) k]) path)) ;; ## Motion, going through the paces ;; All the points along the generated path should have an associated ;; velocity. To start with we can generate a linear velocity along the ;; path, given a randomised total time to traverse the path and the ;; total length of the path. ;; In order to calculate the length of the paths, we will want to do ;; something similar to a map but with pairs of values. Using this we ;; can take two points, calculate the distance between them and then ;; sum all the distances (defn map-2 [f coll] (when-let [s (seq coll)] (let [s1 (first s) s2 (second s)] (if (not (nil? s2)) (cons (f (first s) (second s)) (map-2 f (rest s))))))) ;; in order to find the distance between two points we need subtract ;; the two vectors, square and sum the resultant dimensions and then ;; take the root. (https://en.wikipedia.org/wiki/Euclidean_distance) (defn vector-multiply [vector1 vector2] (map * vector1 vector2)) (defn distance-between-points [point1 point2] (let [difference-vector (vector-subtraction point1 point2) summed-vector (reduce + (vector-multiply difference-vector difference-vector))] (Math/sqrt summed-vector))) (defn path-length [path] (reduce + (map-2 distance-between-points path))) (defn vector-divide-by-const [vector const] (map #(/ % const) vector)) (defn velocity-between [point1 point2 total-time total-distance] (let [difference-vector (vector-subtraction point1 point2) time-between (* total-time (/ (distance-between-points point1 point2) total-distance))] (vector-divide-by-const difference-vector time-between))) ;; This calculation will leave off the last points velocity, we can just set it to 0 (defn path-velocities [path total-time] (let [total-distance (path-length path) number-of-points (count path)] (conj (vec (map-2 #(velocity-between %1 %2 total-time total-distance) path)) [0 0 0]))) ;; As well as the velocity at each point along the path, we also need ;; how much paint there is falling. Again to keep life simple we are ;; going to model this as a linear flow along the path with there ;; always being no paint left. (defn path-masses [path initial-mass] (let [number-of-points (count path) step (- 0 (/ initial-mass number-of-points))] (take number-of-points (range initial-mass 0 step)))) ;; ## Putting it all together ;; I've pulled a bunch of colours that <NAME> used in his seminal ;; work "Number 8" so that each flick of paint can be rendered in a ;; random colour out of this palette (def canvas-colour [142 141 93]) (def paint-colours [[232 51 1] [248 179 10] [247 239 189] [29 16 8]]) (defn pick-a-colour [] (nth paint-colours (rand-int (count paint-colours)))) ;; Now we need to assemble all of the above functions into something ;; the resembles <NAME> applying paint to a canvas. We start ;; with a point, project a path, work out masses and velocities, ;; project and then splatter. This is all then packaged up with a ;; colour for drawing onto our canvas. (defn fling-paint [] (let [position (starting-point) total-time (random-between 1 5) path (ensure-above-canvas (de-casteljau (control-points position 0.1 2 3 15 0.4) 0.01)) velocities (path-velocities path total-time) masses (path-masses path (random-between 0.1 1)) projected-path (map #(project-point %1 %2) path velocities) splatter (map (fn [[position velocity] mass] (if (does-impact-splatter? mass velocity) [position (splatter-vector velocity) (* mass splatter-dampening-constant)] nil)) projected-path masses) projected-splatter (map (fn [[position velocity mass :as point]] (if (nil? point) nil (conj (vec (project-point position velocity)) mass))) splatter)] {:colour (pick-a-colour) :air-path path :canvas-path (map #(conj %1 %2) projected-path masses) :splatter (filter #(not-any? nil? %) (partition-by nil? projected-splatter))})) ;; ## Rendering the canvas ;; We need to know the available size for the outputted image to fit ;; in. To work this out we are going to have to interface with ;; JavaScript directly. Luckily ClojureScript makes this very easy ;; using the `js` namespace. (def image-width (.-clientWidth (.querySelector js/document "#pollock"))) ;; Now we have the width of the image we can use the dimensions of the ;; space to work out the pixel size of the image and how to convert ;; between metres and pixels. (def pixels-in-a-metre (let [[width _ _] space] (/ image-width width))) (defn metres-to-pixels [metres] (Math/floor (* metres pixels-in-a-metre))) ;; We can now use this function to work out the size the sketch should ;; be and how to convert a position in metres over to a position to be ;; drawn in the image. (def sketch-size (let [[width _ height] space] [(metres-to-pixels width) (metres-to-pixels height)])) (defn position-to-pixel [[i j k]] [(metres-to-pixels i) (metres-to-pixels k)]) ;; Now the dimensions of the image our calculated we can use Quil to ;; define the sketch that we will draw into. We also need to define a ;; function that will initialise the image into the state we want it. ;; This function will be run when the sketch is defined. (defn setup-image [] (apply q/background canvas-colour) (q/fill 0)) (q/defsketch pollock :setup setup-image :host "pollock" ;; the id of the <canvas> element :size sketch-size) ;; To draw the trails of paint across the canvas we need draw a path ;; following the defined positions, which takes into account the ;; amount of paint at each position and uses this to set with width of ;; the path. In order to do this cleanly in Quil we need to consider ;; the path as pairs of positions that we shall draw paths between ;; using the initial paint amount as the stroke-weight. This allows ;; for a smooth decrease in the width of the path. (defn mass-to-weight [mass] (* 50 mass)) (defn draw-path [path] (doall (map-2 (fn [[position1 _ mass] [position2 _ _]] (q/stroke-weight (mass-to-weight mass)) (apply q/line (concat (position-to-pixel position1) (position-to-pixel position2)))) path))) ;; For splatter we are just going to draw a point that has a stroke-weight ;; proportional to the amount of paint. (defn draw-splats [path] (doall (map (fn [[position _ mass]] (q/stroke-weight (mass-to-weight mass)) (apply q/point (position-to-pixel position))) path))) ;; Now that we can render the result of flinging some paint around we ;; need a function that will fling the paint and render the result. (defn fling-and-render [& any] (q/with-sketch (q/get-sketch-by-id "pollock") (let [{:keys [colour canvas-path splatter]} (fling-paint)] (q/stroke (apply q/color colour)) (draw-path canvas-path) (doall (map draw-splats splatter))))) ;; Lastly, we shall attach to the buttons and cause our image to come ;; to life. (.addEventListener (.querySelector js/document "#add") "click" fling-and-render) (def interval-ref (atom nil)) (def fill-count (atom 0)) (.addEventListener (.querySelector js/document "#fill") "click" (fn [e] (reset! interval-ref (js/setInterval (fn [] (if (> @fill-count 500) (js/clearInterval @interval-ref) (do (fling-and-render) (swap! fill-count inc)))) 100))))
true
(ns uk.co.tombooth.pollock (:require [quil.core :as q :include-macros true])) ;; --- ;; title: Painting in Clojure ;; ... ;; Learning Clojure by building a digital Jackson Pollock. This ;; article and the source code backing it can be [found on ;; GitHub](https://www.github.com/tombooth/painting-in-clojure). ;; Below is an example of what we will be building, running the code ;; found in this page. ;; <canvas id="pollock" style="width: 100%; border: 5px solid #eee"></canvas> ;; <button id="add">Add stroke</button> ;; <button id="fill">Fill canvas</button> ;; ## PI:NAME:<NAME>END_PI ;; He was an abstract artist who lived through the first half of the ;; 20th century and is most famous for his drip paintings. This style ;; of painting involves him using sticks brushes, sticks and cans to ;; apply paint to the canvas with the motion of his gestures causing ;; the artworks to come alive. You can get a good idea of how this ;; comes together from [this youtube video](https://www.youtube.com/watch?v=7bICqvmKL5s). ;; ## Setting the scene ;; We want to define some facts about the space that our digital ;; Pollock will work in. These facts will not change over the ;; execution of our model and fit Clojure's preference for ;; immutability perfectly. For those who have not come across the idea ;; of mutability before it is simply whether something can be changed ;; in place. In most languages if you set the label `some_number` to ;; equal `5`, further on you can increment the value of `some_number` to ;; `6` or even `7`. In Clojure if you tried to increment `some_number` ;; you would get a new value rather than changing `some_number`. ;; Clojure will let us define facts using one of the following value types: ;; ;; - A number. This could be `5` an integer, `3/2` a ratio/fraction ;; or `3.14` a floating point number; ;; - A string, represented as a sequence of characters, for example ;; `"Hello world!"`; ;; - A keyword, which are very similar to strings in appearance ;; except they are preceded by a colon e.g. `:an-identifier`. As ;; alluded to in the example they are usually used for identifiers or ;; labels and do not allow spaces. ;; - A list `(...)`, this is a way of grouping values into a ;; collection with an explicit order. You may notice all of ;; the code written takes for ;; form of lists. By default if you have written `(...)` Clojure ;; will assume the first item is a function and the rest are ;; arguments to be passed in. In order for the list not to be ;; executed you should prefix it with a `'`; ;; - A vector `[...]`, which is a lot like a list except that they are optimised for ;; appending to the end of the sequence rather than to the front; ;; - A set `#{...}`. If you are not particularly bothered by the order of ;; the values stored in your collection then you can use a set; ;; - Lastly there are maps `{...}`, these store pairs of values ;; where the first is a key and the second is a value. ;; If you would like to learn more about the basic types in Clojure, I ;; suggest you read [this great blog ;; post](http://aphyr.com/posts/302-clojure-from-the-ground-up-basic-types) ;; by Aphyr. ;; The most important fact about the space is its size. We will use ;; metres to measure the size only converting to pixels when we need ;; to draw to the screen. We are going to define size as a vector ;; containing its width, height and depth. (def space [8 ;; width 5 ;; height 6]) ;; depth ;; We need to know the gravity of the space so it can influence the ;; flow of paint as it leaves the brush. This will be defined as a ;; vector that represents acceleration influenced by gravity. (def gravity [0 -9.8 0]) ;; Lastly, we need to know the normal of the surface of the canvas that ;; the paint will impact with. This will be used to dictate how paint ;; acts when it spatters from the impact with the canvas. (def canvas-normal [0 1 0]) ;; ## Starting points and projection ;; Our digital Pollock is going to start a stroke of the brush by ;; picking a random point in space. This point will then be projected ;; to find where it impacts with the canvas. ;; In order to generate a random point inside of the space we need to ;; define a function that each time it is called will emit a vector ;; containing the position of the point. Function values can be ;; created by calling `(fn [...] ...)` with the first vector being the ;; arguments the function should receive and any follow items in the ;; list are the body of the function and executed with the arguments ;; bound. Rather than calling `(def name (fn ...))` Clojure has provided a ;; shortcut function `(defn name [...] ...)`. An example of a defined ;; function is `(defn say-hello [name] (str "Hello " name))`, this ;; creates a function called say-hello that when called `(say-hello ;; "PI:NAME:<NAME>END_PI")` it will return the string "Hello PI:NAME:<NAME>END_PI". ;; We are going to cover a common functional idiom when dealing with ;; lists to change the dimensions of the space above into a random ;; point inside that space. To do this we want to iterate over each ;; dimension of the size of space, generate a random number between 0 ;; and the magnitude of each dimension and then return the resultant ;; list of random numbers as a list. To generate a random number in ;; Clojure we can use the `(rand)` function, which will return a ;; random number between 0 (inclusive) and 1 (exclusive). The rand ;; function can take an optional parameter `(rand 100), this will ;; define the bounds of the number generated to 0 and 100. ;; The function map `(map [fn] [sequence])` will iterate through the ;; sequence executing the function with the current value of the ;; sequence as its first parameter, the values returned from the ;; function will be stored in a list the same length as the sequence ;; and returned by the function. ;; We can now define a random point inside of space as follows (defn starting-point [] (map rand space)) ;; Now that we can generate a random point in space we want to project ;; this to the canvas. We are going to use [Newtonian equations of ;; motion](https://en.wikipedia.org/wiki/Equations_of_motion), ;; we know the position, velocity and acceleration of the ;; point and we want to know what the position and velocity are when y ;; is 0. In order to work out final positions we need to know the ;; total time the point spent falling, we can do this using the y ;; position as we know that the final position should be 0. ;; To work out the time it takes for the point to reach the canvas we ;; will solve the following equation for t: ;; ;; - $r$ = final displacement, ;; - $r_{0}$ = initial displacement, ;; - $v_{0}$ = initial velocity, ;; - $a$ = acceleration, ;; - $t$ = time. ;; ;; $r = r_{0} + v_{0} * t + \frac{at^2}{2}$ ;; ;; This rearranges to: ;; ;; $at^2 + 2v_{0}t + 2r_{0} - 2r = 0$ ;; ;; We can solve this using the Quadratic Equation, but this will yield ;; us two results. In general we can say that we are interested in the ;; result with the maximum value. ;; ;; In the next block of code you can see an example of call out to Java(Script). ;; Clojure doesn't have an in-built square root function, so we are calling out ;; to the Java(Script) version. A function named in the form `foo/bar` means ;; it will call the function `bar` in the namespace `foo`. You might ;; be wondering, what is a namespace?. ;; All good languages need a way to ;; bundle up code that is related, so that it can be reused and ;; accessed only when needed. Clojure's take on this is to provide ;; namespaces. Every Clojure source file will declare its namespace at ;; the top of the file so that other files can reference it, extract ;; values and use functions. Given that Clojure is a hosted language ;; its namespace will related to packages in Java and Google Closure ;; Library namespaces in Javascript. ;; When hosted on Java all of java.util.* is automatically imported ;; and on JavaScript assorted core and Google Closure Library modules ;; are imported. Both of these languages provide us with a Math ;; namespace which contains a `sqrt` function. ;; If you want to learn more about Clojure -> Java(Script) interop ;; then have a read [of this article](http://clojure-doc.org/articles/language/interop.html). (defn time-to-canvas [position velocity acceleration] (let [a acceleration b (* 2 velocity) c (* 2 position) discriminant (- (* b b) (* 4 a c)) minus-b (- 0 b) add-sqrt (/ (+ minus-b (Math/sqrt discriminant)) (* 2 a)) minus-sqrt (/ (- minus-b (Math/sqrt discriminant)) (* 2 a))] (max add-sqrt minus-sqrt))) ;; We can now calculate the time to impact but we want the final position and ;; velocity. For position we can use the same function that we ;; rearranged above to derive the time. (defn position-at [time initial-position initial-velocity acceleration] (+ initial-position (* initial-velocity time) (/ (* acceleration time time) 2))) ;; For velocity we can use another equation of motion: ;; ;; $v = at + v_{0}$ (defn velocity-at [time initial-velocity acceleration] (+ (* acceleration time) initial-velocity)) ;; These functions we just implemented can be joined up so that, given ;; an initial position and velocity we can return the final position and ;; velocity. This function doesn't explicitly ask for the acceleration ;; acting on the paint, it assumes only gravity is acting using the ;; constant defined earlier on. (defn project-point [position velocity] (let [[i j k] position [vi vj vk] velocity [ai aj ak] gravity time (time-to-canvas j vj aj) projected-position [(position-at time i vi ai) 0 ;; we don't need to calculate as it ;; should be 0, on the canvas (position-at time k vk ak)] projected-velocity [(velocity-at time vi ai) (velocity-at time vj aj) (velocity-at time vk ak)]] [projected-position projected-velocity])) ;; ## Paint splatter ;; An important aspect of Pollocks painting is the splatter of the ;; paint hitting the canvas and what this adds to the images. We are ;; going to add a simple splatter model based of the velocity at ;; impact we calculated in the last part. ;; Not all paint that hits the canvas will splatter, so we need to ;; work out the impact force of the paint and use this as a cutoff for ;; whether the paint should splatter. ;; We will work out the impact force of the paint by taking the ;; velocity at impact and calculating the force required to reduce ;; that velocity to 0 over a set impact distance. (def impact-distance 0.05) ;; We can now use the work-energy principle ;; (https://en.wikipedia.org/wiki/Work_(physics)#Work_and_energy) to ;; calculate the impact force. On one side of the equation we will ;; have the forces at play and the other the energy: ;; - $F_{i}$ = impact force, ;; - d = impact distance, ;; - m = mass, ;; - g = gravity, ;; - v = velocity at impact. ;; $-F_{i}d + mgd = 0 - \frac{1}{2}mv^2$ ;; This equation can be rearranged to: ;; $F_{i} = mg + \frac{mv^2}{2d}$ ;; For simplicity of code we are just going to consider the y axis as ;; this is the most important when it comes to working out the impact ;; force of the paint into the canvas. The above equation can ;; therefore be expressed as: (defn impact-force [mass velocity] (let [y-gravity (second gravity) y-velocity (second velocity)] (+ (* mass y-gravity) (/ (* mass y-velocity y-velocity) (* 2 impact-distance))))) ;; Based of this function to calculate the impact force we can define ;; a predicate that will tell us whether paint should splatter based ;; off its mass and velocity. It is idiomatic in Clojure to end ;; predicates with a `?`. We are going to add some randomness to this ;; function so that we don't necessarily just get a uniform line of ;; points. Also defined is a minimum force for us to consider whether ;; some paint could splatter. (def min-impact-force-for-splatter 30) (defn does-impact-splatter? [mass velocity] (and (> (impact-force mass velocity) min-impact-force-for-splatter) (> (rand) 0.8))) ;; If an impact splatters then we will need to bounce its velocity ;; vector as this is the direction it will leave its current position. ;; The equation to bounce a vector, $V$, off a plane with normal, $N$, is: ;; ;; - $N$ is the normal vector of the plane ;; - $V$ = the incoming vector ;; - $B$ is the outgoing, bounced, vector ;; ;; $B = V - (2 * (V.N) * N)$ ;; ;; You can find out a bit more about the derivation on this [Wolfram ;; page](http://mathworld.wolfram.com/Reflection.html). ;; We are missing a few of the required vector operations used in this ;; equation so we should define some more functions before trying to ;; implement it. The first is the vector dot product, this is defined ;; as the sum of the multiples of each dimension. Otherwise we need ;; subtraction of two vectors and a function to multiply a vector by ;; a constant. (defn dot-product [vector1 vector2] (reduce + (map * vector1 vector2))) (defn vector-subtraction [vector1 vector2] (map - vector1 vector2)) ;; This function will introduce a shorthand for defining functions ;; that is very useful in combination with functions like `map` and ;; `reduce`. Rather than writing `(fn [args...] body)` you can use ;; `#(body)` and if you want access to the arguments use `%n` where ;; `n` is the position of the argument. If you are only expecting one ;; argument then you can use just `%` on its own. (defn vector-multiply-by-constant [vector constant] (map #(* % constant) vector)) ;; Using the above functions we can now implement the vector bouncing ;; equation. I have pulled $(2 * (V.N) * N)$ out into a variable ;; called extreme for clarity. (defn bounce-vector [vector normal] (let [vector-dot-normal (dot-product vector normal) extreme (vector-multiply-by-constant normal (* 2 vector-dot-normal))] (vector-subtraction vector extreme))) ;; When an impact splatters it will only take a fraction of the ;; velocity, otherwise know as being an inelastic rather than elastic ;; collision. We can define a constant that will be ;; used to reduce the total velocity of the bounced vector to reflect ;; this elasticity. (def splatter-dampening-constant 0.7) (defn splatter-vector [velocity] (let [bounced-vector (bounce-vector velocity canvas-normal)] (vector-multiply-by-constant bounced-vector splatter-dampening-constant))) ;; ## Paths vs Points ;; All of the gestures Pollock makes are fluid paths, even if the ;; velocity along the path might be rather erratic. We now need to ;; work out how to generate a path of points that we can then use the ;; code we have written above to project and splatter. ;; A [Bezier curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) ;; is a commonly used curve for generating a smooth curve that can be ;; scaled indefinitely allowing us to have as many points along our ;; path as we care to calculate. ;; Bezier curves are defined by an list of control points, so we need ;; to be able to generate a potential unbounded list of random control ;; points that should give use limitless different paths to paint with. ;; In order to generate a list of control points we will need to be ;; able to: ;; - get a random number between two points for distance and steps, ;; - get a random unit vector for the initial direction of the generation, ;; - add vectors together to move between our control points. (defn random-between [lower-bound upper-bound] (+ lower-bound (rand (- upper-bound lower-bound)))) ;; Below is an algorithm that will give well distributed random unit ;; vectors. It was ported from code found [in GameDev the ;; forums](http://www.gamedev.net/topic/499972-generate-a-random-unit-vector/#entry4261773). (defn random-unit-vector [] (let [asimuth (* (rand) 2 Math/PI) k (- (rand 2) 1) a (Math/sqrt (- 1 (* k k))) i (* (Math/cos asimuth) a) j (* (Math/sin asimuth) a)] [i j k])) (defn vector-add [vector1 vector2] (map + vector1 vector2)) ;; Now that we have a random direction in which to move we need to ;; generate an unbounded path that will move in that direction, but ;; randomise the position of each point within provided bounds. ;; Firstly, we can define a function that will generate a random ;; vector inside of lower and upper bounds that can be combined with ;; the non-randomised position to provide a randomised path. (defn random-vector-between [lower upper] [(random-between lower upper) (random-between lower upper) (random-between lower upper)]) ;; In order to provide an unbounded path we can use a lazy sequence. ;; This function returns a value that is somewhat akin to list that ;; never ends. Every time you try to look at the next value in the list ;; it will generate one just in time for you to see no end. ;; In this function the first value returned should always be the ;; initial starting position, each following value should be a step ;; along the path. You can see this below, it returns the position ;; argument cons'd with another iteration of random-path with the ;; position randomised. (defn random-path [position step-vector bounds] (cons position (lazy-seq (random-path (vector-add (vector-add position step-vector) (random-vector-between (- 0 bounds) bounds)) step-vector bounds)))) ;; We can now use this random-path lazy sequence to generate a list of ;; control points given an initial starting point and some bounding ;; variables. The distance, step and variation allow us to request long ;; winding paths or short flicks. (defn control-points [position min-distance max-distance min-steps max-steps variation] (let [direction (random-unit-vector) distance (random-between min-distance max-distance) steps (random-between min-steps max-steps) step-vector (vector-multiply-by-constant direction (/ distance steps)) random-positions (take steps (random-path position step-vector variation)) end-position (vector-add position (vector-multiply-by-constant step-vector steps))] (conj (vec random-positions) end-position))) ;; In order to turn this list of control points into a list of points ;; that represent a path we need an algorithm. The most commonly used ;; is a recursive algorithm proved by De Casteljau. There is a [great ;; video on YouTube](https://www.youtube.com/watch?v=YATikPP2q70) ;; explaining this algorithm that I recommend you watch. ;; At the core of the algorithm is an equation that will return a ;; point along a line weighted by a variable, $t$ which dictates how ;; close it is to each end of the line: ;; $P = (1 - t)P_{0} + tP_{1}$ ;; For example, if a line runs ;; from $P_{0}$ to $P_{1}$ and $t$ is 0 then the outputted point with ;; be equal to $P_{0}$ and if it is 1 then $P_{1}$. ;; De Casteljau's algorithm recursively creates a new set of points by ;; using the above equation for a fixed $t$ against all the lines ;; created by the control points. It does this until there is just a ;; single point, this is a point on the bezier curve. It $t$ from 0 to ;; 1 and for each step gets a point along the curve. (defn recur-relation [t a b] (+ (* t b) (* a (- 1 t)))) (defn for-component [t component-vals] (if (= (count component-vals) 1) (first component-vals) (for-component t (map #(recur-relation t %1 %2) component-vals (rest component-vals))))) (defn for-t [t components] (map #(for-component t %) components)) (defn de-casteljau [control-points step-amount] (let [x-vals (map first control-points) y-vals (map second control-points) z-vals (map #(nth % 2) control-points) points (map #(for-t % [x-vals y-vals z-vals]) (range 0 1 step-amount))] points)) ;; This can generate paths that go below the canvas, we should set ;; these to 0 as it is the equivalent of painting on the canvas (defn ensure-above-canvas [path] (map (fn [[i j k]] [i (if (< j 0) 0 j) k]) path)) ;; ## Motion, going through the paces ;; All the points along the generated path should have an associated ;; velocity. To start with we can generate a linear velocity along the ;; path, given a randomised total time to traverse the path and the ;; total length of the path. ;; In order to calculate the length of the paths, we will want to do ;; something similar to a map but with pairs of values. Using this we ;; can take two points, calculate the distance between them and then ;; sum all the distances (defn map-2 [f coll] (when-let [s (seq coll)] (let [s1 (first s) s2 (second s)] (if (not (nil? s2)) (cons (f (first s) (second s)) (map-2 f (rest s))))))) ;; in order to find the distance between two points we need subtract ;; the two vectors, square and sum the resultant dimensions and then ;; take the root. (https://en.wikipedia.org/wiki/Euclidean_distance) (defn vector-multiply [vector1 vector2] (map * vector1 vector2)) (defn distance-between-points [point1 point2] (let [difference-vector (vector-subtraction point1 point2) summed-vector (reduce + (vector-multiply difference-vector difference-vector))] (Math/sqrt summed-vector))) (defn path-length [path] (reduce + (map-2 distance-between-points path))) (defn vector-divide-by-const [vector const] (map #(/ % const) vector)) (defn velocity-between [point1 point2 total-time total-distance] (let [difference-vector (vector-subtraction point1 point2) time-between (* total-time (/ (distance-between-points point1 point2) total-distance))] (vector-divide-by-const difference-vector time-between))) ;; This calculation will leave off the last points velocity, we can just set it to 0 (defn path-velocities [path total-time] (let [total-distance (path-length path) number-of-points (count path)] (conj (vec (map-2 #(velocity-between %1 %2 total-time total-distance) path)) [0 0 0]))) ;; As well as the velocity at each point along the path, we also need ;; how much paint there is falling. Again to keep life simple we are ;; going to model this as a linear flow along the path with there ;; always being no paint left. (defn path-masses [path initial-mass] (let [number-of-points (count path) step (- 0 (/ initial-mass number-of-points))] (take number-of-points (range initial-mass 0 step)))) ;; ## Putting it all together ;; I've pulled a bunch of colours that PI:NAME:<NAME>END_PI used in his seminal ;; work "Number 8" so that each flick of paint can be rendered in a ;; random colour out of this palette (def canvas-colour [142 141 93]) (def paint-colours [[232 51 1] [248 179 10] [247 239 189] [29 16 8]]) (defn pick-a-colour [] (nth paint-colours (rand-int (count paint-colours)))) ;; Now we need to assemble all of the above functions into something ;; the resembles PI:NAME:<NAME>END_PI applying paint to a canvas. We start ;; with a point, project a path, work out masses and velocities, ;; project and then splatter. This is all then packaged up with a ;; colour for drawing onto our canvas. (defn fling-paint [] (let [position (starting-point) total-time (random-between 1 5) path (ensure-above-canvas (de-casteljau (control-points position 0.1 2 3 15 0.4) 0.01)) velocities (path-velocities path total-time) masses (path-masses path (random-between 0.1 1)) projected-path (map #(project-point %1 %2) path velocities) splatter (map (fn [[position velocity] mass] (if (does-impact-splatter? mass velocity) [position (splatter-vector velocity) (* mass splatter-dampening-constant)] nil)) projected-path masses) projected-splatter (map (fn [[position velocity mass :as point]] (if (nil? point) nil (conj (vec (project-point position velocity)) mass))) splatter)] {:colour (pick-a-colour) :air-path path :canvas-path (map #(conj %1 %2) projected-path masses) :splatter (filter #(not-any? nil? %) (partition-by nil? projected-splatter))})) ;; ## Rendering the canvas ;; We need to know the available size for the outputted image to fit ;; in. To work this out we are going to have to interface with ;; JavaScript directly. Luckily ClojureScript makes this very easy ;; using the `js` namespace. (def image-width (.-clientWidth (.querySelector js/document "#pollock"))) ;; Now we have the width of the image we can use the dimensions of the ;; space to work out the pixel size of the image and how to convert ;; between metres and pixels. (def pixels-in-a-metre (let [[width _ _] space] (/ image-width width))) (defn metres-to-pixels [metres] (Math/floor (* metres pixels-in-a-metre))) ;; We can now use this function to work out the size the sketch should ;; be and how to convert a position in metres over to a position to be ;; drawn in the image. (def sketch-size (let [[width _ height] space] [(metres-to-pixels width) (metres-to-pixels height)])) (defn position-to-pixel [[i j k]] [(metres-to-pixels i) (metres-to-pixels k)]) ;; Now the dimensions of the image our calculated we can use Quil to ;; define the sketch that we will draw into. We also need to define a ;; function that will initialise the image into the state we want it. ;; This function will be run when the sketch is defined. (defn setup-image [] (apply q/background canvas-colour) (q/fill 0)) (q/defsketch pollock :setup setup-image :host "pollock" ;; the id of the <canvas> element :size sketch-size) ;; To draw the trails of paint across the canvas we need draw a path ;; following the defined positions, which takes into account the ;; amount of paint at each position and uses this to set with width of ;; the path. In order to do this cleanly in Quil we need to consider ;; the path as pairs of positions that we shall draw paths between ;; using the initial paint amount as the stroke-weight. This allows ;; for a smooth decrease in the width of the path. (defn mass-to-weight [mass] (* 50 mass)) (defn draw-path [path] (doall (map-2 (fn [[position1 _ mass] [position2 _ _]] (q/stroke-weight (mass-to-weight mass)) (apply q/line (concat (position-to-pixel position1) (position-to-pixel position2)))) path))) ;; For splatter we are just going to draw a point that has a stroke-weight ;; proportional to the amount of paint. (defn draw-splats [path] (doall (map (fn [[position _ mass]] (q/stroke-weight (mass-to-weight mass)) (apply q/point (position-to-pixel position))) path))) ;; Now that we can render the result of flinging some paint around we ;; need a function that will fling the paint and render the result. (defn fling-and-render [& any] (q/with-sketch (q/get-sketch-by-id "pollock") (let [{:keys [colour canvas-path splatter]} (fling-paint)] (q/stroke (apply q/color colour)) (draw-path canvas-path) (doall (map draw-splats splatter))))) ;; Lastly, we shall attach to the buttons and cause our image to come ;; to life. (.addEventListener (.querySelector js/document "#add") "click" fling-and-render) (def interval-ref (atom nil)) (def fill-count (atom 0)) (.addEventListener (.querySelector js/document "#fill") "click" (fn [e] (reset! interval-ref (js/setInterval (fn [] (if (> @fill-count 500) (js/clearInterval @interval-ref) (do (fling-and-render) (swap! fill-count inc)))) 100))))
[ { "context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998820424079895, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
test/territory_bro/domain/congregation_test.clj
3breadt/territory-bro
2
;; Copyright © 2015-2020 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.domain.congregation-test (:require [clojure.test :refer :all] [territory-bro.domain.congregation :as congregation] [territory-bro.events :as events] [territory-bro.infra.permissions :as permissions] [territory-bro.test.testutil :as testutil :refer [re-equals]]) (:import (java.time Instant) (java.util UUID) (territory_bro NoPermitException ValidationException))) (defn- apply-events [events] (testutil/apply-events congregation/projection events)) (defn- handle-command [command events injections] (->> (congregation/handle-command (testutil/validate-command command) (events/validate-events events) injections) (events/validate-events))) (deftest congregation-projection-test (testing "created" (let [cong-id (UUID. 0 1) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}] expected {::congregation/congregations {cong-id {:congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}}}] (is (= expected (apply-events events))) (testing "> view permission granted" (let [user-id (UUID. 0 2) events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation}) (assoc-in [::congregation/user->cong-ids user-id] #{cong-id}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true}))] (is (= expected (apply-events events))) (testing "> view permissing revoked" (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) expected (-> expected (assoc-in [::congregation/user->cong-ids user-id] #{}) (assoc-in [::congregation/congregations cong-id :congregation/user-permissions] {}) (dissoc ::permissions/permissions))] (is (= expected (apply-events events))))) (testing "> other permission granted" (let [events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :configure-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation :configure-congregation}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true :configure-congregation true}))] (is (= expected (apply-events events))) (testing "> other permissing revoked" (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :configure-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true}))] (is (= expected (apply-events events))))))))) (testing "> congregation renamed" (let [events (conj events {:event/type :congregation.event/congregation-renamed :congregation/id cong-id :congregation/name "New Name"}) expected (assoc-in expected [::congregation/congregations cong-id :congregation/name] "New Name")] (is (= expected (apply-events events)))))))) (deftest congregation-access-test (let [cong-id (UUID. 0 1) unrelated-cong-id (UUID. 0 2) user-id (UUID. 0 3) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"} {:event/type :congregation.event/congregation-created :congregation/id unrelated-cong-id :congregation/name "Cong2 Name" :congregation/schema-name "cong2_schema"}] state (apply-events events)] (testing "cannot see congregations by default" (is (nil? (congregation/get-my-congregation state cong-id user-id))) (is (empty? (congregation/get-my-congregations state user-id)))) (let [events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) state (apply-events events)] (testing "can see congregations after granting access" (is (= cong-id (:congregation/id (congregation/get-my-congregation state cong-id user-id)))) (is (= [cong-id] (->> (congregation/get-my-congregations state user-id) (map :congregation/id))))) (testing "list users" (is (= [user-id] (congregation/get-users state cong-id))) (is (empty? (congregation/get-users state unrelated-cong-id)) "unrelated congregation")) (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) state (apply-events events)] (testing "cannot see congregations after revoking access" (is (nil? (congregation/get-my-congregation state cong-id user-id))) (is (empty? (congregation/get-my-congregations state user-id)))) (testing "list users" (is (empty? (congregation/get-users state cong-id))) (is (empty? (congregation/get-users state unrelated-cong-id)) "unrelated congregation")))) (testing "superadmin can access all congregations" (let [state (congregation/sudo state user-id)] (is (= #{cong-id unrelated-cong-id} (->> (congregation/get-my-congregations state user-id) (map :congregation/id) (set)))))))) (deftest check-congregation-exists-test (let [cong-id (UUID. 0 1) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}] state (apply-events events)] (testing "exists" (is (nil? (congregation/check-congregation-exists state cong-id)))) (testing "doesn't exist" (is (thrown-with-msg? ValidationException (re-equals "[[:no-such-congregation #uuid \"00000000-0000-0000-0000-000000000666\"]]") (congregation/check-congregation-exists state (UUID. 0 0x666))))))) ;;;; Commands (deftest admin-permissions-granted-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) events (congregation/admin-permissions-granted cong-id user-id)] (is (= {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation} (first events))) (is (= congregation/all-permissions (map :permission/id events))))) (deftest create-congregation-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) injections {:generate-tenant-schema-name (fn [id] (is (= cong-id id)) "cong_schema")} create-command {:command/type :congregation.command/create-congregation :command/time (Instant/now) :command/user user-id :congregation/id cong-id :congregation/name "the name"} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "the name" :congregation/schema-name "cong_schema"} admin-grants (congregation/admin-permissions-granted cong-id user-id)] (testing "created" (is (= (concat [created-event] admin-grants) (handle-command create-command [] injections)))) (testing "created by system, should make no grants" (let [command (-> create-command (dissoc :command/user) (assoc :command/system "test"))] (is (= [created-event] (handle-command command [] injections))))) (testing "error: name is blank" (let [command (assoc create-command :congregation/name " ")] (is (thrown-with-msg? ValidationException (re-equals "[[:missing-name]]") (handle-command command [] injections))))) (testing "create is idempotent" (is (empty? (handle-command create-command [created-event] injections)))))) (deftest rename-congregation-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "old name" :congregation/schema-name ""} rename-command {:command/type :congregation.command/rename-congregation :command/time (Instant/now) :command/user user-id :congregation/id cong-id :congregation/name "new name"} renamed-event {:event/type :congregation.event/congregation-renamed :congregation/id cong-id :congregation/name "new name"}] (testing "name changed" (is (= [renamed-event] (handle-command rename-command [created-event] injections)))) (testing "name not changed" (testing "from original" (let [command (assoc rename-command :congregation/name "old name")] (is (empty? (handle-command command [created-event] injections))))) (testing "from previous rename" (is (empty? (handle-command rename-command [created-event renamed-event] injections))))) (testing "error: name is blank" (let [command (assoc rename-command :congregation/name " ")] (is (thrown-with-msg? ValidationException (re-equals "[[:missing-name]]") (handle-command command [created-event] injections))))) (testing "checks permits" (let [injections {:check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil)))}] (is (thrown? NoPermitException (handle-command rename-command [created-event] injections))))))) (deftest add-user-to-congregation-test (let [cong-id (UUID. 0 1) admin-id (UUID. 0 2) new-user-id (UUID. 0 3) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "" :congregation/schema-name ""} add-user-command {:command/type :congregation.command/add-user :command/time (Instant/now) :command/user admin-id :congregation/id cong-id :user/id new-user-id} admin-grants (congregation/admin-permissions-granted cong-id new-user-id) view-granted {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id new-user-id :permission/id :view-congregation}] (testing "user added" (is (= admin-grants (handle-command add-user-command [created-event] injections)))) (testing "user already in congregation" (is (empty? (handle-command add-user-command [created-event view-granted] injections)))) (testing "checks permits" (let [injections (assoc injections :check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil))))] (is (thrown? NoPermitException (handle-command add-user-command [created-event] injections))))))) (deftest set-user-permissions-test (let [cong-id (UUID. 0 1) admin-id (UUID. 0 2) target-user-id (UUID. 0 3) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "" :congregation/schema-name ""} permission-granted-event {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id target-user-id :permission/id :PLACEHOLDER} permission-revoked-event {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id target-user-id :permission/id :PLACEHOLDER} set-user-permissions-command {:command/type :congregation.command/set-user-permissions :command/time (Instant/now) :command/user admin-id :congregation/id cong-id :user/id target-user-id :permission/ids []}] (testing "grant permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation :configure-congregation]) then [(assoc permission-granted-event :permission/id :configure-congregation)]] (is (= then (handle-command when given injections))))) (testing "revoke permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation) (assoc permission-granted-event :permission/id :configure-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation]) then [(assoc permission-revoked-event :permission/id :configure-congregation)]] (is (= then (handle-command when given injections))))) (testing "setting permissions is idempotent" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation]) then []] (is (= then (handle-command when given injections))))) (testing "remove user from congregation" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids []) then [(assoc permission-revoked-event :permission/id :view-congregation)]] (is (= then (handle-command when given injections))))) (testing "cannot be used for adding new users to congregation" (let [given [created-event] when (assoc set-user-permissions-command :permission/ids [:view-congregation])] (is (thrown-with-msg? ValidationException (re-equals "[[:user-not-in-congregation #uuid \"00000000-0000-0000-0000-000000000003\"]]") (handle-command when given injections))))) (testing "cannot revoke :view-congregation without also removing all other permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation) (assoc permission-granted-event :permission/id :configure-congregation)] when (assoc set-user-permissions-command :permission/ids [:configure-congregation])] (is (thrown-with-msg? ValidationException (re-equals "[[:cannot-revoke-view-congregation]]") (handle-command when given injections))))) (testing "checks permits" (let [injections (assoc injections :check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil)))) given [created-event] when (assoc set-user-permissions-command :permission/ids [:view-congregation])] (is (thrown? NoPermitException (handle-command when given injections)))))))
42267
;; Copyright © 2015-2020 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.domain.congregation-test (:require [clojure.test :refer :all] [territory-bro.domain.congregation :as congregation] [territory-bro.events :as events] [territory-bro.infra.permissions :as permissions] [territory-bro.test.testutil :as testutil :refer [re-equals]]) (:import (java.time Instant) (java.util UUID) (territory_bro NoPermitException ValidationException))) (defn- apply-events [events] (testutil/apply-events congregation/projection events)) (defn- handle-command [command events injections] (->> (congregation/handle-command (testutil/validate-command command) (events/validate-events events) injections) (events/validate-events))) (deftest congregation-projection-test (testing "created" (let [cong-id (UUID. 0 1) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}] expected {::congregation/congregations {cong-id {:congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}}}] (is (= expected (apply-events events))) (testing "> view permission granted" (let [user-id (UUID. 0 2) events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation}) (assoc-in [::congregation/user->cong-ids user-id] #{cong-id}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true}))] (is (= expected (apply-events events))) (testing "> view permissing revoked" (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) expected (-> expected (assoc-in [::congregation/user->cong-ids user-id] #{}) (assoc-in [::congregation/congregations cong-id :congregation/user-permissions] {}) (dissoc ::permissions/permissions))] (is (= expected (apply-events events))))) (testing "> other permission granted" (let [events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :configure-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation :configure-congregation}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true :configure-congregation true}))] (is (= expected (apply-events events))) (testing "> other permissing revoked" (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :configure-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true}))] (is (= expected (apply-events events))))))))) (testing "> congregation renamed" (let [events (conj events {:event/type :congregation.event/congregation-renamed :congregation/id cong-id :congregation/name "New Name"}) expected (assoc-in expected [::congregation/congregations cong-id :congregation/name] "New Name")] (is (= expected (apply-events events)))))))) (deftest congregation-access-test (let [cong-id (UUID. 0 1) unrelated-cong-id (UUID. 0 2) user-id (UUID. 0 3) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"} {:event/type :congregation.event/congregation-created :congregation/id unrelated-cong-id :congregation/name "Cong2 Name" :congregation/schema-name "cong2_schema"}] state (apply-events events)] (testing "cannot see congregations by default" (is (nil? (congregation/get-my-congregation state cong-id user-id))) (is (empty? (congregation/get-my-congregations state user-id)))) (let [events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) state (apply-events events)] (testing "can see congregations after granting access" (is (= cong-id (:congregation/id (congregation/get-my-congregation state cong-id user-id)))) (is (= [cong-id] (->> (congregation/get-my-congregations state user-id) (map :congregation/id))))) (testing "list users" (is (= [user-id] (congregation/get-users state cong-id))) (is (empty? (congregation/get-users state unrelated-cong-id)) "unrelated congregation")) (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) state (apply-events events)] (testing "cannot see congregations after revoking access" (is (nil? (congregation/get-my-congregation state cong-id user-id))) (is (empty? (congregation/get-my-congregations state user-id)))) (testing "list users" (is (empty? (congregation/get-users state cong-id))) (is (empty? (congregation/get-users state unrelated-cong-id)) "unrelated congregation")))) (testing "superadmin can access all congregations" (let [state (congregation/sudo state user-id)] (is (= #{cong-id unrelated-cong-id} (->> (congregation/get-my-congregations state user-id) (map :congregation/id) (set)))))))) (deftest check-congregation-exists-test (let [cong-id (UUID. 0 1) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}] state (apply-events events)] (testing "exists" (is (nil? (congregation/check-congregation-exists state cong-id)))) (testing "doesn't exist" (is (thrown-with-msg? ValidationException (re-equals "[[:no-such-congregation #uuid \"00000000-0000-0000-0000-000000000666\"]]") (congregation/check-congregation-exists state (UUID. 0 0x666))))))) ;;;; Commands (deftest admin-permissions-granted-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) events (congregation/admin-permissions-granted cong-id user-id)] (is (= {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation} (first events))) (is (= congregation/all-permissions (map :permission/id events))))) (deftest create-congregation-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) injections {:generate-tenant-schema-name (fn [id] (is (= cong-id id)) "cong_schema")} create-command {:command/type :congregation.command/create-congregation :command/time (Instant/now) :command/user user-id :congregation/id cong-id :congregation/name "the name"} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "the name" :congregation/schema-name "cong_schema"} admin-grants (congregation/admin-permissions-granted cong-id user-id)] (testing "created" (is (= (concat [created-event] admin-grants) (handle-command create-command [] injections)))) (testing "created by system, should make no grants" (let [command (-> create-command (dissoc :command/user) (assoc :command/system "test"))] (is (= [created-event] (handle-command command [] injections))))) (testing "error: name is blank" (let [command (assoc create-command :congregation/name " ")] (is (thrown-with-msg? ValidationException (re-equals "[[:missing-name]]") (handle-command command [] injections))))) (testing "create is idempotent" (is (empty? (handle-command create-command [created-event] injections)))))) (deftest rename-congregation-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "old name" :congregation/schema-name ""} rename-command {:command/type :congregation.command/rename-congregation :command/time (Instant/now) :command/user user-id :congregation/id cong-id :congregation/name "new name"} renamed-event {:event/type :congregation.event/congregation-renamed :congregation/id cong-id :congregation/name "new name"}] (testing "name changed" (is (= [renamed-event] (handle-command rename-command [created-event] injections)))) (testing "name not changed" (testing "from original" (let [command (assoc rename-command :congregation/name "old name")] (is (empty? (handle-command command [created-event] injections))))) (testing "from previous rename" (is (empty? (handle-command rename-command [created-event renamed-event] injections))))) (testing "error: name is blank" (let [command (assoc rename-command :congregation/name " ")] (is (thrown-with-msg? ValidationException (re-equals "[[:missing-name]]") (handle-command command [created-event] injections))))) (testing "checks permits" (let [injections {:check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil)))}] (is (thrown? NoPermitException (handle-command rename-command [created-event] injections))))))) (deftest add-user-to-congregation-test (let [cong-id (UUID. 0 1) admin-id (UUID. 0 2) new-user-id (UUID. 0 3) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "" :congregation/schema-name ""} add-user-command {:command/type :congregation.command/add-user :command/time (Instant/now) :command/user admin-id :congregation/id cong-id :user/id new-user-id} admin-grants (congregation/admin-permissions-granted cong-id new-user-id) view-granted {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id new-user-id :permission/id :view-congregation}] (testing "user added" (is (= admin-grants (handle-command add-user-command [created-event] injections)))) (testing "user already in congregation" (is (empty? (handle-command add-user-command [created-event view-granted] injections)))) (testing "checks permits" (let [injections (assoc injections :check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil))))] (is (thrown? NoPermitException (handle-command add-user-command [created-event] injections))))))) (deftest set-user-permissions-test (let [cong-id (UUID. 0 1) admin-id (UUID. 0 2) target-user-id (UUID. 0 3) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "" :congregation/schema-name ""} permission-granted-event {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id target-user-id :permission/id :PLACEHOLDER} permission-revoked-event {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id target-user-id :permission/id :PLACEHOLDER} set-user-permissions-command {:command/type :congregation.command/set-user-permissions :command/time (Instant/now) :command/user admin-id :congregation/id cong-id :user/id target-user-id :permission/ids []}] (testing "grant permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation :configure-congregation]) then [(assoc permission-granted-event :permission/id :configure-congregation)]] (is (= then (handle-command when given injections))))) (testing "revoke permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation) (assoc permission-granted-event :permission/id :configure-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation]) then [(assoc permission-revoked-event :permission/id :configure-congregation)]] (is (= then (handle-command when given injections))))) (testing "setting permissions is idempotent" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation]) then []] (is (= then (handle-command when given injections))))) (testing "remove user from congregation" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids []) then [(assoc permission-revoked-event :permission/id :view-congregation)]] (is (= then (handle-command when given injections))))) (testing "cannot be used for adding new users to congregation" (let [given [created-event] when (assoc set-user-permissions-command :permission/ids [:view-congregation])] (is (thrown-with-msg? ValidationException (re-equals "[[:user-not-in-congregation #uuid \"00000000-0000-0000-0000-000000000003\"]]") (handle-command when given injections))))) (testing "cannot revoke :view-congregation without also removing all other permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation) (assoc permission-granted-event :permission/id :configure-congregation)] when (assoc set-user-permissions-command :permission/ids [:configure-congregation])] (is (thrown-with-msg? ValidationException (re-equals "[[:cannot-revoke-view-congregation]]") (handle-command when given injections))))) (testing "checks permits" (let [injections (assoc injections :check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil)))) given [created-event] when (assoc set-user-permissions-command :permission/ids [:view-congregation])] (is (thrown? NoPermitException (handle-command when given injections)))))))
true
;; Copyright © 2015-2020 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.domain.congregation-test (:require [clojure.test :refer :all] [territory-bro.domain.congregation :as congregation] [territory-bro.events :as events] [territory-bro.infra.permissions :as permissions] [territory-bro.test.testutil :as testutil :refer [re-equals]]) (:import (java.time Instant) (java.util UUID) (territory_bro NoPermitException ValidationException))) (defn- apply-events [events] (testutil/apply-events congregation/projection events)) (defn- handle-command [command events injections] (->> (congregation/handle-command (testutil/validate-command command) (events/validate-events events) injections) (events/validate-events))) (deftest congregation-projection-test (testing "created" (let [cong-id (UUID. 0 1) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}] expected {::congregation/congregations {cong-id {:congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}}}] (is (= expected (apply-events events))) (testing "> view permission granted" (let [user-id (UUID. 0 2) events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation}) (assoc-in [::congregation/user->cong-ids user-id] #{cong-id}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true}))] (is (= expected (apply-events events))) (testing "> view permissing revoked" (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) expected (-> expected (assoc-in [::congregation/user->cong-ids user-id] #{}) (assoc-in [::congregation/congregations cong-id :congregation/user-permissions] {}) (dissoc ::permissions/permissions))] (is (= expected (apply-events events))))) (testing "> other permission granted" (let [events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :configure-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation :configure-congregation}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true :configure-congregation true}))] (is (= expected (apply-events events))) (testing "> other permissing revoked" (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :configure-congregation}) expected (-> expected (assoc-in [::congregation/congregations cong-id :congregation/user-permissions user-id] #{:view-congregation}) (assoc-in [::permissions/permissions user-id cong-id] {:view-congregation true}))] (is (= expected (apply-events events))))))))) (testing "> congregation renamed" (let [events (conj events {:event/type :congregation.event/congregation-renamed :congregation/id cong-id :congregation/name "New Name"}) expected (assoc-in expected [::congregation/congregations cong-id :congregation/name] "New Name")] (is (= expected (apply-events events)))))))) (deftest congregation-access-test (let [cong-id (UUID. 0 1) unrelated-cong-id (UUID. 0 2) user-id (UUID. 0 3) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"} {:event/type :congregation.event/congregation-created :congregation/id unrelated-cong-id :congregation/name "Cong2 Name" :congregation/schema-name "cong2_schema"}] state (apply-events events)] (testing "cannot see congregations by default" (is (nil? (congregation/get-my-congregation state cong-id user-id))) (is (empty? (congregation/get-my-congregations state user-id)))) (let [events (conj events {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) state (apply-events events)] (testing "can see congregations after granting access" (is (= cong-id (:congregation/id (congregation/get-my-congregation state cong-id user-id)))) (is (= [cong-id] (->> (congregation/get-my-congregations state user-id) (map :congregation/id))))) (testing "list users" (is (= [user-id] (congregation/get-users state cong-id))) (is (empty? (congregation/get-users state unrelated-cong-id)) "unrelated congregation")) (let [events (conj events {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id :view-congregation}) state (apply-events events)] (testing "cannot see congregations after revoking access" (is (nil? (congregation/get-my-congregation state cong-id user-id))) (is (empty? (congregation/get-my-congregations state user-id)))) (testing "list users" (is (empty? (congregation/get-users state cong-id))) (is (empty? (congregation/get-users state unrelated-cong-id)) "unrelated congregation")))) (testing "superadmin can access all congregations" (let [state (congregation/sudo state user-id)] (is (= #{cong-id unrelated-cong-id} (->> (congregation/get-my-congregations state user-id) (map :congregation/id) (set)))))))) (deftest check-congregation-exists-test (let [cong-id (UUID. 0 1) events [{:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "Cong1 Name" :congregation/schema-name "cong1_schema"}] state (apply-events events)] (testing "exists" (is (nil? (congregation/check-congregation-exists state cong-id)))) (testing "doesn't exist" (is (thrown-with-msg? ValidationException (re-equals "[[:no-such-congregation #uuid \"00000000-0000-0000-0000-000000000666\"]]") (congregation/check-congregation-exists state (UUID. 0 0x666))))))) ;;;; Commands (deftest admin-permissions-granted-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) events (congregation/admin-permissions-granted cong-id user-id)] (is (= {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id :view-congregation} (first events))) (is (= congregation/all-permissions (map :permission/id events))))) (deftest create-congregation-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) injections {:generate-tenant-schema-name (fn [id] (is (= cong-id id)) "cong_schema")} create-command {:command/type :congregation.command/create-congregation :command/time (Instant/now) :command/user user-id :congregation/id cong-id :congregation/name "the name"} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "the name" :congregation/schema-name "cong_schema"} admin-grants (congregation/admin-permissions-granted cong-id user-id)] (testing "created" (is (= (concat [created-event] admin-grants) (handle-command create-command [] injections)))) (testing "created by system, should make no grants" (let [command (-> create-command (dissoc :command/user) (assoc :command/system "test"))] (is (= [created-event] (handle-command command [] injections))))) (testing "error: name is blank" (let [command (assoc create-command :congregation/name " ")] (is (thrown-with-msg? ValidationException (re-equals "[[:missing-name]]") (handle-command command [] injections))))) (testing "create is idempotent" (is (empty? (handle-command create-command [created-event] injections)))))) (deftest rename-congregation-test (let [cong-id (UUID. 0 1) user-id (UUID. 0 2) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "old name" :congregation/schema-name ""} rename-command {:command/type :congregation.command/rename-congregation :command/time (Instant/now) :command/user user-id :congregation/id cong-id :congregation/name "new name"} renamed-event {:event/type :congregation.event/congregation-renamed :congregation/id cong-id :congregation/name "new name"}] (testing "name changed" (is (= [renamed-event] (handle-command rename-command [created-event] injections)))) (testing "name not changed" (testing "from original" (let [command (assoc rename-command :congregation/name "old name")] (is (empty? (handle-command command [created-event] injections))))) (testing "from previous rename" (is (empty? (handle-command rename-command [created-event renamed-event] injections))))) (testing "error: name is blank" (let [command (assoc rename-command :congregation/name " ")] (is (thrown-with-msg? ValidationException (re-equals "[[:missing-name]]") (handle-command command [created-event] injections))))) (testing "checks permits" (let [injections {:check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil)))}] (is (thrown? NoPermitException (handle-command rename-command [created-event] injections))))))) (deftest add-user-to-congregation-test (let [cong-id (UUID. 0 1) admin-id (UUID. 0 2) new-user-id (UUID. 0 3) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "" :congregation/schema-name ""} add-user-command {:command/type :congregation.command/add-user :command/time (Instant/now) :command/user admin-id :congregation/id cong-id :user/id new-user-id} admin-grants (congregation/admin-permissions-granted cong-id new-user-id) view-granted {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id new-user-id :permission/id :view-congregation}] (testing "user added" (is (= admin-grants (handle-command add-user-command [created-event] injections)))) (testing "user already in congregation" (is (empty? (handle-command add-user-command [created-event view-granted] injections)))) (testing "checks permits" (let [injections (assoc injections :check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil))))] (is (thrown? NoPermitException (handle-command add-user-command [created-event] injections))))))) (deftest set-user-permissions-test (let [cong-id (UUID. 0 1) admin-id (UUID. 0 2) target-user-id (UUID. 0 3) injections {:check-permit (fn [_permit])} created-event {:event/type :congregation.event/congregation-created :congregation/id cong-id :congregation/name "" :congregation/schema-name ""} permission-granted-event {:event/type :congregation.event/permission-granted :congregation/id cong-id :user/id target-user-id :permission/id :PLACEHOLDER} permission-revoked-event {:event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id target-user-id :permission/id :PLACEHOLDER} set-user-permissions-command {:command/type :congregation.command/set-user-permissions :command/time (Instant/now) :command/user admin-id :congregation/id cong-id :user/id target-user-id :permission/ids []}] (testing "grant permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation :configure-congregation]) then [(assoc permission-granted-event :permission/id :configure-congregation)]] (is (= then (handle-command when given injections))))) (testing "revoke permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation) (assoc permission-granted-event :permission/id :configure-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation]) then [(assoc permission-revoked-event :permission/id :configure-congregation)]] (is (= then (handle-command when given injections))))) (testing "setting permissions is idempotent" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids [:view-congregation]) then []] (is (= then (handle-command when given injections))))) (testing "remove user from congregation" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation)] when (assoc set-user-permissions-command :permission/ids []) then [(assoc permission-revoked-event :permission/id :view-congregation)]] (is (= then (handle-command when given injections))))) (testing "cannot be used for adding new users to congregation" (let [given [created-event] when (assoc set-user-permissions-command :permission/ids [:view-congregation])] (is (thrown-with-msg? ValidationException (re-equals "[[:user-not-in-congregation #uuid \"00000000-0000-0000-0000-000000000003\"]]") (handle-command when given injections))))) (testing "cannot revoke :view-congregation without also removing all other permissions" (let [given [created-event (assoc permission-granted-event :permission/id :view-congregation) (assoc permission-granted-event :permission/id :configure-congregation)] when (assoc set-user-permissions-command :permission/ids [:configure-congregation])] (is (thrown-with-msg? ValidationException (re-equals "[[:cannot-revoke-view-congregation]]") (handle-command when given injections))))) (testing "checks permits" (let [injections (assoc injections :check-permit (fn [permit] (is (= [:configure-congregation cong-id] permit)) (throw (NoPermitException. nil nil)))) given [created-event] when (assoc set-user-permissions-command :permission/ids [:view-congregation])] (is (thrown? NoPermitException (handle-command when given injections)))))))
[ { "context": "y contained\"\n ; (let [bob {:kind :author :name \"Bob\"}\n ; presentation (legend/present! bob)]\n", "end": 624, "score": 0.9983497262001038, "start": 621, "tag": "NAME", "value": "Bob" }, { "context": "y contained\"\n ; (let [bob {:kind :author :name \"Bob\"}\n ; coersion (legend/coerce! bob)]\n ; ", "end": 952, "score": 0.9970051050186157, "start": 949, "tag": "NAME", "value": "Bob" }, { "context": "y contained\"\n ; (let [bob {:kind :author :name \"Bob\"}\n ; conformation (legend/conform! bob)]\n", "end": 1150, "score": 0.9968831539154053, "start": 1147, "tag": "NAME", "value": "Bob" } ]
apron/spec/cljc/c3kit/apron/legend_spec.cljc
cleancoders/kit
1
(ns c3kit.apron.legend-spec (:require [c3kit.apron.schema :as s] [c3kit.apron.legend :as sut] [speclj.core #?(:clj :refer :cljs :refer-macros) [context describe it xit should= should-contain should-not-contain should-throw should-not-be-nil with]])) (def foo {:kind (s/kind :foo) :id s/id :name {:type :string} :value {:type :int }}) (describe "Schema Legend" (it "init!" (sut/init! {:foo foo}) (should= {:foo foo} sut/index)) ;(it "presents an entity contained" ; (let [bob {:kind :author :name "Bob"} ; presentation (legend/present! bob)] ; (should= (schema/present! episode.schema/author bob) presentation))) ; ;(it "complains when the entity kind is not in the legend" ; (should-throw (legend/present! {:kind :unknown}))) ; ;(it "coerces an entity contained" ; (let [bob {:kind :author :name "Bob"} ; coersion (legend/coerce! bob)] ; (should= (schema/coerce! episode.schema/author bob) coersion))) ; ;(it "confirms an entity contained" ; (let [bob {:kind :author :name "Bob"} ; conformation (legend/conform! bob)] ; (should= (schema/conform! episode.schema/author bob) conformation))) )
6030
(ns c3kit.apron.legend-spec (:require [c3kit.apron.schema :as s] [c3kit.apron.legend :as sut] [speclj.core #?(:clj :refer :cljs :refer-macros) [context describe it xit should= should-contain should-not-contain should-throw should-not-be-nil with]])) (def foo {:kind (s/kind :foo) :id s/id :name {:type :string} :value {:type :int }}) (describe "Schema Legend" (it "init!" (sut/init! {:foo foo}) (should= {:foo foo} sut/index)) ;(it "presents an entity contained" ; (let [bob {:kind :author :name "<NAME>"} ; presentation (legend/present! bob)] ; (should= (schema/present! episode.schema/author bob) presentation))) ; ;(it "complains when the entity kind is not in the legend" ; (should-throw (legend/present! {:kind :unknown}))) ; ;(it "coerces an entity contained" ; (let [bob {:kind :author :name "<NAME>"} ; coersion (legend/coerce! bob)] ; (should= (schema/coerce! episode.schema/author bob) coersion))) ; ;(it "confirms an entity contained" ; (let [bob {:kind :author :name "<NAME>"} ; conformation (legend/conform! bob)] ; (should= (schema/conform! episode.schema/author bob) conformation))) )
true
(ns c3kit.apron.legend-spec (:require [c3kit.apron.schema :as s] [c3kit.apron.legend :as sut] [speclj.core #?(:clj :refer :cljs :refer-macros) [context describe it xit should= should-contain should-not-contain should-throw should-not-be-nil with]])) (def foo {:kind (s/kind :foo) :id s/id :name {:type :string} :value {:type :int }}) (describe "Schema Legend" (it "init!" (sut/init! {:foo foo}) (should= {:foo foo} sut/index)) ;(it "presents an entity contained" ; (let [bob {:kind :author :name "PI:NAME:<NAME>END_PI"} ; presentation (legend/present! bob)] ; (should= (schema/present! episode.schema/author bob) presentation))) ; ;(it "complains when the entity kind is not in the legend" ; (should-throw (legend/present! {:kind :unknown}))) ; ;(it "coerces an entity contained" ; (let [bob {:kind :author :name "PI:NAME:<NAME>END_PI"} ; coersion (legend/coerce! bob)] ; (should= (schema/coerce! episode.schema/author bob) coersion))) ; ;(it "confirms an entity contained" ; (let [bob {:kind :author :name "PI:NAME:<NAME>END_PI"} ; conformation (legend/conform! bob)] ; (should= (schema/conform! episode.schema/author bob) conformation))) )
[ { "context": "(defproject jstrutz/hashids \"1.0.1\"\n :description \"Generate short", "end": 16, "score": 0.5717676281929016, "start": 12, "tag": "USERNAME", "value": "jstr" }, { "context": "que ids from integers\"\n :url \"https://github.com/jstrutz/hashids.clj\"\n :scm {:name \"git\"\n :url \"ht", "end": 127, "score": 0.9994533658027649, "start": 120, "tag": "USERNAME", "value": "jstrutz" }, { "context": "scm {:name \"git\"\n :url \"https://github.com/jstrutz/hashids.clj\"}\n :license {:name \"MIT License\"\n ", "end": 201, "score": 0.9920499920845032, "start": 194, "tag": "USERNAME", "value": "jstrutz" }, { "context": "ensource.org/licenses/MIT\"}\n :signing {:gpg-key \"j@jasonstrutz.com\"}\n :deploy-repositories [[\"clojars\" {:creds :gpg", "end": 342, "score": 0.9997508525848389, "start": 325, "tag": "EMAIL", "value": "j@jasonstrutz.com" }, { "context": "[:developer\n [:name \"Jason Strutz\"]\n [:url \"http://jas", "end": 487, "score": 0.9985766410827637, "start": 475, "tag": "NAME", "value": "Jason Strutz" }, { "context": "rutz.com\"]\n [:email \"j@jasonstrutz.com\"]\n [:timezone \"-8\"]]", "end": 608, "score": 0.9998709559440613, "start": 591, "tag": "EMAIL", "value": "j@jasonstrutz.com" } ]
project.clj
jstrutz/hashids-clj
84
(defproject jstrutz/hashids "1.0.1" :description "Generate short unique ids from integers" :url "https://github.com/jstrutz/hashids.clj" :scm {:name "git" :url "https://github.com/jstrutz/hashids.clj"} :license {:name "MIT License" :url "http://opensource.org/licenses/MIT"} :signing {:gpg-key "j@jasonstrutz.com"} :deploy-repositories [["clojars" {:creds :gpg}]] :pom-addition [:developers [:developer [:name "Jason Strutz"] [:url "http://jasonstrutz.com"] [:email "j@jasonstrutz.com"] [:timezone "-8"]]] :dependencies [[org.clojure/clojure "1.6.0"]] :profiles {:dev {:dependencies [[org.clojure/test.check "0.7.0"]]}})
76893
(defproject jstrutz/hashids "1.0.1" :description "Generate short unique ids from integers" :url "https://github.com/jstrutz/hashids.clj" :scm {:name "git" :url "https://github.com/jstrutz/hashids.clj"} :license {:name "MIT License" :url "http://opensource.org/licenses/MIT"} :signing {:gpg-key "<EMAIL>"} :deploy-repositories [["clojars" {:creds :gpg}]] :pom-addition [:developers [:developer [:name "<NAME>"] [:url "http://jasonstrutz.com"] [:email "<EMAIL>"] [:timezone "-8"]]] :dependencies [[org.clojure/clojure "1.6.0"]] :profiles {:dev {:dependencies [[org.clojure/test.check "0.7.0"]]}})
true
(defproject jstrutz/hashids "1.0.1" :description "Generate short unique ids from integers" :url "https://github.com/jstrutz/hashids.clj" :scm {:name "git" :url "https://github.com/jstrutz/hashids.clj"} :license {:name "MIT License" :url "http://opensource.org/licenses/MIT"} :signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"} :deploy-repositories [["clojars" {:creds :gpg}]] :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "http://jasonstrutz.com"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:timezone "-8"]]] :dependencies [[org.clojure/clojure "1.6.0"]] :profiles {:dev {:dependencies [[org.clojure/test.check "0.7.0"]]}})
[ { "context": " :password \"hunter2\"}))))\n body (parse-body (:body res", "end": 899, "score": 0.9993384480476379, "start": 892, "tag": "PASSWORD", "value": "hunter2" }, { "context": " :password \"password123\"}))))]\n (:status response) => 401))))", "end": 1353, "score": 0.9993834495544434, "start": 1342, "tag": "PASSWORD", "value": "password123" } ]
test/pigeon_backend/routes/login_routes_test.clj
rulebased-chat/pigeon-backend
0
(ns pigeon-backend.routes.login-routes-test (:require [clojure.test :refer :all] [cheshire.core :as cheshire] [pigeon-backend.handler :refer [app]] [ring.mock.request :as mock] [pigeon-backend.test-util :refer :all] [pigeon-backend.db.migrations :as migrations] [midje.sweet :refer :all] [schema.core :as s])) (deftest login-routes-test (with-state-changes [(before :facts (do (empty-and-create-tables) (migrations/migrate-data-extra)))] (fact (let [response (app (-> (mock/request :post "/api/v0/session") (mock/content-type "application/json") (mock/body (cheshire/generate-string {:username "team_1_player_1" :password "hunter2"})))) body (parse-body (:body response))] (:status response) => 200)) (fact "Incorrect credentials" (let [response (app (-> (mock/request :post "/api/v0/session") (mock/content-type "application/json") (mock/body (cheshire/generate-string {:username "team_1_player_1" :password "password123"}))))] (:status response) => 401))))
121314
(ns pigeon-backend.routes.login-routes-test (:require [clojure.test :refer :all] [cheshire.core :as cheshire] [pigeon-backend.handler :refer [app]] [ring.mock.request :as mock] [pigeon-backend.test-util :refer :all] [pigeon-backend.db.migrations :as migrations] [midje.sweet :refer :all] [schema.core :as s])) (deftest login-routes-test (with-state-changes [(before :facts (do (empty-and-create-tables) (migrations/migrate-data-extra)))] (fact (let [response (app (-> (mock/request :post "/api/v0/session") (mock/content-type "application/json") (mock/body (cheshire/generate-string {:username "team_1_player_1" :password "<PASSWORD>"})))) body (parse-body (:body response))] (:status response) => 200)) (fact "Incorrect credentials" (let [response (app (-> (mock/request :post "/api/v0/session") (mock/content-type "application/json") (mock/body (cheshire/generate-string {:username "team_1_player_1" :password "<PASSWORD>"}))))] (:status response) => 401))))
true
(ns pigeon-backend.routes.login-routes-test (:require [clojure.test :refer :all] [cheshire.core :as cheshire] [pigeon-backend.handler :refer [app]] [ring.mock.request :as mock] [pigeon-backend.test-util :refer :all] [pigeon-backend.db.migrations :as migrations] [midje.sweet :refer :all] [schema.core :as s])) (deftest login-routes-test (with-state-changes [(before :facts (do (empty-and-create-tables) (migrations/migrate-data-extra)))] (fact (let [response (app (-> (mock/request :post "/api/v0/session") (mock/content-type "application/json") (mock/body (cheshire/generate-string {:username "team_1_player_1" :password "PI:PASSWORD:<PASSWORD>END_PI"})))) body (parse-body (:body response))] (:status response) => 200)) (fact "Incorrect credentials" (let [response (app (-> (mock/request :post "/api/v0/session") (mock/content-type "application/json") (mock/body (cheshire/generate-string {:username "team_1_player_1" :password "PI:PASSWORD:<PASSWORD>END_PI"}))))] (:status response) => 401))))
[ { "context": "org\\\"\n :api-key \\\"EDC33DA4D977CFDF7B90545565E07324\\\"\n :app-id \\\"admi", "end": 1285, "score": 0.9997540712356567, "start": 1253, "tag": "KEY", "value": "EDC33DA4D977CFDF7B90545565E07324" } ]
src/clj_osf/ontology/create.clj
structureddynamics/clj-osf
4
(ns clj-osf.ontology.create "Send a Ontology Create service is used to create/import a new OWL ontology into the OSF instance. This service is a web service wrapper over the OWLAPI ontology library. It wraps all the needed functionalities related to ontology creation/import. Most of the relatd API has been implemented. So we can say that web service (with the other related services) turns the OWLAPI into a web service API. This Web service is intended to be used by content management systems, developers or administrators to create ontologies that are hosted on a OSF instance, and that are used to describe the named entities in the system. This endpoint, along with the other related endpoints: Ontology Read, Ontology Update and Ontology Delete; can be seen as the brain of your OSF instance. To use the Ontology: Create code, you have to: ``` ;; Use/require the namespace (require '[clj-osf.ontology.create :as ontology-c]) ;; Define the OSF Sandbox credentials (or your own): (require '[clj-osf.core :as osf]) (osf/defosf osf-test-endpoint {:protocol :http :domain \"sandbox.opensemanticframework.org\" :api-key \"EDC33DA4D977CFDF7B90545565E07324\" :app-id \"administer\"}) (osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"}) ``` [Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/Ontology_Create#Web_Service_Endpoint_Information)" (:require [clj-osf.core :as core] [clojure.string :as string])) (defn uri "Specifies the URI of the ontology. *Note:* you can get the list of all loaded ontologies by using the `(osf-clj.ontology.read/get-loaded-ontologies)` function The usage of this function is **Required** ##### Parameters * `[uri]` Specifies the URI of the ontology; the URI is the URL used to import that ontology in the system. The URL can be the URI of the ontology if it was resolvable on the Web, or the URL where the OWL file, containing the ontology's description, that can be resolved on the Web by this endpoint. This URL can refers to a file accessible on the web, on the file system, etc. The endpoint will get the ontology's description from that URL. ##### Usage ``` (ontology/create (ontology/uri \"http://purl.org/ontology/bibo/\")) ```" [uri] {:uri uri}) (defn enable-reasoner "Enable the reasoner for indexing the ontology into OSF (the triple store and the full text engine) This is the default behavior of this service. ##### Usage ``` (ontology/create (ontology/enable-reasoner) ```" [] {:reasoner "True"}) (defn disable-reasoner "Disable the reasoner for for indexing the ontology into OSF (the triple store and the full text engine) ##### Usage ``` (ontology/create (ontology/disable-reasoner) ```" [] {:reasoner "False"}) (defn enable-advanced-indexation "Enable advanced indexation of the ontology. This means that the ontology's description (so all the classes, properties and named individuals) will be indexed in the other data management system in OSF. This means that all the information in these ontologies will be accessible via the other endpoints such as the Search and the SPARQL web service endpoints. Enabling this option may render the creation process slower depending on the size of the created ontology. ##### Usage ``` (ontology/create (ontology/enable-advanced-indexation) ```" [] {:advancedIndexation "True"}) (defn disable-advanced-indexation "Disable advanced indexation of the ontology. This means that the ontologies will be queriable via the Ontology Read, Ontology Update and Ontology Delete web service endpoints only This is the default behavior of this service. ##### Usage ``` (ontology/create (ontology/disable-advanced-indexation) ```" [] {:advancedIndexation "False"}) (defn create "Ontology: Create query. **Required** ##### Usage ``` ;; Create/import an ontology from a dereferencable URI on the Web (ontology-c/create (ontology-c/enable-advanced-indexation) (ontology-c/enable-reasoner) (ontology-c/uri \"http://purl.org/ontology/bibo/\")) ```" [& body] (let [params (apply merge body) default (apply merge (core/->post) (core/->mime "application/json")) params (merge default params)] (core/osf-query "/ws/ontology/create/" params)))
116083
(ns clj-osf.ontology.create "Send a Ontology Create service is used to create/import a new OWL ontology into the OSF instance. This service is a web service wrapper over the OWLAPI ontology library. It wraps all the needed functionalities related to ontology creation/import. Most of the relatd API has been implemented. So we can say that web service (with the other related services) turns the OWLAPI into a web service API. This Web service is intended to be used by content management systems, developers or administrators to create ontologies that are hosted on a OSF instance, and that are used to describe the named entities in the system. This endpoint, along with the other related endpoints: Ontology Read, Ontology Update and Ontology Delete; can be seen as the brain of your OSF instance. To use the Ontology: Create code, you have to: ``` ;; Use/require the namespace (require '[clj-osf.ontology.create :as ontology-c]) ;; Define the OSF Sandbox credentials (or your own): (require '[clj-osf.core :as osf]) (osf/defosf osf-test-endpoint {:protocol :http :domain \"sandbox.opensemanticframework.org\" :api-key \"<KEY>\" :app-id \"administer\"}) (osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"}) ``` [Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/Ontology_Create#Web_Service_Endpoint_Information)" (:require [clj-osf.core :as core] [clojure.string :as string])) (defn uri "Specifies the URI of the ontology. *Note:* you can get the list of all loaded ontologies by using the `(osf-clj.ontology.read/get-loaded-ontologies)` function The usage of this function is **Required** ##### Parameters * `[uri]` Specifies the URI of the ontology; the URI is the URL used to import that ontology in the system. The URL can be the URI of the ontology if it was resolvable on the Web, or the URL where the OWL file, containing the ontology's description, that can be resolved on the Web by this endpoint. This URL can refers to a file accessible on the web, on the file system, etc. The endpoint will get the ontology's description from that URL. ##### Usage ``` (ontology/create (ontology/uri \"http://purl.org/ontology/bibo/\")) ```" [uri] {:uri uri}) (defn enable-reasoner "Enable the reasoner for indexing the ontology into OSF (the triple store and the full text engine) This is the default behavior of this service. ##### Usage ``` (ontology/create (ontology/enable-reasoner) ```" [] {:reasoner "True"}) (defn disable-reasoner "Disable the reasoner for for indexing the ontology into OSF (the triple store and the full text engine) ##### Usage ``` (ontology/create (ontology/disable-reasoner) ```" [] {:reasoner "False"}) (defn enable-advanced-indexation "Enable advanced indexation of the ontology. This means that the ontology's description (so all the classes, properties and named individuals) will be indexed in the other data management system in OSF. This means that all the information in these ontologies will be accessible via the other endpoints such as the Search and the SPARQL web service endpoints. Enabling this option may render the creation process slower depending on the size of the created ontology. ##### Usage ``` (ontology/create (ontology/enable-advanced-indexation) ```" [] {:advancedIndexation "True"}) (defn disable-advanced-indexation "Disable advanced indexation of the ontology. This means that the ontologies will be queriable via the Ontology Read, Ontology Update and Ontology Delete web service endpoints only This is the default behavior of this service. ##### Usage ``` (ontology/create (ontology/disable-advanced-indexation) ```" [] {:advancedIndexation "False"}) (defn create "Ontology: Create query. **Required** ##### Usage ``` ;; Create/import an ontology from a dereferencable URI on the Web (ontology-c/create (ontology-c/enable-advanced-indexation) (ontology-c/enable-reasoner) (ontology-c/uri \"http://purl.org/ontology/bibo/\")) ```" [& body] (let [params (apply merge body) default (apply merge (core/->post) (core/->mime "application/json")) params (merge default params)] (core/osf-query "/ws/ontology/create/" params)))
true
(ns clj-osf.ontology.create "Send a Ontology Create service is used to create/import a new OWL ontology into the OSF instance. This service is a web service wrapper over the OWLAPI ontology library. It wraps all the needed functionalities related to ontology creation/import. Most of the relatd API has been implemented. So we can say that web service (with the other related services) turns the OWLAPI into a web service API. This Web service is intended to be used by content management systems, developers or administrators to create ontologies that are hosted on a OSF instance, and that are used to describe the named entities in the system. This endpoint, along with the other related endpoints: Ontology Read, Ontology Update and Ontology Delete; can be seen as the brain of your OSF instance. To use the Ontology: Create code, you have to: ``` ;; Use/require the namespace (require '[clj-osf.ontology.create :as ontology-c]) ;; Define the OSF Sandbox credentials (or your own): (require '[clj-osf.core :as osf]) (osf/defosf osf-test-endpoint {:protocol :http :domain \"sandbox.opensemanticframework.org\" :api-key \"PI:KEY:<KEY>END_PI\" :app-id \"administer\"}) (osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"}) ``` [Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/Ontology_Create#Web_Service_Endpoint_Information)" (:require [clj-osf.core :as core] [clojure.string :as string])) (defn uri "Specifies the URI of the ontology. *Note:* you can get the list of all loaded ontologies by using the `(osf-clj.ontology.read/get-loaded-ontologies)` function The usage of this function is **Required** ##### Parameters * `[uri]` Specifies the URI of the ontology; the URI is the URL used to import that ontology in the system. The URL can be the URI of the ontology if it was resolvable on the Web, or the URL where the OWL file, containing the ontology's description, that can be resolved on the Web by this endpoint. This URL can refers to a file accessible on the web, on the file system, etc. The endpoint will get the ontology's description from that URL. ##### Usage ``` (ontology/create (ontology/uri \"http://purl.org/ontology/bibo/\")) ```" [uri] {:uri uri}) (defn enable-reasoner "Enable the reasoner for indexing the ontology into OSF (the triple store and the full text engine) This is the default behavior of this service. ##### Usage ``` (ontology/create (ontology/enable-reasoner) ```" [] {:reasoner "True"}) (defn disable-reasoner "Disable the reasoner for for indexing the ontology into OSF (the triple store and the full text engine) ##### Usage ``` (ontology/create (ontology/disable-reasoner) ```" [] {:reasoner "False"}) (defn enable-advanced-indexation "Enable advanced indexation of the ontology. This means that the ontology's description (so all the classes, properties and named individuals) will be indexed in the other data management system in OSF. This means that all the information in these ontologies will be accessible via the other endpoints such as the Search and the SPARQL web service endpoints. Enabling this option may render the creation process slower depending on the size of the created ontology. ##### Usage ``` (ontology/create (ontology/enable-advanced-indexation) ```" [] {:advancedIndexation "True"}) (defn disable-advanced-indexation "Disable advanced indexation of the ontology. This means that the ontologies will be queriable via the Ontology Read, Ontology Update and Ontology Delete web service endpoints only This is the default behavior of this service. ##### Usage ``` (ontology/create (ontology/disable-advanced-indexation) ```" [] {:advancedIndexation "False"}) (defn create "Ontology: Create query. **Required** ##### Usage ``` ;; Create/import an ontology from a dereferencable URI on the Web (ontology-c/create (ontology-c/enable-advanced-indexation) (ontology-c/enable-reasoner) (ontology-c/uri \"http://purl.org/ontology/bibo/\")) ```" [& body] (let [params (apply merge body) default (apply merge (core/->post) (core/->mime "application/json")) params (merge default params)] (core/osf-query "/ws/ontology/create/" params)))
[ { "context": "\n :authentication {:username \"zcaudate\"\n :password ", "end": 2012, "score": 0.9995166063308716, "start": 2004, "tag": "USERNAME", "value": "zcaudate" }, { "context": "\n :password \"hello\"}}\n RemoteRepository)\n ;;=> #", "end": 2068, "score": 0.9994096159934998, "start": 2063, "tag": "PASSWORD", "value": "hello" }, { "context": "itory)\n ;;=> #remote{:authentication {:username \"zcaudate\", :password \"hello\"},\n ;; :content-typ", "end": 2161, "score": 0.9979777336120605, "start": 2153, "tag": "USERNAME", "value": "zcaudate" }, { "context": ":authentication {:username \"zcaudate\", :password \"hello\"},\n ;; :content-type \"default\",\n ;; ", "end": 2180, "score": 0.9994264841079712, "start": 2175, "tag": "PASSWORD", "value": "hello" }, { "context": " :host \"clojars.org\",\n ;; :id \"clojars\",\n ;; :mirrored-repositories [],\n ;; ", "end": 2287, "score": 0.9963100552558899, "start": 2280, "tag": "USERNAME", "value": "clojars" } ]
test/lucid/aether/remote_repo_test.clj
willcohen/lucidity
3
(ns lucid.aether.remote-repo-test (:use hara.test) (:require [hara.object :as object]) (:import (org.eclipse.aether.repository RemoteRepository RemoteRepository$Builder RepositoryPolicy))) ^{:refer lucid.aether.remote-repo/repository-policy :added "1.2"} (comment "creates a `RepositoryPolicy` from map" (object/from-data {:checksum-policy "warn", :update-policy "daily", :enabled? true} RepositoryPolicy) ;;=> #policy{:checksum-policy "warn", :update-policy "daily", :enabled? true} ) ^{:refer lucid.aether.remote-repo/remote-repository-builder :added "1.2"} (comment "creates a `RemoteRepository$Builder` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/"} RemoteRepository$Builder) ;;=> #builder.remote{:repository-manager false ;; :type "default" ;; :default-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :release-policy {:checksum-policy "warn" ;; :update-policy "daily" ;; :enabled? true} ;; :snapshots-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :id "clojars" ;; :url "http://clojars.org/repo/"} ) ^{:refer lucid.aether.remote-repo/remote-repository :added "1.2"} (comment "creates a `RemoteRepository` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/" :authentication {:username "zcaudate" :password "hello"}} RemoteRepository) ;;=> #remote{:authentication {:username "zcaudate", :password "hello"}, ;; :content-type "default", ;; :host "clojars.org", ;; :id "clojars", ;; :mirrored-repositories [], ;; :protocol "http", ;; :url "http://clojars.org/repo/", ;; :repository-manager? false} )
9322
(ns lucid.aether.remote-repo-test (:use hara.test) (:require [hara.object :as object]) (:import (org.eclipse.aether.repository RemoteRepository RemoteRepository$Builder RepositoryPolicy))) ^{:refer lucid.aether.remote-repo/repository-policy :added "1.2"} (comment "creates a `RepositoryPolicy` from map" (object/from-data {:checksum-policy "warn", :update-policy "daily", :enabled? true} RepositoryPolicy) ;;=> #policy{:checksum-policy "warn", :update-policy "daily", :enabled? true} ) ^{:refer lucid.aether.remote-repo/remote-repository-builder :added "1.2"} (comment "creates a `RemoteRepository$Builder` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/"} RemoteRepository$Builder) ;;=> #builder.remote{:repository-manager false ;; :type "default" ;; :default-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :release-policy {:checksum-policy "warn" ;; :update-policy "daily" ;; :enabled? true} ;; :snapshots-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :id "clojars" ;; :url "http://clojars.org/repo/"} ) ^{:refer lucid.aether.remote-repo/remote-repository :added "1.2"} (comment "creates a `RemoteRepository` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/" :authentication {:username "zcaudate" :password "<PASSWORD>"}} RemoteRepository) ;;=> #remote{:authentication {:username "zcaudate", :password "<PASSWORD>"}, ;; :content-type "default", ;; :host "clojars.org", ;; :id "clojars", ;; :mirrored-repositories [], ;; :protocol "http", ;; :url "http://clojars.org/repo/", ;; :repository-manager? false} )
true
(ns lucid.aether.remote-repo-test (:use hara.test) (:require [hara.object :as object]) (:import (org.eclipse.aether.repository RemoteRepository RemoteRepository$Builder RepositoryPolicy))) ^{:refer lucid.aether.remote-repo/repository-policy :added "1.2"} (comment "creates a `RepositoryPolicy` from map" (object/from-data {:checksum-policy "warn", :update-policy "daily", :enabled? true} RepositoryPolicy) ;;=> #policy{:checksum-policy "warn", :update-policy "daily", :enabled? true} ) ^{:refer lucid.aether.remote-repo/remote-repository-builder :added "1.2"} (comment "creates a `RemoteRepository$Builder` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/"} RemoteRepository$Builder) ;;=> #builder.remote{:repository-manager false ;; :type "default" ;; :default-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :release-policy {:checksum-policy "warn" ;; :update-policy "daily" ;; :enabled? true} ;; :snapshots-policy {:checksum-policy "warn", ;; :update-policy "daily", ;; :enabled? true}, ;; :id "clojars" ;; :url "http://clojars.org/repo/"} ) ^{:refer lucid.aether.remote-repo/remote-repository :added "1.2"} (comment "creates a `RemoteRepository` from map" (object/from-data {:id "clojars" :type "default" :url "http://clojars.org/repo/" :authentication {:username "zcaudate" :password "PI:PASSWORD:<PASSWORD>END_PI"}} RemoteRepository) ;;=> #remote{:authentication {:username "zcaudate", :password "PI:PASSWORD:<PASSWORD>END_PI"}, ;; :content-type "default", ;; :host "clojars.org", ;; :id "clojars", ;; :mirrored-repositories [], ;; :protocol "http", ;; :url "http://clojars.org/repo/", ;; :repository-manager? false} )
[ { "context": " form \"user-id\")\n password (get form \"password\")\n email (get form \"email\")\n ", "end": 3188, "score": 0.6939240097999573, "start": 3180, "tag": "PASSWORD", "value": "password" }, { "context": "\" :label \"Password\" :password? true :placeholder \"password\"}\n {:name \"name\" :label \"Name\" :p", "end": 6290, "score": 0.5366673469543457, "start": 6282, "tag": "PASSWORD", "value": "password" } ]
src/cylon/signup/signup.clj
michaelklishin/cylon
1
(ns cylon.signup.signup (:require [cylon.signup.protocols :refer (render-signup-form send-email render-email-verified Emailer SignupFormRenderer WelcomeRenderer render-welcome)] [clojure.tools.logging :refer :all] [cylon.session :refer (session respond-with-new-session! assoc-session-data!)] [cylon.session.protocols :refer (SessionStore)] [cylon.token-store :refer (create-token! get-token-by-id)] [cylon.token-store.protocols :refer (TokenStore)] [cylon.password.protocols :refer (PasswordVerifier make-password-hash)] [com.stuartsierra.component :as component :refer (Lifecycle)] [modular.bidi :refer (WebService path-for)] [hiccup.core :refer (html)] [ring.middleware.params :refer (params-request)] [ring.middleware.cookies :refer (cookies-response wrap-cookies)] [ring.util.response :refer (response redirect)] [cylon.user :refer (create-user! verify-email!)] [cylon.user.protocols :refer (UserStore)] [cylon.totp :as totp] [cylon.totp :refer (OneTimePasswordStore get-totp-secret set-totp-secret totp-token)] [schema.core :as s ])) (defn make-verification-link [req code email] (let [values ((juxt (comp name :scheme) :server-name :server-port) req) verify-user-email-path (path-for req ::verify-user-email)] (apply format "%s://%s:%d%s?code=%s&email=%s" (conj values verify-user-email-path code email)))) (def new-signup-with-totp-schema {:fields [{:name s/Str :label s/Str (s/optional-key :placeholder) s/Str (s/optional-key :password?) s/Bool}]}) (defrecord SignupWithTotp [renderer session-store user-store password-verifier verification-code-store emailer fields] Lifecycle (start [component] (s/validate (merge new-signup-with-totp-schema {:user-store (s/protocol UserStore) :session-store (s/protocol SessionStore) :password-verifier (s/protocol PasswordVerifier) :verification-code-store (s/protocol TokenStore) :renderer (s/both (s/protocol SignupFormRenderer) (s/protocol WelcomeRenderer)) (s/optional-key :emailer) (s/protocol Emailer)}) component)) (stop [component] component) WebService (request-handlers [this] {::GET-signup-form (fn [req] (let [resp (response (render-signup-form renderer req {:form {:method :post :action (path-for req ::POST-signup-form) :fields fields}}))] (if-not (session session-store req) ;; We create an empty session. This is because the POST ;; handler requires that a session exists within which it can ;; store the identity on a successful login (respond-with-new-session! session-store req {} resp) resp))) ::POST-signup-form (fn [req] (debugf "Processing signup") (let [form (-> req params-request :form-params) uid (get form "user-id") password (get form "password") email (get form "email") name (get form "name") totp-secret (when (satisfies? OneTimePasswordStore user-store) (totp/secret-key))] ;; Add the user (create-user! user-store uid (make-password-hash password-verifier password) email {:name name}) ;; Add the totp-secret (when (satisfies? OneTimePasswordStore user-store) (set-totp-secret user-store uid totp-secret)) ;; Send the email to the user now! (when emailer ;; TODO Possibly we should encrypt and decrypt the verification-code (symmetric) (let [code (str (java.util.UUID/randomUUID))] (create-token! verification-code-store code {:email email :id uid}) (send-email emailer email (format "Thanks for signing up. Please click on this link to verify your account: %s" (make-verification-link req code email))))) ;; Create a session that contains the secret-key (let [data (merge {:cylon/subject-identifier uid :name name} (when (satisfies? OneTimePasswordStore user-store) {:totp-secret totp-secret}) )] (assoc-session-data! session-store req data) (response (render-welcome renderer req (merge {:session (session session-store req)} form data)))))) ::verify-user-email (fn [req] (let [params (-> req params-request :params) body (if-let [[email code] [ (get params "email") (get params "code")]] (if-let [store (get-token-by-id (:verification-code-store this) code)] (if (= email (:email store)) (do (verify-email! user-store (:name store)) (format "Thanks, Your email '%s' has been verified correctly " email)) (format "Sorry but your session associated with this email '%s' seems to not be logic" email)) (format "Sorry but your session associated with this email '%s' seems to not be valid" email)) (format "Sorry but there were problems trying to retrieve your data related with your mail '%s' " (get params "email")))] (response (render-email-verified renderer req {:message body})))) }) (routes [this] ["/" {"signup" {:get ::GET-signup-form :post ::POST-signup-form} "verify-email" {:get ::verify-user-email} }]) (uri-context [this] "")) (defn new-signup-with-totp [& {:as opts}] (component/using (->> opts (merge {:fields [{:name "user-id" :label "User" :placeholder "id"} {:name "password" :label "Password" :password? true :placeholder "password"} {:name "name" :label "Name" :placeholder "name"} {:name "email" :label "Email" :placeholder "email"}] }) (s/validate new-signup-with-totp-schema) map->SignupWithTotp) [:user-store :password-verifier :session-store :renderer :verification-code-store :emailer]))
68374
(ns cylon.signup.signup (:require [cylon.signup.protocols :refer (render-signup-form send-email render-email-verified Emailer SignupFormRenderer WelcomeRenderer render-welcome)] [clojure.tools.logging :refer :all] [cylon.session :refer (session respond-with-new-session! assoc-session-data!)] [cylon.session.protocols :refer (SessionStore)] [cylon.token-store :refer (create-token! get-token-by-id)] [cylon.token-store.protocols :refer (TokenStore)] [cylon.password.protocols :refer (PasswordVerifier make-password-hash)] [com.stuartsierra.component :as component :refer (Lifecycle)] [modular.bidi :refer (WebService path-for)] [hiccup.core :refer (html)] [ring.middleware.params :refer (params-request)] [ring.middleware.cookies :refer (cookies-response wrap-cookies)] [ring.util.response :refer (response redirect)] [cylon.user :refer (create-user! verify-email!)] [cylon.user.protocols :refer (UserStore)] [cylon.totp :as totp] [cylon.totp :refer (OneTimePasswordStore get-totp-secret set-totp-secret totp-token)] [schema.core :as s ])) (defn make-verification-link [req code email] (let [values ((juxt (comp name :scheme) :server-name :server-port) req) verify-user-email-path (path-for req ::verify-user-email)] (apply format "%s://%s:%d%s?code=%s&email=%s" (conj values verify-user-email-path code email)))) (def new-signup-with-totp-schema {:fields [{:name s/Str :label s/Str (s/optional-key :placeholder) s/Str (s/optional-key :password?) s/Bool}]}) (defrecord SignupWithTotp [renderer session-store user-store password-verifier verification-code-store emailer fields] Lifecycle (start [component] (s/validate (merge new-signup-with-totp-schema {:user-store (s/protocol UserStore) :session-store (s/protocol SessionStore) :password-verifier (s/protocol PasswordVerifier) :verification-code-store (s/protocol TokenStore) :renderer (s/both (s/protocol SignupFormRenderer) (s/protocol WelcomeRenderer)) (s/optional-key :emailer) (s/protocol Emailer)}) component)) (stop [component] component) WebService (request-handlers [this] {::GET-signup-form (fn [req] (let [resp (response (render-signup-form renderer req {:form {:method :post :action (path-for req ::POST-signup-form) :fields fields}}))] (if-not (session session-store req) ;; We create an empty session. This is because the POST ;; handler requires that a session exists within which it can ;; store the identity on a successful login (respond-with-new-session! session-store req {} resp) resp))) ::POST-signup-form (fn [req] (debugf "Processing signup") (let [form (-> req params-request :form-params) uid (get form "user-id") password (get form "<PASSWORD>") email (get form "email") name (get form "name") totp-secret (when (satisfies? OneTimePasswordStore user-store) (totp/secret-key))] ;; Add the user (create-user! user-store uid (make-password-hash password-verifier password) email {:name name}) ;; Add the totp-secret (when (satisfies? OneTimePasswordStore user-store) (set-totp-secret user-store uid totp-secret)) ;; Send the email to the user now! (when emailer ;; TODO Possibly we should encrypt and decrypt the verification-code (symmetric) (let [code (str (java.util.UUID/randomUUID))] (create-token! verification-code-store code {:email email :id uid}) (send-email emailer email (format "Thanks for signing up. Please click on this link to verify your account: %s" (make-verification-link req code email))))) ;; Create a session that contains the secret-key (let [data (merge {:cylon/subject-identifier uid :name name} (when (satisfies? OneTimePasswordStore user-store) {:totp-secret totp-secret}) )] (assoc-session-data! session-store req data) (response (render-welcome renderer req (merge {:session (session session-store req)} form data)))))) ::verify-user-email (fn [req] (let [params (-> req params-request :params) body (if-let [[email code] [ (get params "email") (get params "code")]] (if-let [store (get-token-by-id (:verification-code-store this) code)] (if (= email (:email store)) (do (verify-email! user-store (:name store)) (format "Thanks, Your email '%s' has been verified correctly " email)) (format "Sorry but your session associated with this email '%s' seems to not be logic" email)) (format "Sorry but your session associated with this email '%s' seems to not be valid" email)) (format "Sorry but there were problems trying to retrieve your data related with your mail '%s' " (get params "email")))] (response (render-email-verified renderer req {:message body})))) }) (routes [this] ["/" {"signup" {:get ::GET-signup-form :post ::POST-signup-form} "verify-email" {:get ::verify-user-email} }]) (uri-context [this] "")) (defn new-signup-with-totp [& {:as opts}] (component/using (->> opts (merge {:fields [{:name "user-id" :label "User" :placeholder "id"} {:name "password" :label "Password" :password? true :placeholder "<PASSWORD>"} {:name "name" :label "Name" :placeholder "name"} {:name "email" :label "Email" :placeholder "email"}] }) (s/validate new-signup-with-totp-schema) map->SignupWithTotp) [:user-store :password-verifier :session-store :renderer :verification-code-store :emailer]))
true
(ns cylon.signup.signup (:require [cylon.signup.protocols :refer (render-signup-form send-email render-email-verified Emailer SignupFormRenderer WelcomeRenderer render-welcome)] [clojure.tools.logging :refer :all] [cylon.session :refer (session respond-with-new-session! assoc-session-data!)] [cylon.session.protocols :refer (SessionStore)] [cylon.token-store :refer (create-token! get-token-by-id)] [cylon.token-store.protocols :refer (TokenStore)] [cylon.password.protocols :refer (PasswordVerifier make-password-hash)] [com.stuartsierra.component :as component :refer (Lifecycle)] [modular.bidi :refer (WebService path-for)] [hiccup.core :refer (html)] [ring.middleware.params :refer (params-request)] [ring.middleware.cookies :refer (cookies-response wrap-cookies)] [ring.util.response :refer (response redirect)] [cylon.user :refer (create-user! verify-email!)] [cylon.user.protocols :refer (UserStore)] [cylon.totp :as totp] [cylon.totp :refer (OneTimePasswordStore get-totp-secret set-totp-secret totp-token)] [schema.core :as s ])) (defn make-verification-link [req code email] (let [values ((juxt (comp name :scheme) :server-name :server-port) req) verify-user-email-path (path-for req ::verify-user-email)] (apply format "%s://%s:%d%s?code=%s&email=%s" (conj values verify-user-email-path code email)))) (def new-signup-with-totp-schema {:fields [{:name s/Str :label s/Str (s/optional-key :placeholder) s/Str (s/optional-key :password?) s/Bool}]}) (defrecord SignupWithTotp [renderer session-store user-store password-verifier verification-code-store emailer fields] Lifecycle (start [component] (s/validate (merge new-signup-with-totp-schema {:user-store (s/protocol UserStore) :session-store (s/protocol SessionStore) :password-verifier (s/protocol PasswordVerifier) :verification-code-store (s/protocol TokenStore) :renderer (s/both (s/protocol SignupFormRenderer) (s/protocol WelcomeRenderer)) (s/optional-key :emailer) (s/protocol Emailer)}) component)) (stop [component] component) WebService (request-handlers [this] {::GET-signup-form (fn [req] (let [resp (response (render-signup-form renderer req {:form {:method :post :action (path-for req ::POST-signup-form) :fields fields}}))] (if-not (session session-store req) ;; We create an empty session. This is because the POST ;; handler requires that a session exists within which it can ;; store the identity on a successful login (respond-with-new-session! session-store req {} resp) resp))) ::POST-signup-form (fn [req] (debugf "Processing signup") (let [form (-> req params-request :form-params) uid (get form "user-id") password (get form "PI:PASSWORD:<PASSWORD>END_PI") email (get form "email") name (get form "name") totp-secret (when (satisfies? OneTimePasswordStore user-store) (totp/secret-key))] ;; Add the user (create-user! user-store uid (make-password-hash password-verifier password) email {:name name}) ;; Add the totp-secret (when (satisfies? OneTimePasswordStore user-store) (set-totp-secret user-store uid totp-secret)) ;; Send the email to the user now! (when emailer ;; TODO Possibly we should encrypt and decrypt the verification-code (symmetric) (let [code (str (java.util.UUID/randomUUID))] (create-token! verification-code-store code {:email email :id uid}) (send-email emailer email (format "Thanks for signing up. Please click on this link to verify your account: %s" (make-verification-link req code email))))) ;; Create a session that contains the secret-key (let [data (merge {:cylon/subject-identifier uid :name name} (when (satisfies? OneTimePasswordStore user-store) {:totp-secret totp-secret}) )] (assoc-session-data! session-store req data) (response (render-welcome renderer req (merge {:session (session session-store req)} form data)))))) ::verify-user-email (fn [req] (let [params (-> req params-request :params) body (if-let [[email code] [ (get params "email") (get params "code")]] (if-let [store (get-token-by-id (:verification-code-store this) code)] (if (= email (:email store)) (do (verify-email! user-store (:name store)) (format "Thanks, Your email '%s' has been verified correctly " email)) (format "Sorry but your session associated with this email '%s' seems to not be logic" email)) (format "Sorry but your session associated with this email '%s' seems to not be valid" email)) (format "Sorry but there were problems trying to retrieve your data related with your mail '%s' " (get params "email")))] (response (render-email-verified renderer req {:message body})))) }) (routes [this] ["/" {"signup" {:get ::GET-signup-form :post ::POST-signup-form} "verify-email" {:get ::verify-user-email} }]) (uri-context [this] "")) (defn new-signup-with-totp [& {:as opts}] (component/using (->> opts (merge {:fields [{:name "user-id" :label "User" :placeholder "id"} {:name "password" :label "Password" :password? true :placeholder "PI:PASSWORD:<PASSWORD>END_PI"} {:name "name" :label "Name" :placeholder "name"} {:name "email" :label "Email" :placeholder "email"}] }) (s/validate new-signup-with-totp-schema) map->SignupWithTotp) [:user-store :password-verifier :session-store :renderer :verification-code-store :emailer]))
[ { "context": " :new_password (s/maybe (:password User))\n :new_password_ver", "end": 2700, "score": 0.6626996397972107, "start": 2696, "tag": "PASSWORD", "value": "User" }, { "context": " :new_password_verify (s/maybe (:password User))})\n\n(s/defschema EmailAddress {:email ", "end": 2778, "score": 0.5212565660476685, "start": 2774, "tag": "PASSWORD", "value": "User" } ]
src/cljc/salava/user/schemas.cljc
Vilikkki/salava
17
(ns salava.user.schemas (:require [schema.core :as s :include-macros true] ;; cljs only [salava.core.schema-helper :as h] [salava.core.countries :refer [all-countries]])) (def contact-fields [{:type "email" :key :user/Emailaddress} {:type "phone" :key :user/Phonenumber} {:type "address" :key :user/Address} {:type "city" :key :user/City} {:type "state" :key :user/State} {:type "country" :key :user/Country} {:type "facebook" :key :user/Facebookaccount} {:type "linkedin" :key :user/LinkedInaccount} {:type "twitter" :key :user/Twitteraccount} {:type "pinterest" :key :user/Pinterestaccount} {:type "instagram" :key :user/Instagramaccount} {:type "blog" :key :user/Blog}]) (s/defschema User {:email (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255) (h/email-address? %))) :first_name (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255))) :last_name (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255))) :country (apply s/enum (keys all-countries)) :language (s/enum "fi" "en" "fr" "es" "pl" "pt" "ar" "nl" "sv") :password (s/constrained s/Str #(and (>= (count %) 6) (<= (count %) 50))) :password_verify (s/constrained s/Str #(and (>= (count %) 6) (<= (count %) 50))) :profile_visibility (s/enum "public" "internal") :profile_picture (s/maybe s/Str) :about (s/maybe s/Str)}) (s/defschema RegisterUser (merge {:token (s/maybe s/Str) :accept_terms (s/enum "accepted" "declined")} (dissoc User :profile_visibility :profile_picture :about))) (s/defschema LoginUser (select-keys User [:email :password])) (s/defschema ActivateUser (merge {:code s/Str :user_id s/Int} (select-keys User [:password :password_verify]))) (s/defschema EditUser (-> {:email_notifications s/Bool} (merge (select-keys User [:first_name :last_name :language :country])))) (s/defschema EditUserPassword{:current_password (s/maybe (:password User)) :new_password (s/maybe (:password User)) :new_password_verify (s/maybe (:password User))}) (s/defschema EmailAddress {:email (:email User) :verified s/Bool :primary_address s/Bool :backpack_id (s/maybe s/Int) :ctime s/Int :mtime s/Int})
30158
(ns salava.user.schemas (:require [schema.core :as s :include-macros true] ;; cljs only [salava.core.schema-helper :as h] [salava.core.countries :refer [all-countries]])) (def contact-fields [{:type "email" :key :user/Emailaddress} {:type "phone" :key :user/Phonenumber} {:type "address" :key :user/Address} {:type "city" :key :user/City} {:type "state" :key :user/State} {:type "country" :key :user/Country} {:type "facebook" :key :user/Facebookaccount} {:type "linkedin" :key :user/LinkedInaccount} {:type "twitter" :key :user/Twitteraccount} {:type "pinterest" :key :user/Pinterestaccount} {:type "instagram" :key :user/Instagramaccount} {:type "blog" :key :user/Blog}]) (s/defschema User {:email (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255) (h/email-address? %))) :first_name (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255))) :last_name (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255))) :country (apply s/enum (keys all-countries)) :language (s/enum "fi" "en" "fr" "es" "pl" "pt" "ar" "nl" "sv") :password (s/constrained s/Str #(and (>= (count %) 6) (<= (count %) 50))) :password_verify (s/constrained s/Str #(and (>= (count %) 6) (<= (count %) 50))) :profile_visibility (s/enum "public" "internal") :profile_picture (s/maybe s/Str) :about (s/maybe s/Str)}) (s/defschema RegisterUser (merge {:token (s/maybe s/Str) :accept_terms (s/enum "accepted" "declined")} (dissoc User :profile_visibility :profile_picture :about))) (s/defschema LoginUser (select-keys User [:email :password])) (s/defschema ActivateUser (merge {:code s/Str :user_id s/Int} (select-keys User [:password :password_verify]))) (s/defschema EditUser (-> {:email_notifications s/Bool} (merge (select-keys User [:first_name :last_name :language :country])))) (s/defschema EditUserPassword{:current_password (s/maybe (:password User)) :new_password (s/maybe (:password <PASSWORD>)) :new_password_verify (s/maybe (:password <PASSWORD>))}) (s/defschema EmailAddress {:email (:email User) :verified s/Bool :primary_address s/Bool :backpack_id (s/maybe s/Int) :ctime s/Int :mtime s/Int})
true
(ns salava.user.schemas (:require [schema.core :as s :include-macros true] ;; cljs only [salava.core.schema-helper :as h] [salava.core.countries :refer [all-countries]])) (def contact-fields [{:type "email" :key :user/Emailaddress} {:type "phone" :key :user/Phonenumber} {:type "address" :key :user/Address} {:type "city" :key :user/City} {:type "state" :key :user/State} {:type "country" :key :user/Country} {:type "facebook" :key :user/Facebookaccount} {:type "linkedin" :key :user/LinkedInaccount} {:type "twitter" :key :user/Twitteraccount} {:type "pinterest" :key :user/Pinterestaccount} {:type "instagram" :key :user/Instagramaccount} {:type "blog" :key :user/Blog}]) (s/defschema User {:email (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255) (h/email-address? %))) :first_name (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255))) :last_name (s/constrained s/Str #(and (>= (count %) 1) (<= (count %) 255))) :country (apply s/enum (keys all-countries)) :language (s/enum "fi" "en" "fr" "es" "pl" "pt" "ar" "nl" "sv") :password (s/constrained s/Str #(and (>= (count %) 6) (<= (count %) 50))) :password_verify (s/constrained s/Str #(and (>= (count %) 6) (<= (count %) 50))) :profile_visibility (s/enum "public" "internal") :profile_picture (s/maybe s/Str) :about (s/maybe s/Str)}) (s/defschema RegisterUser (merge {:token (s/maybe s/Str) :accept_terms (s/enum "accepted" "declined")} (dissoc User :profile_visibility :profile_picture :about))) (s/defschema LoginUser (select-keys User [:email :password])) (s/defschema ActivateUser (merge {:code s/Str :user_id s/Int} (select-keys User [:password :password_verify]))) (s/defschema EditUser (-> {:email_notifications s/Bool} (merge (select-keys User [:first_name :last_name :language :country])))) (s/defschema EditUserPassword{:current_password (s/maybe (:password User)) :new_password (s/maybe (:password PI:PASSWORD:<PASSWORD>END_PI)) :new_password_verify (s/maybe (:password PI:PASSWORD:<PASSWORD>END_PI))}) (s/defschema EmailAddress {:email (:email User) :verified s/Bool :primary_address s/Bool :backpack_id (s/maybe s/Int) :ctime s/Int :mtime s/Int})
[ { "context": " :json-schema/description \"root password for NuvlaBox\"\n\n :json-schema/order 15)))\n\n\n(s/d", "end": 2007, "score": 0.7098751068115234, "start": 2003, "tag": "PASSWORD", "value": "uvla" }, { "context": "/spec ::core/nonblank-string)\n (assoc :name \"login-username\"\n :json-schema/display-name \"login us", "end": 2150, "score": 0.8240647315979004, "start": 2136, "tag": "USERNAME", "value": "login-username" } ]
code/src/sixsq/nuvla/server/resources/spec/nuvlabox_0.cljc
0xbase12/api-server
6
(ns sixsq.nuvla.server.resources.spec.nuvlabox-0 (:require [clojure.spec.alpha :as s] [sixsq.nuvla.server.resources.spec.common :as common] [sixsq.nuvla.server.resources.spec.core :as core] [sixsq.nuvla.server.resources.spec.nuvlabox :as nb] [sixsq.nuvla.server.util.spec :as su] [spec-tools.core :as st])) (s/def ::state (-> (st/spec #{"NEW" "ACTIVATED" "COMMISSIONED" "DECOMMISSIONING" "DECOMMISSIONED" "ERROR"}) (assoc :name "state" :json-schema/type "string" :json-schema/description "state of NuvlaBox" :json-schema/value-scope {:values ["NEW" "ACTIVATED" "COMMISSIONED" "DECOMMISSIONING" "DECOMMISSIONED" "ERROR"]} :json-schema/order 10))) (s/def ::vm-cidr (-> (st/spec ::core/nonblank-string) (assoc :name "vm-cidr" :json-schema/display-name "VM CIDR" :json-schema/description "network range for virtual machines" :json-schema/order 11))) (s/def ::lan-cidr (-> (st/spec ::core/nonblank-string) (assoc :name "lan-cidr" :json-schema/display-name "LAN CIDR" :json-schema/description "network range for local area network" :json-schema/order 12))) (s/def ::wifi-ssid (-> (st/spec ::core/nonblank-string) (assoc :name "wifi-ssid" :json-schema/display-name "WIFI SSID" :json-schema/description "WIFI network identifier" :json-schema/order 13))) (s/def ::wifi-password (-> (st/spec ::core/nonblank-string) (assoc :name "wifi-password" :json-schema/display-name "WIFI password" :json-schema/description "WIFI network password" :json-schema/order 14))) (s/def ::root-password (-> (st/spec ::core/nonblank-string) (assoc :name "root-password" :json-schema/display-name "root password" :json-schema/description "root password for NuvlaBox" :json-schema/order 15))) (s/def ::login-username (-> (st/spec ::core/nonblank-string) (assoc :name "login-username" :json-schema/display-name "login username" :json-schema/description "username to log into NuvlaBox" :json-schema/order 16))) (s/def ::login-password (-> (st/spec ::core/nonblank-string) (assoc :name "login-password" :json-schema/display-name "login password" :json-schema/description "password to log into NuvlaBox" :json-schema/order 17))) (s/def ::cloud-password (-> (st/spec ::core/nonblank-string) (assoc :name "cloud-password" :json-schema/display-name "cloud password" :json-schema/description "password for cloud infrastructure" :json-schema/order 18))) (s/def ::refresh-interval (-> (st/spec pos-int?) (assoc :name "refresh-interval" :json-schema/display-name "refresh interval" :json-schema/description "refresh interval in seconds for state updates" :json-schema/order 19))) (s/def ::location (-> (st/spec (s/coll-of number? :min-count 2 :max-count 3)) (assoc :name "location" :json-schema/type "geo-point" :json-schema/display-name "location" :json-schema/description "location [longitude, latitude, altitude] associated with the data" :json-schema/order 20))) (s/def ::supplier (-> (st/spec ::core/nonblank-string) (assoc :name "supplier" :json-schema/description "name of hardware supplier" :json-schema/order 21))) (s/def ::organization (-> (st/spec ::core/nonblank-string) (assoc :name "organization" :json-schema/description "organization associated with the NuvlaBox" :json-schema/order 22))) (s/def ::form-factor (-> (st/spec ::core/nonblank-string) (assoc :name "form-factor" :json-schema/display-name "form factor" :json-schema/description "hardware form factor" :json-schema/order 23))) (s/def ::manufacturer-serial-number (-> (st/spec ::core/nonblank-string) (assoc :name "manufacturer-serial-number" :json-schema/display-name "manufacturer serial number" :json-schema/description "hardware manufacturer serial number" :json-schema/order 24))) (s/def ::firmware-version (-> (st/spec ::core/nonblank-string) (assoc :name "firmware-version" :json-schema/display-name "firmware version" :json-schema/description "NuvlaBox software firmware version" :json-schema/order 25))) (s/def ::hardware-type (-> (st/spec ::core/nonblank-string) (assoc :name "hardware-type" :json-schema/display-name "hardware type" :json-schema/description "hardware type of the NuvlaBox" :json-schema/order 26))) (s/def ::comment (-> (st/spec ::core/nonblank-string) (assoc :name "comment" :json-schema/description "comment about the NuvlaBox" :json-schema/order 27))) (s/def ::os-version (-> (st/spec ::core/nonblank-string) (assoc :name "os-version" :json-schema/display-name "OS version" :json-schema/description "operating system version" :json-schema/order 28))) (s/def ::hw-revision-code (-> (st/spec ::core/nonblank-string) (assoc :name "hw-revision-code" :json-schema/display-name "hardware revision code" :json-schema/description "hardware revision code" :json-schema/order 29))) (s/def ::monitored (-> (st/spec boolean?) (assoc :name "monitored" :json-schema/type "boolean" :json-schema/description "flag to indicate whether machine should be monitored" :json-schema/order 30))) (def infra-srvc-id-regex #"^infrastructure-service/[a-zA-Z0-9-]+$") (s/def ::vpn-server-id (-> (st/spec (s/and string? #(re-matches infra-srvc-id-regex %))) (assoc :name "vpn-server-id" :json-schema/type "string" :json-schema/display-name "vpn server id" :json-schema/description "VPN infrastructure service id to connect" :json-schema/order 31))) (s/def ::internal-data-gateway-endpoint (-> (st/spec ::core/nonblank-string) (assoc :name "internal-data-gateway-endpoint" :json-schema/display-name "nuvlabox data gateway endpoint" :json-schema/description "the endpoint users should connect to, from within the NuvlaBox, to subscribe to the data gateway" :json-schema/order 32))) (s/def ::ssh-keys (-> (st/spec (s/coll-of ::core/nonblank-string :kind vector?)) (assoc :name "ssh-keys" :json-schema/display-name "NuvlaBox SSH keys" :json-schema/description "list of SSH keys associated with the NuvlaBox" :json-schema/order 33))) (s/def ::capabilities (-> (st/spec (s/coll-of ::core/nonblank-string :kind vector?)) (assoc :name "capabilities" :json-schema/display-name "NuvlaBox capabilities" :json-schema/description "list of NuvlaBox capabilities" :json-schema/order 34))) (s/def ::online (-> (st/spec boolean?) (assoc :name "online" :json-schema/type "boolean" :json-schema/description "Indicate if the nuvlabox is connected to Nuvla service" :json-schema/server-managed true :json-schema/order 35))) (s/def ::inferred-location (-> (st/spec (s/coll-of number? :min-count 2 :max-count 3)) (assoc :name "inferred-location" :json-schema/type "geo-point" :json-schema/display-name "inferred-location" :json-schema/description "location [longitude, latitude, altitude] - dynamically inferred by the NuvlaBox" :json-schema/server-managed true :json-schema/order 36))) (s/def ::schema (su/only-keys-maps common/common-attrs nb/attributes {:req-un [::state ::refresh-interval] :opt-un [::location ::supplier ::organization ::manufacturer-serial-number ::firmware-version ::hardware-type ::form-factor ::wifi-ssid ::wifi-password ::root-password ::login-username ::login-password ::cloud-password ::comment ::vm-cidr ::lan-cidr ::os-version ::hw-revision-code ::monitored ::vpn-server-id ::internal-data-gateway-endpoint ::ssh-keys ::capabilities ::online ::inferred-location]}))
16538
(ns sixsq.nuvla.server.resources.spec.nuvlabox-0 (:require [clojure.spec.alpha :as s] [sixsq.nuvla.server.resources.spec.common :as common] [sixsq.nuvla.server.resources.spec.core :as core] [sixsq.nuvla.server.resources.spec.nuvlabox :as nb] [sixsq.nuvla.server.util.spec :as su] [spec-tools.core :as st])) (s/def ::state (-> (st/spec #{"NEW" "ACTIVATED" "COMMISSIONED" "DECOMMISSIONING" "DECOMMISSIONED" "ERROR"}) (assoc :name "state" :json-schema/type "string" :json-schema/description "state of NuvlaBox" :json-schema/value-scope {:values ["NEW" "ACTIVATED" "COMMISSIONED" "DECOMMISSIONING" "DECOMMISSIONED" "ERROR"]} :json-schema/order 10))) (s/def ::vm-cidr (-> (st/spec ::core/nonblank-string) (assoc :name "vm-cidr" :json-schema/display-name "VM CIDR" :json-schema/description "network range for virtual machines" :json-schema/order 11))) (s/def ::lan-cidr (-> (st/spec ::core/nonblank-string) (assoc :name "lan-cidr" :json-schema/display-name "LAN CIDR" :json-schema/description "network range for local area network" :json-schema/order 12))) (s/def ::wifi-ssid (-> (st/spec ::core/nonblank-string) (assoc :name "wifi-ssid" :json-schema/display-name "WIFI SSID" :json-schema/description "WIFI network identifier" :json-schema/order 13))) (s/def ::wifi-password (-> (st/spec ::core/nonblank-string) (assoc :name "wifi-password" :json-schema/display-name "WIFI password" :json-schema/description "WIFI network password" :json-schema/order 14))) (s/def ::root-password (-> (st/spec ::core/nonblank-string) (assoc :name "root-password" :json-schema/display-name "root password" :json-schema/description "root password for N<PASSWORD>Box" :json-schema/order 15))) (s/def ::login-username (-> (st/spec ::core/nonblank-string) (assoc :name "login-username" :json-schema/display-name "login username" :json-schema/description "username to log into NuvlaBox" :json-schema/order 16))) (s/def ::login-password (-> (st/spec ::core/nonblank-string) (assoc :name "login-password" :json-schema/display-name "login password" :json-schema/description "password to log into NuvlaBox" :json-schema/order 17))) (s/def ::cloud-password (-> (st/spec ::core/nonblank-string) (assoc :name "cloud-password" :json-schema/display-name "cloud password" :json-schema/description "password for cloud infrastructure" :json-schema/order 18))) (s/def ::refresh-interval (-> (st/spec pos-int?) (assoc :name "refresh-interval" :json-schema/display-name "refresh interval" :json-schema/description "refresh interval in seconds for state updates" :json-schema/order 19))) (s/def ::location (-> (st/spec (s/coll-of number? :min-count 2 :max-count 3)) (assoc :name "location" :json-schema/type "geo-point" :json-schema/display-name "location" :json-schema/description "location [longitude, latitude, altitude] associated with the data" :json-schema/order 20))) (s/def ::supplier (-> (st/spec ::core/nonblank-string) (assoc :name "supplier" :json-schema/description "name of hardware supplier" :json-schema/order 21))) (s/def ::organization (-> (st/spec ::core/nonblank-string) (assoc :name "organization" :json-schema/description "organization associated with the NuvlaBox" :json-schema/order 22))) (s/def ::form-factor (-> (st/spec ::core/nonblank-string) (assoc :name "form-factor" :json-schema/display-name "form factor" :json-schema/description "hardware form factor" :json-schema/order 23))) (s/def ::manufacturer-serial-number (-> (st/spec ::core/nonblank-string) (assoc :name "manufacturer-serial-number" :json-schema/display-name "manufacturer serial number" :json-schema/description "hardware manufacturer serial number" :json-schema/order 24))) (s/def ::firmware-version (-> (st/spec ::core/nonblank-string) (assoc :name "firmware-version" :json-schema/display-name "firmware version" :json-schema/description "NuvlaBox software firmware version" :json-schema/order 25))) (s/def ::hardware-type (-> (st/spec ::core/nonblank-string) (assoc :name "hardware-type" :json-schema/display-name "hardware type" :json-schema/description "hardware type of the NuvlaBox" :json-schema/order 26))) (s/def ::comment (-> (st/spec ::core/nonblank-string) (assoc :name "comment" :json-schema/description "comment about the NuvlaBox" :json-schema/order 27))) (s/def ::os-version (-> (st/spec ::core/nonblank-string) (assoc :name "os-version" :json-schema/display-name "OS version" :json-schema/description "operating system version" :json-schema/order 28))) (s/def ::hw-revision-code (-> (st/spec ::core/nonblank-string) (assoc :name "hw-revision-code" :json-schema/display-name "hardware revision code" :json-schema/description "hardware revision code" :json-schema/order 29))) (s/def ::monitored (-> (st/spec boolean?) (assoc :name "monitored" :json-schema/type "boolean" :json-schema/description "flag to indicate whether machine should be monitored" :json-schema/order 30))) (def infra-srvc-id-regex #"^infrastructure-service/[a-zA-Z0-9-]+$") (s/def ::vpn-server-id (-> (st/spec (s/and string? #(re-matches infra-srvc-id-regex %))) (assoc :name "vpn-server-id" :json-schema/type "string" :json-schema/display-name "vpn server id" :json-schema/description "VPN infrastructure service id to connect" :json-schema/order 31))) (s/def ::internal-data-gateway-endpoint (-> (st/spec ::core/nonblank-string) (assoc :name "internal-data-gateway-endpoint" :json-schema/display-name "nuvlabox data gateway endpoint" :json-schema/description "the endpoint users should connect to, from within the NuvlaBox, to subscribe to the data gateway" :json-schema/order 32))) (s/def ::ssh-keys (-> (st/spec (s/coll-of ::core/nonblank-string :kind vector?)) (assoc :name "ssh-keys" :json-schema/display-name "NuvlaBox SSH keys" :json-schema/description "list of SSH keys associated with the NuvlaBox" :json-schema/order 33))) (s/def ::capabilities (-> (st/spec (s/coll-of ::core/nonblank-string :kind vector?)) (assoc :name "capabilities" :json-schema/display-name "NuvlaBox capabilities" :json-schema/description "list of NuvlaBox capabilities" :json-schema/order 34))) (s/def ::online (-> (st/spec boolean?) (assoc :name "online" :json-schema/type "boolean" :json-schema/description "Indicate if the nuvlabox is connected to Nuvla service" :json-schema/server-managed true :json-schema/order 35))) (s/def ::inferred-location (-> (st/spec (s/coll-of number? :min-count 2 :max-count 3)) (assoc :name "inferred-location" :json-schema/type "geo-point" :json-schema/display-name "inferred-location" :json-schema/description "location [longitude, latitude, altitude] - dynamically inferred by the NuvlaBox" :json-schema/server-managed true :json-schema/order 36))) (s/def ::schema (su/only-keys-maps common/common-attrs nb/attributes {:req-un [::state ::refresh-interval] :opt-un [::location ::supplier ::organization ::manufacturer-serial-number ::firmware-version ::hardware-type ::form-factor ::wifi-ssid ::wifi-password ::root-password ::login-username ::login-password ::cloud-password ::comment ::vm-cidr ::lan-cidr ::os-version ::hw-revision-code ::monitored ::vpn-server-id ::internal-data-gateway-endpoint ::ssh-keys ::capabilities ::online ::inferred-location]}))
true
(ns sixsq.nuvla.server.resources.spec.nuvlabox-0 (:require [clojure.spec.alpha :as s] [sixsq.nuvla.server.resources.spec.common :as common] [sixsq.nuvla.server.resources.spec.core :as core] [sixsq.nuvla.server.resources.spec.nuvlabox :as nb] [sixsq.nuvla.server.util.spec :as su] [spec-tools.core :as st])) (s/def ::state (-> (st/spec #{"NEW" "ACTIVATED" "COMMISSIONED" "DECOMMISSIONING" "DECOMMISSIONED" "ERROR"}) (assoc :name "state" :json-schema/type "string" :json-schema/description "state of NuvlaBox" :json-schema/value-scope {:values ["NEW" "ACTIVATED" "COMMISSIONED" "DECOMMISSIONING" "DECOMMISSIONED" "ERROR"]} :json-schema/order 10))) (s/def ::vm-cidr (-> (st/spec ::core/nonblank-string) (assoc :name "vm-cidr" :json-schema/display-name "VM CIDR" :json-schema/description "network range for virtual machines" :json-schema/order 11))) (s/def ::lan-cidr (-> (st/spec ::core/nonblank-string) (assoc :name "lan-cidr" :json-schema/display-name "LAN CIDR" :json-schema/description "network range for local area network" :json-schema/order 12))) (s/def ::wifi-ssid (-> (st/spec ::core/nonblank-string) (assoc :name "wifi-ssid" :json-schema/display-name "WIFI SSID" :json-schema/description "WIFI network identifier" :json-schema/order 13))) (s/def ::wifi-password (-> (st/spec ::core/nonblank-string) (assoc :name "wifi-password" :json-schema/display-name "WIFI password" :json-schema/description "WIFI network password" :json-schema/order 14))) (s/def ::root-password (-> (st/spec ::core/nonblank-string) (assoc :name "root-password" :json-schema/display-name "root password" :json-schema/description "root password for NPI:PASSWORD:<PASSWORD>END_PIBox" :json-schema/order 15))) (s/def ::login-username (-> (st/spec ::core/nonblank-string) (assoc :name "login-username" :json-schema/display-name "login username" :json-schema/description "username to log into NuvlaBox" :json-schema/order 16))) (s/def ::login-password (-> (st/spec ::core/nonblank-string) (assoc :name "login-password" :json-schema/display-name "login password" :json-schema/description "password to log into NuvlaBox" :json-schema/order 17))) (s/def ::cloud-password (-> (st/spec ::core/nonblank-string) (assoc :name "cloud-password" :json-schema/display-name "cloud password" :json-schema/description "password for cloud infrastructure" :json-schema/order 18))) (s/def ::refresh-interval (-> (st/spec pos-int?) (assoc :name "refresh-interval" :json-schema/display-name "refresh interval" :json-schema/description "refresh interval in seconds for state updates" :json-schema/order 19))) (s/def ::location (-> (st/spec (s/coll-of number? :min-count 2 :max-count 3)) (assoc :name "location" :json-schema/type "geo-point" :json-schema/display-name "location" :json-schema/description "location [longitude, latitude, altitude] associated with the data" :json-schema/order 20))) (s/def ::supplier (-> (st/spec ::core/nonblank-string) (assoc :name "supplier" :json-schema/description "name of hardware supplier" :json-schema/order 21))) (s/def ::organization (-> (st/spec ::core/nonblank-string) (assoc :name "organization" :json-schema/description "organization associated with the NuvlaBox" :json-schema/order 22))) (s/def ::form-factor (-> (st/spec ::core/nonblank-string) (assoc :name "form-factor" :json-schema/display-name "form factor" :json-schema/description "hardware form factor" :json-schema/order 23))) (s/def ::manufacturer-serial-number (-> (st/spec ::core/nonblank-string) (assoc :name "manufacturer-serial-number" :json-schema/display-name "manufacturer serial number" :json-schema/description "hardware manufacturer serial number" :json-schema/order 24))) (s/def ::firmware-version (-> (st/spec ::core/nonblank-string) (assoc :name "firmware-version" :json-schema/display-name "firmware version" :json-schema/description "NuvlaBox software firmware version" :json-schema/order 25))) (s/def ::hardware-type (-> (st/spec ::core/nonblank-string) (assoc :name "hardware-type" :json-schema/display-name "hardware type" :json-schema/description "hardware type of the NuvlaBox" :json-schema/order 26))) (s/def ::comment (-> (st/spec ::core/nonblank-string) (assoc :name "comment" :json-schema/description "comment about the NuvlaBox" :json-schema/order 27))) (s/def ::os-version (-> (st/spec ::core/nonblank-string) (assoc :name "os-version" :json-schema/display-name "OS version" :json-schema/description "operating system version" :json-schema/order 28))) (s/def ::hw-revision-code (-> (st/spec ::core/nonblank-string) (assoc :name "hw-revision-code" :json-schema/display-name "hardware revision code" :json-schema/description "hardware revision code" :json-schema/order 29))) (s/def ::monitored (-> (st/spec boolean?) (assoc :name "monitored" :json-schema/type "boolean" :json-schema/description "flag to indicate whether machine should be monitored" :json-schema/order 30))) (def infra-srvc-id-regex #"^infrastructure-service/[a-zA-Z0-9-]+$") (s/def ::vpn-server-id (-> (st/spec (s/and string? #(re-matches infra-srvc-id-regex %))) (assoc :name "vpn-server-id" :json-schema/type "string" :json-schema/display-name "vpn server id" :json-schema/description "VPN infrastructure service id to connect" :json-schema/order 31))) (s/def ::internal-data-gateway-endpoint (-> (st/spec ::core/nonblank-string) (assoc :name "internal-data-gateway-endpoint" :json-schema/display-name "nuvlabox data gateway endpoint" :json-schema/description "the endpoint users should connect to, from within the NuvlaBox, to subscribe to the data gateway" :json-schema/order 32))) (s/def ::ssh-keys (-> (st/spec (s/coll-of ::core/nonblank-string :kind vector?)) (assoc :name "ssh-keys" :json-schema/display-name "NuvlaBox SSH keys" :json-schema/description "list of SSH keys associated with the NuvlaBox" :json-schema/order 33))) (s/def ::capabilities (-> (st/spec (s/coll-of ::core/nonblank-string :kind vector?)) (assoc :name "capabilities" :json-schema/display-name "NuvlaBox capabilities" :json-schema/description "list of NuvlaBox capabilities" :json-schema/order 34))) (s/def ::online (-> (st/spec boolean?) (assoc :name "online" :json-schema/type "boolean" :json-schema/description "Indicate if the nuvlabox is connected to Nuvla service" :json-schema/server-managed true :json-schema/order 35))) (s/def ::inferred-location (-> (st/spec (s/coll-of number? :min-count 2 :max-count 3)) (assoc :name "inferred-location" :json-schema/type "geo-point" :json-schema/display-name "inferred-location" :json-schema/description "location [longitude, latitude, altitude] - dynamically inferred by the NuvlaBox" :json-schema/server-managed true :json-schema/order 36))) (s/def ::schema (su/only-keys-maps common/common-attrs nb/attributes {:req-un [::state ::refresh-interval] :opt-un [::location ::supplier ::organization ::manufacturer-serial-number ::firmware-version ::hardware-type ::form-factor ::wifi-ssid ::wifi-password ::root-password ::login-username ::login-password ::cloud-password ::comment ::vm-cidr ::lan-cidr ::os-version ::hw-revision-code ::monitored ::vpn-server-id ::internal-data-gateway-endpoint ::ssh-keys ::capabilities ::online ::inferred-location]}))
[ { "context": "(ns #^{:author \"Roger Allen\"\n :doc \"Shadertone lisp-to-glsl translation", "end": 27, "score": 0.9998494386672974, "start": 16, "tag": "NAME", "value": "Roger Allen" } ]
src/shadertone/translate.clj
baskeboler/shadertone
304
(ns #^{:author "Roger Allen" :doc "Shadertone lisp-to-glsl translation."} shadertone.translate (:require [clojure.walk :as walk] [clojure.string :as string])) ;; This is only a single-pass "lisp" to GLSL translator. Very basic. ;; If useful, then perhaps we can work to improve. Send feedback. ;; ;; Basic "docs". See testcases, too. ;; * define functions ;; (defn <return-type> <function-name> <function-args-vector> <body-stmt1> ... ) ;; * function calls ;; (<name> <arg1> <arg2> ... ) ;; * variable creation/assignment ;; (uniform <type> <name>) ;; (setq <type> <name> <statement>) ;; (setq <name> <statement>) ;; * for(;;) {} ;; (forloop [ <init-stmt> <test-stmt> <step-stmt> ] <body-stmt1> ... ) ;; * while() {} ;; (while <test-stmt> <body-stmt1> ... ) ;; * break; ;; (break) ;; * continue; ;; (continue) ;; * return value; ;; (return <statement>) ;; * if() {} ;; (if <test> <stmt>) ;; (if <test> (do <body-stmt1> ...)) ;; * if() {} else {} ;; (if <test> <stmt> <else-stmt>) ;; (if <test> (do <body-stmt1> ...) (do <else-stmt1> ...)) ;; * switch () { case integer: ... break; ... default: ... } ;; (switch <test> <case-int-1> <case-stmt-1> ...) ;; cases can only be integer or :default keyword ;; TODO: ;; o indent spacing ;; o tests ;; o assertions? ;; o defensive coding ;; o error reports ;; ====================================================================== ;; translation functions for a dialect of clojure-like s-expressions (declare shader-walk) (defn- shader-typed-assign-str [z] (let [[type name value] z _ (assert (= 3 (count z))) ;;_ (println "shader-assign-str-0:" type name value) asn-str (format "%s %s = %s;\n" type name (shader-walk (list value)))] ;;(println "shader-assign-str-1:" asn-str) asn-str)) (defn- shader-assign-str [z] (let [[name value] z _ (assert (= 2 (count z))) ;;_ (println "shader-assign-str-0:" name value) asn-str (format "%s = %s;\n" name (shader-walk (list value)))] ;;(println "shader-assign-str-1:" asn-str) asn-str)) (defn- shader-walk-assign [x] ;;(println "shader-walk-assign-0:" x) (case (count (rest x)) 2 (shader-assign-str (rest x)) 3 (shader-typed-assign-str (rest x)) :else (assert false "incorrect number of args for setq statement"))) (defn- shader-walk-defn-args [x] ;;(println "shader-walk-defn-args-0" x (empty? x)) (assert (vector? x)) (if (empty? x) "void" (string/join \, (map #(apply (partial format "%s %s") %) (partition 2 x))))) (defn- shader-walk-defn [x] ;;(println "shader-walk-defn-0:" x) (let [fn-str (format "%s %s(%s) {\n%s}\n" (nth x 1) (nth x 2) (shader-walk-defn-args (nth x 3)) (string/join (shader-walk (drop 4 x))))] ;; FIXME add indentation level? ;;(print "shader-walk-defn-1:" fn-str) fn-str)) (defn- shader-walk-fn [x] ;;(println "shader-walk-fn-0:" x) (let [pre-fn (if (= (first (str (first x))) \.) "" (str (first x))) post-fn (if (= (first (str (first x))) \.) (str (first x)) "") fn-str (format "%s(%s)%s" pre-fn (string/join \, (map #(shader-walk (list %)) (rest x))) post-fn)] ;;(println "shader-walk-fn-1:" fn-str) fn-str)) (defn- shader-walk-infix [x] ;;(println "shader-walk-infix-0:" x) (let [identity-value (case (str (first x)) "*" 1.0 "/" 1.0 0.0) vals (if (> (count (rest x)) 1) (rest x) (cons identity-value (rest x))) fn-str (format "(%s)" (string/join (format " %s " (str (first x))) (map #(shader-walk (list %)) vals)))] ;;(println "shader-walk-infix-1:" fn-str) fn-str)) (defn- infix-operator? [x] (not (nil? (get #{ "+" "-" "*" "/" "=" "<" ">" "<=" ">=" "==" "!=" ">>" "<<"} x)))) (defn- shader-stmt [x] (format "%s;\n" (string/join \space x))) ;; (forloop [ init-stmt test-stmt step-stmt ] body ) (defn- shader-walk-forloop [x] ;;(println "shader-walk-forloop-0:" x) (let [[init-stmt test-stmt step-stmt] (nth x 1) fl-str (format "for( %s %s; %s ) {\n%s}\n" (shader-walk (list init-stmt)) (shader-walk (list test-stmt)) (shader-walk (list step-stmt)) (string/join (shader-walk (drop 2 x))))] ;;(print "shader-walk-forloop-1:" fl-str) fl-str)) ;; (whileloop test-stmt body ) (defn- shader-walk-while [x] ;;(println "shader-walk-while-0:" x) (let [w-str (format "while%s {\n%s}\n" (shader-walk (list (nth x 1))) (string/join (shader-walk (drop 2 x))))] ;;(println "shader-walk-while-1:" w-str) w-str)) (defn- shader-walk-do [x] ;;(println "shader-walk-do-0:" x) (let [w-str (format "{\n%s}\n" (string/join (shader-walk (drop 1 x))))] ;;(println "shader-walk-do-1:" w-str) w-str)) (defn- shader-walk-if [x] ;;(println "shader-walk-if-0:" x) (case (count (rest x)) 2 (let [w-str (format "if%s\n%s" ;; if() {} (shader-walk (list (nth x 1))) (shader-walk (list (nth x 2))))] ;;(println "shader-walk-if-1a:" w-str) w-str) 3 (let [w-str (format "if%s\n%selse\n%s" ;; if() {} else {} (shader-walk (list (nth x 1))) (shader-walk (list (nth x 2))) (shader-walk (list (nth x 3))))] ;;(println "shader-walk-if-1b:" w-str) w-str) :else (assert false "incorrect number of args for if statement"))) (defn- shader-walk-case [x] ;;(println "shader-walk-case-0:" x) (let [[v s] x _ (assert (= 2 (count x))) c-str (if (number? v) (format "case %d:" v) (if (= v :default) "default:" (assert false (format "expected integer or default:, got: %s" v)))) w-str (format "%s\n%s" c-str (shader-walk (list s)))] ;;(println "shader-walk-case-1:" w-str) w-str)) (defn- shader-walk-switch [x] ;;(println "shader-walk-switch-0:" x) (let [v (nth x 1) v-str (if (list? v) (shader-walk (list v)) (format "(%s)" (shader-walk (list v)))) w-str (format "switch%s {\n%s}\n" v-str (string/join (map shader-walk-case (partition 2 (drop 2 x)))))] ;;(println "shader-walk-switch-1:" w-str) w-str)) (defn- shader-walk-return [x] (format "%s;\n" (shader-walk-fn x))) (defn- inner-walk [x] ;;(println "in: " x) (cond (list? x) (let [sfx (str (first x))] (cond (= "defn" sfx) (shader-walk-defn x) (= "setq" sfx) (shader-walk-assign x) (= "forloop" sfx) (shader-walk-forloop x) (= "while" sfx) (shader-walk-while x) (= "if" sfx) (shader-walk-if x) (= "do" sfx) (shader-walk-do x) (= "switch" sfx) (shader-walk-switch x) (= "break" sfx) (shader-stmt x) (= "continue" sfx) (shader-stmt x) (= "uniform" sfx) (shader-stmt x) (= "return" sfx) (shader-walk-return x) (infix-operator? sfx) (shader-walk-infix x) :else (shader-walk-fn x))) (symbol? x) (identity x) (float? x) (identity x) (integer? x) (identity x) :else (shader-walk x))) (defn- outer-walk [x] ;;(println "out: " x) (cond (list? x) (string/join x) :else (identity x))) (defn- shader-walk [form] (walk/walk inner-walk outer-walk form)) ;; ====================================================================== ;; Public API (defn create-shader [& params] (shader-walk (first params))) ;; ??? Maybe we should just call create-shader and get a string back? (defmacro defshader "macro to define the fragment shader. returns shader as a string." [name body] `(def ~name (create-shader ~body))) ;; (str shader) should return the shader text ready to compile ;; ====================================================================== ;; For Testing... (comment ;; simplest possible shader (defshader simplest '((defn void main [] (setq gl_FragColor (vec4 1.0 0.5 0.5 1.0))))) (print simplest) ;; simple test (defshader simple '((uniform vec3 iResolution) (defn void main [] (setq vec2 uv (/ gl_FragCoord.xy iResolution.xy)) (setq gl_FragColor (vec4 uv.x uv.y 0.0 1.0))))) (print simple) ;; simple unary test (defshader simple '((uniform vec3 iResolution) (defn void main [] (setq vec2 uv (/ gl_FragCoord.xy iResolution.xy)) (setq float vs (- uv.y)) (setq float va (+ vs)) (setq float vm (* va)) (setq float vd (/ vm)) (setq float vn (- 0.0 vd)) (setq gl_FragColor (vec4 uv.x vn 0.0 1.0))))) (print simple) ;; preliminary translation of wave.glsl (defshader wave '((uniform vec3 iResolution) (uniform sampler2D iChannel0) (defn float smoothbump [float center float width float x] (setq float w2 (/ width 2.0)) (setq float cp (+ center w2)) (setq float cm (- center w2)) (return (* (smoothstep cm center x) (- 1.0 (smoothstep center cp x))))) (defn void main [] (setq float uv (/ gl_FragCoord.xy iResolution.xy)) (setq uv.y (- 1.0 uv.y)) (setq float freq (.x (texture2D iChannel0 (vec2 uv.x 0.25)))) (setq float wave (.x (texture2D iChannel0 (vec2 uv.x 0.75)))) (setq float freqc (smoothstep 0.0 (/ 1.0 iResolution.y) (+ freq uv.y -0.5))) (setq float wavec (smoothstep 0.0 (/ 4.0 iResolution.y) (+ wave uv.y -0.5))) (setq gl_FragColor (vec4 freqc wavec 0.25 1.0))))) (print wave) (defshader forloop0 '((defn void main [] (setq vec3 c (vec3 0.0)) (forloop [ (setq int i 0) (<= i 10) (setq i (+ i 1)) ] (setq c (+ c (vec3 0.1)))) (setq gl_FragColor (vec4 c 1.0))))) (print forloop0) (defshader iftest0 '((defn void main [] (if (< i 0) (setq i 0)) (if (< j 10) (do (setq i 5) (setq j 10))) (if (< k 10) (setq i 5) (setq j 10)) (if (< k 10) (do (setq i 1) (setq j 2)) (do (setq i 3) (setq j 4)))))) (print iftest0) (defshader swtest0 '((defn void main [] (switch j 0 (do (setq i 0) (break)) 1 (do (setq i 1) (break)) :default (break)) (switch (+ j k) 0 (do (setq l 0) (break)) :default (break))))) (print swtest0) )
114694
(ns #^{:author "<NAME>" :doc "Shadertone lisp-to-glsl translation."} shadertone.translate (:require [clojure.walk :as walk] [clojure.string :as string])) ;; This is only a single-pass "lisp" to GLSL translator. Very basic. ;; If useful, then perhaps we can work to improve. Send feedback. ;; ;; Basic "docs". See testcases, too. ;; * define functions ;; (defn <return-type> <function-name> <function-args-vector> <body-stmt1> ... ) ;; * function calls ;; (<name> <arg1> <arg2> ... ) ;; * variable creation/assignment ;; (uniform <type> <name>) ;; (setq <type> <name> <statement>) ;; (setq <name> <statement>) ;; * for(;;) {} ;; (forloop [ <init-stmt> <test-stmt> <step-stmt> ] <body-stmt1> ... ) ;; * while() {} ;; (while <test-stmt> <body-stmt1> ... ) ;; * break; ;; (break) ;; * continue; ;; (continue) ;; * return value; ;; (return <statement>) ;; * if() {} ;; (if <test> <stmt>) ;; (if <test> (do <body-stmt1> ...)) ;; * if() {} else {} ;; (if <test> <stmt> <else-stmt>) ;; (if <test> (do <body-stmt1> ...) (do <else-stmt1> ...)) ;; * switch () { case integer: ... break; ... default: ... } ;; (switch <test> <case-int-1> <case-stmt-1> ...) ;; cases can only be integer or :default keyword ;; TODO: ;; o indent spacing ;; o tests ;; o assertions? ;; o defensive coding ;; o error reports ;; ====================================================================== ;; translation functions for a dialect of clojure-like s-expressions (declare shader-walk) (defn- shader-typed-assign-str [z] (let [[type name value] z _ (assert (= 3 (count z))) ;;_ (println "shader-assign-str-0:" type name value) asn-str (format "%s %s = %s;\n" type name (shader-walk (list value)))] ;;(println "shader-assign-str-1:" asn-str) asn-str)) (defn- shader-assign-str [z] (let [[name value] z _ (assert (= 2 (count z))) ;;_ (println "shader-assign-str-0:" name value) asn-str (format "%s = %s;\n" name (shader-walk (list value)))] ;;(println "shader-assign-str-1:" asn-str) asn-str)) (defn- shader-walk-assign [x] ;;(println "shader-walk-assign-0:" x) (case (count (rest x)) 2 (shader-assign-str (rest x)) 3 (shader-typed-assign-str (rest x)) :else (assert false "incorrect number of args for setq statement"))) (defn- shader-walk-defn-args [x] ;;(println "shader-walk-defn-args-0" x (empty? x)) (assert (vector? x)) (if (empty? x) "void" (string/join \, (map #(apply (partial format "%s %s") %) (partition 2 x))))) (defn- shader-walk-defn [x] ;;(println "shader-walk-defn-0:" x) (let [fn-str (format "%s %s(%s) {\n%s}\n" (nth x 1) (nth x 2) (shader-walk-defn-args (nth x 3)) (string/join (shader-walk (drop 4 x))))] ;; FIXME add indentation level? ;;(print "shader-walk-defn-1:" fn-str) fn-str)) (defn- shader-walk-fn [x] ;;(println "shader-walk-fn-0:" x) (let [pre-fn (if (= (first (str (first x))) \.) "" (str (first x))) post-fn (if (= (first (str (first x))) \.) (str (first x)) "") fn-str (format "%s(%s)%s" pre-fn (string/join \, (map #(shader-walk (list %)) (rest x))) post-fn)] ;;(println "shader-walk-fn-1:" fn-str) fn-str)) (defn- shader-walk-infix [x] ;;(println "shader-walk-infix-0:" x) (let [identity-value (case (str (first x)) "*" 1.0 "/" 1.0 0.0) vals (if (> (count (rest x)) 1) (rest x) (cons identity-value (rest x))) fn-str (format "(%s)" (string/join (format " %s " (str (first x))) (map #(shader-walk (list %)) vals)))] ;;(println "shader-walk-infix-1:" fn-str) fn-str)) (defn- infix-operator? [x] (not (nil? (get #{ "+" "-" "*" "/" "=" "<" ">" "<=" ">=" "==" "!=" ">>" "<<"} x)))) (defn- shader-stmt [x] (format "%s;\n" (string/join \space x))) ;; (forloop [ init-stmt test-stmt step-stmt ] body ) (defn- shader-walk-forloop [x] ;;(println "shader-walk-forloop-0:" x) (let [[init-stmt test-stmt step-stmt] (nth x 1) fl-str (format "for( %s %s; %s ) {\n%s}\n" (shader-walk (list init-stmt)) (shader-walk (list test-stmt)) (shader-walk (list step-stmt)) (string/join (shader-walk (drop 2 x))))] ;;(print "shader-walk-forloop-1:" fl-str) fl-str)) ;; (whileloop test-stmt body ) (defn- shader-walk-while [x] ;;(println "shader-walk-while-0:" x) (let [w-str (format "while%s {\n%s}\n" (shader-walk (list (nth x 1))) (string/join (shader-walk (drop 2 x))))] ;;(println "shader-walk-while-1:" w-str) w-str)) (defn- shader-walk-do [x] ;;(println "shader-walk-do-0:" x) (let [w-str (format "{\n%s}\n" (string/join (shader-walk (drop 1 x))))] ;;(println "shader-walk-do-1:" w-str) w-str)) (defn- shader-walk-if [x] ;;(println "shader-walk-if-0:" x) (case (count (rest x)) 2 (let [w-str (format "if%s\n%s" ;; if() {} (shader-walk (list (nth x 1))) (shader-walk (list (nth x 2))))] ;;(println "shader-walk-if-1a:" w-str) w-str) 3 (let [w-str (format "if%s\n%selse\n%s" ;; if() {} else {} (shader-walk (list (nth x 1))) (shader-walk (list (nth x 2))) (shader-walk (list (nth x 3))))] ;;(println "shader-walk-if-1b:" w-str) w-str) :else (assert false "incorrect number of args for if statement"))) (defn- shader-walk-case [x] ;;(println "shader-walk-case-0:" x) (let [[v s] x _ (assert (= 2 (count x))) c-str (if (number? v) (format "case %d:" v) (if (= v :default) "default:" (assert false (format "expected integer or default:, got: %s" v)))) w-str (format "%s\n%s" c-str (shader-walk (list s)))] ;;(println "shader-walk-case-1:" w-str) w-str)) (defn- shader-walk-switch [x] ;;(println "shader-walk-switch-0:" x) (let [v (nth x 1) v-str (if (list? v) (shader-walk (list v)) (format "(%s)" (shader-walk (list v)))) w-str (format "switch%s {\n%s}\n" v-str (string/join (map shader-walk-case (partition 2 (drop 2 x)))))] ;;(println "shader-walk-switch-1:" w-str) w-str)) (defn- shader-walk-return [x] (format "%s;\n" (shader-walk-fn x))) (defn- inner-walk [x] ;;(println "in: " x) (cond (list? x) (let [sfx (str (first x))] (cond (= "defn" sfx) (shader-walk-defn x) (= "setq" sfx) (shader-walk-assign x) (= "forloop" sfx) (shader-walk-forloop x) (= "while" sfx) (shader-walk-while x) (= "if" sfx) (shader-walk-if x) (= "do" sfx) (shader-walk-do x) (= "switch" sfx) (shader-walk-switch x) (= "break" sfx) (shader-stmt x) (= "continue" sfx) (shader-stmt x) (= "uniform" sfx) (shader-stmt x) (= "return" sfx) (shader-walk-return x) (infix-operator? sfx) (shader-walk-infix x) :else (shader-walk-fn x))) (symbol? x) (identity x) (float? x) (identity x) (integer? x) (identity x) :else (shader-walk x))) (defn- outer-walk [x] ;;(println "out: " x) (cond (list? x) (string/join x) :else (identity x))) (defn- shader-walk [form] (walk/walk inner-walk outer-walk form)) ;; ====================================================================== ;; Public API (defn create-shader [& params] (shader-walk (first params))) ;; ??? Maybe we should just call create-shader and get a string back? (defmacro defshader "macro to define the fragment shader. returns shader as a string." [name body] `(def ~name (create-shader ~body))) ;; (str shader) should return the shader text ready to compile ;; ====================================================================== ;; For Testing... (comment ;; simplest possible shader (defshader simplest '((defn void main [] (setq gl_FragColor (vec4 1.0 0.5 0.5 1.0))))) (print simplest) ;; simple test (defshader simple '((uniform vec3 iResolution) (defn void main [] (setq vec2 uv (/ gl_FragCoord.xy iResolution.xy)) (setq gl_FragColor (vec4 uv.x uv.y 0.0 1.0))))) (print simple) ;; simple unary test (defshader simple '((uniform vec3 iResolution) (defn void main [] (setq vec2 uv (/ gl_FragCoord.xy iResolution.xy)) (setq float vs (- uv.y)) (setq float va (+ vs)) (setq float vm (* va)) (setq float vd (/ vm)) (setq float vn (- 0.0 vd)) (setq gl_FragColor (vec4 uv.x vn 0.0 1.0))))) (print simple) ;; preliminary translation of wave.glsl (defshader wave '((uniform vec3 iResolution) (uniform sampler2D iChannel0) (defn float smoothbump [float center float width float x] (setq float w2 (/ width 2.0)) (setq float cp (+ center w2)) (setq float cm (- center w2)) (return (* (smoothstep cm center x) (- 1.0 (smoothstep center cp x))))) (defn void main [] (setq float uv (/ gl_FragCoord.xy iResolution.xy)) (setq uv.y (- 1.0 uv.y)) (setq float freq (.x (texture2D iChannel0 (vec2 uv.x 0.25)))) (setq float wave (.x (texture2D iChannel0 (vec2 uv.x 0.75)))) (setq float freqc (smoothstep 0.0 (/ 1.0 iResolution.y) (+ freq uv.y -0.5))) (setq float wavec (smoothstep 0.0 (/ 4.0 iResolution.y) (+ wave uv.y -0.5))) (setq gl_FragColor (vec4 freqc wavec 0.25 1.0))))) (print wave) (defshader forloop0 '((defn void main [] (setq vec3 c (vec3 0.0)) (forloop [ (setq int i 0) (<= i 10) (setq i (+ i 1)) ] (setq c (+ c (vec3 0.1)))) (setq gl_FragColor (vec4 c 1.0))))) (print forloop0) (defshader iftest0 '((defn void main [] (if (< i 0) (setq i 0)) (if (< j 10) (do (setq i 5) (setq j 10))) (if (< k 10) (setq i 5) (setq j 10)) (if (< k 10) (do (setq i 1) (setq j 2)) (do (setq i 3) (setq j 4)))))) (print iftest0) (defshader swtest0 '((defn void main [] (switch j 0 (do (setq i 0) (break)) 1 (do (setq i 1) (break)) :default (break)) (switch (+ j k) 0 (do (setq l 0) (break)) :default (break))))) (print swtest0) )
true
(ns #^{:author "PI:NAME:<NAME>END_PI" :doc "Shadertone lisp-to-glsl translation."} shadertone.translate (:require [clojure.walk :as walk] [clojure.string :as string])) ;; This is only a single-pass "lisp" to GLSL translator. Very basic. ;; If useful, then perhaps we can work to improve. Send feedback. ;; ;; Basic "docs". See testcases, too. ;; * define functions ;; (defn <return-type> <function-name> <function-args-vector> <body-stmt1> ... ) ;; * function calls ;; (<name> <arg1> <arg2> ... ) ;; * variable creation/assignment ;; (uniform <type> <name>) ;; (setq <type> <name> <statement>) ;; (setq <name> <statement>) ;; * for(;;) {} ;; (forloop [ <init-stmt> <test-stmt> <step-stmt> ] <body-stmt1> ... ) ;; * while() {} ;; (while <test-stmt> <body-stmt1> ... ) ;; * break; ;; (break) ;; * continue; ;; (continue) ;; * return value; ;; (return <statement>) ;; * if() {} ;; (if <test> <stmt>) ;; (if <test> (do <body-stmt1> ...)) ;; * if() {} else {} ;; (if <test> <stmt> <else-stmt>) ;; (if <test> (do <body-stmt1> ...) (do <else-stmt1> ...)) ;; * switch () { case integer: ... break; ... default: ... } ;; (switch <test> <case-int-1> <case-stmt-1> ...) ;; cases can only be integer or :default keyword ;; TODO: ;; o indent spacing ;; o tests ;; o assertions? ;; o defensive coding ;; o error reports ;; ====================================================================== ;; translation functions for a dialect of clojure-like s-expressions (declare shader-walk) (defn- shader-typed-assign-str [z] (let [[type name value] z _ (assert (= 3 (count z))) ;;_ (println "shader-assign-str-0:" type name value) asn-str (format "%s %s = %s;\n" type name (shader-walk (list value)))] ;;(println "shader-assign-str-1:" asn-str) asn-str)) (defn- shader-assign-str [z] (let [[name value] z _ (assert (= 2 (count z))) ;;_ (println "shader-assign-str-0:" name value) asn-str (format "%s = %s;\n" name (shader-walk (list value)))] ;;(println "shader-assign-str-1:" asn-str) asn-str)) (defn- shader-walk-assign [x] ;;(println "shader-walk-assign-0:" x) (case (count (rest x)) 2 (shader-assign-str (rest x)) 3 (shader-typed-assign-str (rest x)) :else (assert false "incorrect number of args for setq statement"))) (defn- shader-walk-defn-args [x] ;;(println "shader-walk-defn-args-0" x (empty? x)) (assert (vector? x)) (if (empty? x) "void" (string/join \, (map #(apply (partial format "%s %s") %) (partition 2 x))))) (defn- shader-walk-defn [x] ;;(println "shader-walk-defn-0:" x) (let [fn-str (format "%s %s(%s) {\n%s}\n" (nth x 1) (nth x 2) (shader-walk-defn-args (nth x 3)) (string/join (shader-walk (drop 4 x))))] ;; FIXME add indentation level? ;;(print "shader-walk-defn-1:" fn-str) fn-str)) (defn- shader-walk-fn [x] ;;(println "shader-walk-fn-0:" x) (let [pre-fn (if (= (first (str (first x))) \.) "" (str (first x))) post-fn (if (= (first (str (first x))) \.) (str (first x)) "") fn-str (format "%s(%s)%s" pre-fn (string/join \, (map #(shader-walk (list %)) (rest x))) post-fn)] ;;(println "shader-walk-fn-1:" fn-str) fn-str)) (defn- shader-walk-infix [x] ;;(println "shader-walk-infix-0:" x) (let [identity-value (case (str (first x)) "*" 1.0 "/" 1.0 0.0) vals (if (> (count (rest x)) 1) (rest x) (cons identity-value (rest x))) fn-str (format "(%s)" (string/join (format " %s " (str (first x))) (map #(shader-walk (list %)) vals)))] ;;(println "shader-walk-infix-1:" fn-str) fn-str)) (defn- infix-operator? [x] (not (nil? (get #{ "+" "-" "*" "/" "=" "<" ">" "<=" ">=" "==" "!=" ">>" "<<"} x)))) (defn- shader-stmt [x] (format "%s;\n" (string/join \space x))) ;; (forloop [ init-stmt test-stmt step-stmt ] body ) (defn- shader-walk-forloop [x] ;;(println "shader-walk-forloop-0:" x) (let [[init-stmt test-stmt step-stmt] (nth x 1) fl-str (format "for( %s %s; %s ) {\n%s}\n" (shader-walk (list init-stmt)) (shader-walk (list test-stmt)) (shader-walk (list step-stmt)) (string/join (shader-walk (drop 2 x))))] ;;(print "shader-walk-forloop-1:" fl-str) fl-str)) ;; (whileloop test-stmt body ) (defn- shader-walk-while [x] ;;(println "shader-walk-while-0:" x) (let [w-str (format "while%s {\n%s}\n" (shader-walk (list (nth x 1))) (string/join (shader-walk (drop 2 x))))] ;;(println "shader-walk-while-1:" w-str) w-str)) (defn- shader-walk-do [x] ;;(println "shader-walk-do-0:" x) (let [w-str (format "{\n%s}\n" (string/join (shader-walk (drop 1 x))))] ;;(println "shader-walk-do-1:" w-str) w-str)) (defn- shader-walk-if [x] ;;(println "shader-walk-if-0:" x) (case (count (rest x)) 2 (let [w-str (format "if%s\n%s" ;; if() {} (shader-walk (list (nth x 1))) (shader-walk (list (nth x 2))))] ;;(println "shader-walk-if-1a:" w-str) w-str) 3 (let [w-str (format "if%s\n%selse\n%s" ;; if() {} else {} (shader-walk (list (nth x 1))) (shader-walk (list (nth x 2))) (shader-walk (list (nth x 3))))] ;;(println "shader-walk-if-1b:" w-str) w-str) :else (assert false "incorrect number of args for if statement"))) (defn- shader-walk-case [x] ;;(println "shader-walk-case-0:" x) (let [[v s] x _ (assert (= 2 (count x))) c-str (if (number? v) (format "case %d:" v) (if (= v :default) "default:" (assert false (format "expected integer or default:, got: %s" v)))) w-str (format "%s\n%s" c-str (shader-walk (list s)))] ;;(println "shader-walk-case-1:" w-str) w-str)) (defn- shader-walk-switch [x] ;;(println "shader-walk-switch-0:" x) (let [v (nth x 1) v-str (if (list? v) (shader-walk (list v)) (format "(%s)" (shader-walk (list v)))) w-str (format "switch%s {\n%s}\n" v-str (string/join (map shader-walk-case (partition 2 (drop 2 x)))))] ;;(println "shader-walk-switch-1:" w-str) w-str)) (defn- shader-walk-return [x] (format "%s;\n" (shader-walk-fn x))) (defn- inner-walk [x] ;;(println "in: " x) (cond (list? x) (let [sfx (str (first x))] (cond (= "defn" sfx) (shader-walk-defn x) (= "setq" sfx) (shader-walk-assign x) (= "forloop" sfx) (shader-walk-forloop x) (= "while" sfx) (shader-walk-while x) (= "if" sfx) (shader-walk-if x) (= "do" sfx) (shader-walk-do x) (= "switch" sfx) (shader-walk-switch x) (= "break" sfx) (shader-stmt x) (= "continue" sfx) (shader-stmt x) (= "uniform" sfx) (shader-stmt x) (= "return" sfx) (shader-walk-return x) (infix-operator? sfx) (shader-walk-infix x) :else (shader-walk-fn x))) (symbol? x) (identity x) (float? x) (identity x) (integer? x) (identity x) :else (shader-walk x))) (defn- outer-walk [x] ;;(println "out: " x) (cond (list? x) (string/join x) :else (identity x))) (defn- shader-walk [form] (walk/walk inner-walk outer-walk form)) ;; ====================================================================== ;; Public API (defn create-shader [& params] (shader-walk (first params))) ;; ??? Maybe we should just call create-shader and get a string back? (defmacro defshader "macro to define the fragment shader. returns shader as a string." [name body] `(def ~name (create-shader ~body))) ;; (str shader) should return the shader text ready to compile ;; ====================================================================== ;; For Testing... (comment ;; simplest possible shader (defshader simplest '((defn void main [] (setq gl_FragColor (vec4 1.0 0.5 0.5 1.0))))) (print simplest) ;; simple test (defshader simple '((uniform vec3 iResolution) (defn void main [] (setq vec2 uv (/ gl_FragCoord.xy iResolution.xy)) (setq gl_FragColor (vec4 uv.x uv.y 0.0 1.0))))) (print simple) ;; simple unary test (defshader simple '((uniform vec3 iResolution) (defn void main [] (setq vec2 uv (/ gl_FragCoord.xy iResolution.xy)) (setq float vs (- uv.y)) (setq float va (+ vs)) (setq float vm (* va)) (setq float vd (/ vm)) (setq float vn (- 0.0 vd)) (setq gl_FragColor (vec4 uv.x vn 0.0 1.0))))) (print simple) ;; preliminary translation of wave.glsl (defshader wave '((uniform vec3 iResolution) (uniform sampler2D iChannel0) (defn float smoothbump [float center float width float x] (setq float w2 (/ width 2.0)) (setq float cp (+ center w2)) (setq float cm (- center w2)) (return (* (smoothstep cm center x) (- 1.0 (smoothstep center cp x))))) (defn void main [] (setq float uv (/ gl_FragCoord.xy iResolution.xy)) (setq uv.y (- 1.0 uv.y)) (setq float freq (.x (texture2D iChannel0 (vec2 uv.x 0.25)))) (setq float wave (.x (texture2D iChannel0 (vec2 uv.x 0.75)))) (setq float freqc (smoothstep 0.0 (/ 1.0 iResolution.y) (+ freq uv.y -0.5))) (setq float wavec (smoothstep 0.0 (/ 4.0 iResolution.y) (+ wave uv.y -0.5))) (setq gl_FragColor (vec4 freqc wavec 0.25 1.0))))) (print wave) (defshader forloop0 '((defn void main [] (setq vec3 c (vec3 0.0)) (forloop [ (setq int i 0) (<= i 10) (setq i (+ i 1)) ] (setq c (+ c (vec3 0.1)))) (setq gl_FragColor (vec4 c 1.0))))) (print forloop0) (defshader iftest0 '((defn void main [] (if (< i 0) (setq i 0)) (if (< j 10) (do (setq i 5) (setq j 10))) (if (< k 10) (setq i 5) (setq j 10)) (if (< k 10) (do (setq i 1) (setq j 2)) (do (setq i 3) (setq j 4)))))) (print iftest0) (defshader swtest0 '((defn void main [] (switch j 0 (do (setq i 0) (break)) 1 (do (setq i 1) (break)) :default (break)) (switch (+ j k) 0 (do (setq l 0) (break)) :default (break))))) (print swtest0) )
[ { "context": "s!\"\n (let [spreadsheet-id \"1_8g_ItFMIgpCMFIQ1L1CTRhF4oKsjTs4zYe0UMRSd-w\"\n sheet-names (gs/sheet-names! servic", "end": 1845, "score": 0.7203706502914429, "start": 1821, "tag": "KEY", "value": "CTRhF4oKsjTs4zYe0UMRSd-w" } ]
test/zero_one/fxl/google_sheets_test.clj
zackteo/fxl
114
(ns zero-one.fxl.google-sheets-test (:require [clojure.java.io] [clojure.spec.alpha :as s] [clojure.string] [midje.sweet :refer [facts fact => throws]] [zero-one.fxl.google-sheets :as gs] [zero-one.fxl.specs :as fs])) (def google-props {:credentials "resources/credentials.json"}) (defn action-fn [retries-to-success] (let [n-tries (atom 0)] (fn [] (swap! n-tries inc) (if (<= @n-tries retries-to-success) (throw (Exception. "Try again")) @n-tries)))) (facts "On exponential-backoff" (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 0)}) => 1 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 1)}) => 2 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 2)}) => 3 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 3)}) => (throws Exception)) (defn valid-credentials? [] (try (let [credentials-path "resources/credentials.json"] (and (.exists (clojure.java.io/file credentials-path)) (seq (clojure.string/trim (slurp credentials-path))))) (catch Exception e (str "caught exception: " (.getMessage e))))) (when (valid-credentials?) (defonce service (gs/sheets-service google-props)) (facts "On gs/read-google-sheets!" (let [spreadsheet-id "1_8g_ItFMIgpCMFIQ1L1CTRhF4oKsjTs4zYe0UMRSd-w" sheet-names (gs/sheet-names! service spreadsheet-id) cells (gs/read-google-sheets! service spreadsheet-id (first sheet-names)) values (->> cells (map :value) set)] (fact "Read cells should all be valid" (filter #(not (s/valid? ::fs/cell %)) cells) => ()) (fact "There should be 15 cells" (count cells) => 15) (fact "Values should be extracted" (contains? values "1.4142") => true))))
48978
(ns zero-one.fxl.google-sheets-test (:require [clojure.java.io] [clojure.spec.alpha :as s] [clojure.string] [midje.sweet :refer [facts fact => throws]] [zero-one.fxl.google-sheets :as gs] [zero-one.fxl.specs :as fs])) (def google-props {:credentials "resources/credentials.json"}) (defn action-fn [retries-to-success] (let [n-tries (atom 0)] (fn [] (swap! n-tries inc) (if (<= @n-tries retries-to-success) (throw (Exception. "Try again")) @n-tries)))) (facts "On exponential-backoff" (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 0)}) => 1 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 1)}) => 2 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 2)}) => 3 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 3)}) => (throws Exception)) (defn valid-credentials? [] (try (let [credentials-path "resources/credentials.json"] (and (.exists (clojure.java.io/file credentials-path)) (seq (clojure.string/trim (slurp credentials-path))))) (catch Exception e (str "caught exception: " (.getMessage e))))) (when (valid-credentials?) (defonce service (gs/sheets-service google-props)) (facts "On gs/read-google-sheets!" (let [spreadsheet-id "1_8g_ItFMIgpCMFIQ1L1<KEY>" sheet-names (gs/sheet-names! service spreadsheet-id) cells (gs/read-google-sheets! service spreadsheet-id (first sheet-names)) values (->> cells (map :value) set)] (fact "Read cells should all be valid" (filter #(not (s/valid? ::fs/cell %)) cells) => ()) (fact "There should be 15 cells" (count cells) => 15) (fact "Values should be extracted" (contains? values "1.4142") => true))))
true
(ns zero-one.fxl.google-sheets-test (:require [clojure.java.io] [clojure.spec.alpha :as s] [clojure.string] [midje.sweet :refer [facts fact => throws]] [zero-one.fxl.google-sheets :as gs] [zero-one.fxl.specs :as fs])) (def google-props {:credentials "resources/credentials.json"}) (defn action-fn [retries-to-success] (let [n-tries (atom 0)] (fn [] (swap! n-tries inc) (if (<= @n-tries retries-to-success) (throw (Exception. "Try again")) @n-tries)))) (facts "On exponential-backoff" (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 0)}) => 1 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 1)}) => 2 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 2)}) => 3 (gs/exponential-backoff {:wait-ms 100 :growth-rate 2 :max-ms 399 :action! (action-fn 3)}) => (throws Exception)) (defn valid-credentials? [] (try (let [credentials-path "resources/credentials.json"] (and (.exists (clojure.java.io/file credentials-path)) (seq (clojure.string/trim (slurp credentials-path))))) (catch Exception e (str "caught exception: " (.getMessage e))))) (when (valid-credentials?) (defonce service (gs/sheets-service google-props)) (facts "On gs/read-google-sheets!" (let [spreadsheet-id "1_8g_ItFMIgpCMFIQ1L1PI:KEY:<KEY>END_PI" sheet-names (gs/sheet-names! service spreadsheet-id) cells (gs/read-google-sheets! service spreadsheet-id (first sheet-names)) values (->> cells (map :value) set)] (fact "Read cells should all be valid" (filter #(not (s/valid? ::fs/cell %)) cells) => ()) (fact "There should be 15 cells" (count cells) => 15) (fact "Values should be extracted" (contains? values "1.4142") => true))))
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2015 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.999782383441925, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
test/wam/grammar_test.clj
rm-hull/wam
23
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 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 wam.grammar-test (:import [java.text ParseException] [wam.grammar Constant Variable Structure Functor]) (:require [clojure.test :refer :all] [jasentaa.parser :refer [parse-all]] [wam.grammar :refer [structure predicate constant variable]])) (deftest check-variable (testing "Variables" (is (= (parse-all variable "W") (Variable. 'W))) (is (= (parse-all variable "TEMP") (Variable. 'TEMP))) (is (= (parse-all variable "Temp") (Variable. 'Temp))) (is (= (parse-all variable "_") (Variable. '_))) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all variable "w"))) (is (not= (parse-all variable "W") (Variable. 'X))))) (deftest check-constant (testing "Constants" (is (= (parse-all constant "3") (Constant. 3))) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all constant "W"))))) (deftest check-predicate (testing "Predicates" (is (= (parse-all predicate "fred") "fred")) (is (= (parse-all predicate "b4rn3y") "b4rn3y")) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all predicate "Wilma!"))))) (deftest check-structure (testing "Structures" (is (= (parse-all structure "p") (Structure. (Functor. 'p 0) nil))) (is (= (parse-all structure "f(W)") (Structure. (Functor. 'f 1) (list (Variable. 'W))))) (is (= (parse-all structure "h(Z, W)") (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))))) (is (= (parse-all structure "h(Z,W)") (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))))) (is (= (parse-all structure "p(Z, h(Z, W), f(W))") (Structure. (Functor. 'p 3) (list (Variable. 'Z) (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))) (Structure. (Functor. 'f 1) (list (Variable. 'W))))))))) (deftest writer-output (testing "Output rendering" (is (= (with-out-str (print (parse-all structure "p(Z,h(Z,W),f(W))"))) "p(Z h(Z W) f(W))"))))
71633
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 <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 wam.grammar-test (:import [java.text ParseException] [wam.grammar Constant Variable Structure Functor]) (:require [clojure.test :refer :all] [jasentaa.parser :refer [parse-all]] [wam.grammar :refer [structure predicate constant variable]])) (deftest check-variable (testing "Variables" (is (= (parse-all variable "W") (Variable. 'W))) (is (= (parse-all variable "TEMP") (Variable. 'TEMP))) (is (= (parse-all variable "Temp") (Variable. 'Temp))) (is (= (parse-all variable "_") (Variable. '_))) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all variable "w"))) (is (not= (parse-all variable "W") (Variable. 'X))))) (deftest check-constant (testing "Constants" (is (= (parse-all constant "3") (Constant. 3))) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all constant "W"))))) (deftest check-predicate (testing "Predicates" (is (= (parse-all predicate "fred") "fred")) (is (= (parse-all predicate "b4rn3y") "b4rn3y")) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all predicate "Wilma!"))))) (deftest check-structure (testing "Structures" (is (= (parse-all structure "p") (Structure. (Functor. 'p 0) nil))) (is (= (parse-all structure "f(W)") (Structure. (Functor. 'f 1) (list (Variable. 'W))))) (is (= (parse-all structure "h(Z, W)") (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))))) (is (= (parse-all structure "h(Z,W)") (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))))) (is (= (parse-all structure "p(Z, h(Z, W), f(W))") (Structure. (Functor. 'p 3) (list (Variable. 'Z) (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))) (Structure. (Functor. 'f 1) (list (Variable. 'W))))))))) (deftest writer-output (testing "Output rendering" (is (= (with-out-str (print (parse-all structure "p(Z,h(Z,W),f(W))"))) "p(Z h(Z W) f(W))"))))
true
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 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 wam.grammar-test (:import [java.text ParseException] [wam.grammar Constant Variable Structure Functor]) (:require [clojure.test :refer :all] [jasentaa.parser :refer [parse-all]] [wam.grammar :refer [structure predicate constant variable]])) (deftest check-variable (testing "Variables" (is (= (parse-all variable "W") (Variable. 'W))) (is (= (parse-all variable "TEMP") (Variable. 'TEMP))) (is (= (parse-all variable "Temp") (Variable. 'Temp))) (is (= (parse-all variable "_") (Variable. '_))) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all variable "w"))) (is (not= (parse-all variable "W") (Variable. 'X))))) (deftest check-constant (testing "Constants" (is (= (parse-all constant "3") (Constant. 3))) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all constant "W"))))) (deftest check-predicate (testing "Predicates" (is (= (parse-all predicate "fred") "fred")) (is (= (parse-all predicate "b4rn3y") "b4rn3y")) (is (thrown-with-msg? ParseException #"Unable to parse text" (parse-all predicate "Wilma!"))))) (deftest check-structure (testing "Structures" (is (= (parse-all structure "p") (Structure. (Functor. 'p 0) nil))) (is (= (parse-all structure "f(W)") (Structure. (Functor. 'f 1) (list (Variable. 'W))))) (is (= (parse-all structure "h(Z, W)") (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))))) (is (= (parse-all structure "h(Z,W)") (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))))) (is (= (parse-all structure "p(Z, h(Z, W), f(W))") (Structure. (Functor. 'p 3) (list (Variable. 'Z) (Structure. (Functor. 'h 2) (list (Variable. 'Z) (Variable. 'W))) (Structure. (Functor. 'f 1) (list (Variable. 'W))))))))) (deftest writer-output (testing "Output rendering" (is (= (with-out-str (print (parse-all structure "p(Z,h(Z,W),f(W))"))) "p(Z h(Z W) f(W))"))))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 30, "score": 0.9997804164886475, "start": 19, "tag": "NAME", "value": "Rich Hickey" } ]
Clojure/clojure/test_clojure/clr/io.clj
AydarLukmanov/ArcadiaGodot
1,447
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.test-clojure.clr.io (:use clojure.test clojure.clr.io [clojure.test-helper :only [platform-newlines]]) (:import (System.IO FileInfo FileMode FileStream StreamReader StreamWriter MemoryStream Path) (System.Text Encoding UTF8Encoding UnicodeEncoding UTF32Encoding) )) (def utf8 (UTF8Encoding.)) (def utf16 (UnicodeEncoding.)) (def utf32 (UTF32Encoding.)) (defmacro with-temp-file [[v] & body] `(let [~v (FileInfo. (Path/GetTempFileName))] (try ~@body (finally (.Delete ~v))))) (defn temp-file [fname] (let [fi (FileInfo. fname)] (when (.Exists fi) (.Delete fi)) ;(doto (.Create fi) (.Close)) fi)) (defn- get-bytes [^String s ^Encoding encoding] (let [cs (.ToCharArray s) enc (.GetEncoder encoding) cnt (.GetByteCount enc cs 0 (.Length cs) true) bs (make-array Byte cnt)] (.GetBytes enc cs 0 (.Length cs) bs 0 true) bs)) (deftest test-spit-and-slurp (let [content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))] (with-temp-file [f] (testing "spit/slurp with default encoding" (spit f content) (is (= content (slurp f :encoding utf8))))) ;;RJ Added :encoding utf8 (doseq [enc [ utf8 utf16 utf32 ]] (with-temp-file [f] (testing (str "split/slurp with encoding " enc) (spit f content :encoding enc) (is (= content (slurp f :encoding enc)))))) (testing "deprecated arity" (with-temp-file [f] (spit f content :encoding utf16) (is (= (platform-newlines "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).\n") (with-out-str (is (= content (slurp f utf16)))))))))) (deftest test-streams-defaults (let [f (temp-file "test-reader-writer") content "testing"] (try (is (thrown? Exception (text-reader (Object.)))) (is (thrown? Exception (text-writer (Object.)))) (are [write-to read-from] (= content (do (spit write-to content :encoding utf8) (slurp read-from :encoding utf8))) f f (.FullName f) (.FullName f) (FileStream. (.FullName f) FileMode/Create) (FileStream. (.FullName f) FileMode/Open) (StreamWriter. (FileStream. (.FullName f) FileMode/Create) utf8) (text-reader f :encoding utf8) f (FileStream. (.FullName f) FileMode/Open) (text-writer f :encoding utf8) (StreamReader. (FileStream. (.FullName f) FileMode/Open) utf8)) (is (= content (slurp (get-bytes content utf8) :encoding utf8))) ;;RJ Added :encoding utf8 ;(is (= content (slurp (.ToCharArray content)))) (finally (.Delete f))))) (deftest test-streams-nil (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (text-reader nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (text-writer nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (input-stream nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (output-stream nil)))) ;;; IllegalArgumentException (defn bytes-should-equal [byte-array-1 byte-array-2 msg] (is (= |System.Byte[]| (class byte-array-1) (class byte-array-2)) msg) (is (= (into [] byte-array-1) (into [] byte-array-2)) msg)) (defn data-fixture "in memory fixture data for tests" [in-encoding out-encoding] (let [s (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03"))) bs (get-bytes s in-encoding) i (MemoryStream. bs) r (StreamReader. i in-encoding) o (MemoryStream.) w (StreamWriter. o out-encoding )] {:bs bs :i i :r r :o o :s s :w w})) (deftest test-copy (dorun (for [{:keys [in out flush] :as test} [{:in :i :out :o} {:in :i :out :w} {:in :r :out :o} {:in :r :out :w} {:in :bs :out :o} {:in :bs :out :w}] opts [{} {:buffer-size 16} {:buffer-size 256}]] (let [{:keys [s o] :as d} (data-fixture utf8 utf8)] (apply copy (in d) (out d) (flatten (vec opts))) #_(when (= out :w) (.Flush (:w d))) (.Flush (out d)) (bytes-should-equal (get-bytes s utf8) (.ToArray o) (str "combination " test opts)))))) (deftest test-copy-encodings (doseq [enc [ utf8 utf16 utf32 ]] (testing (str "from inputstream " enc " to writer UTF-8") (let [{:keys [i s o w bs]} (data-fixture enc utf8)] (copy i w :encoding enc :buffer-size 16) (.Flush w) (bytes-should-equal (get-bytes s utf8) (.ToArray o) ""))) (testing (str "from reader UTF-8 to output-stream " enc) (let [{:keys [r o s]} (data-fixture utf8 enc)] (copy r o :encoding enc :buffer-size 16) (bytes-should-equal (get-bytes s enc) (.ToArray o) ""))))) ;(deftest test-as-file ; (are [result input] (= result (as-file input)) ; (File. "foo") "foo" ; (File. "bar") (File. "bar") ; (File. "baz") (URL. "file:baz") ; (File. "quux") (URI. "file:quux") ; nil nil)) ;(deftest test-file ; (are [result args] (= (File. result) (apply file args)) ; "foo" ["foo"] ; "foo/bar" ["foo" "bar"] ; "foo/bar/baz" ["foo" "bar" "baz"])) ;(deftest test-as-url ; (are [file-part input] (= (URL. (str "file:" file-part)) (as-url input)) ; "foo" "file:foo" ; "/foo" (File. "/foo") ; "baz" (URL. "file:baz") ; "quux" (URI. "file:quux")) ; (is (nil? (as-url nil)))) ; ;(deftest test-input-stream ; (let [file (temp-file "test-input-stream" "txt") ; content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03"))) ; bytes (.getBytes content)] ; (spit file content) ; (doseq [[expr msg] ; [[file File] ; [(FileInputStream. file) FileInputStream] ; [(BufferedInputStream. (FileInputStream. file)) BufferedInputStream] ; [(.. file toURI) URI] ; [(.. file toURI toURL) URL] ; [(.. file toURI toURL toString) "URL as String"] ; [(.. file toString) "File as String"]]] ; (with-open [s (input-stream expr)] ; (stream-should-have s bytes msg))))) ;(deftest test-socket-iofactory ; (let [server-socket (ServerSocket. 0) ; client-socket (Socket. "localhost" (.getLocalPort server-socket))] ; (try ; (is (instance? InputStream (input-stream client-socket))) ; (is (instance? OutputStream (output-stream client-socket))) ; (finally (.close server-socket) ; (.close client-socket)))))
113181
; 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 clojure.test-clojure.clr.io (:use clojure.test clojure.clr.io [clojure.test-helper :only [platform-newlines]]) (:import (System.IO FileInfo FileMode FileStream StreamReader StreamWriter MemoryStream Path) (System.Text Encoding UTF8Encoding UnicodeEncoding UTF32Encoding) )) (def utf8 (UTF8Encoding.)) (def utf16 (UnicodeEncoding.)) (def utf32 (UTF32Encoding.)) (defmacro with-temp-file [[v] & body] `(let [~v (FileInfo. (Path/GetTempFileName))] (try ~@body (finally (.Delete ~v))))) (defn temp-file [fname] (let [fi (FileInfo. fname)] (when (.Exists fi) (.Delete fi)) ;(doto (.Create fi) (.Close)) fi)) (defn- get-bytes [^String s ^Encoding encoding] (let [cs (.ToCharArray s) enc (.GetEncoder encoding) cnt (.GetByteCount enc cs 0 (.Length cs) true) bs (make-array Byte cnt)] (.GetBytes enc cs 0 (.Length cs) bs 0 true) bs)) (deftest test-spit-and-slurp (let [content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))] (with-temp-file [f] (testing "spit/slurp with default encoding" (spit f content) (is (= content (slurp f :encoding utf8))))) ;;RJ Added :encoding utf8 (doseq [enc [ utf8 utf16 utf32 ]] (with-temp-file [f] (testing (str "split/slurp with encoding " enc) (spit f content :encoding enc) (is (= content (slurp f :encoding enc)))))) (testing "deprecated arity" (with-temp-file [f] (spit f content :encoding utf16) (is (= (platform-newlines "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).\n") (with-out-str (is (= content (slurp f utf16)))))))))) (deftest test-streams-defaults (let [f (temp-file "test-reader-writer") content "testing"] (try (is (thrown? Exception (text-reader (Object.)))) (is (thrown? Exception (text-writer (Object.)))) (are [write-to read-from] (= content (do (spit write-to content :encoding utf8) (slurp read-from :encoding utf8))) f f (.FullName f) (.FullName f) (FileStream. (.FullName f) FileMode/Create) (FileStream. (.FullName f) FileMode/Open) (StreamWriter. (FileStream. (.FullName f) FileMode/Create) utf8) (text-reader f :encoding utf8) f (FileStream. (.FullName f) FileMode/Open) (text-writer f :encoding utf8) (StreamReader. (FileStream. (.FullName f) FileMode/Open) utf8)) (is (= content (slurp (get-bytes content utf8) :encoding utf8))) ;;RJ Added :encoding utf8 ;(is (= content (slurp (.ToCharArray content)))) (finally (.Delete f))))) (deftest test-streams-nil (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (text-reader nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (text-writer nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (input-stream nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (output-stream nil)))) ;;; IllegalArgumentException (defn bytes-should-equal [byte-array-1 byte-array-2 msg] (is (= |System.Byte[]| (class byte-array-1) (class byte-array-2)) msg) (is (= (into [] byte-array-1) (into [] byte-array-2)) msg)) (defn data-fixture "in memory fixture data for tests" [in-encoding out-encoding] (let [s (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03"))) bs (get-bytes s in-encoding) i (MemoryStream. bs) r (StreamReader. i in-encoding) o (MemoryStream.) w (StreamWriter. o out-encoding )] {:bs bs :i i :r r :o o :s s :w w})) (deftest test-copy (dorun (for [{:keys [in out flush] :as test} [{:in :i :out :o} {:in :i :out :w} {:in :r :out :o} {:in :r :out :w} {:in :bs :out :o} {:in :bs :out :w}] opts [{} {:buffer-size 16} {:buffer-size 256}]] (let [{:keys [s o] :as d} (data-fixture utf8 utf8)] (apply copy (in d) (out d) (flatten (vec opts))) #_(when (= out :w) (.Flush (:w d))) (.Flush (out d)) (bytes-should-equal (get-bytes s utf8) (.ToArray o) (str "combination " test opts)))))) (deftest test-copy-encodings (doseq [enc [ utf8 utf16 utf32 ]] (testing (str "from inputstream " enc " to writer UTF-8") (let [{:keys [i s o w bs]} (data-fixture enc utf8)] (copy i w :encoding enc :buffer-size 16) (.Flush w) (bytes-should-equal (get-bytes s utf8) (.ToArray o) ""))) (testing (str "from reader UTF-8 to output-stream " enc) (let [{:keys [r o s]} (data-fixture utf8 enc)] (copy r o :encoding enc :buffer-size 16) (bytes-should-equal (get-bytes s enc) (.ToArray o) ""))))) ;(deftest test-as-file ; (are [result input] (= result (as-file input)) ; (File. "foo") "foo" ; (File. "bar") (File. "bar") ; (File. "baz") (URL. "file:baz") ; (File. "quux") (URI. "file:quux") ; nil nil)) ;(deftest test-file ; (are [result args] (= (File. result) (apply file args)) ; "foo" ["foo"] ; "foo/bar" ["foo" "bar"] ; "foo/bar/baz" ["foo" "bar" "baz"])) ;(deftest test-as-url ; (are [file-part input] (= (URL. (str "file:" file-part)) (as-url input)) ; "foo" "file:foo" ; "/foo" (File. "/foo") ; "baz" (URL. "file:baz") ; "quux" (URI. "file:quux")) ; (is (nil? (as-url nil)))) ; ;(deftest test-input-stream ; (let [file (temp-file "test-input-stream" "txt") ; content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03"))) ; bytes (.getBytes content)] ; (spit file content) ; (doseq [[expr msg] ; [[file File] ; [(FileInputStream. file) FileInputStream] ; [(BufferedInputStream. (FileInputStream. file)) BufferedInputStream] ; [(.. file toURI) URI] ; [(.. file toURI toURL) URL] ; [(.. file toURI toURL toString) "URL as String"] ; [(.. file toString) "File as String"]]] ; (with-open [s (input-stream expr)] ; (stream-should-have s bytes msg))))) ;(deftest test-socket-iofactory ; (let [server-socket (ServerSocket. 0) ; client-socket (Socket. "localhost" (.getLocalPort server-socket))] ; (try ; (is (instance? InputStream (input-stream client-socket))) ; (is (instance? OutputStream (output-stream client-socket))) ; (finally (.close server-socket) ; (.close client-socket)))))
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 clojure.test-clojure.clr.io (:use clojure.test clojure.clr.io [clojure.test-helper :only [platform-newlines]]) (:import (System.IO FileInfo FileMode FileStream StreamReader StreamWriter MemoryStream Path) (System.Text Encoding UTF8Encoding UnicodeEncoding UTF32Encoding) )) (def utf8 (UTF8Encoding.)) (def utf16 (UnicodeEncoding.)) (def utf32 (UTF32Encoding.)) (defmacro with-temp-file [[v] & body] `(let [~v (FileInfo. (Path/GetTempFileName))] (try ~@body (finally (.Delete ~v))))) (defn temp-file [fname] (let [fi (FileInfo. fname)] (when (.Exists fi) (.Delete fi)) ;(doto (.Create fi) (.Close)) fi)) (defn- get-bytes [^String s ^Encoding encoding] (let [cs (.ToCharArray s) enc (.GetEncoder encoding) cnt (.GetByteCount enc cs 0 (.Length cs) true) bs (make-array Byte cnt)] (.GetBytes enc cs 0 (.Length cs) bs 0 true) bs)) (deftest test-spit-and-slurp (let [content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))] (with-temp-file [f] (testing "spit/slurp with default encoding" (spit f content) (is (= content (slurp f :encoding utf8))))) ;;RJ Added :encoding utf8 (doseq [enc [ utf8 utf16 utf32 ]] (with-temp-file [f] (testing (str "split/slurp with encoding " enc) (spit f content :encoding enc) (is (= content (slurp f :encoding enc)))))) (testing "deprecated arity" (with-temp-file [f] (spit f content :encoding utf16) (is (= (platform-newlines "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).\n") (with-out-str (is (= content (slurp f utf16)))))))))) (deftest test-streams-defaults (let [f (temp-file "test-reader-writer") content "testing"] (try (is (thrown? Exception (text-reader (Object.)))) (is (thrown? Exception (text-writer (Object.)))) (are [write-to read-from] (= content (do (spit write-to content :encoding utf8) (slurp read-from :encoding utf8))) f f (.FullName f) (.FullName f) (FileStream. (.FullName f) FileMode/Create) (FileStream. (.FullName f) FileMode/Open) (StreamWriter. (FileStream. (.FullName f) FileMode/Create) utf8) (text-reader f :encoding utf8) f (FileStream. (.FullName f) FileMode/Open) (text-writer f :encoding utf8) (StreamReader. (FileStream. (.FullName f) FileMode/Open) utf8)) (is (= content (slurp (get-bytes content utf8) :encoding utf8))) ;;RJ Added :encoding utf8 ;(is (= content (slurp (.ToCharArray content)))) (finally (.Delete f))))) (deftest test-streams-nil (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (text-reader nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (text-writer nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (input-stream nil))) ;;; IllegalArgumentException (is (thrown-with-msg? ArgumentException #"Cannot open.*nil" (output-stream nil)))) ;;; IllegalArgumentException (defn bytes-should-equal [byte-array-1 byte-array-2 msg] (is (= |System.Byte[]| (class byte-array-1) (class byte-array-2)) msg) (is (= (into [] byte-array-1) (into [] byte-array-2)) msg)) (defn data-fixture "in memory fixture data for tests" [in-encoding out-encoding] (let [s (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03"))) bs (get-bytes s in-encoding) i (MemoryStream. bs) r (StreamReader. i in-encoding) o (MemoryStream.) w (StreamWriter. o out-encoding )] {:bs bs :i i :r r :o o :s s :w w})) (deftest test-copy (dorun (for [{:keys [in out flush] :as test} [{:in :i :out :o} {:in :i :out :w} {:in :r :out :o} {:in :r :out :w} {:in :bs :out :o} {:in :bs :out :w}] opts [{} {:buffer-size 16} {:buffer-size 256}]] (let [{:keys [s o] :as d} (data-fixture utf8 utf8)] (apply copy (in d) (out d) (flatten (vec opts))) #_(when (= out :w) (.Flush (:w d))) (.Flush (out d)) (bytes-should-equal (get-bytes s utf8) (.ToArray o) (str "combination " test opts)))))) (deftest test-copy-encodings (doseq [enc [ utf8 utf16 utf32 ]] (testing (str "from inputstream " enc " to writer UTF-8") (let [{:keys [i s o w bs]} (data-fixture enc utf8)] (copy i w :encoding enc :buffer-size 16) (.Flush w) (bytes-should-equal (get-bytes s utf8) (.ToArray o) ""))) (testing (str "from reader UTF-8 to output-stream " enc) (let [{:keys [r o s]} (data-fixture utf8 enc)] (copy r o :encoding enc :buffer-size 16) (bytes-should-equal (get-bytes s enc) (.ToArray o) ""))))) ;(deftest test-as-file ; (are [result input] (= result (as-file input)) ; (File. "foo") "foo" ; (File. "bar") (File. "bar") ; (File. "baz") (URL. "file:baz") ; (File. "quux") (URI. "file:quux") ; nil nil)) ;(deftest test-file ; (are [result args] (= (File. result) (apply file args)) ; "foo" ["foo"] ; "foo/bar" ["foo" "bar"] ; "foo/bar/baz" ["foo" "bar" "baz"])) ;(deftest test-as-url ; (are [file-part input] (= (URL. (str "file:" file-part)) (as-url input)) ; "foo" "file:foo" ; "/foo" (File. "/foo") ; "baz" (URL. "file:baz") ; "quux" (URI. "file:quux")) ; (is (nil? (as-url nil)))) ; ;(deftest test-input-stream ; (let [file (temp-file "test-input-stream" "txt") ; content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03"))) ; bytes (.getBytes content)] ; (spit file content) ; (doseq [[expr msg] ; [[file File] ; [(FileInputStream. file) FileInputStream] ; [(BufferedInputStream. (FileInputStream. file)) BufferedInputStream] ; [(.. file toURI) URI] ; [(.. file toURI toURL) URL] ; [(.. file toURI toURL toString) "URL as String"] ; [(.. file toString) "File as String"]]] ; (with-open [s (input-stream expr)] ; (stream-should-have s bytes msg))))) ;(deftest test-socket-iofactory ; (let [server-socket (ServerSocket. 0) ; client-socket (Socket. "localhost" (.getLocalPort server-socket))] ; (try ; (is (instance? InputStream (input-stream client-socket))) ; (is (instance? OutputStream (output-stream client-socket))) ; (finally (.close server-socket) ; (.close client-socket)))))
[ { "context": "3} Or with many arguments\n(= \"Hello to this group: Peter, Paul, Mary!\"\n (hello \"Peter\" \"Paul\" \"Mary\"))\n\n;{4} Multimet", "end": 8667, "score": 0.9787507057189941, "start": 8650, "tag": "NAME", "value": "Peter, Paul, Mary" }, { "context": "ello to this group: Peter, Paul, Mary!\"\n (hello \"Peter\" \"Paul\" \"Mary\"))\n\n;{4} Multimethods allow more co", "end": 8685, "score": 0.9998332262039185, "start": 8680, "tag": "NAME", "value": "Peter" }, { "context": "this group: Peter, Paul, Mary!\"\n (hello \"Peter\" \"Paul\" \"Mary\"))\n\n;{4} Multimethods allow more complex d", "end": 8692, "score": 0.999687910079956, "start": 8688, "tag": "NAME", "value": "Paul" }, { "context": "oup: Peter, Paul, Mary!\"\n (hello \"Peter\" \"Paul\" \"Mary\"))\n\n;{4} Multimethods allow more complex dispatch", "end": 8699, "score": 0.9995840787887573, "start": 8695, "tag": "NAME", "value": "Mary" }, { "context": "bi eats veggies.\" (diet {:species \"deer\", :name \"Bambi\", :age 1, :eater :herbivore}))\n\n;{5} Different me", "end": 9056, "score": 0.577710747718811, "start": 9052, "tag": "NAME", "value": "ambi" }, { "context": " method when no others match\n(= \"I don't know what Rich Hickey eats.\" (diet {:name \"Rich Hickey\"}))\n\n\n\n;; ------", "end": 9345, "score": 0.6881769895553589, "start": 9334, "tag": "NAME", "value": "Rich Hickey" }, { "context": " don't know what Rich Hickey eats.\" (diet {:name \"Rich Hickey\"}))\n\n\n\n;; -------------------------------- ;;\n;; ", "end": 9378, "score": 0.9598966836929321, "start": 9367, "tag": "NAME", "value": "Rich Hickey" }, { "context": "age\" \"Clojure\"]))\n\n;{3} Or in let expressions\n(= \"Rich Hickey aka The Clojurer aka Go Time aka Macro Killah\"\n ", "end": 12894, "score": 0.9998335838317871, "start": 12883, "tag": "NAME", "value": "Rich Hickey" }, { "context": "\"\n (let [[first-name last-name & aliases] (list \"Rich\" \"Hickey\" \"The Clojurer\" \"Go Time\" \"Macro Killah\"", "end": 12994, "score": 0.9998281002044678, "start": 12990, "tag": "NAME", "value": "Rich" }, { "context": "t [[first-name last-name & aliases] (list \"Rich\" \"Hickey\" \"The Clojurer\" \"Go Time\" \"Macro Killah\")]\n (s", "end": 13003, "score": 0.9991340041160583, "start": 12997, "tag": "NAME", "value": "Hickey" }, { "context": "rgument if you like arguing\n(= {:original-parts [\"Stephen\" \"Hawking\"], :named-parts {:first \"Stephen\", :las", "end": 13429, "score": 0.999714195728302, "start": 13422, "tag": "NAME", "value": "Stephen" }, { "context": " you like arguing\n(= {:original-parts [\"Stephen\" \"Hawking\"], :named-parts {:first \"Stephen\", :last \"Hawking", "end": 13439, "score": 0.999643087387085, "start": 13432, "tag": "NAME", "value": "Hawking" }, { "context": "arts [\"Stephen\" \"Hawking\"], :named-parts {:first \"Stephen\", :last \"Hawking\"}}\n (let [[first-name last-name", "end": 13472, "score": 0.999703049659729, "start": 13465, "tag": "NAME", "value": "Stephen" }, { "context": "Hawking\"], :named-parts {:first \"Stephen\", :last \"Hawking\"}}\n (let [[first-name last-name :as full-name] [", "end": 13489, "score": 0.9997484683990479, "start": 13482, "tag": "NAME", "value": "Hawking" }, { "context": "}}\n (let [[first-name last-name :as full-name] [\"Stephen\" \"Hawking\"]]\n {:original-parts full-name, :nam", "end": 13547, "score": 0.9997209310531616, "start": 13540, "tag": "NAME", "value": "Stephen" }, { "context": "[[first-name last-name :as full-name] [\"Stephen\" \"Hawking\"]]\n {:original-parts full-name, :named-parts {", "end": 13557, "score": 0.9997382760047913, "start": 13550, "tag": "NAME", "value": "Hawking" }, { "context": " \" city \", \" state)))\n\n;{7} All together now!\n(= \"Test Testerson, 123 Test Lane, Testerville, TX\"\n ((fn [[first-n", "end": 14141, "score": 0.8132506012916565, "start": 14127, "tag": "NAME", "value": "Test Testerson" }, { "context": " %)))))\n\n;{7} Two worlds are better than one\n(= [\"Real Jerry\" \"Bizarro Jerry\"]\n (do\n (dosync\n (ref-se", "end": 17106, "score": 0.9563117027282715, "start": 17096, "tag": "NAME", "value": "Real Jerry" }, { "context": " Two worlds are better than one\n(= [\"Real Jerry\" \"Bizarro Jerry\"]\n (do\n (dosync\n (ref-set the-world {})\n", "end": 17122, "score": 0.9989233016967773, "start": 17109, "tag": "NAME", "value": "Bizarro Jerry" }, { "context": "f-set the-world {})\n (alter the-world assoc :jerry \"Real Jerry\")\n (alter bizarro-world assoc :j", "end": 17207, "score": 0.6153358817100525, "start": 17202, "tag": "NAME", "value": "jerry" }, { "context": "he-world {})\n (alter the-world assoc :jerry \"Real Jerry\")\n (alter bizarro-world assoc :jerry \"Bizarr", "end": 17219, "score": 0.9887111186981201, "start": 17209, "tag": "NAME", "value": "Real Jerry" }, { "context": "y \"Real Jerry\")\n (alter bizarro-world assoc :jerry \"Bizarro Jerry\")\n [(:jerry @the-world) (", "end": 17257, "score": 0.5368403792381287, "start": 17256, "tag": "NAME", "value": "j" }, { "context": " Jerry\")\n (alter bizarro-world assoc :jerry \"Bizarro Jerry\")\n [(:jerry @the-world) (:jerry @bizarro-wor", "end": 17276, "score": 0.9968492388725281, "start": 17263, "tag": "NAME", "value": "Bizarro Jerry" } ]
clojure/avulsos/clojurescript_koans.clj
micalevisk/x-de-cada-dia
0
;; -------------------------- ;; ;; -------- Equality -------- ;; ;; -------------------------- ;; ;{1} We shall contemplate truth by testing reality, via equality (= true true) ;{2} To understand reality, we must compare our expectations against reality (= 2 (+ 1 1)) ;{3} You can test equality of many things (= (+ 3 4) 7 (+ 2 5)) ;{4} But you may not string yourself along (= false (= 2 "2")) ;{5} Something is not equal to nothing (= true (not (= 1 nil))) ;{6} Strings, and keywords, and symbols: oh my! (= false (= "foo" :foo 'foo)) ;{7} Make a keyword with yout keyboard (= :foo (keyword "foo")) ;{8} Symbolism is all around us (= 'foo (symbol "foo")) ;{9} When things cannot be equal, they must be different (not= :fill-in-the-blank '()) (not= :fill-in-the-blank "") ;; ----------------------- ;; ;; -------- Lists -------- ;; ;; ----------------------- ;; ;{1} Lists can be expressed by function or a quoted form (= '(1 2 3 4 5) (list 1 2 3 4 5)) ;{2} They are Clojure seqs (sequences), so they allow access to the first (= 1 (first '(1 2 3 4 5))) ;{3} As well as the rest (= '(2 3 4 5) (rest '(1 2 3 4 5))) ;{4} Count your blessings (= 3 (count '(dracula dooku chocula))) ;{5} Before they are gone (= 0 (count '())) ;{6} The rest, when nothing is left, is empty (= '() (rest '(100))) ;{7} Construction by adding an element to the front is easy (= '(:a :b :c :d :e) (cons :a '(:b :c :d :e))) ;{8} Conjoining an element to a list is strikingly similar (= '(:a :b :c :d :e) (conj '(:b :c :d :e) :a)) ;{9} You can use a list like a stack to get the first element (= :a (peek '(:a :b :c :d :e))) ;{10} Or the others (= '(:b :c :d :e) (pop '(:a :b :c :d :e))) ;; ------------------------ ;; ;; -------- Vector -------- ;; ;; ------------------------ ;; ;{1} You can use vectors in clojure as array-like structures (= 1 (count [42])) ;{2} You can create a vector from a list (= [1] (vec '(1))) ;{3} Or from some elements (= [nil nil] (vector nil nil)) ;{4} But you can populate it with any number of elements at once (= [1 2] (vec '(1 2))) ;{5} Conjoining a vector is different than to a list (= [111 222 333] (conj [111 222] 333)) ;{6} You can get the first element of a vector like so (= :peanut (first [:peanut :butter :and :jelly])) ;{7} And the last in a similar fashion (= :jelly (last [:peanut :butter :and :jelly])) ;{8} Or any index if you wish (= :jelly (nth [:peanut :butter :and :jelly] 3)) ;{9} You can also slice a vector (= [:butter :and] (subvec [:peanut :butter :and :jelly] 1 3)) ;{10} Equality with collections is in terms of values (= (list 1 2 3) (vector 1 2 3)) ;{11} You can create a set by converting another collection (= #{3} (set '(3))) ;; ---------------------- ;; ;; -------- Sets -------- ;; ;; ---------------------- ;; ;{1} You can create a set by converting another collection (= #{3} (set '(3))) ;{2} Counting them is like counting other collections (= 3 (count #{1 3 2})) ;{3} Remeber that a set is a *mathematical* set (= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5))) ;; ---------------------- ;; ;; -------- Maps -------- ;; ;; ---------------------- ;; ;{1} Don't get lost when creating a map (= {:a 1, :b 2} (hash-map :a 1 :b 2)) ;{2} A value must be supplied for each key (= {:a 1} (hash-map :a 1)) ;{3} The size is the number of entries (= 2 (count {:a 1, :b 2})) ;{4} You can look up the value for a given key (= 2 (get {:a 1, :b 2} :b)) ;{5} Maps can be used as functions to do lookups (= 1 ({:a 1, :b 2} :a)) ;{6} And so can keywords (= 1 (:a {:a 1, :b 2})) ;{7} But map keys need not be keywords (= "Vancouver" ({2006 "Torino", 2010 "Vancouver", 2014 "Sochi"} 2010)) ;{8} You may not be able to find an entry for a key (= nil (get {:a 1, :b 2} :c)) ;{9} But you can provide your own default (= :key-not-found (get {:a 1, :b 2} :c :key-not-found)) ;{10} You can find out if a key is present (= true (contains? {:a nil, :b nil} :b)) ;{11} Or if it is missing (= false (contains? {:a nil, :b nil} :c)) ;{12} Maps are immutable, but you can create a new and improved version (= {1 "January", 2 "February"} (assoc {1 "January" 2 "February"})) ;{13} You can also create a new version with an entry removed (= {1 "January"} (dissoc {1 "January", 2 "February"} 2)) ;{14} Often you will need to get the keys, but the order is undependable (= (list 2006 2010 2014s) (sort (keys {2010 "Vancouver", 2014 "Sochi", 2006 "Torino"}))) ;{15} You can get the values in a similar way (= (list "Sochi" "Torino" "Vancouver") (sort (vals {2010 "Vancouver", 2014 "Sochi", 2006 "Torino"}))) ;; --------------------------- ;; ;; -------- Functions -------- ;; ;; --------------------------- ;; (defn square [n] (* n n)) (defn multiply-by-ten [n] (* 10 n)) ;{1} Calling a function is like giving it a hug with parentheses (= 81 (square 9)) ;{2} Functions are usually defined before they are used (= 20 (multiply-by-ten 2)) ;{3} But they can also be defined inline (= 10 ((fn [n] (* 5 n)) 2)) ;{4} Or using an even shorter syntax (= 60 (#(* 15 %) 4)) ;{5} Even anonymous funcions may take multiple arguments (= 15 (#(+ %1 %2 %3) 4 5 6)) ;{6} Arguments can also be skipped (= 30 (#(* 15 %2) 1 2)) ;{7} One function can beget another (= 9 (((fn [] +)) 4 5)) ;{8} Functions can also take other functions as input (= 20 ((fn [f] (f 4 5)) *)) ;{9} Higher-order functions take function arguments (= 25 (#(% 5) (fn [n] (* n n)))) ;{10} But they are often better written using the names of functions (= 25 (#(% 5) square)) ;; ------------------------------ ;; ;; -------- Conditionals -------- ;; ;; ------------------------------ ;; (defn explain-defcon-level [exercise-term] (case exercise-term :fade-out :you-and-what-army :double-take :call-me-when-its-important :round-house :o-rly :fast-pace :thats-pretty-bad :cocked-pistol :sirens :say-what?)) ;{1} You will face many decisions (= :a (if (false? (= 4 5)) :a :b)) ;{2} Some of them leave you no alternative (= [] (if (> 4 3) [])) ;{3} And in such a situation you may have nothing (= nil (if (nil? 0) [:a :b :C])) ;{4} In others you alternative may be interesting (= :glory (if (not (empty? ())) :doom :glory)) ;{5} You may have a multitude of possible of possible paths (let [x 5] (= :your-road (cond (= x 1) :road-not-taken (= x 2) :another-road-not-taken :else :your-road))) ;{6} Or your fate may be sealed (= 'doom (if-not (zero? :anything) 'doom 'doom)) ;{7} In case of emergency, sound the alarms (= :sirens (explain-defcon-level :cocked-pistol)) ;{8} But admit it when you don't kwno what to do (= :say-what? (explain-defcon-level :yo-mama)) ;; ---------------------------------------- ;; ;; -------- Higher Order Functions -------- ;; ;; ---------------------------------------- ;; ;{1} The map function relates a sequence to another (= '(4 8 12) (map (fn [x] (* 4 x)) [1 2 3])) ;{2} You may create that mapping (= '(1 4 9 16 25) (map (fn [x] (* x x)) [1 2 3 4 5])) ;{2} Or use the names of existing functions (= '(false false true false false) (map nil? [:a :b nil :c :d])) ;{3} A filter can be strong (= '() (filter (fn [x] false) '(:anything :goes :here))) ;{4} Or very weak (= '(:anything :goes :here) (filter (fn [x] true) '(:anything :goes :here))) ;{5} Or somewhere in between (= [10 20 30] (filter (fn [x] (< x 31)) [10 20 30 40 50 60 70 80])) ;{6} Maps and filters may be combined (= [10 20 30] (map (fn [x] (* x 10)) (filter (fn [x] (< x 4)) [1 2 3 4 5 6 7 8]))) ;{7} Reducing can increase the result (= 24 (reduce (fn [a b] (* a b)) [1 2 3 4])) ;{8} You can start somewhere else (= 2400 (reduce (fn [a b] (* a b)) 100 [1 2 3 4])) ;{9} Numbers are not the only things one can reduce (= "longest" (reduce (fn [a b] (if (< (count a) (count b)) b a)) ["which" "is" "the" "longest" "word"])) ;; -------------------------------------- ;; ;; -------- Runtime Polymorphism -------- ;; ;; -------------------------------------- ;; (defn hello ([] "Hello World!") ([a] (str "Hello, you silly " a ".")) ([a & more] (str "Hello to this group: " (apply str (interpose ", " (concat (list a) more))) "!"))) ;{1} Some functions can be used in different ways - with no arguments (= "Hello World!" (hello)) ;{2} With one arguments (= "Hello, you silly world." (hello "world")) ;{3} Or with many arguments (= "Hello to this group: Peter, Paul, Mary!" (hello "Peter" "Paul" "Mary")) ;{4} Multimethods allow more complex dispatching (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] (str (:name a) " eats veggies.")) (defmethod diet :carnivore [a] (str (:name a) " eats animals.")) (defmethod diet :default [a] (str "I don't know what " (:name a) " eats.")) (= "Bambi eats veggies." (diet {:species "deer", :name "Bambi", :age 1, :eater :herbivore})) ;{5} Different methods are used depending on the dispatch function result (= "Simba eats animals." (diet {:species "lion", :name "Simba", :age 1, :eater :carnivore})) ;{6} You may use a default method when no others match (= "I don't know what Rich Hickey eats." (diet {:name "Rich Hickey"})) ;; -------------------------------- ;; ;; -------- Lazy Sequences -------- ;; ;; -------------------------------- ;; ;{1} There are many ways to generate a sequence (= '(1 2 3 4) (range 1 5)) ;{2} The range starts at the beginning by default (= '(0 1 2 3 4) (range 5)) ;{3} Only take what you need when the sequence is large (= [0 1 2 3 4 5 6 7 8 9] (take 10 (range 100))) ;{4} Or limit results by dropping what you don't need (= [95 96 97 98 99] (drop 95 (range 100))) ;{5} Iteration provides an infinite lazy sequence (= '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) (take 20 (iterate inc 0))) ;{6} Repetition is key (= [:a :a :a :a :a :a :a :a :a :a] (repeat 10 :a)) ;{7} Iteration can be used for repetion (= (repeat 100 :foo) (take 100 (iterate identity :foo))) ;; ----------------------------------------- ;; ;; -------- Sequence Comprehensions -------- ;; ;; ----------------------------------------- ;; ;{1} Sequence comprehensions can bind each element in turn to a symbol (= '(0 1 2 3 4 5) (for [index (range 6)] index)) ;{2} They can easily emulate mapping (= '(0 1 4 9 16 25) (map (fn [index] (* index index)) (range 6)) (for [index (range 6)] (* index index))) ;{3} And also filtering (= '(1 3 5 7 9) (filter odd? (range 10)) (for [index (range 10) :when (odd? index)] index)) ;{4} Combinations of these transformations is trivial (= '(1 9 25 49 81) (map #(* % %) (filter odd? (range 10))) (for [index (range 10) :when odd?] (* index index))) ;{5} More complex transformations simply take multiple binding forms (= [[:top :left] [:top :middle] [:top :right] [:middle :left] [:middle :middle] [:middle :right] [:bottom :left] [:bottom :middle] [:bottom :right]] (for [row [:top :middle :bottom] column [:left :middle :right]] [row column])) ;; ------------------------------------ ;; ;; -------- Creating Functions -------- ;; ;; ------------------------------------ ;; ;{1} One may know what they seek by knowing what they do not seek (= [true false true] (let [not-a-symbol? (complement symbol?)] (map not-a-symbol? [:a 'b "c"]))) ;{2} Praise and 'complement' may help you separate the wheat from the chaff (= [:wheat "wheat" 'wheat] (let [not-nil? (complement nil?)] (filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil]))) ;{3} Partial functions alllow procrastination (= 20 (let [multiply-by-5 (partial * 5)] (multiply-by-5 4))) ;{4} Don't forget: first things first (= [:a :b :c] (let [ab-adder (partial concat [:a :b])] (ab-adder [:c]))) ;{5} Functions can join forces as one 'composed' function (defn square [x] (* x x)) (= 25 (let [inc-and-square (comp square inc)] (inc-and-square 4))) ;{6} Have a go on a double dec-er (= 8 (let [double-dec (comp dec dec)] (double-dec 10))) ;{7} Be careful about the order in which you mix your functions (= 99 (let [square-and-dec (comp dec square)] (square-and-dec 10))) ;; ------------------------------- ;; ;; -------- Destructuring -------- ;; ;; ------------------------------- ;; ;{1} Destructuring is an arbiter: it breaks up arguments (= ":bar:foo" ((fn [[a b]] (str a b)) [:foo :bar])) ;{2} Whether in function definitions (= (str "First comes love, " "then comes marriage, " "then comes Clojure with the baby carriage") ((fn [[a b c]] (str "First comes " a ", then comes " b ", " "then comes " c " with the baby carriage")) ["love" "marriage" "Clojure"])) ;{3} Or in let expressions (= "Rich Hickey aka The Clojurer aka Go Time aka Macro Killah" (let [[first-name last-name & aliases] (list "Rich" "Hickey" "The Clojurer" "Go Time" "Macro Killah")] (str first-name " " last-name " aka " (nth aliases 0) " aka " (nth aliases 1) " aka " (nth aliases 2)))) ; (str first-name " " last-name " aka " (clojure.string/join " aka " aliases)))) ; (clojure.string/join " " (reduce conj [first-name last-name "aka"] (interpose "aka" aliases)) ;{4} You can regain the full argument if you like arguing (= {:original-parts ["Stephen" "Hawking"], :named-parts {:first "Stephen", :last "Hawking"}} (let [[first-name last-name :as full-name] ["Stephen" "Hawking"]] {:original-parts full-name, :named-parts {:first first-name, :last last-name}})) ;{5} Break up maps by key (def test-address {:street-address "123 Test Lane" :city "Testerville" :state "TX"}) (= "123 Test Lane, Testerville, TX" (let [{street-address :street-address, city :city, state :state} test-address] (str street-address ", " city ", " state))) ;{6} Or more succinctly (= "123 Test Lane, Testerville, TX" (let [{:keys [street-address city state]} test-address] (str street-address ", " city ", " state))) ;{7} All together now! (= "Test Testerson, 123 Test Lane, Testerville, TX" ((fn [[first-name last-name] {:keys [street-address city state]}] (str first-name " " last-name ", " street-address ", " city ", " state)) ["Test" "Testerson"] test-address)) ;; ---------------------- ;; ;; -------- Atom -------- ;; ;; ---------------------- ;; (def atomic-clock (atom 0)) ;{1} Atoms are references to values (= 0 (deref atomic-clock)) ;{2} You can get its value more succintly (= 0 (@atomic-clok)) ;{3} You can even change at the swap meet (= 1 (do (swap! atomic-clock inc) @atomic-clock)) ;{4} Keep taxes out of this: swapping requires no transaction (= 5 (do (swap! atomic-clock #(+ 5 %)) @atomic-clock)) ;{5} Any number of arguments might happen during a swap (= 15 (do (swap! atomic-clock + 1 2 3 4 5) @atomic-clock)) ;{6} Atomic atoms are atomic (= 0 (do (compare-and-set! atomic-clock 100 :fin) @atomic-clock)) ;{7} When your expectations are aligned with reality things, proceed that way (= :fin (do (compare-and-set! atomic-clock 0 :fin) @atomic-clock)) ;; --------------------------- ;; ;; -------- Partition -------- ;; ;; --------------------------- ;; ;{1} To split a collection you can use the partition function (= '((0 1) (2 3)) (partition 2 (range 4))) ;{2} But watch out if there are not enough elements to form n sequences (= '((:a :b :c)) (partition 3 [:a :b :c :d :e])) ;{3} You can use partition-all to also get partitions with less than n elements (= '((0 1 2) (3 4)) (partion-all 3 (range 5))) ;{4} If you need to, you can start each sequence with an offset (= '((0 1 2) (5 6 7) (10 11 12)) (partition 3 5 (range 13))) ;{5} Consider padding the last sequence with some default values.. (= '((0 1 2) (3 4 5) (6 :hello)) (partition 3 3 [:hello] (range 7))) ;{6} ..but notice that they will only pad up to given sequence length (= '( (0 1 2) (3 4 5) (6 :this :are) ) (partition 3 3 [:this :are "my" "words"] (range 7))) ;; ----------------------------------------- ;; ;; -------- Ref [non-clojurescript] -------- ;; ;; ----------------------------------------- ;; (def the-world (ref "hello")) (def bizarro-world (ref {})) ;{1} In the beginning, there was a word (= "hello" (deref the-world)) ;{2} You can get the word more succinctly, but it's the same (= "hello" @the-world) ;{3} You can be the change you wish to see in the world. (= "better" (do (dosync (ref-set the-world "better")) @the-world)) ;{4} Alter where you need not replace (= "better!!!" (let [exclamator (fn [x] (str x "!"))] (dosync (alter the-world exclamator) (alter the-world exclamator) (alter the-world exclamator)) @the-world)) ;{5} Don't forget to do your work in a transaction! (= 0 (do (dosync (ref-set the-world 0)) @the-world)) ;{6} Functions passed to alter may depend on the data in the ref (= 20 (do (dosync (alter the-world #(+ 20 %))))) ;{7} Two worlds are better than one (= ["Real Jerry" "Bizarro Jerry"] (do (dosync (ref-set the-world {}) (alter the-world assoc :jerry "Real Jerry") (alter bizarro-world assoc :jerry "Bizarro Jerry") [(:jerry @the-world) (:jerry @bizarro-world)]))) ;; ----------------------------------------------- ;; ;; -------- Datatypes [non-clojurescript] -------- ;; ;; ----------------------------------------------- ;; (defrecord Nobel [prize]) (deftype Pulitzer [prize]) (defprotocol Award (present [this recipient])) ;{1} Holding records is meaningful only when the record is worthy of you (= "peace" (.prize (Nobel. "peace"))) ;{2} Types are quite similar (= "literature" (.prize (Pulitzer. "literature"))) ;{3} Records may be treated like maps (= "physics" (:prize (Nobel. "physics"))) ;{4} While types may not (= nil (:prize (Pulitzer. "poetry"))) ;{5} Further study reveals why (= '(true false) (map map? [(Nobel. "chemistry") (Pulitzer. "music")])) ;{6} Either sort of datatype can define methods in a protocol (defrecord Oscar [category] Award (present [this recipient] (print (str "Congratulations on your " (:category this) " Oscar, " recipient "!")))) (= "Congratulations on your Best Picture Oscar, Evil Alien Conquerors!" (with-out-str (present (Oscar. "Best Picture") "Evil Alien Conquerors"))) ;{7} Surely we can implement our own by now (defrecord Razzie [category] Award (present [this recipient] (print (str "You're really the " (:category this) ", " recipient "... sorry.")))) (= "You're really the Worst Picture, Final Destination 5... sorry." (with-out-str (present (Razzie. "Worst Picture") "Final Destination 5")))
68947
;; -------------------------- ;; ;; -------- Equality -------- ;; ;; -------------------------- ;; ;{1} We shall contemplate truth by testing reality, via equality (= true true) ;{2} To understand reality, we must compare our expectations against reality (= 2 (+ 1 1)) ;{3} You can test equality of many things (= (+ 3 4) 7 (+ 2 5)) ;{4} But you may not string yourself along (= false (= 2 "2")) ;{5} Something is not equal to nothing (= true (not (= 1 nil))) ;{6} Strings, and keywords, and symbols: oh my! (= false (= "foo" :foo 'foo)) ;{7} Make a keyword with yout keyboard (= :foo (keyword "foo")) ;{8} Symbolism is all around us (= 'foo (symbol "foo")) ;{9} When things cannot be equal, they must be different (not= :fill-in-the-blank '()) (not= :fill-in-the-blank "") ;; ----------------------- ;; ;; -------- Lists -------- ;; ;; ----------------------- ;; ;{1} Lists can be expressed by function or a quoted form (= '(1 2 3 4 5) (list 1 2 3 4 5)) ;{2} They are Clojure seqs (sequences), so they allow access to the first (= 1 (first '(1 2 3 4 5))) ;{3} As well as the rest (= '(2 3 4 5) (rest '(1 2 3 4 5))) ;{4} Count your blessings (= 3 (count '(dracula dooku chocula))) ;{5} Before they are gone (= 0 (count '())) ;{6} The rest, when nothing is left, is empty (= '() (rest '(100))) ;{7} Construction by adding an element to the front is easy (= '(:a :b :c :d :e) (cons :a '(:b :c :d :e))) ;{8} Conjoining an element to a list is strikingly similar (= '(:a :b :c :d :e) (conj '(:b :c :d :e) :a)) ;{9} You can use a list like a stack to get the first element (= :a (peek '(:a :b :c :d :e))) ;{10} Or the others (= '(:b :c :d :e) (pop '(:a :b :c :d :e))) ;; ------------------------ ;; ;; -------- Vector -------- ;; ;; ------------------------ ;; ;{1} You can use vectors in clojure as array-like structures (= 1 (count [42])) ;{2} You can create a vector from a list (= [1] (vec '(1))) ;{3} Or from some elements (= [nil nil] (vector nil nil)) ;{4} But you can populate it with any number of elements at once (= [1 2] (vec '(1 2))) ;{5} Conjoining a vector is different than to a list (= [111 222 333] (conj [111 222] 333)) ;{6} You can get the first element of a vector like so (= :peanut (first [:peanut :butter :and :jelly])) ;{7} And the last in a similar fashion (= :jelly (last [:peanut :butter :and :jelly])) ;{8} Or any index if you wish (= :jelly (nth [:peanut :butter :and :jelly] 3)) ;{9} You can also slice a vector (= [:butter :and] (subvec [:peanut :butter :and :jelly] 1 3)) ;{10} Equality with collections is in terms of values (= (list 1 2 3) (vector 1 2 3)) ;{11} You can create a set by converting another collection (= #{3} (set '(3))) ;; ---------------------- ;; ;; -------- Sets -------- ;; ;; ---------------------- ;; ;{1} You can create a set by converting another collection (= #{3} (set '(3))) ;{2} Counting them is like counting other collections (= 3 (count #{1 3 2})) ;{3} Remeber that a set is a *mathematical* set (= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5))) ;; ---------------------- ;; ;; -------- Maps -------- ;; ;; ---------------------- ;; ;{1} Don't get lost when creating a map (= {:a 1, :b 2} (hash-map :a 1 :b 2)) ;{2} A value must be supplied for each key (= {:a 1} (hash-map :a 1)) ;{3} The size is the number of entries (= 2 (count {:a 1, :b 2})) ;{4} You can look up the value for a given key (= 2 (get {:a 1, :b 2} :b)) ;{5} Maps can be used as functions to do lookups (= 1 ({:a 1, :b 2} :a)) ;{6} And so can keywords (= 1 (:a {:a 1, :b 2})) ;{7} But map keys need not be keywords (= "Vancouver" ({2006 "Torino", 2010 "Vancouver", 2014 "Sochi"} 2010)) ;{8} You may not be able to find an entry for a key (= nil (get {:a 1, :b 2} :c)) ;{9} But you can provide your own default (= :key-not-found (get {:a 1, :b 2} :c :key-not-found)) ;{10} You can find out if a key is present (= true (contains? {:a nil, :b nil} :b)) ;{11} Or if it is missing (= false (contains? {:a nil, :b nil} :c)) ;{12} Maps are immutable, but you can create a new and improved version (= {1 "January", 2 "February"} (assoc {1 "January" 2 "February"})) ;{13} You can also create a new version with an entry removed (= {1 "January"} (dissoc {1 "January", 2 "February"} 2)) ;{14} Often you will need to get the keys, but the order is undependable (= (list 2006 2010 2014s) (sort (keys {2010 "Vancouver", 2014 "Sochi", 2006 "Torino"}))) ;{15} You can get the values in a similar way (= (list "Sochi" "Torino" "Vancouver") (sort (vals {2010 "Vancouver", 2014 "Sochi", 2006 "Torino"}))) ;; --------------------------- ;; ;; -------- Functions -------- ;; ;; --------------------------- ;; (defn square [n] (* n n)) (defn multiply-by-ten [n] (* 10 n)) ;{1} Calling a function is like giving it a hug with parentheses (= 81 (square 9)) ;{2} Functions are usually defined before they are used (= 20 (multiply-by-ten 2)) ;{3} But they can also be defined inline (= 10 ((fn [n] (* 5 n)) 2)) ;{4} Or using an even shorter syntax (= 60 (#(* 15 %) 4)) ;{5} Even anonymous funcions may take multiple arguments (= 15 (#(+ %1 %2 %3) 4 5 6)) ;{6} Arguments can also be skipped (= 30 (#(* 15 %2) 1 2)) ;{7} One function can beget another (= 9 (((fn [] +)) 4 5)) ;{8} Functions can also take other functions as input (= 20 ((fn [f] (f 4 5)) *)) ;{9} Higher-order functions take function arguments (= 25 (#(% 5) (fn [n] (* n n)))) ;{10} But they are often better written using the names of functions (= 25 (#(% 5) square)) ;; ------------------------------ ;; ;; -------- Conditionals -------- ;; ;; ------------------------------ ;; (defn explain-defcon-level [exercise-term] (case exercise-term :fade-out :you-and-what-army :double-take :call-me-when-its-important :round-house :o-rly :fast-pace :thats-pretty-bad :cocked-pistol :sirens :say-what?)) ;{1} You will face many decisions (= :a (if (false? (= 4 5)) :a :b)) ;{2} Some of them leave you no alternative (= [] (if (> 4 3) [])) ;{3} And in such a situation you may have nothing (= nil (if (nil? 0) [:a :b :C])) ;{4} In others you alternative may be interesting (= :glory (if (not (empty? ())) :doom :glory)) ;{5} You may have a multitude of possible of possible paths (let [x 5] (= :your-road (cond (= x 1) :road-not-taken (= x 2) :another-road-not-taken :else :your-road))) ;{6} Or your fate may be sealed (= 'doom (if-not (zero? :anything) 'doom 'doom)) ;{7} In case of emergency, sound the alarms (= :sirens (explain-defcon-level :cocked-pistol)) ;{8} But admit it when you don't kwno what to do (= :say-what? (explain-defcon-level :yo-mama)) ;; ---------------------------------------- ;; ;; -------- Higher Order Functions -------- ;; ;; ---------------------------------------- ;; ;{1} The map function relates a sequence to another (= '(4 8 12) (map (fn [x] (* 4 x)) [1 2 3])) ;{2} You may create that mapping (= '(1 4 9 16 25) (map (fn [x] (* x x)) [1 2 3 4 5])) ;{2} Or use the names of existing functions (= '(false false true false false) (map nil? [:a :b nil :c :d])) ;{3} A filter can be strong (= '() (filter (fn [x] false) '(:anything :goes :here))) ;{4} Or very weak (= '(:anything :goes :here) (filter (fn [x] true) '(:anything :goes :here))) ;{5} Or somewhere in between (= [10 20 30] (filter (fn [x] (< x 31)) [10 20 30 40 50 60 70 80])) ;{6} Maps and filters may be combined (= [10 20 30] (map (fn [x] (* x 10)) (filter (fn [x] (< x 4)) [1 2 3 4 5 6 7 8]))) ;{7} Reducing can increase the result (= 24 (reduce (fn [a b] (* a b)) [1 2 3 4])) ;{8} You can start somewhere else (= 2400 (reduce (fn [a b] (* a b)) 100 [1 2 3 4])) ;{9} Numbers are not the only things one can reduce (= "longest" (reduce (fn [a b] (if (< (count a) (count b)) b a)) ["which" "is" "the" "longest" "word"])) ;; -------------------------------------- ;; ;; -------- Runtime Polymorphism -------- ;; ;; -------------------------------------- ;; (defn hello ([] "Hello World!") ([a] (str "Hello, you silly " a ".")) ([a & more] (str "Hello to this group: " (apply str (interpose ", " (concat (list a) more))) "!"))) ;{1} Some functions can be used in different ways - with no arguments (= "Hello World!" (hello)) ;{2} With one arguments (= "Hello, you silly world." (hello "world")) ;{3} Or with many arguments (= "Hello to this group: <NAME>!" (hello "<NAME>" "<NAME>" "<NAME>")) ;{4} Multimethods allow more complex dispatching (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] (str (:name a) " eats veggies.")) (defmethod diet :carnivore [a] (str (:name a) " eats animals.")) (defmethod diet :default [a] (str "I don't know what " (:name a) " eats.")) (= "Bambi eats veggies." (diet {:species "deer", :name "B<NAME>", :age 1, :eater :herbivore})) ;{5} Different methods are used depending on the dispatch function result (= "Simba eats animals." (diet {:species "lion", :name "Simba", :age 1, :eater :carnivore})) ;{6} You may use a default method when no others match (= "I don't know what <NAME> eats." (diet {:name "<NAME>"})) ;; -------------------------------- ;; ;; -------- Lazy Sequences -------- ;; ;; -------------------------------- ;; ;{1} There are many ways to generate a sequence (= '(1 2 3 4) (range 1 5)) ;{2} The range starts at the beginning by default (= '(0 1 2 3 4) (range 5)) ;{3} Only take what you need when the sequence is large (= [0 1 2 3 4 5 6 7 8 9] (take 10 (range 100))) ;{4} Or limit results by dropping what you don't need (= [95 96 97 98 99] (drop 95 (range 100))) ;{5} Iteration provides an infinite lazy sequence (= '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) (take 20 (iterate inc 0))) ;{6} Repetition is key (= [:a :a :a :a :a :a :a :a :a :a] (repeat 10 :a)) ;{7} Iteration can be used for repetion (= (repeat 100 :foo) (take 100 (iterate identity :foo))) ;; ----------------------------------------- ;; ;; -------- Sequence Comprehensions -------- ;; ;; ----------------------------------------- ;; ;{1} Sequence comprehensions can bind each element in turn to a symbol (= '(0 1 2 3 4 5) (for [index (range 6)] index)) ;{2} They can easily emulate mapping (= '(0 1 4 9 16 25) (map (fn [index] (* index index)) (range 6)) (for [index (range 6)] (* index index))) ;{3} And also filtering (= '(1 3 5 7 9) (filter odd? (range 10)) (for [index (range 10) :when (odd? index)] index)) ;{4} Combinations of these transformations is trivial (= '(1 9 25 49 81) (map #(* % %) (filter odd? (range 10))) (for [index (range 10) :when odd?] (* index index))) ;{5} More complex transformations simply take multiple binding forms (= [[:top :left] [:top :middle] [:top :right] [:middle :left] [:middle :middle] [:middle :right] [:bottom :left] [:bottom :middle] [:bottom :right]] (for [row [:top :middle :bottom] column [:left :middle :right]] [row column])) ;; ------------------------------------ ;; ;; -------- Creating Functions -------- ;; ;; ------------------------------------ ;; ;{1} One may know what they seek by knowing what they do not seek (= [true false true] (let [not-a-symbol? (complement symbol?)] (map not-a-symbol? [:a 'b "c"]))) ;{2} Praise and 'complement' may help you separate the wheat from the chaff (= [:wheat "wheat" 'wheat] (let [not-nil? (complement nil?)] (filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil]))) ;{3} Partial functions alllow procrastination (= 20 (let [multiply-by-5 (partial * 5)] (multiply-by-5 4))) ;{4} Don't forget: first things first (= [:a :b :c] (let [ab-adder (partial concat [:a :b])] (ab-adder [:c]))) ;{5} Functions can join forces as one 'composed' function (defn square [x] (* x x)) (= 25 (let [inc-and-square (comp square inc)] (inc-and-square 4))) ;{6} Have a go on a double dec-er (= 8 (let [double-dec (comp dec dec)] (double-dec 10))) ;{7} Be careful about the order in which you mix your functions (= 99 (let [square-and-dec (comp dec square)] (square-and-dec 10))) ;; ------------------------------- ;; ;; -------- Destructuring -------- ;; ;; ------------------------------- ;; ;{1} Destructuring is an arbiter: it breaks up arguments (= ":bar:foo" ((fn [[a b]] (str a b)) [:foo :bar])) ;{2} Whether in function definitions (= (str "First comes love, " "then comes marriage, " "then comes Clojure with the baby carriage") ((fn [[a b c]] (str "First comes " a ", then comes " b ", " "then comes " c " with the baby carriage")) ["love" "marriage" "Clojure"])) ;{3} Or in let expressions (= "<NAME> aka The Clojurer aka Go Time aka Macro Killah" (let [[first-name last-name & aliases] (list "<NAME>" "<NAME>" "The Clojurer" "Go Time" "Macro Killah")] (str first-name " " last-name " aka " (nth aliases 0) " aka " (nth aliases 1) " aka " (nth aliases 2)))) ; (str first-name " " last-name " aka " (clojure.string/join " aka " aliases)))) ; (clojure.string/join " " (reduce conj [first-name last-name "aka"] (interpose "aka" aliases)) ;{4} You can regain the full argument if you like arguing (= {:original-parts ["<NAME>" "<NAME>"], :named-parts {:first "<NAME>", :last "<NAME>"}} (let [[first-name last-name :as full-name] ["<NAME>" "<NAME>"]] {:original-parts full-name, :named-parts {:first first-name, :last last-name}})) ;{5} Break up maps by key (def test-address {:street-address "123 Test Lane" :city "Testerville" :state "TX"}) (= "123 Test Lane, Testerville, TX" (let [{street-address :street-address, city :city, state :state} test-address] (str street-address ", " city ", " state))) ;{6} Or more succinctly (= "123 Test Lane, Testerville, TX" (let [{:keys [street-address city state]} test-address] (str street-address ", " city ", " state))) ;{7} All together now! (= "<NAME>, 123 Test Lane, Testerville, TX" ((fn [[first-name last-name] {:keys [street-address city state]}] (str first-name " " last-name ", " street-address ", " city ", " state)) ["Test" "Testerson"] test-address)) ;; ---------------------- ;; ;; -------- Atom -------- ;; ;; ---------------------- ;; (def atomic-clock (atom 0)) ;{1} Atoms are references to values (= 0 (deref atomic-clock)) ;{2} You can get its value more succintly (= 0 (@atomic-clok)) ;{3} You can even change at the swap meet (= 1 (do (swap! atomic-clock inc) @atomic-clock)) ;{4} Keep taxes out of this: swapping requires no transaction (= 5 (do (swap! atomic-clock #(+ 5 %)) @atomic-clock)) ;{5} Any number of arguments might happen during a swap (= 15 (do (swap! atomic-clock + 1 2 3 4 5) @atomic-clock)) ;{6} Atomic atoms are atomic (= 0 (do (compare-and-set! atomic-clock 100 :fin) @atomic-clock)) ;{7} When your expectations are aligned with reality things, proceed that way (= :fin (do (compare-and-set! atomic-clock 0 :fin) @atomic-clock)) ;; --------------------------- ;; ;; -------- Partition -------- ;; ;; --------------------------- ;; ;{1} To split a collection you can use the partition function (= '((0 1) (2 3)) (partition 2 (range 4))) ;{2} But watch out if there are not enough elements to form n sequences (= '((:a :b :c)) (partition 3 [:a :b :c :d :e])) ;{3} You can use partition-all to also get partitions with less than n elements (= '((0 1 2) (3 4)) (partion-all 3 (range 5))) ;{4} If you need to, you can start each sequence with an offset (= '((0 1 2) (5 6 7) (10 11 12)) (partition 3 5 (range 13))) ;{5} Consider padding the last sequence with some default values.. (= '((0 1 2) (3 4 5) (6 :hello)) (partition 3 3 [:hello] (range 7))) ;{6} ..but notice that they will only pad up to given sequence length (= '( (0 1 2) (3 4 5) (6 :this :are) ) (partition 3 3 [:this :are "my" "words"] (range 7))) ;; ----------------------------------------- ;; ;; -------- Ref [non-clojurescript] -------- ;; ;; ----------------------------------------- ;; (def the-world (ref "hello")) (def bizarro-world (ref {})) ;{1} In the beginning, there was a word (= "hello" (deref the-world)) ;{2} You can get the word more succinctly, but it's the same (= "hello" @the-world) ;{3} You can be the change you wish to see in the world. (= "better" (do (dosync (ref-set the-world "better")) @the-world)) ;{4} Alter where you need not replace (= "better!!!" (let [exclamator (fn [x] (str x "!"))] (dosync (alter the-world exclamator) (alter the-world exclamator) (alter the-world exclamator)) @the-world)) ;{5} Don't forget to do your work in a transaction! (= 0 (do (dosync (ref-set the-world 0)) @the-world)) ;{6} Functions passed to alter may depend on the data in the ref (= 20 (do (dosync (alter the-world #(+ 20 %))))) ;{7} Two worlds are better than one (= ["<NAME>" "<NAME>"] (do (dosync (ref-set the-world {}) (alter the-world assoc :<NAME> "<NAME>") (alter bizarro-world assoc :<NAME>erry "<NAME>") [(:jerry @the-world) (:jerry @bizarro-world)]))) ;; ----------------------------------------------- ;; ;; -------- Datatypes [non-clojurescript] -------- ;; ;; ----------------------------------------------- ;; (defrecord Nobel [prize]) (deftype Pulitzer [prize]) (defprotocol Award (present [this recipient])) ;{1} Holding records is meaningful only when the record is worthy of you (= "peace" (.prize (Nobel. "peace"))) ;{2} Types are quite similar (= "literature" (.prize (Pulitzer. "literature"))) ;{3} Records may be treated like maps (= "physics" (:prize (Nobel. "physics"))) ;{4} While types may not (= nil (:prize (Pulitzer. "poetry"))) ;{5} Further study reveals why (= '(true false) (map map? [(Nobel. "chemistry") (Pulitzer. "music")])) ;{6} Either sort of datatype can define methods in a protocol (defrecord Oscar [category] Award (present [this recipient] (print (str "Congratulations on your " (:category this) " Oscar, " recipient "!")))) (= "Congratulations on your Best Picture Oscar, Evil Alien Conquerors!" (with-out-str (present (Oscar. "Best Picture") "Evil Alien Conquerors"))) ;{7} Surely we can implement our own by now (defrecord Razzie [category] Award (present [this recipient] (print (str "You're really the " (:category this) ", " recipient "... sorry.")))) (= "You're really the Worst Picture, Final Destination 5... sorry." (with-out-str (present (Razzie. "Worst Picture") "Final Destination 5")))
true
;; -------------------------- ;; ;; -------- Equality -------- ;; ;; -------------------------- ;; ;{1} We shall contemplate truth by testing reality, via equality (= true true) ;{2} To understand reality, we must compare our expectations against reality (= 2 (+ 1 1)) ;{3} You can test equality of many things (= (+ 3 4) 7 (+ 2 5)) ;{4} But you may not string yourself along (= false (= 2 "2")) ;{5} Something is not equal to nothing (= true (not (= 1 nil))) ;{6} Strings, and keywords, and symbols: oh my! (= false (= "foo" :foo 'foo)) ;{7} Make a keyword with yout keyboard (= :foo (keyword "foo")) ;{8} Symbolism is all around us (= 'foo (symbol "foo")) ;{9} When things cannot be equal, they must be different (not= :fill-in-the-blank '()) (not= :fill-in-the-blank "") ;; ----------------------- ;; ;; -------- Lists -------- ;; ;; ----------------------- ;; ;{1} Lists can be expressed by function or a quoted form (= '(1 2 3 4 5) (list 1 2 3 4 5)) ;{2} They are Clojure seqs (sequences), so they allow access to the first (= 1 (first '(1 2 3 4 5))) ;{3} As well as the rest (= '(2 3 4 5) (rest '(1 2 3 4 5))) ;{4} Count your blessings (= 3 (count '(dracula dooku chocula))) ;{5} Before they are gone (= 0 (count '())) ;{6} The rest, when nothing is left, is empty (= '() (rest '(100))) ;{7} Construction by adding an element to the front is easy (= '(:a :b :c :d :e) (cons :a '(:b :c :d :e))) ;{8} Conjoining an element to a list is strikingly similar (= '(:a :b :c :d :e) (conj '(:b :c :d :e) :a)) ;{9} You can use a list like a stack to get the first element (= :a (peek '(:a :b :c :d :e))) ;{10} Or the others (= '(:b :c :d :e) (pop '(:a :b :c :d :e))) ;; ------------------------ ;; ;; -------- Vector -------- ;; ;; ------------------------ ;; ;{1} You can use vectors in clojure as array-like structures (= 1 (count [42])) ;{2} You can create a vector from a list (= [1] (vec '(1))) ;{3} Or from some elements (= [nil nil] (vector nil nil)) ;{4} But you can populate it with any number of elements at once (= [1 2] (vec '(1 2))) ;{5} Conjoining a vector is different than to a list (= [111 222 333] (conj [111 222] 333)) ;{6} You can get the first element of a vector like so (= :peanut (first [:peanut :butter :and :jelly])) ;{7} And the last in a similar fashion (= :jelly (last [:peanut :butter :and :jelly])) ;{8} Or any index if you wish (= :jelly (nth [:peanut :butter :and :jelly] 3)) ;{9} You can also slice a vector (= [:butter :and] (subvec [:peanut :butter :and :jelly] 1 3)) ;{10} Equality with collections is in terms of values (= (list 1 2 3) (vector 1 2 3)) ;{11} You can create a set by converting another collection (= #{3} (set '(3))) ;; ---------------------- ;; ;; -------- Sets -------- ;; ;; ---------------------- ;; ;{1} You can create a set by converting another collection (= #{3} (set '(3))) ;{2} Counting them is like counting other collections (= 3 (count #{1 3 2})) ;{3} Remeber that a set is a *mathematical* set (= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5))) ;; ---------------------- ;; ;; -------- Maps -------- ;; ;; ---------------------- ;; ;{1} Don't get lost when creating a map (= {:a 1, :b 2} (hash-map :a 1 :b 2)) ;{2} A value must be supplied for each key (= {:a 1} (hash-map :a 1)) ;{3} The size is the number of entries (= 2 (count {:a 1, :b 2})) ;{4} You can look up the value for a given key (= 2 (get {:a 1, :b 2} :b)) ;{5} Maps can be used as functions to do lookups (= 1 ({:a 1, :b 2} :a)) ;{6} And so can keywords (= 1 (:a {:a 1, :b 2})) ;{7} But map keys need not be keywords (= "Vancouver" ({2006 "Torino", 2010 "Vancouver", 2014 "Sochi"} 2010)) ;{8} You may not be able to find an entry for a key (= nil (get {:a 1, :b 2} :c)) ;{9} But you can provide your own default (= :key-not-found (get {:a 1, :b 2} :c :key-not-found)) ;{10} You can find out if a key is present (= true (contains? {:a nil, :b nil} :b)) ;{11} Or if it is missing (= false (contains? {:a nil, :b nil} :c)) ;{12} Maps are immutable, but you can create a new and improved version (= {1 "January", 2 "February"} (assoc {1 "January" 2 "February"})) ;{13} You can also create a new version with an entry removed (= {1 "January"} (dissoc {1 "January", 2 "February"} 2)) ;{14} Often you will need to get the keys, but the order is undependable (= (list 2006 2010 2014s) (sort (keys {2010 "Vancouver", 2014 "Sochi", 2006 "Torino"}))) ;{15} You can get the values in a similar way (= (list "Sochi" "Torino" "Vancouver") (sort (vals {2010 "Vancouver", 2014 "Sochi", 2006 "Torino"}))) ;; --------------------------- ;; ;; -------- Functions -------- ;; ;; --------------------------- ;; (defn square [n] (* n n)) (defn multiply-by-ten [n] (* 10 n)) ;{1} Calling a function is like giving it a hug with parentheses (= 81 (square 9)) ;{2} Functions are usually defined before they are used (= 20 (multiply-by-ten 2)) ;{3} But they can also be defined inline (= 10 ((fn [n] (* 5 n)) 2)) ;{4} Or using an even shorter syntax (= 60 (#(* 15 %) 4)) ;{5} Even anonymous funcions may take multiple arguments (= 15 (#(+ %1 %2 %3) 4 5 6)) ;{6} Arguments can also be skipped (= 30 (#(* 15 %2) 1 2)) ;{7} One function can beget another (= 9 (((fn [] +)) 4 5)) ;{8} Functions can also take other functions as input (= 20 ((fn [f] (f 4 5)) *)) ;{9} Higher-order functions take function arguments (= 25 (#(% 5) (fn [n] (* n n)))) ;{10} But they are often better written using the names of functions (= 25 (#(% 5) square)) ;; ------------------------------ ;; ;; -------- Conditionals -------- ;; ;; ------------------------------ ;; (defn explain-defcon-level [exercise-term] (case exercise-term :fade-out :you-and-what-army :double-take :call-me-when-its-important :round-house :o-rly :fast-pace :thats-pretty-bad :cocked-pistol :sirens :say-what?)) ;{1} You will face many decisions (= :a (if (false? (= 4 5)) :a :b)) ;{2} Some of them leave you no alternative (= [] (if (> 4 3) [])) ;{3} And in such a situation you may have nothing (= nil (if (nil? 0) [:a :b :C])) ;{4} In others you alternative may be interesting (= :glory (if (not (empty? ())) :doom :glory)) ;{5} You may have a multitude of possible of possible paths (let [x 5] (= :your-road (cond (= x 1) :road-not-taken (= x 2) :another-road-not-taken :else :your-road))) ;{6} Or your fate may be sealed (= 'doom (if-not (zero? :anything) 'doom 'doom)) ;{7} In case of emergency, sound the alarms (= :sirens (explain-defcon-level :cocked-pistol)) ;{8} But admit it when you don't kwno what to do (= :say-what? (explain-defcon-level :yo-mama)) ;; ---------------------------------------- ;; ;; -------- Higher Order Functions -------- ;; ;; ---------------------------------------- ;; ;{1} The map function relates a sequence to another (= '(4 8 12) (map (fn [x] (* 4 x)) [1 2 3])) ;{2} You may create that mapping (= '(1 4 9 16 25) (map (fn [x] (* x x)) [1 2 3 4 5])) ;{2} Or use the names of existing functions (= '(false false true false false) (map nil? [:a :b nil :c :d])) ;{3} A filter can be strong (= '() (filter (fn [x] false) '(:anything :goes :here))) ;{4} Or very weak (= '(:anything :goes :here) (filter (fn [x] true) '(:anything :goes :here))) ;{5} Or somewhere in between (= [10 20 30] (filter (fn [x] (< x 31)) [10 20 30 40 50 60 70 80])) ;{6} Maps and filters may be combined (= [10 20 30] (map (fn [x] (* x 10)) (filter (fn [x] (< x 4)) [1 2 3 4 5 6 7 8]))) ;{7} Reducing can increase the result (= 24 (reduce (fn [a b] (* a b)) [1 2 3 4])) ;{8} You can start somewhere else (= 2400 (reduce (fn [a b] (* a b)) 100 [1 2 3 4])) ;{9} Numbers are not the only things one can reduce (= "longest" (reduce (fn [a b] (if (< (count a) (count b)) b a)) ["which" "is" "the" "longest" "word"])) ;; -------------------------------------- ;; ;; -------- Runtime Polymorphism -------- ;; ;; -------------------------------------- ;; (defn hello ([] "Hello World!") ([a] (str "Hello, you silly " a ".")) ([a & more] (str "Hello to this group: " (apply str (interpose ", " (concat (list a) more))) "!"))) ;{1} Some functions can be used in different ways - with no arguments (= "Hello World!" (hello)) ;{2} With one arguments (= "Hello, you silly world." (hello "world")) ;{3} Or with many arguments (= "Hello to this group: PI:NAME:<NAME>END_PI!" (hello "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")) ;{4} Multimethods allow more complex dispatching (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] (str (:name a) " eats veggies.")) (defmethod diet :carnivore [a] (str (:name a) " eats animals.")) (defmethod diet :default [a] (str "I don't know what " (:name a) " eats.")) (= "Bambi eats veggies." (diet {:species "deer", :name "BPI:NAME:<NAME>END_PI", :age 1, :eater :herbivore})) ;{5} Different methods are used depending on the dispatch function result (= "Simba eats animals." (diet {:species "lion", :name "Simba", :age 1, :eater :carnivore})) ;{6} You may use a default method when no others match (= "I don't know what PI:NAME:<NAME>END_PI eats." (diet {:name "PI:NAME:<NAME>END_PI"})) ;; -------------------------------- ;; ;; -------- Lazy Sequences -------- ;; ;; -------------------------------- ;; ;{1} There are many ways to generate a sequence (= '(1 2 3 4) (range 1 5)) ;{2} The range starts at the beginning by default (= '(0 1 2 3 4) (range 5)) ;{3} Only take what you need when the sequence is large (= [0 1 2 3 4 5 6 7 8 9] (take 10 (range 100))) ;{4} Or limit results by dropping what you don't need (= [95 96 97 98 99] (drop 95 (range 100))) ;{5} Iteration provides an infinite lazy sequence (= '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) (take 20 (iterate inc 0))) ;{6} Repetition is key (= [:a :a :a :a :a :a :a :a :a :a] (repeat 10 :a)) ;{7} Iteration can be used for repetion (= (repeat 100 :foo) (take 100 (iterate identity :foo))) ;; ----------------------------------------- ;; ;; -------- Sequence Comprehensions -------- ;; ;; ----------------------------------------- ;; ;{1} Sequence comprehensions can bind each element in turn to a symbol (= '(0 1 2 3 4 5) (for [index (range 6)] index)) ;{2} They can easily emulate mapping (= '(0 1 4 9 16 25) (map (fn [index] (* index index)) (range 6)) (for [index (range 6)] (* index index))) ;{3} And also filtering (= '(1 3 5 7 9) (filter odd? (range 10)) (for [index (range 10) :when (odd? index)] index)) ;{4} Combinations of these transformations is trivial (= '(1 9 25 49 81) (map #(* % %) (filter odd? (range 10))) (for [index (range 10) :when odd?] (* index index))) ;{5} More complex transformations simply take multiple binding forms (= [[:top :left] [:top :middle] [:top :right] [:middle :left] [:middle :middle] [:middle :right] [:bottom :left] [:bottom :middle] [:bottom :right]] (for [row [:top :middle :bottom] column [:left :middle :right]] [row column])) ;; ------------------------------------ ;; ;; -------- Creating Functions -------- ;; ;; ------------------------------------ ;; ;{1} One may know what they seek by knowing what they do not seek (= [true false true] (let [not-a-symbol? (complement symbol?)] (map not-a-symbol? [:a 'b "c"]))) ;{2} Praise and 'complement' may help you separate the wheat from the chaff (= [:wheat "wheat" 'wheat] (let [not-nil? (complement nil?)] (filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil]))) ;{3} Partial functions alllow procrastination (= 20 (let [multiply-by-5 (partial * 5)] (multiply-by-5 4))) ;{4} Don't forget: first things first (= [:a :b :c] (let [ab-adder (partial concat [:a :b])] (ab-adder [:c]))) ;{5} Functions can join forces as one 'composed' function (defn square [x] (* x x)) (= 25 (let [inc-and-square (comp square inc)] (inc-and-square 4))) ;{6} Have a go on a double dec-er (= 8 (let [double-dec (comp dec dec)] (double-dec 10))) ;{7} Be careful about the order in which you mix your functions (= 99 (let [square-and-dec (comp dec square)] (square-and-dec 10))) ;; ------------------------------- ;; ;; -------- Destructuring -------- ;; ;; ------------------------------- ;; ;{1} Destructuring is an arbiter: it breaks up arguments (= ":bar:foo" ((fn [[a b]] (str a b)) [:foo :bar])) ;{2} Whether in function definitions (= (str "First comes love, " "then comes marriage, " "then comes Clojure with the baby carriage") ((fn [[a b c]] (str "First comes " a ", then comes " b ", " "then comes " c " with the baby carriage")) ["love" "marriage" "Clojure"])) ;{3} Or in let expressions (= "PI:NAME:<NAME>END_PI aka The Clojurer aka Go Time aka Macro Killah" (let [[first-name last-name & aliases] (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "The Clojurer" "Go Time" "Macro Killah")] (str first-name " " last-name " aka " (nth aliases 0) " aka " (nth aliases 1) " aka " (nth aliases 2)))) ; (str first-name " " last-name " aka " (clojure.string/join " aka " aliases)))) ; (clojure.string/join " " (reduce conj [first-name last-name "aka"] (interpose "aka" aliases)) ;{4} You can regain the full argument if you like arguing (= {:original-parts ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"], :named-parts {:first "PI:NAME:<NAME>END_PI", :last "PI:NAME:<NAME>END_PI"}} (let [[first-name last-name :as full-name] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]] {:original-parts full-name, :named-parts {:first first-name, :last last-name}})) ;{5} Break up maps by key (def test-address {:street-address "123 Test Lane" :city "Testerville" :state "TX"}) (= "123 Test Lane, Testerville, TX" (let [{street-address :street-address, city :city, state :state} test-address] (str street-address ", " city ", " state))) ;{6} Or more succinctly (= "123 Test Lane, Testerville, TX" (let [{:keys [street-address city state]} test-address] (str street-address ", " city ", " state))) ;{7} All together now! (= "PI:NAME:<NAME>END_PI, 123 Test Lane, Testerville, TX" ((fn [[first-name last-name] {:keys [street-address city state]}] (str first-name " " last-name ", " street-address ", " city ", " state)) ["Test" "Testerson"] test-address)) ;; ---------------------- ;; ;; -------- Atom -------- ;; ;; ---------------------- ;; (def atomic-clock (atom 0)) ;{1} Atoms are references to values (= 0 (deref atomic-clock)) ;{2} You can get its value more succintly (= 0 (@atomic-clok)) ;{3} You can even change at the swap meet (= 1 (do (swap! atomic-clock inc) @atomic-clock)) ;{4} Keep taxes out of this: swapping requires no transaction (= 5 (do (swap! atomic-clock #(+ 5 %)) @atomic-clock)) ;{5} Any number of arguments might happen during a swap (= 15 (do (swap! atomic-clock + 1 2 3 4 5) @atomic-clock)) ;{6} Atomic atoms are atomic (= 0 (do (compare-and-set! atomic-clock 100 :fin) @atomic-clock)) ;{7} When your expectations are aligned with reality things, proceed that way (= :fin (do (compare-and-set! atomic-clock 0 :fin) @atomic-clock)) ;; --------------------------- ;; ;; -------- Partition -------- ;; ;; --------------------------- ;; ;{1} To split a collection you can use the partition function (= '((0 1) (2 3)) (partition 2 (range 4))) ;{2} But watch out if there are not enough elements to form n sequences (= '((:a :b :c)) (partition 3 [:a :b :c :d :e])) ;{3} You can use partition-all to also get partitions with less than n elements (= '((0 1 2) (3 4)) (partion-all 3 (range 5))) ;{4} If you need to, you can start each sequence with an offset (= '((0 1 2) (5 6 7) (10 11 12)) (partition 3 5 (range 13))) ;{5} Consider padding the last sequence with some default values.. (= '((0 1 2) (3 4 5) (6 :hello)) (partition 3 3 [:hello] (range 7))) ;{6} ..but notice that they will only pad up to given sequence length (= '( (0 1 2) (3 4 5) (6 :this :are) ) (partition 3 3 [:this :are "my" "words"] (range 7))) ;; ----------------------------------------- ;; ;; -------- Ref [non-clojurescript] -------- ;; ;; ----------------------------------------- ;; (def the-world (ref "hello")) (def bizarro-world (ref {})) ;{1} In the beginning, there was a word (= "hello" (deref the-world)) ;{2} You can get the word more succinctly, but it's the same (= "hello" @the-world) ;{3} You can be the change you wish to see in the world. (= "better" (do (dosync (ref-set the-world "better")) @the-world)) ;{4} Alter where you need not replace (= "better!!!" (let [exclamator (fn [x] (str x "!"))] (dosync (alter the-world exclamator) (alter the-world exclamator) (alter the-world exclamator)) @the-world)) ;{5} Don't forget to do your work in a transaction! (= 0 (do (dosync (ref-set the-world 0)) @the-world)) ;{6} Functions passed to alter may depend on the data in the ref (= 20 (do (dosync (alter the-world #(+ 20 %))))) ;{7} Two worlds are better than one (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (do (dosync (ref-set the-world {}) (alter the-world assoc :PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI") (alter bizarro-world assoc :PI:NAME:<NAME>END_PIerry "PI:NAME:<NAME>END_PI") [(:jerry @the-world) (:jerry @bizarro-world)]))) ;; ----------------------------------------------- ;; ;; -------- Datatypes [non-clojurescript] -------- ;; ;; ----------------------------------------------- ;; (defrecord Nobel [prize]) (deftype Pulitzer [prize]) (defprotocol Award (present [this recipient])) ;{1} Holding records is meaningful only when the record is worthy of you (= "peace" (.prize (Nobel. "peace"))) ;{2} Types are quite similar (= "literature" (.prize (Pulitzer. "literature"))) ;{3} Records may be treated like maps (= "physics" (:prize (Nobel. "physics"))) ;{4} While types may not (= nil (:prize (Pulitzer. "poetry"))) ;{5} Further study reveals why (= '(true false) (map map? [(Nobel. "chemistry") (Pulitzer. "music")])) ;{6} Either sort of datatype can define methods in a protocol (defrecord Oscar [category] Award (present [this recipient] (print (str "Congratulations on your " (:category this) " Oscar, " recipient "!")))) (= "Congratulations on your Best Picture Oscar, Evil Alien Conquerors!" (with-out-str (present (Oscar. "Best Picture") "Evil Alien Conquerors"))) ;{7} Surely we can implement our own by now (defrecord Razzie [category] Award (present [this recipient] (print (str "You're really the " (:category this) ", " recipient "... sorry.")))) (= "You're really the Worst Picture, Final Destination 5... sorry." (with-out-str (present (Razzie. "Worst Picture") "Final Destination 5")))
[ { "context": "produces a bad generator\n ;; --- {\"mbox\" \"mailto:some@email.test\" :objectType \"Agent\"}\n ;; ---- not sure how to e", "end": 8854, "score": 0.9997886419296265, "start": 8839, "tag": "EMAIL", "value": "some@email.test" }, { "context": "ctType must be specified\n -- https://github.com/adlnet/xAPI-Spec/blob/master/xAPI-Data.md#requirements-6", "end": 11400, "score": 0.9989300966262817, "start": 11394, "tag": "USERNAME", "value": "adlnet" } ]
src/com/yetanalytics/dave/func/common.cljc
blakeplock/dave-1
25
(ns com.yetanalytics.dave.func.common (:require [xapi-schema.spec :as xs] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as sgen] [com.yetanalytics.dave.util.spec :as su] [com.yetanalytics.dave.func.util :as util])) (s/fdef scale :args (s/with-gen (s/cat :raw number? :min number? :max number?) su/raw-min-max-gen) :ret (s/double-in :min 0.0 :max 100.0)) (defn scale "Given a number (raw) and its native domain (min and max), scale raw to the domain of 0.0..100.0 DAVE 2.6.6" [raw min max] (let [rng (- max min)] (if (< 0 rng) (double (* 100 (/ (- raw min) rng))) 100.0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; common helpers for parsing statements ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef get-helper :args (s/cat :src (s/map-of ::xs/any-json ::xs/any-json) :k ::xs/any-json) :ret ::xs/any-json) (defn get-helper "get the value at `k` within `src`. - Returns nil if value is nil or empty" [src k] (let [query-result (get src k)] (cond (number? query-result) query-result (boolean? query-result) query-result :else (not-empty query-result)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ifi from agent or group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-ifi ;; :agent/[ifi-type] are defined in xapi-schema (s/or :mbox :agent/mbox :account :agent/account :mbox-sha1sum :agent/mbox_sha1sum :open-id :agent/openid)) (s/def ::group-ifi ;; :group/[ifi-type] are defined in xapi-schema (s/nilable ;; anon groups have no ifi (s/or :mbox :group/mbox :account :group/account :mbox-sha1sum :group/mbox_sha1sum :open-id :group/openid))) (s/fdef get-ifi :args (s/cat :actor ::xs/actor) :ret (s/or :agent ::agent-ifi :group ::group-ifi)) (defn get-ifi "check `m` for one of the possible IFI keys" [m] (or (get-helper m "mbox") (get-helper m "account") (get-helper m "openid") (get-helper m "mbox_sha1sum"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; language map text ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef get-lmap-val :args (s/alt :unary (s/cat :lmap ::xs/language-map) :two (s/cat :lmap ::xs/language-map :language-tag ::xs/language-tag)) :ret (s/nilable ;; provided language tag may be incorrect ::xs/language-map-text)) (defn get-lmap-val "single arity: return the first label across all language tags within a language map - ordering of labels is dictated by `vals` call double arity: return the label found at `language-tag` within `lmap`" ([lmap] (-> lmap vals first)) ([lmap language-tag] (get-helper lmap language-tag))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an agent ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-name ;; :agent/name defined in xapi-schema :agent/name) (s/def ::parse-agent-ret (s/keys :req-un [::agent-name ::agent-ifi])) (s/fdef parse-agent :args (s/cat :agent ::xs/agent) :ret ::parse-agent-ret) (defn parse-agent "return `agent-name` and `agent-ifi` given `m`" [m] (let [agent-name (or (get-helper m "name") "Unamed Agent") agent-ifi (get-ifi m)] {:agent-name agent-name :agent-ifi agent-ifi})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::group-name :group/name) (s/def ::group-members (s/coll-of ::parse-agent-ret :kind vector? :into [] :gen-max 3)) (s/def ::parse-group-ret (s/keys :req-un [::group-name] :opt-un [::group-members ::group-ifi])) (s/fdef parse-group :args (s/cat :group ::xs/group) :ret ::parse-group-ret) (defn parse-group "return `group-name` and possibly `group-members` and/or `group-ifi` - `group-members` is a vector of maps containing `agent-name` and `agent-ifi`" [m] (let [group-name (or (get-helper m "name") "Unamed Group") group-members (when-let [members (get-helper m "member")] (mapv parse-agent members)) group-ifi (get-ifi m)] (cond-> {:group-name group-name} ;; did we have any members? (not-empty group-members) (assoc :group-members group-members) ;; did we have an ifi for the group? group-ifi (assoc :group-ifi group-ifi)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an activity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::activity-id ;; :activity/id defined in xapi-schema :activity/id) (s/def ::activity-name ;; because of call to `get-lmap-val` ::xs/language-map-text) (s/def ::parse-activity-ret (s/keys :req-un [::activity-id ::activity-name])) (s/fdef parse-activity :args (s/alt :unary (s/cat :activity ::xs/activity) :two (s/cat :activity ::xs/activity :language-tag ::xs/language-tag)) :ret ::parse-activity-ret) (defn parse-activity "return `activity-id` and `activity-name` from `m` - single arity assumes `language-tag` is not known - double arity requires `language-tag` as an argument" ([m] (let [{activity-id "id" {activity-name-lmap "name"} "definition"} m activity-name (or (get-lmap-val activity-name-lmap) "Unamed Activity")] {:activity-id activity-id :activity-name activity-name})) ([m language-tag] (let [{activity-id "id" {activity-name-lmap "name"} "definition"} m activity-name (or (get-lmap-val activity-name-lmap language-tag) "Unamed Activity")] {:activity-id activity-id :activity-name activity-name}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an actor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::parse-actor-ret (s/or :agent ::parse-agent-ret :group ::parse-group-ret)) (s/fdef parse-actor :args (s/cat :actor ::xs/actor) :ret ::parse-actor-ret) (defn parse-actor "parse the actor as an agent or group based on the objectType - defaults to parsing as agent" [m] (case (get-helper m "objectType") "Group" (parse-group m) "Agent" (parse-agent m) ;; objectType is optional for Agents but not Groups (parse-agent m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a verb ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::verb-id ;; :verb/id defined in xapi-schema :verb/id) (s/def ::verb-name ;; because of call to `get-lmap-val` ::xs/language-map-text) (s/def ::parse-verb-ret (s/keys :req-un [::verb-id ::verb-name])) (s/fdef parse-verb :args (s/alt :unary (s/cat :verb ::xs/verb) :two (s/cat :verb ::xs/verb :language-tag ::xs/language-tag)) :ret ::parse-verb-ret) (defn parse-verb "return `verb-id` and `verb-name` from `m` - single arity assumes `language-tag` is not known - double arity requires `language-tag` as an argument" ([m] {:verb-id (get-helper m "id") :verb-name (or (-> m (get-helper "display") get-lmap-val) "Unamed Verb")}) ([m language-tag] {:verb-id (get-helper m "id") :verb-name (or (-> m (get-helper "display") (get-lmap-val language-tag)) "Unamed Verb")})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-as-object ;; temporary solution for generative testing ;; - can't use :statement/object for generative testing ;; -- not supporting substatements or statement refs ;; --- currently throwing when they are passed in, not sure how to write a spec for that ;; - can't use ::xs/agent because it doesn't properly enforce the objectType constraint (agent must have objectType) ;; -- simple approach (s/merge ::xs/agent (s/keys :req-un [:agent/objectType])) produces a bad generator ;; --- {"mbox" "mailto:some@email.test" :objectType "Agent"} ;; ---- not sure how to enforce all string keys from the outside ;; Solution = recreate ::xs/agent but will necessary objectType constraint applied (s/with-gen (s/and (s/conformer (partial xs/conform-ns-map "agent") xs/unform-ns-map) (s/keys :req [(or :agent/mbox :agent/mbox_sha1sum :agent/openid :agent/account) :agent/objectType] :opt [:agent/name]) (xs/restrict-keys :agent/mbox :agent/mbox_sha1sum :agent/openid :agent/account :agent/name :agent/objectType) xs/max-one-ifi) #(sgen/fmap xs/unform-ns-map (s/gen (s/or :ifi-mbox (s/keys :req [:agent/mbox :agent/objectType] :opt [:agent/name]) :ifi-mbox_sha1sum (s/keys :req [:agent/mbox_sha1sum :agent/objectType] :opt [:agent/name]) :ifi-openid (s/keys :req [:agent/openid :agent/objectType] :opt [:agent/name]) :ifi-account (s/keys :req [:agent/account :agent/objectType] :opt [:agent/name])))))) (s/def ::object (s/or :agent ::agent-as-object :group ::xs/group :activity ::xs/activity)) (s/def ::parse-object-ret (s/or :agent ::parse-agent-ret :group ::parse-group-ret :activity ::parse-activity-ret)) (s/fdef parse-object ;; limiting args to supported object types ;; - TODO: may be possible to spec intentional errors from (`throw` (`ex-info` ...)) but not sure how ;; -- some form of macro magic...I am but an apprentice :args (s/alt :unary (s/cat :supported-object-types ::object) :two (s/cat :only-activity ::xs/activity :language-tag ::xs/language-tag)) :ret ::parse-object-ret) (defn parse-object "based on the object's type - pass `m` to `parse-group` - pass `m` to `parse-agent` - pass `m` to `parse-activity` - StatementRef and SubStatement are NOT SUPPORTED! defaults to `parse-activity` - when the object is an Agent or Group, objectType must be specified -- https://github.com/adlnet/xAPI-Spec/blob/master/xAPI-Data.md#requirements-6 supports `language-tag` in 2-arity case but `m` must be an activity!" ([m] (case (get-helper m "objectType") "Group" (parse-group m) "Agent" (parse-agent m) "Activity" (parse-activity m) "StatementRef" (throw (ex-info "Statement References are not supported by `parse-object`" {:type ::operation-not-supported})) "SubStatement" (throw (ex-info "SubStatements are not supported by `parse-object`" {:type ::operation-not-supported})) (parse-activity m))) ([activity-m language-tag] ;; object = activity bc only case where `language-tag` is relevant (parse-activity activity-m language-tag))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a statement specs ;; - warning...shield your eyes, it gets ugly ;; (╯°□°)╯︵ ┻━┻ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; return specs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :statement-simple.ret/id :statement/id) (s/def :statement-simple.ret/actor ::parse-actor-ret) (s/def :statement-simple.ret/verb ::parse-verb-ret) (s/def :statement-simple.ret/object ::parse-object-ret) (s/def :statement-simple.ret/timestamp number?) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; arg specs - single arity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: there is probably a better way to handle this ;; - this is bc of ;; -- multi arity parse fns - target `language-tag` support...what have I done ;; -- intentional throwing on some objectTypes w/in parse-object ;; -- generate maps with string keys (s/def :statement-simple.one.arg/id :statement/id) (s/def :statement-simple.one.arg/actor :statement/actor) (s/def :statement-simple.one.arg/verb :statement/verb) (s/def :statement-simple.one.arg/object ::object) (s/def :statement-simple.one.arg/timestamp :statement/timestamp) (s/def :statement-simple.one.arg/statement (xs/conform-ns "statement-simple.one.arg" (s/keys :req [:statement-simple.one.arg/id :statement-simple.one.arg/actor :statement-simple.one.arg/verb :statement-simple.one.arg/object :statement-simple.one.arg/timestamp]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; arg specs - multi arity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: there is probably a better way to handle this ;; - this is bc of ;; -- multi arity parse fns - target `language-tag` support...what have I done ;; -- intentional throwing on some objectTypes w/in parse-object ;; -- generate maps with string keys (s/def :statement-simple.many.arg/id :statement/id) (s/def :statement-simple.many.arg/actor :statement/actor) (s/def :statement-simple.many.arg/verb :statement/verb) (s/def :statement-simple.many.arg/object ::xs/activity) (s/def :statement-simple.many.arg/timestamp :statement/timestamp) (s/def :statement-simple.many.arg/statement (xs/conform-ns "statement-simple.many.arg" (s/keys :req [:statement-simple.many.arg/id :statement-simple.many.arg/actor :statement-simple.many.arg/verb :statement-simple.many.arg/object :statement-simple.many.arg/timestamp]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we've made it to the fdef... щ(゚Д゚щ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef parse-statement-simple :args (s/alt :only-statement (s/cat :simple-statement :statement-simple.one.arg/statement) :shared-language-tag (s/cat :simple-statement :statement-simple.many.arg/statement :shared-language-tag ::xs/language-tag) :targeted-language-tag (s/cat :simple-statement :statement-simple.many.arg/statement :language-tag-verb ::xs/language-tag :language-tag-activity ::xs/language-tag)) :ret (s/keys :req-un [:statement-simple.ret/id :statement-simple.ret/actor :statement-simple.ret/verb :statement-simple.ret/object :statement-simple.ret/timestamp])) (defn parse-statement-simple "parses a statement to return - `id` = statement id - `actor` = return of `parse-actor` - `verb` = return of `parse-verb` - `object` = return of `parse-object` - `timestamp` = unix representation of the ISO timestamp 1-arity case, language-tag is assumed to be unkown or irrelevant 2-arity case, `language-tag` used for both `object` and `verb` - `object` must be an activity 3-arity case `language-tag-verb` and `language-tag-activity` allow for differing language tags - its easy enough to do but unlikely to be needed." ([{:strs [id actor verb object timestamp] :as statement}] {:id id :actor (parse-actor actor) :verb (parse-verb verb) :object (parse-object object) :timestamp (.getTime (util/timestamp->inst timestamp))}) ([{:strs [id actor verb object timestamp] :as statement} language-tag] {:id id :actor (parse-actor actor) :verb (parse-verb verb language-tag) :object (parse-object object language-tag) :timestamp (.getTime (util/timestamp->inst timestamp))}) ([{:strs [id actor verb object timestamp] :as statement} language-tag-verb language-tag-activity] {:id id :actor (parse-actor actor) :verb (parse-verb verb language-tag-verb) :object (parse-object object language-tag-activity) :timestamp (.getTime (util/timestamp->inst timestamp))})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; my generators actually work ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment ;; can't use this because throw on statement refs and sub statements (first (sgen/sample (s/gen ::xs/statement))) ;; object can be agent, group or activity (let [agent-group-or-activity (first (sgen/sample (s/gen :statement-simple.one.arg/statement))) the-obj (get-helper agent-group-or-activity "object")] (and ;; valid statement (s/valid? ::xs/statement agent-group-or-activity) ;; valid agent, group or activity (s/valid? ::object the-obj) ;; not a sub-statement (false? (s/valid? ::xs/sub-statement the-obj)) ;; not a statement ref (false? (s/valid? ::xs/statement-ref the-obj)))) ;; object can only be activity (let [with-activity-obj (first (sgen/sample (s/gen :statement-simple.many.arg/statement))) the-obj (get-helper with-activity-obj "object")] (and ;; valid statement (s/valid? ::xs/statement with-activity-obj) ;; valid activity (s/valid? ::xs/activity the-obj) ;; not an agent (false? (s/valid? ::xs/agent the-obj)) ;; not a group (false? (s/valid? ::xs/group the-obj)) ;; not a substatement (false? (s/valid? ::xs/sub-statement the-obj)) ;; not a statement ref (false? (s/valid? ::xs/statement-ref the-obj))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; helper for return information after statement has been parsed ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; actor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :handle-actor.ret/agent-ordering (s/cat :name ::agent-name :ifi ::agent-ifi)) (s/def :handle-actor.ret/agent (s/with-gen (s/and vector? :handle-actor.ret/agent-ordering) #(sgen/fmap vec (s/gen :handle-actor.ret/agent-ordering)))) (s/def :handle-actor.ret/group-ordering (s/cat :name ::group-name :ifi ::group-ifi)) (s/def :handle-actor.ret/group (s/with-gen (s/and vector? :handle-actor.ret/group-ordering) #(sgen/fmap vec (s/gen :handle-actor.ret/group-ordering)))) (s/def :handle-actor.ret/members (s/coll-of :handle-actor.ret/agent :kind vector? :into [])) (s/fdef handle-actor :args (s/cat :parsed-actor (s/keys :req-un [(or (and ::agent-name ::agent-ifi) ::group-name)] :opt-un [::group-members ::group-ifi])) :ret (s/or :agent :handle-actor.ret/agent :group :handle-actor.ret/group :members :handle-actor.ret/members :dont-accept nil?)) (defn handle-actor [{:keys [agent-name agent-ifi group-name group-members group-ifi]}] (if group-name ;; dealing with a group (if-let [members (not-empty (mapv (fn [member] (let [{a-name :agent-name a-ifi :agent-ifi} member] [a-name a-ifi])) group-members))] ;; we had members, they are all we care about members ;; we didnt' have members, treat the group as an individual ;; - need their identity, only safe way to save their info in state (when group-ifi [group-name group-ifi])) ;; dealing with an agent, return what we know [agent-name agent-ifi])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :handle-object.ret/agent :handle-actor.ret/agent) (s/def :handle-object.ret/identified-group :handle-actor.ret/group) (s/def :handle-object.ret/members (s/coll-of :handle-object.ret/agent :kind vector? :into [])) (s/def :handle-object.ret/group-with-members-ordering (s/cat :name ::group-name :members :handle-object.ret/members)) (s/def :handle-object.ret/group-with-members (s/with-gen (s/and vector? :handle-object.ret/group-with-members-ordering) #(sgen/fmap vec (s/gen :handle-object.ret/group-with-members-ordering)))) (s/def :handle-object.ret/activity-ordering (s/cat :name ::activity-name :ifi ::activity-id)) (s/def :handle-object.ret/activity (s/with-gen (s/and vector? :handle-object.ret/activity-ordering) #(sgen/fmap vec (s/gen :handle-object.ret/activity-ordering)))) (s/def :handle-object.ret/group-only-name (s/coll-of ::group-name :kind vector? :into [] :count 1)) (s/fdef handle-object :args (s/cat :parsed-object (s/keys :req-un [(or (and ::agent-name ::agent-ifi) (and ::activity-id ::activity-name) ::group-name)] :opt-un [::group-members ::group-ifi])) :ret (s/or :activity :handle-object.ret/activity :agent :handle-object.ret/agent :group :handle-object.ret/identified-group :with-members :handle-object.ret/group-with-members :only-name :handle-object.ret/group-only-name)) (defn handle-object [{:keys [agent-name agent-ifi group-name group-members group-ifi activity-id activity-name]}] (cond (and activity-id activity-name) [activity-name activity-id] (and agent-name agent-ifi) [agent-name agent-ifi] (and group-name group-ifi) [group-name group-ifi] :else (if-let [members (not-empty (mapv (fn [member] (let [{a-name :agent-name a-ifi :agent-ifi} member] [a-name a-ifi])) group-members))] [group-name members] [group-name])))
20489
(ns com.yetanalytics.dave.func.common (:require [xapi-schema.spec :as xs] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as sgen] [com.yetanalytics.dave.util.spec :as su] [com.yetanalytics.dave.func.util :as util])) (s/fdef scale :args (s/with-gen (s/cat :raw number? :min number? :max number?) su/raw-min-max-gen) :ret (s/double-in :min 0.0 :max 100.0)) (defn scale "Given a number (raw) and its native domain (min and max), scale raw to the domain of 0.0..100.0 DAVE 2.6.6" [raw min max] (let [rng (- max min)] (if (< 0 rng) (double (* 100 (/ (- raw min) rng))) 100.0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; common helpers for parsing statements ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef get-helper :args (s/cat :src (s/map-of ::xs/any-json ::xs/any-json) :k ::xs/any-json) :ret ::xs/any-json) (defn get-helper "get the value at `k` within `src`. - Returns nil if value is nil or empty" [src k] (let [query-result (get src k)] (cond (number? query-result) query-result (boolean? query-result) query-result :else (not-empty query-result)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ifi from agent or group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-ifi ;; :agent/[ifi-type] are defined in xapi-schema (s/or :mbox :agent/mbox :account :agent/account :mbox-sha1sum :agent/mbox_sha1sum :open-id :agent/openid)) (s/def ::group-ifi ;; :group/[ifi-type] are defined in xapi-schema (s/nilable ;; anon groups have no ifi (s/or :mbox :group/mbox :account :group/account :mbox-sha1sum :group/mbox_sha1sum :open-id :group/openid))) (s/fdef get-ifi :args (s/cat :actor ::xs/actor) :ret (s/or :agent ::agent-ifi :group ::group-ifi)) (defn get-ifi "check `m` for one of the possible IFI keys" [m] (or (get-helper m "mbox") (get-helper m "account") (get-helper m "openid") (get-helper m "mbox_sha1sum"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; language map text ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef get-lmap-val :args (s/alt :unary (s/cat :lmap ::xs/language-map) :two (s/cat :lmap ::xs/language-map :language-tag ::xs/language-tag)) :ret (s/nilable ;; provided language tag may be incorrect ::xs/language-map-text)) (defn get-lmap-val "single arity: return the first label across all language tags within a language map - ordering of labels is dictated by `vals` call double arity: return the label found at `language-tag` within `lmap`" ([lmap] (-> lmap vals first)) ([lmap language-tag] (get-helper lmap language-tag))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an agent ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-name ;; :agent/name defined in xapi-schema :agent/name) (s/def ::parse-agent-ret (s/keys :req-un [::agent-name ::agent-ifi])) (s/fdef parse-agent :args (s/cat :agent ::xs/agent) :ret ::parse-agent-ret) (defn parse-agent "return `agent-name` and `agent-ifi` given `m`" [m] (let [agent-name (or (get-helper m "name") "Unamed Agent") agent-ifi (get-ifi m)] {:agent-name agent-name :agent-ifi agent-ifi})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::group-name :group/name) (s/def ::group-members (s/coll-of ::parse-agent-ret :kind vector? :into [] :gen-max 3)) (s/def ::parse-group-ret (s/keys :req-un [::group-name] :opt-un [::group-members ::group-ifi])) (s/fdef parse-group :args (s/cat :group ::xs/group) :ret ::parse-group-ret) (defn parse-group "return `group-name` and possibly `group-members` and/or `group-ifi` - `group-members` is a vector of maps containing `agent-name` and `agent-ifi`" [m] (let [group-name (or (get-helper m "name") "Unamed Group") group-members (when-let [members (get-helper m "member")] (mapv parse-agent members)) group-ifi (get-ifi m)] (cond-> {:group-name group-name} ;; did we have any members? (not-empty group-members) (assoc :group-members group-members) ;; did we have an ifi for the group? group-ifi (assoc :group-ifi group-ifi)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an activity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::activity-id ;; :activity/id defined in xapi-schema :activity/id) (s/def ::activity-name ;; because of call to `get-lmap-val` ::xs/language-map-text) (s/def ::parse-activity-ret (s/keys :req-un [::activity-id ::activity-name])) (s/fdef parse-activity :args (s/alt :unary (s/cat :activity ::xs/activity) :two (s/cat :activity ::xs/activity :language-tag ::xs/language-tag)) :ret ::parse-activity-ret) (defn parse-activity "return `activity-id` and `activity-name` from `m` - single arity assumes `language-tag` is not known - double arity requires `language-tag` as an argument" ([m] (let [{activity-id "id" {activity-name-lmap "name"} "definition"} m activity-name (or (get-lmap-val activity-name-lmap) "Unamed Activity")] {:activity-id activity-id :activity-name activity-name})) ([m language-tag] (let [{activity-id "id" {activity-name-lmap "name"} "definition"} m activity-name (or (get-lmap-val activity-name-lmap language-tag) "Unamed Activity")] {:activity-id activity-id :activity-name activity-name}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an actor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::parse-actor-ret (s/or :agent ::parse-agent-ret :group ::parse-group-ret)) (s/fdef parse-actor :args (s/cat :actor ::xs/actor) :ret ::parse-actor-ret) (defn parse-actor "parse the actor as an agent or group based on the objectType - defaults to parsing as agent" [m] (case (get-helper m "objectType") "Group" (parse-group m) "Agent" (parse-agent m) ;; objectType is optional for Agents but not Groups (parse-agent m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a verb ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::verb-id ;; :verb/id defined in xapi-schema :verb/id) (s/def ::verb-name ;; because of call to `get-lmap-val` ::xs/language-map-text) (s/def ::parse-verb-ret (s/keys :req-un [::verb-id ::verb-name])) (s/fdef parse-verb :args (s/alt :unary (s/cat :verb ::xs/verb) :two (s/cat :verb ::xs/verb :language-tag ::xs/language-tag)) :ret ::parse-verb-ret) (defn parse-verb "return `verb-id` and `verb-name` from `m` - single arity assumes `language-tag` is not known - double arity requires `language-tag` as an argument" ([m] {:verb-id (get-helper m "id") :verb-name (or (-> m (get-helper "display") get-lmap-val) "Unamed Verb")}) ([m language-tag] {:verb-id (get-helper m "id") :verb-name (or (-> m (get-helper "display") (get-lmap-val language-tag)) "Unamed Verb")})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-as-object ;; temporary solution for generative testing ;; - can't use :statement/object for generative testing ;; -- not supporting substatements or statement refs ;; --- currently throwing when they are passed in, not sure how to write a spec for that ;; - can't use ::xs/agent because it doesn't properly enforce the objectType constraint (agent must have objectType) ;; -- simple approach (s/merge ::xs/agent (s/keys :req-un [:agent/objectType])) produces a bad generator ;; --- {"mbox" "mailto:<EMAIL>" :objectType "Agent"} ;; ---- not sure how to enforce all string keys from the outside ;; Solution = recreate ::xs/agent but will necessary objectType constraint applied (s/with-gen (s/and (s/conformer (partial xs/conform-ns-map "agent") xs/unform-ns-map) (s/keys :req [(or :agent/mbox :agent/mbox_sha1sum :agent/openid :agent/account) :agent/objectType] :opt [:agent/name]) (xs/restrict-keys :agent/mbox :agent/mbox_sha1sum :agent/openid :agent/account :agent/name :agent/objectType) xs/max-one-ifi) #(sgen/fmap xs/unform-ns-map (s/gen (s/or :ifi-mbox (s/keys :req [:agent/mbox :agent/objectType] :opt [:agent/name]) :ifi-mbox_sha1sum (s/keys :req [:agent/mbox_sha1sum :agent/objectType] :opt [:agent/name]) :ifi-openid (s/keys :req [:agent/openid :agent/objectType] :opt [:agent/name]) :ifi-account (s/keys :req [:agent/account :agent/objectType] :opt [:agent/name])))))) (s/def ::object (s/or :agent ::agent-as-object :group ::xs/group :activity ::xs/activity)) (s/def ::parse-object-ret (s/or :agent ::parse-agent-ret :group ::parse-group-ret :activity ::parse-activity-ret)) (s/fdef parse-object ;; limiting args to supported object types ;; - TODO: may be possible to spec intentional errors from (`throw` (`ex-info` ...)) but not sure how ;; -- some form of macro magic...I am but an apprentice :args (s/alt :unary (s/cat :supported-object-types ::object) :two (s/cat :only-activity ::xs/activity :language-tag ::xs/language-tag)) :ret ::parse-object-ret) (defn parse-object "based on the object's type - pass `m` to `parse-group` - pass `m` to `parse-agent` - pass `m` to `parse-activity` - StatementRef and SubStatement are NOT SUPPORTED! defaults to `parse-activity` - when the object is an Agent or Group, objectType must be specified -- https://github.com/adlnet/xAPI-Spec/blob/master/xAPI-Data.md#requirements-6 supports `language-tag` in 2-arity case but `m` must be an activity!" ([m] (case (get-helper m "objectType") "Group" (parse-group m) "Agent" (parse-agent m) "Activity" (parse-activity m) "StatementRef" (throw (ex-info "Statement References are not supported by `parse-object`" {:type ::operation-not-supported})) "SubStatement" (throw (ex-info "SubStatements are not supported by `parse-object`" {:type ::operation-not-supported})) (parse-activity m))) ([activity-m language-tag] ;; object = activity bc only case where `language-tag` is relevant (parse-activity activity-m language-tag))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a statement specs ;; - warning...shield your eyes, it gets ugly ;; (╯°□°)╯︵ ┻━┻ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; return specs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :statement-simple.ret/id :statement/id) (s/def :statement-simple.ret/actor ::parse-actor-ret) (s/def :statement-simple.ret/verb ::parse-verb-ret) (s/def :statement-simple.ret/object ::parse-object-ret) (s/def :statement-simple.ret/timestamp number?) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; arg specs - single arity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: there is probably a better way to handle this ;; - this is bc of ;; -- multi arity parse fns - target `language-tag` support...what have I done ;; -- intentional throwing on some objectTypes w/in parse-object ;; -- generate maps with string keys (s/def :statement-simple.one.arg/id :statement/id) (s/def :statement-simple.one.arg/actor :statement/actor) (s/def :statement-simple.one.arg/verb :statement/verb) (s/def :statement-simple.one.arg/object ::object) (s/def :statement-simple.one.arg/timestamp :statement/timestamp) (s/def :statement-simple.one.arg/statement (xs/conform-ns "statement-simple.one.arg" (s/keys :req [:statement-simple.one.arg/id :statement-simple.one.arg/actor :statement-simple.one.arg/verb :statement-simple.one.arg/object :statement-simple.one.arg/timestamp]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; arg specs - multi arity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: there is probably a better way to handle this ;; - this is bc of ;; -- multi arity parse fns - target `language-tag` support...what have I done ;; -- intentional throwing on some objectTypes w/in parse-object ;; -- generate maps with string keys (s/def :statement-simple.many.arg/id :statement/id) (s/def :statement-simple.many.arg/actor :statement/actor) (s/def :statement-simple.many.arg/verb :statement/verb) (s/def :statement-simple.many.arg/object ::xs/activity) (s/def :statement-simple.many.arg/timestamp :statement/timestamp) (s/def :statement-simple.many.arg/statement (xs/conform-ns "statement-simple.many.arg" (s/keys :req [:statement-simple.many.arg/id :statement-simple.many.arg/actor :statement-simple.many.arg/verb :statement-simple.many.arg/object :statement-simple.many.arg/timestamp]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we've made it to the fdef... щ(゚Д゚щ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef parse-statement-simple :args (s/alt :only-statement (s/cat :simple-statement :statement-simple.one.arg/statement) :shared-language-tag (s/cat :simple-statement :statement-simple.many.arg/statement :shared-language-tag ::xs/language-tag) :targeted-language-tag (s/cat :simple-statement :statement-simple.many.arg/statement :language-tag-verb ::xs/language-tag :language-tag-activity ::xs/language-tag)) :ret (s/keys :req-un [:statement-simple.ret/id :statement-simple.ret/actor :statement-simple.ret/verb :statement-simple.ret/object :statement-simple.ret/timestamp])) (defn parse-statement-simple "parses a statement to return - `id` = statement id - `actor` = return of `parse-actor` - `verb` = return of `parse-verb` - `object` = return of `parse-object` - `timestamp` = unix representation of the ISO timestamp 1-arity case, language-tag is assumed to be unkown or irrelevant 2-arity case, `language-tag` used for both `object` and `verb` - `object` must be an activity 3-arity case `language-tag-verb` and `language-tag-activity` allow for differing language tags - its easy enough to do but unlikely to be needed." ([{:strs [id actor verb object timestamp] :as statement}] {:id id :actor (parse-actor actor) :verb (parse-verb verb) :object (parse-object object) :timestamp (.getTime (util/timestamp->inst timestamp))}) ([{:strs [id actor verb object timestamp] :as statement} language-tag] {:id id :actor (parse-actor actor) :verb (parse-verb verb language-tag) :object (parse-object object language-tag) :timestamp (.getTime (util/timestamp->inst timestamp))}) ([{:strs [id actor verb object timestamp] :as statement} language-tag-verb language-tag-activity] {:id id :actor (parse-actor actor) :verb (parse-verb verb language-tag-verb) :object (parse-object object language-tag-activity) :timestamp (.getTime (util/timestamp->inst timestamp))})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; my generators actually work ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment ;; can't use this because throw on statement refs and sub statements (first (sgen/sample (s/gen ::xs/statement))) ;; object can be agent, group or activity (let [agent-group-or-activity (first (sgen/sample (s/gen :statement-simple.one.arg/statement))) the-obj (get-helper agent-group-or-activity "object")] (and ;; valid statement (s/valid? ::xs/statement agent-group-or-activity) ;; valid agent, group or activity (s/valid? ::object the-obj) ;; not a sub-statement (false? (s/valid? ::xs/sub-statement the-obj)) ;; not a statement ref (false? (s/valid? ::xs/statement-ref the-obj)))) ;; object can only be activity (let [with-activity-obj (first (sgen/sample (s/gen :statement-simple.many.arg/statement))) the-obj (get-helper with-activity-obj "object")] (and ;; valid statement (s/valid? ::xs/statement with-activity-obj) ;; valid activity (s/valid? ::xs/activity the-obj) ;; not an agent (false? (s/valid? ::xs/agent the-obj)) ;; not a group (false? (s/valid? ::xs/group the-obj)) ;; not a substatement (false? (s/valid? ::xs/sub-statement the-obj)) ;; not a statement ref (false? (s/valid? ::xs/statement-ref the-obj))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; helper for return information after statement has been parsed ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; actor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :handle-actor.ret/agent-ordering (s/cat :name ::agent-name :ifi ::agent-ifi)) (s/def :handle-actor.ret/agent (s/with-gen (s/and vector? :handle-actor.ret/agent-ordering) #(sgen/fmap vec (s/gen :handle-actor.ret/agent-ordering)))) (s/def :handle-actor.ret/group-ordering (s/cat :name ::group-name :ifi ::group-ifi)) (s/def :handle-actor.ret/group (s/with-gen (s/and vector? :handle-actor.ret/group-ordering) #(sgen/fmap vec (s/gen :handle-actor.ret/group-ordering)))) (s/def :handle-actor.ret/members (s/coll-of :handle-actor.ret/agent :kind vector? :into [])) (s/fdef handle-actor :args (s/cat :parsed-actor (s/keys :req-un [(or (and ::agent-name ::agent-ifi) ::group-name)] :opt-un [::group-members ::group-ifi])) :ret (s/or :agent :handle-actor.ret/agent :group :handle-actor.ret/group :members :handle-actor.ret/members :dont-accept nil?)) (defn handle-actor [{:keys [agent-name agent-ifi group-name group-members group-ifi]}] (if group-name ;; dealing with a group (if-let [members (not-empty (mapv (fn [member] (let [{a-name :agent-name a-ifi :agent-ifi} member] [a-name a-ifi])) group-members))] ;; we had members, they are all we care about members ;; we didnt' have members, treat the group as an individual ;; - need their identity, only safe way to save their info in state (when group-ifi [group-name group-ifi])) ;; dealing with an agent, return what we know [agent-name agent-ifi])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :handle-object.ret/agent :handle-actor.ret/agent) (s/def :handle-object.ret/identified-group :handle-actor.ret/group) (s/def :handle-object.ret/members (s/coll-of :handle-object.ret/agent :kind vector? :into [])) (s/def :handle-object.ret/group-with-members-ordering (s/cat :name ::group-name :members :handle-object.ret/members)) (s/def :handle-object.ret/group-with-members (s/with-gen (s/and vector? :handle-object.ret/group-with-members-ordering) #(sgen/fmap vec (s/gen :handle-object.ret/group-with-members-ordering)))) (s/def :handle-object.ret/activity-ordering (s/cat :name ::activity-name :ifi ::activity-id)) (s/def :handle-object.ret/activity (s/with-gen (s/and vector? :handle-object.ret/activity-ordering) #(sgen/fmap vec (s/gen :handle-object.ret/activity-ordering)))) (s/def :handle-object.ret/group-only-name (s/coll-of ::group-name :kind vector? :into [] :count 1)) (s/fdef handle-object :args (s/cat :parsed-object (s/keys :req-un [(or (and ::agent-name ::agent-ifi) (and ::activity-id ::activity-name) ::group-name)] :opt-un [::group-members ::group-ifi])) :ret (s/or :activity :handle-object.ret/activity :agent :handle-object.ret/agent :group :handle-object.ret/identified-group :with-members :handle-object.ret/group-with-members :only-name :handle-object.ret/group-only-name)) (defn handle-object [{:keys [agent-name agent-ifi group-name group-members group-ifi activity-id activity-name]}] (cond (and activity-id activity-name) [activity-name activity-id] (and agent-name agent-ifi) [agent-name agent-ifi] (and group-name group-ifi) [group-name group-ifi] :else (if-let [members (not-empty (mapv (fn [member] (let [{a-name :agent-name a-ifi :agent-ifi} member] [a-name a-ifi])) group-members))] [group-name members] [group-name])))
true
(ns com.yetanalytics.dave.func.common (:require [xapi-schema.spec :as xs] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as sgen] [com.yetanalytics.dave.util.spec :as su] [com.yetanalytics.dave.func.util :as util])) (s/fdef scale :args (s/with-gen (s/cat :raw number? :min number? :max number?) su/raw-min-max-gen) :ret (s/double-in :min 0.0 :max 100.0)) (defn scale "Given a number (raw) and its native domain (min and max), scale raw to the domain of 0.0..100.0 DAVE 2.6.6" [raw min max] (let [rng (- max min)] (if (< 0 rng) (double (* 100 (/ (- raw min) rng))) 100.0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; common helpers for parsing statements ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef get-helper :args (s/cat :src (s/map-of ::xs/any-json ::xs/any-json) :k ::xs/any-json) :ret ::xs/any-json) (defn get-helper "get the value at `k` within `src`. - Returns nil if value is nil or empty" [src k] (let [query-result (get src k)] (cond (number? query-result) query-result (boolean? query-result) query-result :else (not-empty query-result)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ifi from agent or group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-ifi ;; :agent/[ifi-type] are defined in xapi-schema (s/or :mbox :agent/mbox :account :agent/account :mbox-sha1sum :agent/mbox_sha1sum :open-id :agent/openid)) (s/def ::group-ifi ;; :group/[ifi-type] are defined in xapi-schema (s/nilable ;; anon groups have no ifi (s/or :mbox :group/mbox :account :group/account :mbox-sha1sum :group/mbox_sha1sum :open-id :group/openid))) (s/fdef get-ifi :args (s/cat :actor ::xs/actor) :ret (s/or :agent ::agent-ifi :group ::group-ifi)) (defn get-ifi "check `m` for one of the possible IFI keys" [m] (or (get-helper m "mbox") (get-helper m "account") (get-helper m "openid") (get-helper m "mbox_sha1sum"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; language map text ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef get-lmap-val :args (s/alt :unary (s/cat :lmap ::xs/language-map) :two (s/cat :lmap ::xs/language-map :language-tag ::xs/language-tag)) :ret (s/nilable ;; provided language tag may be incorrect ::xs/language-map-text)) (defn get-lmap-val "single arity: return the first label across all language tags within a language map - ordering of labels is dictated by `vals` call double arity: return the label found at `language-tag` within `lmap`" ([lmap] (-> lmap vals first)) ([lmap language-tag] (get-helper lmap language-tag))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an agent ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-name ;; :agent/name defined in xapi-schema :agent/name) (s/def ::parse-agent-ret (s/keys :req-un [::agent-name ::agent-ifi])) (s/fdef parse-agent :args (s/cat :agent ::xs/agent) :ret ::parse-agent-ret) (defn parse-agent "return `agent-name` and `agent-ifi` given `m`" [m] (let [agent-name (or (get-helper m "name") "Unamed Agent") agent-ifi (get-ifi m)] {:agent-name agent-name :agent-ifi agent-ifi})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a group ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::group-name :group/name) (s/def ::group-members (s/coll-of ::parse-agent-ret :kind vector? :into [] :gen-max 3)) (s/def ::parse-group-ret (s/keys :req-un [::group-name] :opt-un [::group-members ::group-ifi])) (s/fdef parse-group :args (s/cat :group ::xs/group) :ret ::parse-group-ret) (defn parse-group "return `group-name` and possibly `group-members` and/or `group-ifi` - `group-members` is a vector of maps containing `agent-name` and `agent-ifi`" [m] (let [group-name (or (get-helper m "name") "Unamed Group") group-members (when-let [members (get-helper m "member")] (mapv parse-agent members)) group-ifi (get-ifi m)] (cond-> {:group-name group-name} ;; did we have any members? (not-empty group-members) (assoc :group-members group-members) ;; did we have an ifi for the group? group-ifi (assoc :group-ifi group-ifi)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an activity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::activity-id ;; :activity/id defined in xapi-schema :activity/id) (s/def ::activity-name ;; because of call to `get-lmap-val` ::xs/language-map-text) (s/def ::parse-activity-ret (s/keys :req-un [::activity-id ::activity-name])) (s/fdef parse-activity :args (s/alt :unary (s/cat :activity ::xs/activity) :two (s/cat :activity ::xs/activity :language-tag ::xs/language-tag)) :ret ::parse-activity-ret) (defn parse-activity "return `activity-id` and `activity-name` from `m` - single arity assumes `language-tag` is not known - double arity requires `language-tag` as an argument" ([m] (let [{activity-id "id" {activity-name-lmap "name"} "definition"} m activity-name (or (get-lmap-val activity-name-lmap) "Unamed Activity")] {:activity-id activity-id :activity-name activity-name})) ([m language-tag] (let [{activity-id "id" {activity-name-lmap "name"} "definition"} m activity-name (or (get-lmap-val activity-name-lmap language-tag) "Unamed Activity")] {:activity-id activity-id :activity-name activity-name}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an actor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::parse-actor-ret (s/or :agent ::parse-agent-ret :group ::parse-group-ret)) (s/fdef parse-actor :args (s/cat :actor ::xs/actor) :ret ::parse-actor-ret) (defn parse-actor "parse the actor as an agent or group based on the objectType - defaults to parsing as agent" [m] (case (get-helper m "objectType") "Group" (parse-group m) "Agent" (parse-agent m) ;; objectType is optional for Agents but not Groups (parse-agent m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a verb ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::verb-id ;; :verb/id defined in xapi-schema :verb/id) (s/def ::verb-name ;; because of call to `get-lmap-val` ::xs/language-map-text) (s/def ::parse-verb-ret (s/keys :req-un [::verb-id ::verb-name])) (s/fdef parse-verb :args (s/alt :unary (s/cat :verb ::xs/verb) :two (s/cat :verb ::xs/verb :language-tag ::xs/language-tag)) :ret ::parse-verb-ret) (defn parse-verb "return `verb-id` and `verb-name` from `m` - single arity assumes `language-tag` is not known - double arity requires `language-tag` as an argument" ([m] {:verb-id (get-helper m "id") :verb-name (or (-> m (get-helper "display") get-lmap-val) "Unamed Verb")}) ([m language-tag] {:verb-id (get-helper m "id") :verb-name (or (-> m (get-helper "display") (get-lmap-val language-tag)) "Unamed Verb")})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from an object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::agent-as-object ;; temporary solution for generative testing ;; - can't use :statement/object for generative testing ;; -- not supporting substatements or statement refs ;; --- currently throwing when they are passed in, not sure how to write a spec for that ;; - can't use ::xs/agent because it doesn't properly enforce the objectType constraint (agent must have objectType) ;; -- simple approach (s/merge ::xs/agent (s/keys :req-un [:agent/objectType])) produces a bad generator ;; --- {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" :objectType "Agent"} ;; ---- not sure how to enforce all string keys from the outside ;; Solution = recreate ::xs/agent but will necessary objectType constraint applied (s/with-gen (s/and (s/conformer (partial xs/conform-ns-map "agent") xs/unform-ns-map) (s/keys :req [(or :agent/mbox :agent/mbox_sha1sum :agent/openid :agent/account) :agent/objectType] :opt [:agent/name]) (xs/restrict-keys :agent/mbox :agent/mbox_sha1sum :agent/openid :agent/account :agent/name :agent/objectType) xs/max-one-ifi) #(sgen/fmap xs/unform-ns-map (s/gen (s/or :ifi-mbox (s/keys :req [:agent/mbox :agent/objectType] :opt [:agent/name]) :ifi-mbox_sha1sum (s/keys :req [:agent/mbox_sha1sum :agent/objectType] :opt [:agent/name]) :ifi-openid (s/keys :req [:agent/openid :agent/objectType] :opt [:agent/name]) :ifi-account (s/keys :req [:agent/account :agent/objectType] :opt [:agent/name])))))) (s/def ::object (s/or :agent ::agent-as-object :group ::xs/group :activity ::xs/activity)) (s/def ::parse-object-ret (s/or :agent ::parse-agent-ret :group ::parse-group-ret :activity ::parse-activity-ret)) (s/fdef parse-object ;; limiting args to supported object types ;; - TODO: may be possible to spec intentional errors from (`throw` (`ex-info` ...)) but not sure how ;; -- some form of macro magic...I am but an apprentice :args (s/alt :unary (s/cat :supported-object-types ::object) :two (s/cat :only-activity ::xs/activity :language-tag ::xs/language-tag)) :ret ::parse-object-ret) (defn parse-object "based on the object's type - pass `m` to `parse-group` - pass `m` to `parse-agent` - pass `m` to `parse-activity` - StatementRef and SubStatement are NOT SUPPORTED! defaults to `parse-activity` - when the object is an Agent or Group, objectType must be specified -- https://github.com/adlnet/xAPI-Spec/blob/master/xAPI-Data.md#requirements-6 supports `language-tag` in 2-arity case but `m` must be an activity!" ([m] (case (get-helper m "objectType") "Group" (parse-group m) "Agent" (parse-agent m) "Activity" (parse-activity m) "StatementRef" (throw (ex-info "Statement References are not supported by `parse-object`" {:type ::operation-not-supported})) "SubStatement" (throw (ex-info "SubStatements are not supported by `parse-object`" {:type ::operation-not-supported})) (parse-activity m))) ([activity-m language-tag] ;; object = activity bc only case where `language-tag` is relevant (parse-activity activity-m language-tag))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic info from a statement specs ;; - warning...shield your eyes, it gets ugly ;; (╯°□°)╯︵ ┻━┻ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; return specs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :statement-simple.ret/id :statement/id) (s/def :statement-simple.ret/actor ::parse-actor-ret) (s/def :statement-simple.ret/verb ::parse-verb-ret) (s/def :statement-simple.ret/object ::parse-object-ret) (s/def :statement-simple.ret/timestamp number?) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; arg specs - single arity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: there is probably a better way to handle this ;; - this is bc of ;; -- multi arity parse fns - target `language-tag` support...what have I done ;; -- intentional throwing on some objectTypes w/in parse-object ;; -- generate maps with string keys (s/def :statement-simple.one.arg/id :statement/id) (s/def :statement-simple.one.arg/actor :statement/actor) (s/def :statement-simple.one.arg/verb :statement/verb) (s/def :statement-simple.one.arg/object ::object) (s/def :statement-simple.one.arg/timestamp :statement/timestamp) (s/def :statement-simple.one.arg/statement (xs/conform-ns "statement-simple.one.arg" (s/keys :req [:statement-simple.one.arg/id :statement-simple.one.arg/actor :statement-simple.one.arg/verb :statement-simple.one.arg/object :statement-simple.one.arg/timestamp]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; arg specs - multi arity ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: there is probably a better way to handle this ;; - this is bc of ;; -- multi arity parse fns - target `language-tag` support...what have I done ;; -- intentional throwing on some objectTypes w/in parse-object ;; -- generate maps with string keys (s/def :statement-simple.many.arg/id :statement/id) (s/def :statement-simple.many.arg/actor :statement/actor) (s/def :statement-simple.many.arg/verb :statement/verb) (s/def :statement-simple.many.arg/object ::xs/activity) (s/def :statement-simple.many.arg/timestamp :statement/timestamp) (s/def :statement-simple.many.arg/statement (xs/conform-ns "statement-simple.many.arg" (s/keys :req [:statement-simple.many.arg/id :statement-simple.many.arg/actor :statement-simple.many.arg/verb :statement-simple.many.arg/object :statement-simple.many.arg/timestamp]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we've made it to the fdef... щ(゚Д゚щ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/fdef parse-statement-simple :args (s/alt :only-statement (s/cat :simple-statement :statement-simple.one.arg/statement) :shared-language-tag (s/cat :simple-statement :statement-simple.many.arg/statement :shared-language-tag ::xs/language-tag) :targeted-language-tag (s/cat :simple-statement :statement-simple.many.arg/statement :language-tag-verb ::xs/language-tag :language-tag-activity ::xs/language-tag)) :ret (s/keys :req-un [:statement-simple.ret/id :statement-simple.ret/actor :statement-simple.ret/verb :statement-simple.ret/object :statement-simple.ret/timestamp])) (defn parse-statement-simple "parses a statement to return - `id` = statement id - `actor` = return of `parse-actor` - `verb` = return of `parse-verb` - `object` = return of `parse-object` - `timestamp` = unix representation of the ISO timestamp 1-arity case, language-tag is assumed to be unkown or irrelevant 2-arity case, `language-tag` used for both `object` and `verb` - `object` must be an activity 3-arity case `language-tag-verb` and `language-tag-activity` allow for differing language tags - its easy enough to do but unlikely to be needed." ([{:strs [id actor verb object timestamp] :as statement}] {:id id :actor (parse-actor actor) :verb (parse-verb verb) :object (parse-object object) :timestamp (.getTime (util/timestamp->inst timestamp))}) ([{:strs [id actor verb object timestamp] :as statement} language-tag] {:id id :actor (parse-actor actor) :verb (parse-verb verb language-tag) :object (parse-object object language-tag) :timestamp (.getTime (util/timestamp->inst timestamp))}) ([{:strs [id actor verb object timestamp] :as statement} language-tag-verb language-tag-activity] {:id id :actor (parse-actor actor) :verb (parse-verb verb language-tag-verb) :object (parse-object object language-tag-activity) :timestamp (.getTime (util/timestamp->inst timestamp))})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; my generators actually work ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment ;; can't use this because throw on statement refs and sub statements (first (sgen/sample (s/gen ::xs/statement))) ;; object can be agent, group or activity (let [agent-group-or-activity (first (sgen/sample (s/gen :statement-simple.one.arg/statement))) the-obj (get-helper agent-group-or-activity "object")] (and ;; valid statement (s/valid? ::xs/statement agent-group-or-activity) ;; valid agent, group or activity (s/valid? ::object the-obj) ;; not a sub-statement (false? (s/valid? ::xs/sub-statement the-obj)) ;; not a statement ref (false? (s/valid? ::xs/statement-ref the-obj)))) ;; object can only be activity (let [with-activity-obj (first (sgen/sample (s/gen :statement-simple.many.arg/statement))) the-obj (get-helper with-activity-obj "object")] (and ;; valid statement (s/valid? ::xs/statement with-activity-obj) ;; valid activity (s/valid? ::xs/activity the-obj) ;; not an agent (false? (s/valid? ::xs/agent the-obj)) ;; not a group (false? (s/valid? ::xs/group the-obj)) ;; not a substatement (false? (s/valid? ::xs/sub-statement the-obj)) ;; not a statement ref (false? (s/valid? ::xs/statement-ref the-obj))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; helper for return information after statement has been parsed ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; actor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :handle-actor.ret/agent-ordering (s/cat :name ::agent-name :ifi ::agent-ifi)) (s/def :handle-actor.ret/agent (s/with-gen (s/and vector? :handle-actor.ret/agent-ordering) #(sgen/fmap vec (s/gen :handle-actor.ret/agent-ordering)))) (s/def :handle-actor.ret/group-ordering (s/cat :name ::group-name :ifi ::group-ifi)) (s/def :handle-actor.ret/group (s/with-gen (s/and vector? :handle-actor.ret/group-ordering) #(sgen/fmap vec (s/gen :handle-actor.ret/group-ordering)))) (s/def :handle-actor.ret/members (s/coll-of :handle-actor.ret/agent :kind vector? :into [])) (s/fdef handle-actor :args (s/cat :parsed-actor (s/keys :req-un [(or (and ::agent-name ::agent-ifi) ::group-name)] :opt-un [::group-members ::group-ifi])) :ret (s/or :agent :handle-actor.ret/agent :group :handle-actor.ret/group :members :handle-actor.ret/members :dont-accept nil?)) (defn handle-actor [{:keys [agent-name agent-ifi group-name group-members group-ifi]}] (if group-name ;; dealing with a group (if-let [members (not-empty (mapv (fn [member] (let [{a-name :agent-name a-ifi :agent-ifi} member] [a-name a-ifi])) group-members))] ;; we had members, they are all we care about members ;; we didnt' have members, treat the group as an individual ;; - need their identity, only safe way to save their info in state (when group-ifi [group-name group-ifi])) ;; dealing with an agent, return what we know [agent-name agent-ifi])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def :handle-object.ret/agent :handle-actor.ret/agent) (s/def :handle-object.ret/identified-group :handle-actor.ret/group) (s/def :handle-object.ret/members (s/coll-of :handle-object.ret/agent :kind vector? :into [])) (s/def :handle-object.ret/group-with-members-ordering (s/cat :name ::group-name :members :handle-object.ret/members)) (s/def :handle-object.ret/group-with-members (s/with-gen (s/and vector? :handle-object.ret/group-with-members-ordering) #(sgen/fmap vec (s/gen :handle-object.ret/group-with-members-ordering)))) (s/def :handle-object.ret/activity-ordering (s/cat :name ::activity-name :ifi ::activity-id)) (s/def :handle-object.ret/activity (s/with-gen (s/and vector? :handle-object.ret/activity-ordering) #(sgen/fmap vec (s/gen :handle-object.ret/activity-ordering)))) (s/def :handle-object.ret/group-only-name (s/coll-of ::group-name :kind vector? :into [] :count 1)) (s/fdef handle-object :args (s/cat :parsed-object (s/keys :req-un [(or (and ::agent-name ::agent-ifi) (and ::activity-id ::activity-name) ::group-name)] :opt-un [::group-members ::group-ifi])) :ret (s/or :activity :handle-object.ret/activity :agent :handle-object.ret/agent :group :handle-object.ret/identified-group :with-members :handle-object.ret/group-with-members :only-name :handle-object.ret/group-only-name)) (defn handle-object [{:keys [agent-name agent-ifi group-name group-members group-ifi activity-id activity-name]}] (cond (and activity-id activity-name) [activity-name activity-id] (and agent-name agent-ifi) [agent-name agent-ifi] (and group-name group-ifi) [group-name group-ifi] :else (if-let [members (not-empty (mapv (fn [member] (let [{a-name :agent-name a-ifi :agent-ifi} member] [a-name a-ifi])) group-members))] [group-name members] [group-name])))
[ { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 40, "score": 0.9998801350593567, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 54, "score": 0.9999327063560486, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/promesa/impl/scheduler.cljc
laurio/promesa
0
;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz> ;; 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 promesa.impl.scheduler "Scheduler helpers implementation. This is private api and should not used directly." (:require [promesa.protocols :as pt]) #?(:clj (:import java.util.concurrent.ScheduledExecutorService java.util.concurrent.Executors java.util.concurrent.Future java.util.concurrent.TimeUnit java.util.concurrent.TimeoutException))) #?(:cljs (defn- scheduled-task [cur done?] (let [cancelled (volatile! false)] (reify cljs.core/IPending (-realized? [_] @done?) pt/ICancellable (-cancelled? [_] @cancelled) (-cancel [_] (when-not @cancelled (vreset! cancelled true) (js/clearTimeout cur)))))) :clj (defn- scheduled-task [^Future fut] (reify clojure.lang.IDeref (deref [_] (.get fut)) clojure.lang.IBlockingDeref (deref [_ ms default] (try (.get fut ms TimeUnit/MILLISECONDS) (catch TimeoutException e default))) clojure.lang.IPending (isRealized [_] (and (.isDone fut) (not (.isCancelled fut)))) pt/ICancellable (-cancelled? [_] (.isCancelled fut)) (-cancel [_] (when-not (.isCancelled fut) (.cancel fut true)))))) #?(:clj (extend-type ScheduledExecutorService pt/IScheduler (-schedule [this ms func] (let [fut (.schedule this ^Runnable func ^long ms TimeUnit/MILLISECONDS)] (scheduled-task fut))))) #?(:cljs (defn scheduler [] (reify pt/IScheduler (-schedule [_ ms func] (let [done? (volatile! false) task (fn [] (try (func) (finally (vreset! done? true)))) cur (js/setTimeout task ms)] (scheduled-task cur done?))))) :clj (defn- scheduler [] (Executors/newScheduledThreadPool 1))) (def ^:dynamic *scheduler* "A default lazy scheduler instance." (delay (scheduler))) (defn schedule [ms func] (pt/-schedule @*scheduler* ms func))
100218
;; Copyright (c) 2015-2016 <NAME> <<EMAIL>> ;; 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 promesa.impl.scheduler "Scheduler helpers implementation. This is private api and should not used directly." (:require [promesa.protocols :as pt]) #?(:clj (:import java.util.concurrent.ScheduledExecutorService java.util.concurrent.Executors java.util.concurrent.Future java.util.concurrent.TimeUnit java.util.concurrent.TimeoutException))) #?(:cljs (defn- scheduled-task [cur done?] (let [cancelled (volatile! false)] (reify cljs.core/IPending (-realized? [_] @done?) pt/ICancellable (-cancelled? [_] @cancelled) (-cancel [_] (when-not @cancelled (vreset! cancelled true) (js/clearTimeout cur)))))) :clj (defn- scheduled-task [^Future fut] (reify clojure.lang.IDeref (deref [_] (.get fut)) clojure.lang.IBlockingDeref (deref [_ ms default] (try (.get fut ms TimeUnit/MILLISECONDS) (catch TimeoutException e default))) clojure.lang.IPending (isRealized [_] (and (.isDone fut) (not (.isCancelled fut)))) pt/ICancellable (-cancelled? [_] (.isCancelled fut)) (-cancel [_] (when-not (.isCancelled fut) (.cancel fut true)))))) #?(:clj (extend-type ScheduledExecutorService pt/IScheduler (-schedule [this ms func] (let [fut (.schedule this ^Runnable func ^long ms TimeUnit/MILLISECONDS)] (scheduled-task fut))))) #?(:cljs (defn scheduler [] (reify pt/IScheduler (-schedule [_ ms func] (let [done? (volatile! false) task (fn [] (try (func) (finally (vreset! done? true)))) cur (js/setTimeout task ms)] (scheduled-task cur done?))))) :clj (defn- scheduler [] (Executors/newScheduledThreadPool 1))) (def ^:dynamic *scheduler* "A default lazy scheduler instance." (delay (scheduler))) (defn schedule [ms func] (pt/-schedule @*scheduler* ms func))
true
;; Copyright (c) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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 promesa.impl.scheduler "Scheduler helpers implementation. This is private api and should not used directly." (:require [promesa.protocols :as pt]) #?(:clj (:import java.util.concurrent.ScheduledExecutorService java.util.concurrent.Executors java.util.concurrent.Future java.util.concurrent.TimeUnit java.util.concurrent.TimeoutException))) #?(:cljs (defn- scheduled-task [cur done?] (let [cancelled (volatile! false)] (reify cljs.core/IPending (-realized? [_] @done?) pt/ICancellable (-cancelled? [_] @cancelled) (-cancel [_] (when-not @cancelled (vreset! cancelled true) (js/clearTimeout cur)))))) :clj (defn- scheduled-task [^Future fut] (reify clojure.lang.IDeref (deref [_] (.get fut)) clojure.lang.IBlockingDeref (deref [_ ms default] (try (.get fut ms TimeUnit/MILLISECONDS) (catch TimeoutException e default))) clojure.lang.IPending (isRealized [_] (and (.isDone fut) (not (.isCancelled fut)))) pt/ICancellable (-cancelled? [_] (.isCancelled fut)) (-cancel [_] (when-not (.isCancelled fut) (.cancel fut true)))))) #?(:clj (extend-type ScheduledExecutorService pt/IScheduler (-schedule [this ms func] (let [fut (.schedule this ^Runnable func ^long ms TimeUnit/MILLISECONDS)] (scheduled-task fut))))) #?(:cljs (defn scheduler [] (reify pt/IScheduler (-schedule [_ ms func] (let [done? (volatile! false) task (fn [] (try (func) (finally (vreset! done? true)))) cur (js/setTimeout task ms)] (scheduled-task cur done?))))) :clj (defn- scheduler [] (Executors/newScheduledThreadPool 1))) (def ^:dynamic *scheduler* "A default lazy scheduler instance." (delay (scheduler))) (defn schedule [ms func] (pt/-schedule @*scheduler* ms func))
[ { "context": "500 on server error\n\")\n\n(def valid-key-regex #\"[\\d\\w-_.,]+\")\n\n(defn add-response-header\n \"Add a head", "end": 1971, "score": 0.5763851404190063, "start": 1971, "tag": "KEY", "value": "" }, { "context": "0 on server error\n\")\n\n(def valid-key-regex #\"[\\d\\w-_.,]+\")\n\n(defn add-response-header\n \"Add a header", "end": 1973, "score": 0.6063236594200134, "start": 1973, "tag": "KEY", "value": "" } ]
src/poky/protocol/http.clj
drsnyder/poky
2
(ns poky.protocol.http (:require [poky.kv.core :as kv] [poky.util :as util] [clojure.java.io :as io] [clojure.tools.logging :refer [infof warnf]] [clj-logging-config.log4j :refer [set-logger!]] (compojure [core :refer :all] [route :as route] [handler :as handler]) [ring.adapter.jetty :as jetty] [ring.util.response :refer [response status not-found charset header]] (ring.middleware [format-response :as format-response ] [format-params :as format-params]) [cheshire.core :as json] [environ.core :refer [env]] [clj-time.coerce :as tc] [ring.middleware.stacktrace :as trace] [ring.middleware.statsd :as statsd] [ring.middleware.new-relic :as new-relic])) (def ^:private default-jetty-max-threads 25) (def ^:private default-log-level :info) (set-logger! :level (-> (env :log-level default-log-level) name clojure.string/lower-case keyword)) (def ^:private help-message " For key-value objects, the following are supported: - PUT /kv/:bucket/:key | creates object - POST /kv/:bucket/:key | creates object - DELETE /kv/:bucket/:key | deletes object - GET /kv/:bucket/:key | returns object For dealing with batches of objects, the following are supported: - POST /multi/:bucket | returns objects - PUT /multi/:bucket | creates objects - DELETE /multi/:bucket | deletes objects * Request body should be JSON encoded array of objects. * Request's Content-Type header must be JSON MIME type. * Responses are JSON encoded * Rejected gets/sets are not currently reported Other: - GET /status | returns 'ok' and status 200 Status codes to expect: - 200 on success - 404 when the object is not found - 412 when an update is rejected - 500 on server error ") (def valid-key-regex #"[\d\w-_.,]+") (defn add-response-header "Add a header field and value to the response object r." [r field value] (cond-> r value (header field value))) (defn generate-etag "Generate an etag given a string." [^:String s] (when s s)) (defn response-with-status [body status-code] (-> (response body) (status status-code))) (defn response-with-purge "Also send a PURGE request to varnish if VARNISH_LISTEN_ADDRESS and VARNISH_LISTEN_PORT are defined in the environment." [body status-code uri] (let [host (env :varnish-purge-host) port (env :varnish-purge-port)] (when (and uri host port) (infof "purging http://%s:%s/%s" host port uri) (future (util/varnish-purge host port uri)))) (response-with-status body status-code)) (defn- wrap-get [kvstore b k headers body] (let [if-match (util/strip-char (or (get headers "if-match") (get headers "x-if-match")) \")] (if-let [t (kv/get* kvstore b k)] (let [modified (util/Timestamp->http-date (get t :modified_at nil)) etag (generate-etag modified)] (if (or (not if-match) (= if-match etag) (= if-match "*")) (-> (response (get t k)) (add-response-header "Last-Modified" modified) (add-response-header "Vary" "If-Match") ; this ensures we can purge and match hits with and without If-Match (add-response-header "ETag" (util/quote-string etag \"))) (do (warnf "GET rejected for '%s/%s' If-Match (%s) != etag (%s)" b k if-match etag) (response-with-status "" 412)))) (if (and if-match (= if-match "*")) (response-with-status "" 412) (not-found ""))))) (defn- wrap-put [kvstore b k headers body uri] (let [if-unmodified-since (get headers "if-unmodified-since" nil) modified (util/http-date->Timestamp if-unmodified-since)] (if-not if-unmodified-since (warnf "If-Unmodified-Since not provided for %s/%s" b k)) (if (and if-unmodified-since (not modified)) ; if If-Unmodified-Since was specified in the header, but didn't parse, ; reject this as a bad request. (response-with-status "Error in If-Unmodified-Since format. Use RFC 1123 date format." 400) (condp = (kv/set* kvstore b k body {:modified_at modified}) :updated (response-with-purge "" 200 uri) :inserted (response-with-status "" 200) ; no need to purge on insert :rejected (do (warnf "PUT/POST rejected for '%s/%s'" b k) (response-with-status "" 412)) (response-with-status "Error, PUT/POST could not be completed." 500))))) (defn- wrap-delete [kvstore b k headers uri] (if (kv/delete* kvstore b k) (response-with-purge "" 200 uri) ; empty 200 (not-found ""))) ; empty 404 (defn- put-body "Returns body if non-empty otherwise body-params" [body body-params] (let [body (slurp body)] (if (clojure.string/blank? body) body-params body))) (defn- wrap-charset "Middleware for setting the charset of the response." [handler char-set] (fn [req] (charset (handler req) char-set))) (defn kv-routes [kvstore] (let [kv-api-routes (routes (GET ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [headers body] {:keys [b k]} :params} (wrap-get kvstore b k headers body)) (PUT ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body body-params headers uri] {:keys [b k]} :params} (wrap-put kvstore b k headers (put-body body body-params) uri)) (POST ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body body-params headers uri] {:keys [b k]} :params} (wrap-put kvstore b k headers (put-body body body-params) uri)) (DELETE ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body headers] {:keys [b k]} :params :as request} (wrap-delete kvstore b k headers (:uri request))) (GET "/help" [] (response help-message)) (route/not-found (str "Object not found.\n" help-message)))] kv-api-routes)) (defroutes fall-back-routes (ANY "*" [] (route/not-found help-message))) (defroutes status-routes (GET "/" [] (response "ok"))) ;; ======== MULTI (defn- multi-item "Creates and associates Timestamp objects for timestamp columns" [{:keys [modified_at created_at] :as item}] (cond-> item modified_at (assoc :modified_at (util/http-date->Timestamp modified_at)) created_at (assoc :created_at (util/http-date->Timestamp created_at)))) (defn- multi-get [kvstore b body] (kv/mget* kvstore b (map multi-item body))) (defn- multi-set [kvstore b body] (kv/mset* kvstore b (map multi-item body))) (defn- multi-handler "Handler logic for multi-* operations. Provides generic & consistent handling for JSON responses. Parses JSON request body and invokes, (multi-fn kvstore bucket json-body)" [kvstore multi-fn {:keys [params headers body] {:keys [b]} :params}] (if (not= (get headers "content-type") "application/json") (-> (response "Invalid Content-Type") (status 415)) (try (let [json-body (json/parse-stream (io/reader body) true) result (multi-fn kvstore b json-body)] (-> (response (json/generate-string result)) (header "Content-Type" "application/json"))) (catch com.fasterxml.jackson.core.JsonParseException e (-> (response "Failed to parse JSON body") (status 400))) (catch com.fasterxml.jackson.core.JsonGenerationException e (-> (response "Failed to build JSON response") (status 500)))))) (defn multi-routes [kvstore] (routes (POST ["/:b" :b valid-key-regex] request (multi-handler kvstore multi-get request)) (PUT ["/:b" :b valid-key-regex] request (multi-handler kvstore multi-set request)) (DELETE ["/:b" :b valid-key-regex] request (-> (response "Multi-delete not supported yet") (status 501))))) ;; ======== (defn api [kvstore] (let [api-routes (routes (context "/kv" [] (-> (kv-routes kvstore) (new-relic/wrap-transaction-name :tx-name-fn #(str "/kv/" (name (:request-method %)))))) (context "/multi" [] (-> (multi-routes kvstore) (new-relic/wrap-transaction-name :tx-name-fn #(str "/multi/" (name (:request-method %)))))) (context "/status" [] status-routes) (context "*" [] fall-back-routes))] (-> (handler/api api-routes) ; for curl default content type & possibly others. pass the data ; through as is (format-params/wrap-format-params :predicate (format-params/make-type-request-pred #"^application/x-www-form-urlencoded") :decoder identity :charset "utf-8") ; this is required to make sure we handle multi-byte content responses ; properly (wrap-charset "utf-8") trace/wrap-stacktrace (statsd/wrap-request-method-counter (str (env :statsd-key-base "poky") ".req_method")) (statsd/wrap-response-code-counter (str (env :statsd-key-base "poky") ".resp_status"))))) (defn start-server "Start the jetty http server. Environment: MAX_THREADS STATSD_HOST STATSD_KEY_BASE " [kvstore port] (when-let [statsd-host (env :statsd-host)] (let [[host port] (clojure.string/split statsd-host #":")] (when (and host port) (infof "Sending statsd metrics to %s" statsd-host) (statsd/setup! host (Integer/parseInt port))))) (let [max-threads (util/parse-int (env :max-threads default-jetty-max-threads)) max-pool-size (util/parse-int (env :max-pool-size -1))] (infof "Starting poky on port %d with %d jetty threads and connection pool of %d." port max-threads max-pool-size) (jetty/run-jetty (api kvstore) {:port port :max-threads max-threads :join? false})))
27174
(ns poky.protocol.http (:require [poky.kv.core :as kv] [poky.util :as util] [clojure.java.io :as io] [clojure.tools.logging :refer [infof warnf]] [clj-logging-config.log4j :refer [set-logger!]] (compojure [core :refer :all] [route :as route] [handler :as handler]) [ring.adapter.jetty :as jetty] [ring.util.response :refer [response status not-found charset header]] (ring.middleware [format-response :as format-response ] [format-params :as format-params]) [cheshire.core :as json] [environ.core :refer [env]] [clj-time.coerce :as tc] [ring.middleware.stacktrace :as trace] [ring.middleware.statsd :as statsd] [ring.middleware.new-relic :as new-relic])) (def ^:private default-jetty-max-threads 25) (def ^:private default-log-level :info) (set-logger! :level (-> (env :log-level default-log-level) name clojure.string/lower-case keyword)) (def ^:private help-message " For key-value objects, the following are supported: - PUT /kv/:bucket/:key | creates object - POST /kv/:bucket/:key | creates object - DELETE /kv/:bucket/:key | deletes object - GET /kv/:bucket/:key | returns object For dealing with batches of objects, the following are supported: - POST /multi/:bucket | returns objects - PUT /multi/:bucket | creates objects - DELETE /multi/:bucket | deletes objects * Request body should be JSON encoded array of objects. * Request's Content-Type header must be JSON MIME type. * Responses are JSON encoded * Rejected gets/sets are not currently reported Other: - GET /status | returns 'ok' and status 200 Status codes to expect: - 200 on success - 404 when the object is not found - 412 when an update is rejected - 500 on server error ") (def valid-key-regex #"[\d<KEY>\w<KEY>-_.,]+") (defn add-response-header "Add a header field and value to the response object r." [r field value] (cond-> r value (header field value))) (defn generate-etag "Generate an etag given a string." [^:String s] (when s s)) (defn response-with-status [body status-code] (-> (response body) (status status-code))) (defn response-with-purge "Also send a PURGE request to varnish if VARNISH_LISTEN_ADDRESS and VARNISH_LISTEN_PORT are defined in the environment." [body status-code uri] (let [host (env :varnish-purge-host) port (env :varnish-purge-port)] (when (and uri host port) (infof "purging http://%s:%s/%s" host port uri) (future (util/varnish-purge host port uri)))) (response-with-status body status-code)) (defn- wrap-get [kvstore b k headers body] (let [if-match (util/strip-char (or (get headers "if-match") (get headers "x-if-match")) \")] (if-let [t (kv/get* kvstore b k)] (let [modified (util/Timestamp->http-date (get t :modified_at nil)) etag (generate-etag modified)] (if (or (not if-match) (= if-match etag) (= if-match "*")) (-> (response (get t k)) (add-response-header "Last-Modified" modified) (add-response-header "Vary" "If-Match") ; this ensures we can purge and match hits with and without If-Match (add-response-header "ETag" (util/quote-string etag \"))) (do (warnf "GET rejected for '%s/%s' If-Match (%s) != etag (%s)" b k if-match etag) (response-with-status "" 412)))) (if (and if-match (= if-match "*")) (response-with-status "" 412) (not-found ""))))) (defn- wrap-put [kvstore b k headers body uri] (let [if-unmodified-since (get headers "if-unmodified-since" nil) modified (util/http-date->Timestamp if-unmodified-since)] (if-not if-unmodified-since (warnf "If-Unmodified-Since not provided for %s/%s" b k)) (if (and if-unmodified-since (not modified)) ; if If-Unmodified-Since was specified in the header, but didn't parse, ; reject this as a bad request. (response-with-status "Error in If-Unmodified-Since format. Use RFC 1123 date format." 400) (condp = (kv/set* kvstore b k body {:modified_at modified}) :updated (response-with-purge "" 200 uri) :inserted (response-with-status "" 200) ; no need to purge on insert :rejected (do (warnf "PUT/POST rejected for '%s/%s'" b k) (response-with-status "" 412)) (response-with-status "Error, PUT/POST could not be completed." 500))))) (defn- wrap-delete [kvstore b k headers uri] (if (kv/delete* kvstore b k) (response-with-purge "" 200 uri) ; empty 200 (not-found ""))) ; empty 404 (defn- put-body "Returns body if non-empty otherwise body-params" [body body-params] (let [body (slurp body)] (if (clojure.string/blank? body) body-params body))) (defn- wrap-charset "Middleware for setting the charset of the response." [handler char-set] (fn [req] (charset (handler req) char-set))) (defn kv-routes [kvstore] (let [kv-api-routes (routes (GET ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [headers body] {:keys [b k]} :params} (wrap-get kvstore b k headers body)) (PUT ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body body-params headers uri] {:keys [b k]} :params} (wrap-put kvstore b k headers (put-body body body-params) uri)) (POST ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body body-params headers uri] {:keys [b k]} :params} (wrap-put kvstore b k headers (put-body body body-params) uri)) (DELETE ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body headers] {:keys [b k]} :params :as request} (wrap-delete kvstore b k headers (:uri request))) (GET "/help" [] (response help-message)) (route/not-found (str "Object not found.\n" help-message)))] kv-api-routes)) (defroutes fall-back-routes (ANY "*" [] (route/not-found help-message))) (defroutes status-routes (GET "/" [] (response "ok"))) ;; ======== MULTI (defn- multi-item "Creates and associates Timestamp objects for timestamp columns" [{:keys [modified_at created_at] :as item}] (cond-> item modified_at (assoc :modified_at (util/http-date->Timestamp modified_at)) created_at (assoc :created_at (util/http-date->Timestamp created_at)))) (defn- multi-get [kvstore b body] (kv/mget* kvstore b (map multi-item body))) (defn- multi-set [kvstore b body] (kv/mset* kvstore b (map multi-item body))) (defn- multi-handler "Handler logic for multi-* operations. Provides generic & consistent handling for JSON responses. Parses JSON request body and invokes, (multi-fn kvstore bucket json-body)" [kvstore multi-fn {:keys [params headers body] {:keys [b]} :params}] (if (not= (get headers "content-type") "application/json") (-> (response "Invalid Content-Type") (status 415)) (try (let [json-body (json/parse-stream (io/reader body) true) result (multi-fn kvstore b json-body)] (-> (response (json/generate-string result)) (header "Content-Type" "application/json"))) (catch com.fasterxml.jackson.core.JsonParseException e (-> (response "Failed to parse JSON body") (status 400))) (catch com.fasterxml.jackson.core.JsonGenerationException e (-> (response "Failed to build JSON response") (status 500)))))) (defn multi-routes [kvstore] (routes (POST ["/:b" :b valid-key-regex] request (multi-handler kvstore multi-get request)) (PUT ["/:b" :b valid-key-regex] request (multi-handler kvstore multi-set request)) (DELETE ["/:b" :b valid-key-regex] request (-> (response "Multi-delete not supported yet") (status 501))))) ;; ======== (defn api [kvstore] (let [api-routes (routes (context "/kv" [] (-> (kv-routes kvstore) (new-relic/wrap-transaction-name :tx-name-fn #(str "/kv/" (name (:request-method %)))))) (context "/multi" [] (-> (multi-routes kvstore) (new-relic/wrap-transaction-name :tx-name-fn #(str "/multi/" (name (:request-method %)))))) (context "/status" [] status-routes) (context "*" [] fall-back-routes))] (-> (handler/api api-routes) ; for curl default content type & possibly others. pass the data ; through as is (format-params/wrap-format-params :predicate (format-params/make-type-request-pred #"^application/x-www-form-urlencoded") :decoder identity :charset "utf-8") ; this is required to make sure we handle multi-byte content responses ; properly (wrap-charset "utf-8") trace/wrap-stacktrace (statsd/wrap-request-method-counter (str (env :statsd-key-base "poky") ".req_method")) (statsd/wrap-response-code-counter (str (env :statsd-key-base "poky") ".resp_status"))))) (defn start-server "Start the jetty http server. Environment: MAX_THREADS STATSD_HOST STATSD_KEY_BASE " [kvstore port] (when-let [statsd-host (env :statsd-host)] (let [[host port] (clojure.string/split statsd-host #":")] (when (and host port) (infof "Sending statsd metrics to %s" statsd-host) (statsd/setup! host (Integer/parseInt port))))) (let [max-threads (util/parse-int (env :max-threads default-jetty-max-threads)) max-pool-size (util/parse-int (env :max-pool-size -1))] (infof "Starting poky on port %d with %d jetty threads and connection pool of %d." port max-threads max-pool-size) (jetty/run-jetty (api kvstore) {:port port :max-threads max-threads :join? false})))
true
(ns poky.protocol.http (:require [poky.kv.core :as kv] [poky.util :as util] [clojure.java.io :as io] [clojure.tools.logging :refer [infof warnf]] [clj-logging-config.log4j :refer [set-logger!]] (compojure [core :refer :all] [route :as route] [handler :as handler]) [ring.adapter.jetty :as jetty] [ring.util.response :refer [response status not-found charset header]] (ring.middleware [format-response :as format-response ] [format-params :as format-params]) [cheshire.core :as json] [environ.core :refer [env]] [clj-time.coerce :as tc] [ring.middleware.stacktrace :as trace] [ring.middleware.statsd :as statsd] [ring.middleware.new-relic :as new-relic])) (def ^:private default-jetty-max-threads 25) (def ^:private default-log-level :info) (set-logger! :level (-> (env :log-level default-log-level) name clojure.string/lower-case keyword)) (def ^:private help-message " For key-value objects, the following are supported: - PUT /kv/:bucket/:key | creates object - POST /kv/:bucket/:key | creates object - DELETE /kv/:bucket/:key | deletes object - GET /kv/:bucket/:key | returns object For dealing with batches of objects, the following are supported: - POST /multi/:bucket | returns objects - PUT /multi/:bucket | creates objects - DELETE /multi/:bucket | deletes objects * Request body should be JSON encoded array of objects. * Request's Content-Type header must be JSON MIME type. * Responses are JSON encoded * Rejected gets/sets are not currently reported Other: - GET /status | returns 'ok' and status 200 Status codes to expect: - 200 on success - 404 when the object is not found - 412 when an update is rejected - 500 on server error ") (def valid-key-regex #"[\dPI:KEY:<KEY>END_PI\wPI:KEY:<KEY>END_PI-_.,]+") (defn add-response-header "Add a header field and value to the response object r." [r field value] (cond-> r value (header field value))) (defn generate-etag "Generate an etag given a string." [^:String s] (when s s)) (defn response-with-status [body status-code] (-> (response body) (status status-code))) (defn response-with-purge "Also send a PURGE request to varnish if VARNISH_LISTEN_ADDRESS and VARNISH_LISTEN_PORT are defined in the environment." [body status-code uri] (let [host (env :varnish-purge-host) port (env :varnish-purge-port)] (when (and uri host port) (infof "purging http://%s:%s/%s" host port uri) (future (util/varnish-purge host port uri)))) (response-with-status body status-code)) (defn- wrap-get [kvstore b k headers body] (let [if-match (util/strip-char (or (get headers "if-match") (get headers "x-if-match")) \")] (if-let [t (kv/get* kvstore b k)] (let [modified (util/Timestamp->http-date (get t :modified_at nil)) etag (generate-etag modified)] (if (or (not if-match) (= if-match etag) (= if-match "*")) (-> (response (get t k)) (add-response-header "Last-Modified" modified) (add-response-header "Vary" "If-Match") ; this ensures we can purge and match hits with and without If-Match (add-response-header "ETag" (util/quote-string etag \"))) (do (warnf "GET rejected for '%s/%s' If-Match (%s) != etag (%s)" b k if-match etag) (response-with-status "" 412)))) (if (and if-match (= if-match "*")) (response-with-status "" 412) (not-found ""))))) (defn- wrap-put [kvstore b k headers body uri] (let [if-unmodified-since (get headers "if-unmodified-since" nil) modified (util/http-date->Timestamp if-unmodified-since)] (if-not if-unmodified-since (warnf "If-Unmodified-Since not provided for %s/%s" b k)) (if (and if-unmodified-since (not modified)) ; if If-Unmodified-Since was specified in the header, but didn't parse, ; reject this as a bad request. (response-with-status "Error in If-Unmodified-Since format. Use RFC 1123 date format." 400) (condp = (kv/set* kvstore b k body {:modified_at modified}) :updated (response-with-purge "" 200 uri) :inserted (response-with-status "" 200) ; no need to purge on insert :rejected (do (warnf "PUT/POST rejected for '%s/%s'" b k) (response-with-status "" 412)) (response-with-status "Error, PUT/POST could not be completed." 500))))) (defn- wrap-delete [kvstore b k headers uri] (if (kv/delete* kvstore b k) (response-with-purge "" 200 uri) ; empty 200 (not-found ""))) ; empty 404 (defn- put-body "Returns body if non-empty otherwise body-params" [body body-params] (let [body (slurp body)] (if (clojure.string/blank? body) body-params body))) (defn- wrap-charset "Middleware for setting the charset of the response." [handler char-set] (fn [req] (charset (handler req) char-set))) (defn kv-routes [kvstore] (let [kv-api-routes (routes (GET ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [headers body] {:keys [b k]} :params} (wrap-get kvstore b k headers body)) (PUT ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body body-params headers uri] {:keys [b k]} :params} (wrap-put kvstore b k headers (put-body body body-params) uri)) (POST ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body body-params headers uri] {:keys [b k]} :params} (wrap-put kvstore b k headers (put-body body body-params) uri)) (DELETE ["/:b/:k" :b valid-key-regex :k valid-key-regex] {:keys [body headers] {:keys [b k]} :params :as request} (wrap-delete kvstore b k headers (:uri request))) (GET "/help" [] (response help-message)) (route/not-found (str "Object not found.\n" help-message)))] kv-api-routes)) (defroutes fall-back-routes (ANY "*" [] (route/not-found help-message))) (defroutes status-routes (GET "/" [] (response "ok"))) ;; ======== MULTI (defn- multi-item "Creates and associates Timestamp objects for timestamp columns" [{:keys [modified_at created_at] :as item}] (cond-> item modified_at (assoc :modified_at (util/http-date->Timestamp modified_at)) created_at (assoc :created_at (util/http-date->Timestamp created_at)))) (defn- multi-get [kvstore b body] (kv/mget* kvstore b (map multi-item body))) (defn- multi-set [kvstore b body] (kv/mset* kvstore b (map multi-item body))) (defn- multi-handler "Handler logic for multi-* operations. Provides generic & consistent handling for JSON responses. Parses JSON request body and invokes, (multi-fn kvstore bucket json-body)" [kvstore multi-fn {:keys [params headers body] {:keys [b]} :params}] (if (not= (get headers "content-type") "application/json") (-> (response "Invalid Content-Type") (status 415)) (try (let [json-body (json/parse-stream (io/reader body) true) result (multi-fn kvstore b json-body)] (-> (response (json/generate-string result)) (header "Content-Type" "application/json"))) (catch com.fasterxml.jackson.core.JsonParseException e (-> (response "Failed to parse JSON body") (status 400))) (catch com.fasterxml.jackson.core.JsonGenerationException e (-> (response "Failed to build JSON response") (status 500)))))) (defn multi-routes [kvstore] (routes (POST ["/:b" :b valid-key-regex] request (multi-handler kvstore multi-get request)) (PUT ["/:b" :b valid-key-regex] request (multi-handler kvstore multi-set request)) (DELETE ["/:b" :b valid-key-regex] request (-> (response "Multi-delete not supported yet") (status 501))))) ;; ======== (defn api [kvstore] (let [api-routes (routes (context "/kv" [] (-> (kv-routes kvstore) (new-relic/wrap-transaction-name :tx-name-fn #(str "/kv/" (name (:request-method %)))))) (context "/multi" [] (-> (multi-routes kvstore) (new-relic/wrap-transaction-name :tx-name-fn #(str "/multi/" (name (:request-method %)))))) (context "/status" [] status-routes) (context "*" [] fall-back-routes))] (-> (handler/api api-routes) ; for curl default content type & possibly others. pass the data ; through as is (format-params/wrap-format-params :predicate (format-params/make-type-request-pred #"^application/x-www-form-urlencoded") :decoder identity :charset "utf-8") ; this is required to make sure we handle multi-byte content responses ; properly (wrap-charset "utf-8") trace/wrap-stacktrace (statsd/wrap-request-method-counter (str (env :statsd-key-base "poky") ".req_method")) (statsd/wrap-response-code-counter (str (env :statsd-key-base "poky") ".resp_status"))))) (defn start-server "Start the jetty http server. Environment: MAX_THREADS STATSD_HOST STATSD_KEY_BASE " [kvstore port] (when-let [statsd-host (env :statsd-host)] (let [[host port] (clojure.string/split statsd-host #":")] (when (and host port) (infof "Sending statsd metrics to %s" statsd-host) (statsd/setup! host (Integer/parseInt port))))) (let [max-threads (util/parse-int (env :max-threads default-jetty-max-threads)) max-pool-size (util/parse-int (env :max-pool-size -1))] (infof "Starting poky on port %d with %d jetty threads and connection pool of %d." port max-threads max-pool-size) (jetty/run-jetty (api kvstore) {:port port :max-threads max-threads :join? false})))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\r\n; The use and distributi", "end": 30, "score": 0.9998674392700195, "start": 19, "tag": "NAME", "value": "Rich Hickey" }, { "context": " other, from this software.\r\n\r\n(ns \r\n ^{:author \"Stuart Halloway\",\r\n :doc \"Non-core data functions.\"}\r\n clojur", "end": 507, "score": 0.9998847842216492, "start": 492, "tag": "NAME", "value": "Stuart Halloway" } ]
Source/clojure/data.clj
pjago/Arcadia
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 ^{:author "Stuart Halloway", :doc "Non-core data functions."} clojure.data (:require [clojure.set :as set])) (declare diff) (defn- atom-diff "Internal helper for diff." [a b] (if (= a b) [nil nil a] [a b nil])) ;; for big things a sparse vector class would be better (defn- vectorize "Convert an associative-by-numeric-index collection into an equivalent vector, with nil for any missing keys" [m] (when (seq m) (reduce (fn [result [k v]] (assoc result k v)) (vec (repeat (apply max (keys m)) nil)) m))) (defn- diff-associative-key "Diff associative things a and b, comparing only the key k." [a b k] (let [va (get a k) vb (get b k) [a* b* ab] (diff va vb) in-a (contains? a k) in-b (contains? b k) same (and in-a in-b (or (not (nil? ab)) (and (nil? va) (nil? vb))))] [(when (and in-a (or (not (nil? a*)) (not same))) {k a*}) (when (and in-b (or (not (nil? b*)) (not same))) {k b*}) (when same {k ab}) ])) (defn- diff-associative "Diff associative things a and b, comparing only keys in ks." [a b ks] (reduce (fn [diff1 diff2] (doall (map merge diff1 diff2))) [nil nil nil] (map (partial diff-associative-key a b) ks))) (defn- diff-sequential [a b] (vec (map vectorize (diff-associative (if (vector? a) a (vec a)) (if (vector? b) b (vec b)) (range (max (count a) (count b))))))) (defprotocol ^{:added "1.3"} EqualityPartition "Implementation detail. Subject to change." (^{:added "1.3"} equality-partition [x] "Implementation detail. Subject to change.")) (defprotocol ^{:added "1.3"} Diff "Implementation detail. Subject to change." (^{:added "1.3"} diff-similar [a b] "Implementation detail. Subject to change.")) (extend nil Diff {:diff-similar atom-diff}) (extend Object Diff {:diff-similar (fn [a b] ((if (.. a GetType IsArray) diff-sequential atom-diff) a b))} ;;; (.. a getClass isArray) EqualityPartition {:equality-partition (fn [x] (if (.. x GetType IsArray) :sequential :atom))}) ;;; (.. x getClass isArray) (extend-protocol EqualityPartition nil (equality-partition [x] :atom) clojure.lang.IPersistentSet ;;; java.util.Set (equality-partition [x] :set) System.Collections.IList ;;; java.util.List (equality-partition [x] :sequential) System.Collections.IDictionary ;;; java.util.Map (equality-partition [x] :map)) (defn- as-set-value [s] (if (set? s) s (into #{} s))) (extend-protocol Diff clojure.lang.IPersistentSet ;;; java.util.Set -- we should be working with ISet here, but that 4.0 only. -- also can't handle generics in extend-protocol (diff-similar [a b] (let [aval (as-set-value a) bval (as-set-value b)] [(not-empty (set/difference aval bval)) (not-empty (set/difference bval aval)) (not-empty (set/intersection aval bval))])) System.Collections.IList ;;; java.util.List (diff-similar [a b] (diff-sequential a b)) System.Collections.IDictionary ;;; java.util.Map (diff-similar [a b] (diff-associative a b (set/union (keys a) (keys b))))) (defn diff "Recursively compares a and b, returning a tuple of [things-only-in-a things-only-in-b things-in-both]. Comparison rules: * For equal a and b, return [nil nil a]. * Maps are subdiffed where keys match and values differ. * Sets are never subdiffed. * All sequential things are treated as associative collections by their indexes, with results returned as vectors. * Everything else (including strings!) is treated as an atom and compared for equality." {:added "1.3"} [a b] (if (= a b) [nil nil a] (if (= (equality-partition a) (equality-partition b)) (diff-similar a b) (atom-diff a b))))
56783
; 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 ^{:author "<NAME>", :doc "Non-core data functions."} clojure.data (:require [clojure.set :as set])) (declare diff) (defn- atom-diff "Internal helper for diff." [a b] (if (= a b) [nil nil a] [a b nil])) ;; for big things a sparse vector class would be better (defn- vectorize "Convert an associative-by-numeric-index collection into an equivalent vector, with nil for any missing keys" [m] (when (seq m) (reduce (fn [result [k v]] (assoc result k v)) (vec (repeat (apply max (keys m)) nil)) m))) (defn- diff-associative-key "Diff associative things a and b, comparing only the key k." [a b k] (let [va (get a k) vb (get b k) [a* b* ab] (diff va vb) in-a (contains? a k) in-b (contains? b k) same (and in-a in-b (or (not (nil? ab)) (and (nil? va) (nil? vb))))] [(when (and in-a (or (not (nil? a*)) (not same))) {k a*}) (when (and in-b (or (not (nil? b*)) (not same))) {k b*}) (when same {k ab}) ])) (defn- diff-associative "Diff associative things a and b, comparing only keys in ks." [a b ks] (reduce (fn [diff1 diff2] (doall (map merge diff1 diff2))) [nil nil nil] (map (partial diff-associative-key a b) ks))) (defn- diff-sequential [a b] (vec (map vectorize (diff-associative (if (vector? a) a (vec a)) (if (vector? b) b (vec b)) (range (max (count a) (count b))))))) (defprotocol ^{:added "1.3"} EqualityPartition "Implementation detail. Subject to change." (^{:added "1.3"} equality-partition [x] "Implementation detail. Subject to change.")) (defprotocol ^{:added "1.3"} Diff "Implementation detail. Subject to change." (^{:added "1.3"} diff-similar [a b] "Implementation detail. Subject to change.")) (extend nil Diff {:diff-similar atom-diff}) (extend Object Diff {:diff-similar (fn [a b] ((if (.. a GetType IsArray) diff-sequential atom-diff) a b))} ;;; (.. a getClass isArray) EqualityPartition {:equality-partition (fn [x] (if (.. x GetType IsArray) :sequential :atom))}) ;;; (.. x getClass isArray) (extend-protocol EqualityPartition nil (equality-partition [x] :atom) clojure.lang.IPersistentSet ;;; java.util.Set (equality-partition [x] :set) System.Collections.IList ;;; java.util.List (equality-partition [x] :sequential) System.Collections.IDictionary ;;; java.util.Map (equality-partition [x] :map)) (defn- as-set-value [s] (if (set? s) s (into #{} s))) (extend-protocol Diff clojure.lang.IPersistentSet ;;; java.util.Set -- we should be working with ISet here, but that 4.0 only. -- also can't handle generics in extend-protocol (diff-similar [a b] (let [aval (as-set-value a) bval (as-set-value b)] [(not-empty (set/difference aval bval)) (not-empty (set/difference bval aval)) (not-empty (set/intersection aval bval))])) System.Collections.IList ;;; java.util.List (diff-similar [a b] (diff-sequential a b)) System.Collections.IDictionary ;;; java.util.Map (diff-similar [a b] (diff-associative a b (set/union (keys a) (keys b))))) (defn diff "Recursively compares a and b, returning a tuple of [things-only-in-a things-only-in-b things-in-both]. Comparison rules: * For equal a and b, return [nil nil a]. * Maps are subdiffed where keys match and values differ. * Sets are never subdiffed. * All sequential things are treated as associative collections by their indexes, with results returned as vectors. * Everything else (including strings!) is treated as an atom and compared for equality." {:added "1.3"} [a b] (if (= a b) [nil nil a] (if (= (equality-partition a) (equality-partition b)) (diff-similar a b) (atom-diff a b))))
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 ^{:author "PI:NAME:<NAME>END_PI", :doc "Non-core data functions."} clojure.data (:require [clojure.set :as set])) (declare diff) (defn- atom-diff "Internal helper for diff." [a b] (if (= a b) [nil nil a] [a b nil])) ;; for big things a sparse vector class would be better (defn- vectorize "Convert an associative-by-numeric-index collection into an equivalent vector, with nil for any missing keys" [m] (when (seq m) (reduce (fn [result [k v]] (assoc result k v)) (vec (repeat (apply max (keys m)) nil)) m))) (defn- diff-associative-key "Diff associative things a and b, comparing only the key k." [a b k] (let [va (get a k) vb (get b k) [a* b* ab] (diff va vb) in-a (contains? a k) in-b (contains? b k) same (and in-a in-b (or (not (nil? ab)) (and (nil? va) (nil? vb))))] [(when (and in-a (or (not (nil? a*)) (not same))) {k a*}) (when (and in-b (or (not (nil? b*)) (not same))) {k b*}) (when same {k ab}) ])) (defn- diff-associative "Diff associative things a and b, comparing only keys in ks." [a b ks] (reduce (fn [diff1 diff2] (doall (map merge diff1 diff2))) [nil nil nil] (map (partial diff-associative-key a b) ks))) (defn- diff-sequential [a b] (vec (map vectorize (diff-associative (if (vector? a) a (vec a)) (if (vector? b) b (vec b)) (range (max (count a) (count b))))))) (defprotocol ^{:added "1.3"} EqualityPartition "Implementation detail. Subject to change." (^{:added "1.3"} equality-partition [x] "Implementation detail. Subject to change.")) (defprotocol ^{:added "1.3"} Diff "Implementation detail. Subject to change." (^{:added "1.3"} diff-similar [a b] "Implementation detail. Subject to change.")) (extend nil Diff {:diff-similar atom-diff}) (extend Object Diff {:diff-similar (fn [a b] ((if (.. a GetType IsArray) diff-sequential atom-diff) a b))} ;;; (.. a getClass isArray) EqualityPartition {:equality-partition (fn [x] (if (.. x GetType IsArray) :sequential :atom))}) ;;; (.. x getClass isArray) (extend-protocol EqualityPartition nil (equality-partition [x] :atom) clojure.lang.IPersistentSet ;;; java.util.Set (equality-partition [x] :set) System.Collections.IList ;;; java.util.List (equality-partition [x] :sequential) System.Collections.IDictionary ;;; java.util.Map (equality-partition [x] :map)) (defn- as-set-value [s] (if (set? s) s (into #{} s))) (extend-protocol Diff clojure.lang.IPersistentSet ;;; java.util.Set -- we should be working with ISet here, but that 4.0 only. -- also can't handle generics in extend-protocol (diff-similar [a b] (let [aval (as-set-value a) bval (as-set-value b)] [(not-empty (set/difference aval bval)) (not-empty (set/difference bval aval)) (not-empty (set/intersection aval bval))])) System.Collections.IList ;;; java.util.List (diff-similar [a b] (diff-sequential a b)) System.Collections.IDictionary ;;; java.util.Map (diff-similar [a b] (diff-associative a b (set/union (keys a) (keys b))))) (defn diff "Recursively compares a and b, returning a tuple of [things-only-in-a things-only-in-b things-in-both]. Comparison rules: * For equal a and b, return [nil nil a]. * Maps are subdiffed where keys match and values differ. * Sets are never subdiffed. * All sequential things are treated as associative collections by their indexes, with results returned as vectors. * Everything else (including strings!) is treated as an atom and compared for equality." {:added "1.3"} [a b] (if (= a b) [nil nil a] (if (= (equality-partition a) (equality-partition b)) (diff-similar a b) (atom-diff a b))))