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": "without needing to duplicate them\"\n :author \"Sam Aaron\"}\n overtone.libs.asset\n (:use [clojure.java.io ", "end": 381, "score": 0.9998889565467834, "start": 372, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/libs/asset.clj
rosejn/overtone
4
(ns ^{:doc "A simple local file system-cached asset management system. Assets are specified as URLs which are then cached by being copied to a centralised place in the file system if not already there. This allows assets to be shared by multiple projects on the same system without needing to duplicate them" :author "Sam Aaron"} overtone.libs.asset (:use [clojure.java.io :only [file]] [clojure.string :only [split]] [overtone.helpers file zip string] [overtone.config.store :only [OVERTONE-DIRS]])) (def ^{:dynamic true} *cache-root* (:assets OVERTONE-DIRS)) (defn- download-asset-file "Download file at url to local filesystem at tmp-file verbosely." [url tmp-file] (println "Asset not cached - starting download...") (binding [*verbose-overtone-file-helpers* 2] (download-file url tmp-file 20000 100 5000))) (defn- safe-url "Replace all non a-z A-Z 0-9 - chars in stringified version of url with _" [url] (let [url (str url) safe (.replaceAll url "http://" "") safe (.replaceAll safe "https://" "") safe (.replaceAll safe "/" "-") safe (.replaceAll safe "[^a-zA-Z0-9-.]" "")] safe)) (defn- url-hash "Return a hash for stringified version of url" [url] (let [url (str url)] (str (hash url)))) (defn- cache-dir "Returns the name of a directory to cache an asset with the given url." [url] (let [safe (safe-url url) hsh (url-hash url)] (mk-path *cache-root* (str safe "--" hsh)))) (defn- mk-cache-dir! "Create a new cache dir for the specified url" [url] (let [dir (cache-dir url)] (mkdir! dir))) (defn- fetch-cached-path "Returns the path to the cached asset if present, otherwise nil." [url name] (let [path (mk-path (cache-dir url) name)] (when (path-exists? path) path))) (defn- download-and-cache-asset "Downloads the file pointed to by url and caches it on the local file system" [url name] (let [tmp-dir (str (mk-tmp-dir!)) tmp-file (mk-path tmp-dir name) dest-dir (cache-dir url) dest-file (mk-path dest-dir name)] (try (mk-cache-dir! url) (download-asset-file url tmp-file) (mv! tmp-file dest-file ) (rm-rf! tmp-dir) dest-file (catch Exception e (rm-rf! tmp-dir) (rm-rf! dest-dir) (throw e))))) (defn asset-seq "Returns a seq of previously cached asset names for a specific url" [url] (let [dir (cache-dir url) dir (file dir)] (ls-names dir))) (defn asset-path "Given a url will return a path to a copy of the asset on the local file system. Will download and persist the asset if necessary." ([url] (asset-path url (last (split url #"/")))) ([url name] (if-let [path (fetch-cached-path url name)] path (download-and-cache-asset url name)))) (defn- download-unzip-and-cache-bundled-asset "Downloads zip file referenced by url, unzips it safely, and then moves all contents to cache dir." [url] (let [tmp-dir (str (mk-tmp-dir!)) tmp-file (mk-path tmp-dir "bundled-asset") tmp-extract-dir (mk-path tmp-dir "extraction") dest-dir (cache-dir url)] (try (mkdir! tmp-extract-dir) (download-asset-file url tmp-file) (unzip tmp-file tmp-extract-dir) (mk-cache-dir! url) (let [asset-names (ls-names tmp-extract-dir)] (dorun (map #(mv! (mk-path tmp-extract-dir %) (mk-path dest-dir %)) asset-names))) (rm-rf! tmp-dir) tmp-extract-dir (catch Exception e (rm-rf! tmp-dir) (rm-rf! dest-dir) (throw e))))) (defn asset-bundle-path "Given a url to a remote zipfile and either a / separated internal path or seq of strings will return a path to a copy of the internal extracted asset on the local file system. Will download, extract and persist all the assets of the zipfile if necessary. usage: (asset-bundle-path \"http://foo.com/a.zip\" \"internal/asset.wav\") (asset-bundle-path \"http://foo.com/a.zip\" [\"internal\" \"asset.wav\"])" [url name] (let [name (if (string? name) (split-on-char name "/") name) internal-path (apply mk-path name)] (if-let [path (fetch-cached-path url internal-path)] path (do (when (dir-empty? (cache-dir url)) (download-unzip-and-cache-bundled-asset url)) (fetch-cached-path url internal-path))))) (defn asset-bundle-dir "Returns the cached directory of of the bundled asset. Will download, extract and persist all the assets of the zipfile referenced by url if necessary" [url] (asset-bundle-path url "") (cache-dir url))
56300
(ns ^{:doc "A simple local file system-cached asset management system. Assets are specified as URLs which are then cached by being copied to a centralised place in the file system if not already there. This allows assets to be shared by multiple projects on the same system without needing to duplicate them" :author "<NAME>"} overtone.libs.asset (:use [clojure.java.io :only [file]] [clojure.string :only [split]] [overtone.helpers file zip string] [overtone.config.store :only [OVERTONE-DIRS]])) (def ^{:dynamic true} *cache-root* (:assets OVERTONE-DIRS)) (defn- download-asset-file "Download file at url to local filesystem at tmp-file verbosely." [url tmp-file] (println "Asset not cached - starting download...") (binding [*verbose-overtone-file-helpers* 2] (download-file url tmp-file 20000 100 5000))) (defn- safe-url "Replace all non a-z A-Z 0-9 - chars in stringified version of url with _" [url] (let [url (str url) safe (.replaceAll url "http://" "") safe (.replaceAll safe "https://" "") safe (.replaceAll safe "/" "-") safe (.replaceAll safe "[^a-zA-Z0-9-.]" "")] safe)) (defn- url-hash "Return a hash for stringified version of url" [url] (let [url (str url)] (str (hash url)))) (defn- cache-dir "Returns the name of a directory to cache an asset with the given url." [url] (let [safe (safe-url url) hsh (url-hash url)] (mk-path *cache-root* (str safe "--" hsh)))) (defn- mk-cache-dir! "Create a new cache dir for the specified url" [url] (let [dir (cache-dir url)] (mkdir! dir))) (defn- fetch-cached-path "Returns the path to the cached asset if present, otherwise nil." [url name] (let [path (mk-path (cache-dir url) name)] (when (path-exists? path) path))) (defn- download-and-cache-asset "Downloads the file pointed to by url and caches it on the local file system" [url name] (let [tmp-dir (str (mk-tmp-dir!)) tmp-file (mk-path tmp-dir name) dest-dir (cache-dir url) dest-file (mk-path dest-dir name)] (try (mk-cache-dir! url) (download-asset-file url tmp-file) (mv! tmp-file dest-file ) (rm-rf! tmp-dir) dest-file (catch Exception e (rm-rf! tmp-dir) (rm-rf! dest-dir) (throw e))))) (defn asset-seq "Returns a seq of previously cached asset names for a specific url" [url] (let [dir (cache-dir url) dir (file dir)] (ls-names dir))) (defn asset-path "Given a url will return a path to a copy of the asset on the local file system. Will download and persist the asset if necessary." ([url] (asset-path url (last (split url #"/")))) ([url name] (if-let [path (fetch-cached-path url name)] path (download-and-cache-asset url name)))) (defn- download-unzip-and-cache-bundled-asset "Downloads zip file referenced by url, unzips it safely, and then moves all contents to cache dir." [url] (let [tmp-dir (str (mk-tmp-dir!)) tmp-file (mk-path tmp-dir "bundled-asset") tmp-extract-dir (mk-path tmp-dir "extraction") dest-dir (cache-dir url)] (try (mkdir! tmp-extract-dir) (download-asset-file url tmp-file) (unzip tmp-file tmp-extract-dir) (mk-cache-dir! url) (let [asset-names (ls-names tmp-extract-dir)] (dorun (map #(mv! (mk-path tmp-extract-dir %) (mk-path dest-dir %)) asset-names))) (rm-rf! tmp-dir) tmp-extract-dir (catch Exception e (rm-rf! tmp-dir) (rm-rf! dest-dir) (throw e))))) (defn asset-bundle-path "Given a url to a remote zipfile and either a / separated internal path or seq of strings will return a path to a copy of the internal extracted asset on the local file system. Will download, extract and persist all the assets of the zipfile if necessary. usage: (asset-bundle-path \"http://foo.com/a.zip\" \"internal/asset.wav\") (asset-bundle-path \"http://foo.com/a.zip\" [\"internal\" \"asset.wav\"])" [url name] (let [name (if (string? name) (split-on-char name "/") name) internal-path (apply mk-path name)] (if-let [path (fetch-cached-path url internal-path)] path (do (when (dir-empty? (cache-dir url)) (download-unzip-and-cache-bundled-asset url)) (fetch-cached-path url internal-path))))) (defn asset-bundle-dir "Returns the cached directory of of the bundled asset. Will download, extract and persist all the assets of the zipfile referenced by url if necessary" [url] (asset-bundle-path url "") (cache-dir url))
true
(ns ^{:doc "A simple local file system-cached asset management system. Assets are specified as URLs which are then cached by being copied to a centralised place in the file system if not already there. This allows assets to be shared by multiple projects on the same system without needing to duplicate them" :author "PI:NAME:<NAME>END_PI"} overtone.libs.asset (:use [clojure.java.io :only [file]] [clojure.string :only [split]] [overtone.helpers file zip string] [overtone.config.store :only [OVERTONE-DIRS]])) (def ^{:dynamic true} *cache-root* (:assets OVERTONE-DIRS)) (defn- download-asset-file "Download file at url to local filesystem at tmp-file verbosely." [url tmp-file] (println "Asset not cached - starting download...") (binding [*verbose-overtone-file-helpers* 2] (download-file url tmp-file 20000 100 5000))) (defn- safe-url "Replace all non a-z A-Z 0-9 - chars in stringified version of url with _" [url] (let [url (str url) safe (.replaceAll url "http://" "") safe (.replaceAll safe "https://" "") safe (.replaceAll safe "/" "-") safe (.replaceAll safe "[^a-zA-Z0-9-.]" "")] safe)) (defn- url-hash "Return a hash for stringified version of url" [url] (let [url (str url)] (str (hash url)))) (defn- cache-dir "Returns the name of a directory to cache an asset with the given url." [url] (let [safe (safe-url url) hsh (url-hash url)] (mk-path *cache-root* (str safe "--" hsh)))) (defn- mk-cache-dir! "Create a new cache dir for the specified url" [url] (let [dir (cache-dir url)] (mkdir! dir))) (defn- fetch-cached-path "Returns the path to the cached asset if present, otherwise nil." [url name] (let [path (mk-path (cache-dir url) name)] (when (path-exists? path) path))) (defn- download-and-cache-asset "Downloads the file pointed to by url and caches it on the local file system" [url name] (let [tmp-dir (str (mk-tmp-dir!)) tmp-file (mk-path tmp-dir name) dest-dir (cache-dir url) dest-file (mk-path dest-dir name)] (try (mk-cache-dir! url) (download-asset-file url tmp-file) (mv! tmp-file dest-file ) (rm-rf! tmp-dir) dest-file (catch Exception e (rm-rf! tmp-dir) (rm-rf! dest-dir) (throw e))))) (defn asset-seq "Returns a seq of previously cached asset names for a specific url" [url] (let [dir (cache-dir url) dir (file dir)] (ls-names dir))) (defn asset-path "Given a url will return a path to a copy of the asset on the local file system. Will download and persist the asset if necessary." ([url] (asset-path url (last (split url #"/")))) ([url name] (if-let [path (fetch-cached-path url name)] path (download-and-cache-asset url name)))) (defn- download-unzip-and-cache-bundled-asset "Downloads zip file referenced by url, unzips it safely, and then moves all contents to cache dir." [url] (let [tmp-dir (str (mk-tmp-dir!)) tmp-file (mk-path tmp-dir "bundled-asset") tmp-extract-dir (mk-path tmp-dir "extraction") dest-dir (cache-dir url)] (try (mkdir! tmp-extract-dir) (download-asset-file url tmp-file) (unzip tmp-file tmp-extract-dir) (mk-cache-dir! url) (let [asset-names (ls-names tmp-extract-dir)] (dorun (map #(mv! (mk-path tmp-extract-dir %) (mk-path dest-dir %)) asset-names))) (rm-rf! tmp-dir) tmp-extract-dir (catch Exception e (rm-rf! tmp-dir) (rm-rf! dest-dir) (throw e))))) (defn asset-bundle-path "Given a url to a remote zipfile and either a / separated internal path or seq of strings will return a path to a copy of the internal extracted asset on the local file system. Will download, extract and persist all the assets of the zipfile if necessary. usage: (asset-bundle-path \"http://foo.com/a.zip\" \"internal/asset.wav\") (asset-bundle-path \"http://foo.com/a.zip\" [\"internal\" \"asset.wav\"])" [url name] (let [name (if (string? name) (split-on-char name "/") name) internal-path (apply mk-path name)] (if-let [path (fetch-cached-path url internal-path)] path (do (when (dir-empty? (cache-dir url)) (download-unzip-and-cache-bundled-asset url)) (fetch-cached-path url internal-path))))) (defn asset-bundle-dir "Returns the cached directory of of the bundled asset. Will download, extract and persist all the assets of the zipfile referenced by url if necessary" [url] (asset-bundle-path url "") (cache-dir url))
[ { "context": "lurp \"test/ca_cert.edn\"))))\n\n(def ca-key (gen-key 65537 (read-string (slurp \"test/ca_key.edn\"))))\n\n(def s", "end": 1386, "score": 0.9744812846183777, "start": 1381, "tag": "KEY", "value": "65537" }, { "context": "st/server_cert.edn\"))))\n\n(def server-key (gen-key 65537 (read-string (slurp \"test/server_key.edn\"))))\n\n(d", "end": 1535, "score": 0.9536935687065125, "start": 1530, "tag": "KEY", "value": "65537" } ]
test/aleph/tcp_ssl_test.clj
7theta/aleph
0
(ns aleph.tcp-ssl-test (:use [clojure test]) (:require [aleph.tcp-test :refer [with-server]] [aleph.tcp :as tcp] [aleph.netty :as netty] [manifold.stream :as s] [byte-streams.core :as bs]) (:import [java.security KeyFactory PrivateKey] [java.security.cert CertificateFactory X509Certificate] [java.io ByteArrayInputStream] [java.security.spec RSAPrivateCrtKeySpec] [io.netty.handler.ssl SslContextBuilder ClientAuth] [org.apache.commons.codec.binary Base64])) (netty/leak-detector-level! :paranoid) (set! *warn-on-reflection* false) (defn gen-key ^PrivateKey [public-exponent k] (let [k (zipmap (keys k) (->> k vals (map #(BigInteger. % 16)))) spec (RSAPrivateCrtKeySpec. (:modulus k) (biginteger public-exponent) (:privateExponent k) (:prime1 k) (:prime2 k) (:exponent1 k) (:exponent2 k) (:coefficient k)) gen (KeyFactory/getInstance "RSA")] (.generatePrivate gen spec))) (defn gen-cert ^X509Certificate [^String pemstr] (.generateCertificate (CertificateFactory/getInstance "X.509") (ByteArrayInputStream. (Base64/decodeBase64 pemstr)))) (def ca-cert (gen-cert (read-string (slurp "test/ca_cert.edn")))) (def ca-key (gen-key 65537 (read-string (slurp "test/ca_key.edn")))) (def server-cert (gen-cert (read-string (slurp "test/server_cert.edn")))) (def server-key (gen-key 65537 (read-string (slurp "test/server_key.edn")))) (def ^X509Certificate client-cert (gen-cert (read-string (slurp "test/client_cert.edn")))) (def client-key (gen-key 65537 (read-string (slurp "test/client_key.edn")))) (def server-ssl-context (-> (SslContextBuilder/forServer server-key (into-array X509Certificate [server-cert])) (.trustManager (into-array X509Certificate [ca-cert])) (.clientAuth ClientAuth/OPTIONAL) .build)) (def client-ssl-context (netty/ssl-client-context {:private-key client-key :certificate-chain (into-array X509Certificate [client-cert]) :trust-store (into-array X509Certificate [ca-cert])})) (defn ssl-echo-handler [s c] (is (some? (:ssl-session c)) "SSL session should be defined") (s/connect ; note we need to inspect the SSL session *after* we start reading ; data. Otherwise, the session might not be set up yet. (s/map (fn [msg] (is (= (.getSubjectDN ^X509Certificate client-cert) (.getSubjectDN ^X509Certificate (first (.getPeerCertificates (:ssl-session c)))))) msg) s) s)) (deftest test-ssl-echo (with-server (tcp/start-server ssl-echo-handler {:port 10001 :ssl-context server-ssl-context}) (let [c @(tcp/client {:host "localhost" :port 10001 :ssl-context client-ssl-context})] (s/put! c "foo") (is (= "foo" (bs/to-string @(s/take! c)))))))
80374
(ns aleph.tcp-ssl-test (:use [clojure test]) (:require [aleph.tcp-test :refer [with-server]] [aleph.tcp :as tcp] [aleph.netty :as netty] [manifold.stream :as s] [byte-streams.core :as bs]) (:import [java.security KeyFactory PrivateKey] [java.security.cert CertificateFactory X509Certificate] [java.io ByteArrayInputStream] [java.security.spec RSAPrivateCrtKeySpec] [io.netty.handler.ssl SslContextBuilder ClientAuth] [org.apache.commons.codec.binary Base64])) (netty/leak-detector-level! :paranoid) (set! *warn-on-reflection* false) (defn gen-key ^PrivateKey [public-exponent k] (let [k (zipmap (keys k) (->> k vals (map #(BigInteger. % 16)))) spec (RSAPrivateCrtKeySpec. (:modulus k) (biginteger public-exponent) (:privateExponent k) (:prime1 k) (:prime2 k) (:exponent1 k) (:exponent2 k) (:coefficient k)) gen (KeyFactory/getInstance "RSA")] (.generatePrivate gen spec))) (defn gen-cert ^X509Certificate [^String pemstr] (.generateCertificate (CertificateFactory/getInstance "X.509") (ByteArrayInputStream. (Base64/decodeBase64 pemstr)))) (def ca-cert (gen-cert (read-string (slurp "test/ca_cert.edn")))) (def ca-key (gen-key <KEY> (read-string (slurp "test/ca_key.edn")))) (def server-cert (gen-cert (read-string (slurp "test/server_cert.edn")))) (def server-key (gen-key <KEY> (read-string (slurp "test/server_key.edn")))) (def ^X509Certificate client-cert (gen-cert (read-string (slurp "test/client_cert.edn")))) (def client-key (gen-key 65537 (read-string (slurp "test/client_key.edn")))) (def server-ssl-context (-> (SslContextBuilder/forServer server-key (into-array X509Certificate [server-cert])) (.trustManager (into-array X509Certificate [ca-cert])) (.clientAuth ClientAuth/OPTIONAL) .build)) (def client-ssl-context (netty/ssl-client-context {:private-key client-key :certificate-chain (into-array X509Certificate [client-cert]) :trust-store (into-array X509Certificate [ca-cert])})) (defn ssl-echo-handler [s c] (is (some? (:ssl-session c)) "SSL session should be defined") (s/connect ; note we need to inspect the SSL session *after* we start reading ; data. Otherwise, the session might not be set up yet. (s/map (fn [msg] (is (= (.getSubjectDN ^X509Certificate client-cert) (.getSubjectDN ^X509Certificate (first (.getPeerCertificates (:ssl-session c)))))) msg) s) s)) (deftest test-ssl-echo (with-server (tcp/start-server ssl-echo-handler {:port 10001 :ssl-context server-ssl-context}) (let [c @(tcp/client {:host "localhost" :port 10001 :ssl-context client-ssl-context})] (s/put! c "foo") (is (= "foo" (bs/to-string @(s/take! c)))))))
true
(ns aleph.tcp-ssl-test (:use [clojure test]) (:require [aleph.tcp-test :refer [with-server]] [aleph.tcp :as tcp] [aleph.netty :as netty] [manifold.stream :as s] [byte-streams.core :as bs]) (:import [java.security KeyFactory PrivateKey] [java.security.cert CertificateFactory X509Certificate] [java.io ByteArrayInputStream] [java.security.spec RSAPrivateCrtKeySpec] [io.netty.handler.ssl SslContextBuilder ClientAuth] [org.apache.commons.codec.binary Base64])) (netty/leak-detector-level! :paranoid) (set! *warn-on-reflection* false) (defn gen-key ^PrivateKey [public-exponent k] (let [k (zipmap (keys k) (->> k vals (map #(BigInteger. % 16)))) spec (RSAPrivateCrtKeySpec. (:modulus k) (biginteger public-exponent) (:privateExponent k) (:prime1 k) (:prime2 k) (:exponent1 k) (:exponent2 k) (:coefficient k)) gen (KeyFactory/getInstance "RSA")] (.generatePrivate gen spec))) (defn gen-cert ^X509Certificate [^String pemstr] (.generateCertificate (CertificateFactory/getInstance "X.509") (ByteArrayInputStream. (Base64/decodeBase64 pemstr)))) (def ca-cert (gen-cert (read-string (slurp "test/ca_cert.edn")))) (def ca-key (gen-key PI:KEY:<KEY>END_PI (read-string (slurp "test/ca_key.edn")))) (def server-cert (gen-cert (read-string (slurp "test/server_cert.edn")))) (def server-key (gen-key PI:KEY:<KEY>END_PI (read-string (slurp "test/server_key.edn")))) (def ^X509Certificate client-cert (gen-cert (read-string (slurp "test/client_cert.edn")))) (def client-key (gen-key 65537 (read-string (slurp "test/client_key.edn")))) (def server-ssl-context (-> (SslContextBuilder/forServer server-key (into-array X509Certificate [server-cert])) (.trustManager (into-array X509Certificate [ca-cert])) (.clientAuth ClientAuth/OPTIONAL) .build)) (def client-ssl-context (netty/ssl-client-context {:private-key client-key :certificate-chain (into-array X509Certificate [client-cert]) :trust-store (into-array X509Certificate [ca-cert])})) (defn ssl-echo-handler [s c] (is (some? (:ssl-session c)) "SSL session should be defined") (s/connect ; note we need to inspect the SSL session *after* we start reading ; data. Otherwise, the session might not be set up yet. (s/map (fn [msg] (is (= (.getSubjectDN ^X509Certificate client-cert) (.getSubjectDN ^X509Certificate (first (.getPeerCertificates (:ssl-session c)))))) msg) s) s)) (deftest test-ssl-echo (with-server (tcp/start-server ssl-echo-handler {:port 10001 :ssl-context server-ssl-context}) (let [c @(tcp/client {:host "localhost" :port 10001 :ssl-context client-ssl-context})] (s/put! c "foo") (is (= "foo" (bs/to-string @(s/take! c)))))))
[ { "context": "gent\",\n \"name\" \"xAPI mbox\",\n \"mbox\" \"mailto:xapi@adlnet.gov\"},\n \"verb\"\n {\"id\" \"http://adlnet.gov/expapi/v", "end": 1025, "score": 0.9996930360794067, "start": 1010, "tag": "EMAIL", "value": "xapi@adlnet.gov" }, { "context": "hments\"\n [sig-attachment-object]})\n\n(def sig\n \"eyJhbGciOiJSUzI1NiJ9.eyJhY3RvciI6eyJvYmplY3RUeXBlIjoiQWdlbnQiLCJuYW1lIjoieEFQSSBtYm94IiwibWJveCI6Im1haWx0bzp4YXBpQGFkbG5ldC5nb3YifSwidmVyYiI6eyJpZCI6Imh0dHA6Ly9hZGxuZXQuZ292L2V4cGFwaS92ZXJicy9hdHRlbmRlZCIsImRpc3BsYXkiOnsiZW4tR0IiOiJhdHRlbmRlZCIsImVuLVVTIjoiYXR0ZW5kZWQifX0sIm9iamVjdCI6eyJvYmplY3RUeXBlIjoiQWN0aXZpdHkiLCJpZCI6Imh0dHA6Ly93d3cuZXhhbXBsZS5jb20vbWVldGluZ3Mvb2NjdXJhbmNlcy8zNDUzNCJ9LCJpZCI6IjJlMmYxYWQ3LThkMTAtNGM3My1hZTZlLTI4NDI3MjllMjVjZSJ9.roBpi7viDC4DyNikcWtjuvfXEfrVqNtukVfOjoj-VEGbskcxc9H21GKQBsw3LxnpblIpiDPithCs2AOZK7RFy4vB9wsL5HmX8jpxGvGnYCWNEbVRGoYyntFWjF3wFtTaJMHvZLnirL6k1qhxdfJPcV2C-uc-FXC9AR4__xYbJioJDb37wvPtetD8x8YTdkMkM7nlv20GjV3YF-wa_cxt9hWVS-8LDikCswY6PpMLFR6eYeqIqrZxJQtqDhsZK3k28eHDxAnNB-dGoYeiSeFSbcToyVh4iz2lZGNUmfkltiVs7mLTVJNilU0Z41JIFrdYEGXEfYQwFmiIf5denL5_lg\")\n\n(def sig-partial-multipart\n {:content-type \"a", "end": 2154, "score": 0.9997853636741638, "start": 1358, "tag": "KEY", "value": "eyJhbGciOiJSUzI1NiJ9.eyJhY3RvciI6eyJvYmplY3RUeXBlIjoiQWdlbnQiLCJuYW1lIjoieEFQSSBtYm94IiwibWJveCI6Im1haWx0bzp4YXBpQGFkbG5ldC5nb3YifSwidmVyYiI6eyJpZCI6Imh0dHA6Ly9hZGxuZXQuZ292L2V4cGFwaS92ZXJicy9hdHRlbmRlZCIsImRpc3BsYXkiOnsiZW4tR0IiOiJhdHRlbmRlZCIsImVuLVVTIjoiYXR0ZW5kZWQifX0sIm9iamVjdCI6eyJvYmplY3RUeXBlIjoiQWN0aXZpdHkiLCJpZCI6Imh0dHA6Ly93d3cuZXhhbXBsZS5jb20vbWVldGluZ3Mvb2NjdXJhbmNlcy8zNDUzNCJ9LCJpZCI6IjJlMmYxYWQ3LThkMTAtNGM3My1hZTZlLTI4NDI3MjllMjVjZSJ9.roBpi7viDC4DyNikcWtjuvfXEfrVqNtukVfOjoj-VEGbskcxc9H21GKQBsw3LxnpblIpiDPithCs2AOZK7RFy4vB9wsL5HmX8jpxGvGnYCWNEbVRGoYyntFWjF3wFtTaJMHvZLnirL6k1qhxdfJPcV2C-uc-FXC9AR4__xYbJioJDb37wvPtetD8x8YTdkMkM7nlv20GjV3YF-wa_cxt9hWVS-8LDikCswY6PpMLFR6eYeqIqrZxJQtqDhsZK3k28eHDxAnNB-dGoYeiSeFSbcToyVh4iz2lZGNUmfkltiVs7mLTVJNilU0Z41JIFrdYEGXEfYQwFmiIf5denL5_lg" }, { "context": " \"actor\" {\"mbox\" \"mailto:bob@example.com\"\n \"objectType\" ", "end": 3818, "score": 0.9999185800552368, "start": 3803, "tag": "EMAIL", "value": "bob@example.com" } ]
src/test/com/yetanalytics/lrs/pedestal/interceptor/xapi/statements/attachment_test.cljc
yetanalytics/lrs
1
(ns com.yetanalytics.lrs.pedestal.interceptor.xapi.statements.attachment-test (:require [clojure.test :refer [deftest testing is] :include-macros true] [clojure.spec.test.alpha :as stest :include-macros true] [com.yetanalytics.test-support :refer [failures stc-opts]] [com.yetanalytics.lrs.pedestal.interceptor.xapi.statements.attachment :as attachment :refer [decode-sig validate-sig validate-multiparts]]) #?(:clj (:import [java.io ByteArrayInputStream]))) (def sig-attachment-object {"usageType" "http://adlnet.gov/expapi/attachments/signature", "display" {"en-US" "Signed by the Test Suite"}, "description" {"en-US" "Signed by the Test Suite"}, "contentType" "application/octet-stream", "length" 796, "sha2" "f7db3634a22ea2fe4de1fc519751046a3bdf1e5605a316a19343109bd6daa388"}) (def sig-statement {"actor" {"objectType" "Agent", "name" "xAPI mbox", "mbox" "mailto:xapi@adlnet.gov"}, "verb" {"id" "http://adlnet.gov/expapi/verbs/attended", "display" {"en-GB" "attended", "en-US" "attended"}}, "object" {"objectType" "Activity", "id" "http://www.example.com/meetings/occurances/34534"}, "id" "2e2f1ad7-8d10-4c73-ae6e-2842729e25ce", "attachments" [sig-attachment-object]}) (def sig "eyJhbGciOiJSUzI1NiJ9.eyJhY3RvciI6eyJvYmplY3RUeXBlIjoiQWdlbnQiLCJuYW1lIjoieEFQSSBtYm94IiwibWJveCI6Im1haWx0bzp4YXBpQGFkbG5ldC5nb3YifSwidmVyYiI6eyJpZCI6Imh0dHA6Ly9hZGxuZXQuZ292L2V4cGFwaS92ZXJicy9hdHRlbmRlZCIsImRpc3BsYXkiOnsiZW4tR0IiOiJhdHRlbmRlZCIsImVuLVVTIjoiYXR0ZW5kZWQifX0sIm9iamVjdCI6eyJvYmplY3RUeXBlIjoiQWN0aXZpdHkiLCJpZCI6Imh0dHA6Ly93d3cuZXhhbXBsZS5jb20vbWVldGluZ3Mvb2NjdXJhbmNlcy8zNDUzNCJ9LCJpZCI6IjJlMmYxYWQ3LThkMTAtNGM3My1hZTZlLTI4NDI3MjllMjVjZSJ9.roBpi7viDC4DyNikcWtjuvfXEfrVqNtukVfOjoj-VEGbskcxc9H21GKQBsw3LxnpblIpiDPithCs2AOZK7RFy4vB9wsL5HmX8jpxGvGnYCWNEbVRGoYyntFWjF3wFtTaJMHvZLnirL6k1qhxdfJPcV2C-uc-FXC9AR4__xYbJioJDb37wvPtetD8x8YTdkMkM7nlv20GjV3YF-wa_cxt9hWVS-8LDikCswY6PpMLFR6eYeqIqrZxJQtqDhsZK3k28eHDxAnNB-dGoYeiSeFSbcToyVh4iz2lZGNUmfkltiVs7mLTVJNilU0Z41JIFrdYEGXEfYQwFmiIf5denL5_lg") (def sig-partial-multipart {:content-type "application/octet-stream" :content-length 796 :headers {"Content-Type" "application/octet-stream" "Content-Transfer-Encoding" "binary" "X-Experience-API-Hash" "f7db3634a22ea2fe4de1fc519751046a3bdf1e5605a316a19343109bd6daa388"}}) (deftest sig-test (testing "decode-sig" (= (dissoc sig-statement "attachments") (decode-sig sig))) (testing "valid-sig" (is (= sig (-> (validate-sig sig-statement sig-attachment-object (assoc sig-partial-multipart :input-stream #?(:clj (ByteArrayInputStream. (.getBytes sig "UTF-8")) :cljs sig))) :input-stream #?(:clj slurp))))) (testing "invalid-sig" (let [invalid-sig (apply str (drop 10 sig))] (is (= ::attachment/invalid-signature-json (try (validate-sig sig-statement sig-attachment-object (assoc sig-partial-multipart :input-stream #?(:clj (ByteArrayInputStream. (.getBytes invalid-sig "UTF-8")) :cljs invalid-sig))) (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type)))))))) (deftest validate-multiparts-test (let [s-template {"id" "78efaab3-1c65-4cb7-9289-f34e0594b274" "actor" {"mbox" "mailto:bob@example.com" "objectType" "Agent"} "verb" {"id" "https://example.com/verb"} "timestamp" "2022-05-04T13:32:10.486195Z" "version" "1.0.3" "object" {"id" "https://example.com/activity"}} multipart {:content-type "application/octet-stream" :content-length 20 :headers {"Content-Type" "application/octet-stream" "Content-Transfer-Encoding" "binary" "X-Experience-API-Hash" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"} :input-stream #?(:clj (ByteArrayInputStream. (.getBytes "some text\n some more" "UTF-8")) :cljs "some text\n some more")}] (testing "empty" (is (= [] (validate-multiparts [] [])))) (testing "simple" (is (= [multipart] (validate-multiparts [(assoc s-template "attachments" [{"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"}])] [multipart])))) (testing "dup reference" ;; TODO: per this test, the lib currently requires that each referenced ;; multipart be provided, even if they share a SHA. ;; Is this what we intend? (let [statements [(assoc s-template "attachments" [{"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"} {"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"}])]] (testing "works with a dup multipart, deduplicates" (is (= [multipart] (validate-multiparts statements [multipart multipart])))) (testing "works with a dedup multipart" (is (= [multipart] (validate-multiparts statements [multipart])))) (testing "fails with missing attachment" (is (= ::attachment/statement-attachment-missing (try (validate-multiparts statements []) ;; no attachments (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type)))))) (testing "fails with left over multiparts" (is (= ::attachment/statement-attachment-mismatch (try (validate-multiparts [s-template] ;; no attachments [multipart]) (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type))))))))))
88786
(ns com.yetanalytics.lrs.pedestal.interceptor.xapi.statements.attachment-test (:require [clojure.test :refer [deftest testing is] :include-macros true] [clojure.spec.test.alpha :as stest :include-macros true] [com.yetanalytics.test-support :refer [failures stc-opts]] [com.yetanalytics.lrs.pedestal.interceptor.xapi.statements.attachment :as attachment :refer [decode-sig validate-sig validate-multiparts]]) #?(:clj (:import [java.io ByteArrayInputStream]))) (def sig-attachment-object {"usageType" "http://adlnet.gov/expapi/attachments/signature", "display" {"en-US" "Signed by the Test Suite"}, "description" {"en-US" "Signed by the Test Suite"}, "contentType" "application/octet-stream", "length" 796, "sha2" "f7db3634a22ea2fe4de1fc519751046a3bdf1e5605a316a19343109bd6daa388"}) (def sig-statement {"actor" {"objectType" "Agent", "name" "xAPI mbox", "mbox" "mailto:<EMAIL>"}, "verb" {"id" "http://adlnet.gov/expapi/verbs/attended", "display" {"en-GB" "attended", "en-US" "attended"}}, "object" {"objectType" "Activity", "id" "http://www.example.com/meetings/occurances/34534"}, "id" "2e2f1ad7-8d10-4c73-ae6e-2842729e25ce", "attachments" [sig-attachment-object]}) (def sig "<KEY>") (def sig-partial-multipart {:content-type "application/octet-stream" :content-length 796 :headers {"Content-Type" "application/octet-stream" "Content-Transfer-Encoding" "binary" "X-Experience-API-Hash" "f7db3634a22ea2fe4de1fc519751046a3bdf1e5605a316a19343109bd6daa388"}}) (deftest sig-test (testing "decode-sig" (= (dissoc sig-statement "attachments") (decode-sig sig))) (testing "valid-sig" (is (= sig (-> (validate-sig sig-statement sig-attachment-object (assoc sig-partial-multipart :input-stream #?(:clj (ByteArrayInputStream. (.getBytes sig "UTF-8")) :cljs sig))) :input-stream #?(:clj slurp))))) (testing "invalid-sig" (let [invalid-sig (apply str (drop 10 sig))] (is (= ::attachment/invalid-signature-json (try (validate-sig sig-statement sig-attachment-object (assoc sig-partial-multipart :input-stream #?(:clj (ByteArrayInputStream. (.getBytes invalid-sig "UTF-8")) :cljs invalid-sig))) (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type)))))))) (deftest validate-multiparts-test (let [s-template {"id" "78efaab3-1c65-4cb7-9289-f34e0594b274" "actor" {"mbox" "mailto:<EMAIL>" "objectType" "Agent"} "verb" {"id" "https://example.com/verb"} "timestamp" "2022-05-04T13:32:10.486195Z" "version" "1.0.3" "object" {"id" "https://example.com/activity"}} multipart {:content-type "application/octet-stream" :content-length 20 :headers {"Content-Type" "application/octet-stream" "Content-Transfer-Encoding" "binary" "X-Experience-API-Hash" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"} :input-stream #?(:clj (ByteArrayInputStream. (.getBytes "some text\n some more" "UTF-8")) :cljs "some text\n some more")}] (testing "empty" (is (= [] (validate-multiparts [] [])))) (testing "simple" (is (= [multipart] (validate-multiparts [(assoc s-template "attachments" [{"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"}])] [multipart])))) (testing "dup reference" ;; TODO: per this test, the lib currently requires that each referenced ;; multipart be provided, even if they share a SHA. ;; Is this what we intend? (let [statements [(assoc s-template "attachments" [{"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"} {"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"}])]] (testing "works with a dup multipart, deduplicates" (is (= [multipart] (validate-multiparts statements [multipart multipart])))) (testing "works with a dedup multipart" (is (= [multipart] (validate-multiparts statements [multipart])))) (testing "fails with missing attachment" (is (= ::attachment/statement-attachment-missing (try (validate-multiparts statements []) ;; no attachments (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type)))))) (testing "fails with left over multiparts" (is (= ::attachment/statement-attachment-mismatch (try (validate-multiparts [s-template] ;; no attachments [multipart]) (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type))))))))))
true
(ns com.yetanalytics.lrs.pedestal.interceptor.xapi.statements.attachment-test (:require [clojure.test :refer [deftest testing is] :include-macros true] [clojure.spec.test.alpha :as stest :include-macros true] [com.yetanalytics.test-support :refer [failures stc-opts]] [com.yetanalytics.lrs.pedestal.interceptor.xapi.statements.attachment :as attachment :refer [decode-sig validate-sig validate-multiparts]]) #?(:clj (:import [java.io ByteArrayInputStream]))) (def sig-attachment-object {"usageType" "http://adlnet.gov/expapi/attachments/signature", "display" {"en-US" "Signed by the Test Suite"}, "description" {"en-US" "Signed by the Test Suite"}, "contentType" "application/octet-stream", "length" 796, "sha2" "f7db3634a22ea2fe4de1fc519751046a3bdf1e5605a316a19343109bd6daa388"}) (def sig-statement {"actor" {"objectType" "Agent", "name" "xAPI mbox", "mbox" "mailto:PI:EMAIL:<EMAIL>END_PI"}, "verb" {"id" "http://adlnet.gov/expapi/verbs/attended", "display" {"en-GB" "attended", "en-US" "attended"}}, "object" {"objectType" "Activity", "id" "http://www.example.com/meetings/occurances/34534"}, "id" "2e2f1ad7-8d10-4c73-ae6e-2842729e25ce", "attachments" [sig-attachment-object]}) (def sig "PI:KEY:<KEY>END_PI") (def sig-partial-multipart {:content-type "application/octet-stream" :content-length 796 :headers {"Content-Type" "application/octet-stream" "Content-Transfer-Encoding" "binary" "X-Experience-API-Hash" "f7db3634a22ea2fe4de1fc519751046a3bdf1e5605a316a19343109bd6daa388"}}) (deftest sig-test (testing "decode-sig" (= (dissoc sig-statement "attachments") (decode-sig sig))) (testing "valid-sig" (is (= sig (-> (validate-sig sig-statement sig-attachment-object (assoc sig-partial-multipart :input-stream #?(:clj (ByteArrayInputStream. (.getBytes sig "UTF-8")) :cljs sig))) :input-stream #?(:clj slurp))))) (testing "invalid-sig" (let [invalid-sig (apply str (drop 10 sig))] (is (= ::attachment/invalid-signature-json (try (validate-sig sig-statement sig-attachment-object (assoc sig-partial-multipart :input-stream #?(:clj (ByteArrayInputStream. (.getBytes invalid-sig "UTF-8")) :cljs invalid-sig))) (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type)))))))) (deftest validate-multiparts-test (let [s-template {"id" "78efaab3-1c65-4cb7-9289-f34e0594b274" "actor" {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "objectType" "Agent"} "verb" {"id" "https://example.com/verb"} "timestamp" "2022-05-04T13:32:10.486195Z" "version" "1.0.3" "object" {"id" "https://example.com/activity"}} multipart {:content-type "application/octet-stream" :content-length 20 :headers {"Content-Type" "application/octet-stream" "Content-Transfer-Encoding" "binary" "X-Experience-API-Hash" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"} :input-stream #?(:clj (ByteArrayInputStream. (.getBytes "some text\n some more" "UTF-8")) :cljs "some text\n some more")}] (testing "empty" (is (= [] (validate-multiparts [] [])))) (testing "simple" (is (= [multipart] (validate-multiparts [(assoc s-template "attachments" [{"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"}])] [multipart])))) (testing "dup reference" ;; TODO: per this test, the lib currently requires that each referenced ;; multipart be provided, even if they share a SHA. ;; Is this what we intend? (let [statements [(assoc s-template "attachments" [{"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"} {"usageType" "https://example.com/usagetype" "display" {"en-US" "someattachment"} "contentType" "application/octet-stream" "length" 20 "sha2" "7e0c4bbe6280e85cf8525dd7afe8d6ffe9051fbc5fadff71d4aded1ba4c74b53"}])]] (testing "works with a dup multipart, deduplicates" (is (= [multipart] (validate-multiparts statements [multipart multipart])))) (testing "works with a dedup multipart" (is (= [multipart] (validate-multiparts statements [multipart])))) (testing "fails with missing attachment" (is (= ::attachment/statement-attachment-missing (try (validate-multiparts statements []) ;; no attachments (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type)))))) (testing "fails with left over multiparts" (is (= ::attachment/statement-attachment-mismatch (try (validate-multiparts [s-template] ;; no attachments [multipart]) (catch #?(:clj clojure.lang.ExceptionInfo :cljs ExceptionInfo) exi (-> exi ex-data :type))))))))))
[ { "context": " (is (= [\"Email to <https://site.com/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was reject", "end": 608, "score": 0.9996117949485779, "start": 593, "tag": "EMAIL", "value": "arthur@dent.com" }, { "context": " to <https://site.com/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was rejected: \\\"Database o", "end": 624, "score": 0.9995936751365662, "start": 609, "tag": "EMAIL", "value": "arthur@dent.com" }, { "context": "/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was rejected: \\\"Database on fire\\\"\"]\n ", "end": 647, "score": 0.9996631741523743, "start": 631, "tag": "EMAIL", "value": "support@site.com" }, { "context": " (is (= [\"Email to <https://site.com/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was reject", "end": 1063, "score": 0.9997479319572449, "start": 1048, "tag": "EMAIL", "value": "arthur@dent.com" }, { "context": " to <https://site.com/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was rejected: \\\"Database o", "end": 1079, "score": 0.9998002648353577, "start": 1064, "tag": "EMAIL", "value": "arthur@dent.com" }, { "context": "/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was rejected: \\\"Database on fire\\\"\"\n ", "end": 1102, "score": 0.9997920989990234, "start": 1086, "tag": "EMAIL", "value": "support@site.com" }, { "context": " \"Email to <https://site.com/customers?q=ford@prefect.com|ford@prefect.com> from support@site.com was rejec", "end": 1211, "score": 0.9999013543128967, "start": 1195, "tag": "EMAIL", "value": "ford@prefect.com" }, { "context": "to <https://site.com/customers?q=ford@prefect.com|ford@prefect.com> from support@site.com was rejected: \\\"App under ", "end": 1228, "score": 0.9998984336853027, "start": 1212, "tag": "EMAIL", "value": "ford@prefect.com" }, { "context": "ustomers?q=ford@prefect.com|ford@prefect.com> from support@site.com was rejected: \\\"App under water\\\"\"]\n ", "end": 1251, "score": 0.9998422861099243, "start": 1235, "tag": "EMAIL", "value": "support@site.com" } ]
test/slack_hooks/service/mandrill_test.clj
papertrail/slack-hooks
15
(ns slack-hooks.service.mandrill-test (:use clojure.test) (:require [slack-hooks.service.mandrill :as mandrill] [clojure.data.json :as json])) (deftest formatted-message-test (with-redefs [mandrill/customer-search-base-url "https://site.com/customers?q="] (testing "Formatting a rejected Mandrill webhook" (let [text (slurp "test/resources/mandrill-reject.json") request {:form-params {"mandrill_events" text}} formatted-text (mandrill/formatted-message request)] (is (= ["Email to <https://site.com/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was rejected: \"Database on fire\""] formatted-text)))) (testing "Formatting multiple rejected Mandrill webhooks" (let [text (slurp "test/resources/mandrill-multiple.json") request {:form-params {"mandrill_events" text}} formatted-text (mandrill/formatted-message request)] (is (= ["Email to <https://site.com/customers?q=arthur@dent.com|arthur@dent.com> from support@site.com was rejected: \"Database on fire\"" "Email to <https://site.com/customers?q=ford@prefect.com|ford@prefect.com> from support@site.com was rejected: \"App under water\""] formatted-text))))))
30786
(ns slack-hooks.service.mandrill-test (:use clojure.test) (:require [slack-hooks.service.mandrill :as mandrill] [clojure.data.json :as json])) (deftest formatted-message-test (with-redefs [mandrill/customer-search-base-url "https://site.com/customers?q="] (testing "Formatting a rejected Mandrill webhook" (let [text (slurp "test/resources/mandrill-reject.json") request {:form-params {"mandrill_events" text}} formatted-text (mandrill/formatted-message request)] (is (= ["Email to <https://site.com/customers?q=<EMAIL>|<EMAIL>> from <EMAIL> was rejected: \"Database on fire\""] formatted-text)))) (testing "Formatting multiple rejected Mandrill webhooks" (let [text (slurp "test/resources/mandrill-multiple.json") request {:form-params {"mandrill_events" text}} formatted-text (mandrill/formatted-message request)] (is (= ["Email to <https://site.com/customers?q=<EMAIL>|<EMAIL>> from <EMAIL> was rejected: \"Database on fire\"" "Email to <https://site.com/customers?q=<EMAIL>|<EMAIL>> from <EMAIL> was rejected: \"App under water\""] formatted-text))))))
true
(ns slack-hooks.service.mandrill-test (:use clojure.test) (:require [slack-hooks.service.mandrill :as mandrill] [clojure.data.json :as json])) (deftest formatted-message-test (with-redefs [mandrill/customer-search-base-url "https://site.com/customers?q="] (testing "Formatting a rejected Mandrill webhook" (let [text (slurp "test/resources/mandrill-reject.json") request {:form-params {"mandrill_events" text}} formatted-text (mandrill/formatted-message request)] (is (= ["Email to <https://site.com/customers?q=PI:EMAIL:<EMAIL>END_PI|PI:EMAIL:<EMAIL>END_PI> from PI:EMAIL:<EMAIL>END_PI was rejected: \"Database on fire\""] formatted-text)))) (testing "Formatting multiple rejected Mandrill webhooks" (let [text (slurp "test/resources/mandrill-multiple.json") request {:form-params {"mandrill_events" text}} formatted-text (mandrill/formatted-message request)] (is (= ["Email to <https://site.com/customers?q=PI:EMAIL:<EMAIL>END_PI|PI:EMAIL:<EMAIL>END_PI> from PI:EMAIL:<EMAIL>END_PI was rejected: \"Database on fire\"" "Email to <https://site.com/customers?q=PI:EMAIL:<EMAIL>END_PI|PI:EMAIL:<EMAIL>END_PI> from PI:EMAIL:<EMAIL>END_PI was rejected: \"App under water\""] formatted-text))))))
[ { "context": " [[:type-code \"Tyyppikoodi\"]\n [:name \"Nimi\"]\n [:main-category \"Pääluokka\"]\n ", "end": 9671, "score": 0.946590781211853, "start": 9667, "tag": "NAME", "value": "Nimi" }, { "context": " :on-click #(==> [::events/edit-user [:email] \"fix@me.com\"])}\n [mui/icon \"add\"]]]\n\n ;", "end": 11452, "score": 0.9999181628227234, "start": 11442, "tag": "EMAIL", "value": "fix@me.com" } ]
webapp/src/cljs/lipas/ui/admin/views.cljs
lipas-liikuntapaikat/lipas
49
(ns lipas.ui.admin.views (:require [clojure.spec.alpha :as s] [lipas.data.styles :as styles] [lipas.ui.admin.events :as events] [lipas.ui.admin.subs :as subs] [lipas.ui.components :as lui] [lipas.ui.mui :as mui] [lipas.ui.utils :refer [<== ==>] :as utils])) (defn magic-link-dialog [{:keys [tr]}] (let [open? (<== [::subs/magic-link-dialog-open?]) variants (<== [::subs/magic-link-variants]) variant (<== [::subs/selected-magic-link-variant]) user (<== [::subs/editing-user])] [mui/dialog {:open open?} [mui/dialog-title (tr :lipas.admin/send-magic-link (:email user))] [mui/dialog-content [mui/form-group [lui/select {:label (tr :lipas.admin/select-magic-link-template) :items variants :value variant :on-change #(==> [::events/select-magic-link-variant %])}] [mui/button {:style {:margin-top "1em"} :on-click #(==> [::events/send-magic-link user variant])} (tr :actions/submit)] [mui/button {:style {:margin-top "1em"} :on-click #(==> [::events/close-magic-link-dialog])} (tr :actions/cancel)]]]])) (defn user-dialog [tr] (let [locale (tr) cities (<== [::subs/cities-list locale]) types (<== [::subs/types-list locale]) sites (<== [::subs/sites-list]) user (<== [::subs/editing-user]) history (<== [::subs/user-history]) existing? (some? (:id user))] [lui/full-screen-dialog {:open? (boolean (seq user)) :title (or (:username user) (:email user)) :close-label (tr :actions/close) :on-close #(==> [::events/set-user-to-edit nil]) :bottom-actions [;; Archive button (when (= "active" (:status user)) [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/update-user-status user "archived"])} [mui/icon {:style {:margin-right "0.25em"}} "archive"] "Arkistoi"]) ;; Restore button (when (= "archived" (:status user)) [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/update-user-status user "active"])} [mui/icon {:style {:margin-right "0.25em"}} "restore"] "Palauta"]) ;; Send magic link button [lui/email-button {:label (tr :lipas.admin/magic-link) :disabled (not (s/valid? :lipas/new-user user)) :on-click #(==> [::events/open-magic-link-dialog])}] ;; Save button (when existing? [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/save-user user])} [mui/icon {:style {:margin-right "0.25em"}} "save"] (tr :actions/save)])]} [mui/grid {:container true :spacing 8} [magic-link-dialog {:tr tr}] ;;; Contact info [lui/form-card {:title (tr :lipas.user/contact-info)} [mui/form-group ;; Email [lui/text-field {:label (tr :lipas.user/email) :value (:email user) :on-change #(==> [::events/edit-user [:email] %]) :disabled existing?}] ;; Username [lui/text-field {:label (tr :lipas.user/username) :value (:username user) :on-change #(==> [::events/edit-user [:username] %]) :disabled existing?}] ;; Firstname [lui/text-field {:label (tr :lipas.user/firstname) :value (-> user :user-data :firstname) :on-change #(==> [::events/edit-user [:user-data :firstname] %]) :disabled existing?}] ;; Lastname [lui/text-field {:label (tr :lipas.user/lastname) :value (-> user :user-data :lastname) :on-change #(==> [::events/edit-user [:user-data :lastname] %]) :disabled existing?}]]] ;;; Permissions [lui/form-card {:title (tr :lipas.user/permissions)} [mui/form-group [mui/card {:style {:background-color mui/gray3 :margin-bottom "1em"}} [mui/card-header {:subheader (tr :lipas.user/requested-permissions)}] [mui/card-content [mui/typography [:i (or (-> user :user-data :permissions-request) "-")]]]] ;; Admin? [lui/checkbox {:label (tr :lipas.user.permissions/admin?) :value (-> user :permissions :admin?) :on-change #(==> [::events/edit-user [:permissions :admin?] %])}] ;; Permission to all types? [lui/checkbox {:label (tr :lipas.user.permissions/all-types?) :value (-> user :permissions :all-types?) :on-change #(==> [::events/edit-user [:permissions :all-types?] %])}] ;; Permission to all cities? [lui/checkbox {:label (tr :lipas.user.permissions/all-cities?) :value (-> user :permissions :all-cities?) :on-change #(==> [::events/edit-user [:permissions :all-cities?] %])}] ;; Permission to individual spoorts-sites [lui/autocomplete {:items sites :label (tr :lipas.user.permissions/sports-sites) :value (-> user :permissions :sports-sites) :on-change #(==> [::events/edit-user [:permissions :sports-sites] %])}] ;; Permission to individual types [lui/autocomplete {:items types :label (tr :lipas.user.permissions/types) :value (-> user :permissions :types) :on-change #(==> [::events/edit-user [:permissions :types] %])}] ;; Permission to individual cities [lui/autocomplete {:items cities :label (tr :lipas.user.permissions/cities) :value (-> user :permissions :cities) :on-change #(==> [::events/edit-user [:permissions :cities] %])}]]] ;;; History [lui/form-card {:title (tr :lipas.user/history)} [lui/table-v2 {:items history :headers {:event {:label (tr :general/event)} :event-date {:label (tr :time/time)}}}]]]])) (defn color-picker [{:keys [value on-change]}] [:input {:type "color" :value value :on-change #(on-change (-> % .-target .-value))}]) (defn color-selector [] (let [new-colors (<== [::subs/selected-colors]) pick-color (fn [k1 k2 v] (==> [::events/select-color k1 k2 v])) types (<== [:lipas.ui.sports-sites.subs/all-types])] [mui/table [mui/table-head [mui/table-row [mui/table-cell "Type-code"] [mui/table-cell "Type-name"] [mui/table-cell "Geometry"] [mui/table-cell "Old symbol"] [mui/table-cell "New symbol"] [mui/table-cell "Old-fill"] [mui/table-cell "New-fill"] [mui/table-cell "Old-stroke"] [mui/table-cell "New-stroke"]]] (into [mui/table-body] (for [[type-code type] (sort-by first types) :let [shape (-> type-code types :geometry-type) fill (-> type-code styles/temp-symbols :fill) stroke (-> type-code styles/temp-symbols :stroke)]] [mui/table-row [mui/table-cell type-code] [mui/table-cell (-> type :name :fi)] [mui/table-cell shape] ;; Old symbol [mui/table-cell (condp = shape "Point" "Circle" shape)] ;; New symbol [mui/table-cell (condp = shape "Point" [lui/select {:items [{:label "Circle" :value "circle"} {:label "Square" :value "square"}] :value (or (-> type-code new-colors :symbol) "circle") :on-change (partial pick-color type-code :symbol)}] shape)] ;; Old fill [mui/table-cell [color-picker {:value fill :on-change #()}]] ;; New fill [mui/table-cell [mui/grid {:container true :wrap "nowrap"} [mui/grid {:item true} [color-picker {:value (-> (new-colors type-code) :fill) :on-change (partial pick-color type-code :fill)}]] [mui/grid {:item true} [mui/button {:size :small :on-click #(pick-color type-code :fill fill)} "reset"]]]] ;; Old stroke [mui/table-cell [color-picker {:value stroke :on-change #()}]] ;; New stroke [mui/table-cell [mui/grid {:container true :wrap "nowrap"} [mui/grid {:item true} [color-picker {:value (-> (new-colors type-code) :stroke) :on-change (partial pick-color type-code :stroke)}]] [mui/grid {:item true} [mui/button {:size :small :on-click #(pick-color type-code :stroke stroke)} "reset"]]]]]))])) (defn type-codes-view [] (let [types (<== [:lipas.ui.sports-sites.subs/type-table])] [mui/card {:square true} [mui/card-content [mui/typography {:variant "h5"} "Tyyppikoodit"] [lui/table {:hide-action-btn? true :headers [[:type-code "Tyyppikoodi"] [:name "Nimi"] [:main-category "Pääluokka"] [:sub-category "Alaluokka"] [:description "Kuvaus"] [:geometry-type "Geometria"]] :sort-fn :type-code :items types :on-select #(js/alert "Ei tee mitään vielä...")}]]])) (defn admin-panel [] (let [tr (<== [:lipas.ui.subs/translator]) status (<== [::subs/users-status]) users (<== [::subs/users-list]) users-filter (<== [::subs/users-filter]) selected-tab (<== [::subs/selected-tab])] [mui/grid {:container true} [mui/grid {:item true :xs 12} [mui/tool-bar [mui/tabs {:value selected-tab :on-change #(==> [::events/select-tab %2])} [mui/tab {:label (tr :lipas.admin/users)}] [mui/tab {:label "Symbolityökalu"}] [mui/tab {:label "Tyyppikoodit"}]]] (when (= 1 selected-tab) [:<> [color-selector] [mui/fab {:style {:position "sticky" :bottom "1em" :left "1em"} :variant "extended" :color "secondary" :on-click #(==> [::events/download-new-colors-excel])} [mui/icon "save"] "Lataa"]]) (when (= 0 selected-tab) [mui/card {:square true} [mui/card-content [mui/typography {:variant "h5"} (tr :lipas.admin/users)] ;; Full-screen user dialog [user-dialog tr] [mui/grid {:container true :spacing 32} ;; Add user button [mui/grid {:item true :style {:flex-grow 1}} [mui/fab {:color "secondary" :size "small" :style {:margin-top "1em"} :on-click #(==> [::events/edit-user [:email] "fix@me.com"])} [mui/icon "add"]]] ;; Status selector [mui/grid {:item true} [lui/select {:style {:width "150px"} :label "Status" :value status :items ["active" "archived"] :value-fn identity :label-fn identity :on-change #(==> [::events/select-status %])}]] ;; Users filter [mui/grid {:item true} [lui/text-field {:label (tr :search/search) :on-change #(==> [::events/filter-users %]) :value users-filter}]]] ;; Users table [lui/table {:headers [[:email (tr :lipas.user/email)] [:firstname (tr :lipas.user/firstname)] [:lastname (tr :lipas.user/lastname)] [:sports-sites (tr :lipas.user.permissions/sports-sites)] [:cities (tr :lipas.user.permissions/cities)] [:types (tr :lipas.user.permissions/types)]] :sort-fn :email :items users :on-select #(==> [::events/set-user-to-edit %])}]]]) (when (= 2 selected-tab) [type-codes-view])]])) (defn main [] (let [admin? (<== [:lipas.ui.user.subs/admin?])] (if admin? [admin-panel] (==> [:lipas.ui.events/navigate "/"]))))
23193
(ns lipas.ui.admin.views (:require [clojure.spec.alpha :as s] [lipas.data.styles :as styles] [lipas.ui.admin.events :as events] [lipas.ui.admin.subs :as subs] [lipas.ui.components :as lui] [lipas.ui.mui :as mui] [lipas.ui.utils :refer [<== ==>] :as utils])) (defn magic-link-dialog [{:keys [tr]}] (let [open? (<== [::subs/magic-link-dialog-open?]) variants (<== [::subs/magic-link-variants]) variant (<== [::subs/selected-magic-link-variant]) user (<== [::subs/editing-user])] [mui/dialog {:open open?} [mui/dialog-title (tr :lipas.admin/send-magic-link (:email user))] [mui/dialog-content [mui/form-group [lui/select {:label (tr :lipas.admin/select-magic-link-template) :items variants :value variant :on-change #(==> [::events/select-magic-link-variant %])}] [mui/button {:style {:margin-top "1em"} :on-click #(==> [::events/send-magic-link user variant])} (tr :actions/submit)] [mui/button {:style {:margin-top "1em"} :on-click #(==> [::events/close-magic-link-dialog])} (tr :actions/cancel)]]]])) (defn user-dialog [tr] (let [locale (tr) cities (<== [::subs/cities-list locale]) types (<== [::subs/types-list locale]) sites (<== [::subs/sites-list]) user (<== [::subs/editing-user]) history (<== [::subs/user-history]) existing? (some? (:id user))] [lui/full-screen-dialog {:open? (boolean (seq user)) :title (or (:username user) (:email user)) :close-label (tr :actions/close) :on-close #(==> [::events/set-user-to-edit nil]) :bottom-actions [;; Archive button (when (= "active" (:status user)) [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/update-user-status user "archived"])} [mui/icon {:style {:margin-right "0.25em"}} "archive"] "Arkistoi"]) ;; Restore button (when (= "archived" (:status user)) [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/update-user-status user "active"])} [mui/icon {:style {:margin-right "0.25em"}} "restore"] "Palauta"]) ;; Send magic link button [lui/email-button {:label (tr :lipas.admin/magic-link) :disabled (not (s/valid? :lipas/new-user user)) :on-click #(==> [::events/open-magic-link-dialog])}] ;; Save button (when existing? [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/save-user user])} [mui/icon {:style {:margin-right "0.25em"}} "save"] (tr :actions/save)])]} [mui/grid {:container true :spacing 8} [magic-link-dialog {:tr tr}] ;;; Contact info [lui/form-card {:title (tr :lipas.user/contact-info)} [mui/form-group ;; Email [lui/text-field {:label (tr :lipas.user/email) :value (:email user) :on-change #(==> [::events/edit-user [:email] %]) :disabled existing?}] ;; Username [lui/text-field {:label (tr :lipas.user/username) :value (:username user) :on-change #(==> [::events/edit-user [:username] %]) :disabled existing?}] ;; Firstname [lui/text-field {:label (tr :lipas.user/firstname) :value (-> user :user-data :firstname) :on-change #(==> [::events/edit-user [:user-data :firstname] %]) :disabled existing?}] ;; Lastname [lui/text-field {:label (tr :lipas.user/lastname) :value (-> user :user-data :lastname) :on-change #(==> [::events/edit-user [:user-data :lastname] %]) :disabled existing?}]]] ;;; Permissions [lui/form-card {:title (tr :lipas.user/permissions)} [mui/form-group [mui/card {:style {:background-color mui/gray3 :margin-bottom "1em"}} [mui/card-header {:subheader (tr :lipas.user/requested-permissions)}] [mui/card-content [mui/typography [:i (or (-> user :user-data :permissions-request) "-")]]]] ;; Admin? [lui/checkbox {:label (tr :lipas.user.permissions/admin?) :value (-> user :permissions :admin?) :on-change #(==> [::events/edit-user [:permissions :admin?] %])}] ;; Permission to all types? [lui/checkbox {:label (tr :lipas.user.permissions/all-types?) :value (-> user :permissions :all-types?) :on-change #(==> [::events/edit-user [:permissions :all-types?] %])}] ;; Permission to all cities? [lui/checkbox {:label (tr :lipas.user.permissions/all-cities?) :value (-> user :permissions :all-cities?) :on-change #(==> [::events/edit-user [:permissions :all-cities?] %])}] ;; Permission to individual spoorts-sites [lui/autocomplete {:items sites :label (tr :lipas.user.permissions/sports-sites) :value (-> user :permissions :sports-sites) :on-change #(==> [::events/edit-user [:permissions :sports-sites] %])}] ;; Permission to individual types [lui/autocomplete {:items types :label (tr :lipas.user.permissions/types) :value (-> user :permissions :types) :on-change #(==> [::events/edit-user [:permissions :types] %])}] ;; Permission to individual cities [lui/autocomplete {:items cities :label (tr :lipas.user.permissions/cities) :value (-> user :permissions :cities) :on-change #(==> [::events/edit-user [:permissions :cities] %])}]]] ;;; History [lui/form-card {:title (tr :lipas.user/history)} [lui/table-v2 {:items history :headers {:event {:label (tr :general/event)} :event-date {:label (tr :time/time)}}}]]]])) (defn color-picker [{:keys [value on-change]}] [:input {:type "color" :value value :on-change #(on-change (-> % .-target .-value))}]) (defn color-selector [] (let [new-colors (<== [::subs/selected-colors]) pick-color (fn [k1 k2 v] (==> [::events/select-color k1 k2 v])) types (<== [:lipas.ui.sports-sites.subs/all-types])] [mui/table [mui/table-head [mui/table-row [mui/table-cell "Type-code"] [mui/table-cell "Type-name"] [mui/table-cell "Geometry"] [mui/table-cell "Old symbol"] [mui/table-cell "New symbol"] [mui/table-cell "Old-fill"] [mui/table-cell "New-fill"] [mui/table-cell "Old-stroke"] [mui/table-cell "New-stroke"]]] (into [mui/table-body] (for [[type-code type] (sort-by first types) :let [shape (-> type-code types :geometry-type) fill (-> type-code styles/temp-symbols :fill) stroke (-> type-code styles/temp-symbols :stroke)]] [mui/table-row [mui/table-cell type-code] [mui/table-cell (-> type :name :fi)] [mui/table-cell shape] ;; Old symbol [mui/table-cell (condp = shape "Point" "Circle" shape)] ;; New symbol [mui/table-cell (condp = shape "Point" [lui/select {:items [{:label "Circle" :value "circle"} {:label "Square" :value "square"}] :value (or (-> type-code new-colors :symbol) "circle") :on-change (partial pick-color type-code :symbol)}] shape)] ;; Old fill [mui/table-cell [color-picker {:value fill :on-change #()}]] ;; New fill [mui/table-cell [mui/grid {:container true :wrap "nowrap"} [mui/grid {:item true} [color-picker {:value (-> (new-colors type-code) :fill) :on-change (partial pick-color type-code :fill)}]] [mui/grid {:item true} [mui/button {:size :small :on-click #(pick-color type-code :fill fill)} "reset"]]]] ;; Old stroke [mui/table-cell [color-picker {:value stroke :on-change #()}]] ;; New stroke [mui/table-cell [mui/grid {:container true :wrap "nowrap"} [mui/grid {:item true} [color-picker {:value (-> (new-colors type-code) :stroke) :on-change (partial pick-color type-code :stroke)}]] [mui/grid {:item true} [mui/button {:size :small :on-click #(pick-color type-code :stroke stroke)} "reset"]]]]]))])) (defn type-codes-view [] (let [types (<== [:lipas.ui.sports-sites.subs/type-table])] [mui/card {:square true} [mui/card-content [mui/typography {:variant "h5"} "Tyyppikoodit"] [lui/table {:hide-action-btn? true :headers [[:type-code "Tyyppikoodi"] [:name "<NAME>"] [:main-category "Pääluokka"] [:sub-category "Alaluokka"] [:description "Kuvaus"] [:geometry-type "Geometria"]] :sort-fn :type-code :items types :on-select #(js/alert "Ei tee mitään vielä...")}]]])) (defn admin-panel [] (let [tr (<== [:lipas.ui.subs/translator]) status (<== [::subs/users-status]) users (<== [::subs/users-list]) users-filter (<== [::subs/users-filter]) selected-tab (<== [::subs/selected-tab])] [mui/grid {:container true} [mui/grid {:item true :xs 12} [mui/tool-bar [mui/tabs {:value selected-tab :on-change #(==> [::events/select-tab %2])} [mui/tab {:label (tr :lipas.admin/users)}] [mui/tab {:label "Symbolityökalu"}] [mui/tab {:label "Tyyppikoodit"}]]] (when (= 1 selected-tab) [:<> [color-selector] [mui/fab {:style {:position "sticky" :bottom "1em" :left "1em"} :variant "extended" :color "secondary" :on-click #(==> [::events/download-new-colors-excel])} [mui/icon "save"] "Lataa"]]) (when (= 0 selected-tab) [mui/card {:square true} [mui/card-content [mui/typography {:variant "h5"} (tr :lipas.admin/users)] ;; Full-screen user dialog [user-dialog tr] [mui/grid {:container true :spacing 32} ;; Add user button [mui/grid {:item true :style {:flex-grow 1}} [mui/fab {:color "secondary" :size "small" :style {:margin-top "1em"} :on-click #(==> [::events/edit-user [:email] "<EMAIL>"])} [mui/icon "add"]]] ;; Status selector [mui/grid {:item true} [lui/select {:style {:width "150px"} :label "Status" :value status :items ["active" "archived"] :value-fn identity :label-fn identity :on-change #(==> [::events/select-status %])}]] ;; Users filter [mui/grid {:item true} [lui/text-field {:label (tr :search/search) :on-change #(==> [::events/filter-users %]) :value users-filter}]]] ;; Users table [lui/table {:headers [[:email (tr :lipas.user/email)] [:firstname (tr :lipas.user/firstname)] [:lastname (tr :lipas.user/lastname)] [:sports-sites (tr :lipas.user.permissions/sports-sites)] [:cities (tr :lipas.user.permissions/cities)] [:types (tr :lipas.user.permissions/types)]] :sort-fn :email :items users :on-select #(==> [::events/set-user-to-edit %])}]]]) (when (= 2 selected-tab) [type-codes-view])]])) (defn main [] (let [admin? (<== [:lipas.ui.user.subs/admin?])] (if admin? [admin-panel] (==> [:lipas.ui.events/navigate "/"]))))
true
(ns lipas.ui.admin.views (:require [clojure.spec.alpha :as s] [lipas.data.styles :as styles] [lipas.ui.admin.events :as events] [lipas.ui.admin.subs :as subs] [lipas.ui.components :as lui] [lipas.ui.mui :as mui] [lipas.ui.utils :refer [<== ==>] :as utils])) (defn magic-link-dialog [{:keys [tr]}] (let [open? (<== [::subs/magic-link-dialog-open?]) variants (<== [::subs/magic-link-variants]) variant (<== [::subs/selected-magic-link-variant]) user (<== [::subs/editing-user])] [mui/dialog {:open open?} [mui/dialog-title (tr :lipas.admin/send-magic-link (:email user))] [mui/dialog-content [mui/form-group [lui/select {:label (tr :lipas.admin/select-magic-link-template) :items variants :value variant :on-change #(==> [::events/select-magic-link-variant %])}] [mui/button {:style {:margin-top "1em"} :on-click #(==> [::events/send-magic-link user variant])} (tr :actions/submit)] [mui/button {:style {:margin-top "1em"} :on-click #(==> [::events/close-magic-link-dialog])} (tr :actions/cancel)]]]])) (defn user-dialog [tr] (let [locale (tr) cities (<== [::subs/cities-list locale]) types (<== [::subs/types-list locale]) sites (<== [::subs/sites-list]) user (<== [::subs/editing-user]) history (<== [::subs/user-history]) existing? (some? (:id user))] [lui/full-screen-dialog {:open? (boolean (seq user)) :title (or (:username user) (:email user)) :close-label (tr :actions/close) :on-close #(==> [::events/set-user-to-edit nil]) :bottom-actions [;; Archive button (when (= "active" (:status user)) [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/update-user-status user "archived"])} [mui/icon {:style {:margin-right "0.25em"}} "archive"] "Arkistoi"]) ;; Restore button (when (= "archived" (:status user)) [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/update-user-status user "active"])} [mui/icon {:style {:margin-right "0.25em"}} "restore"] "Palauta"]) ;; Send magic link button [lui/email-button {:label (tr :lipas.admin/magic-link) :disabled (not (s/valid? :lipas/new-user user)) :on-click #(==> [::events/open-magic-link-dialog])}] ;; Save button (when existing? [mui/button {:variant "contained" :color "secondary" :on-click #(==> [::events/save-user user])} [mui/icon {:style {:margin-right "0.25em"}} "save"] (tr :actions/save)])]} [mui/grid {:container true :spacing 8} [magic-link-dialog {:tr tr}] ;;; Contact info [lui/form-card {:title (tr :lipas.user/contact-info)} [mui/form-group ;; Email [lui/text-field {:label (tr :lipas.user/email) :value (:email user) :on-change #(==> [::events/edit-user [:email] %]) :disabled existing?}] ;; Username [lui/text-field {:label (tr :lipas.user/username) :value (:username user) :on-change #(==> [::events/edit-user [:username] %]) :disabled existing?}] ;; Firstname [lui/text-field {:label (tr :lipas.user/firstname) :value (-> user :user-data :firstname) :on-change #(==> [::events/edit-user [:user-data :firstname] %]) :disabled existing?}] ;; Lastname [lui/text-field {:label (tr :lipas.user/lastname) :value (-> user :user-data :lastname) :on-change #(==> [::events/edit-user [:user-data :lastname] %]) :disabled existing?}]]] ;;; Permissions [lui/form-card {:title (tr :lipas.user/permissions)} [mui/form-group [mui/card {:style {:background-color mui/gray3 :margin-bottom "1em"}} [mui/card-header {:subheader (tr :lipas.user/requested-permissions)}] [mui/card-content [mui/typography [:i (or (-> user :user-data :permissions-request) "-")]]]] ;; Admin? [lui/checkbox {:label (tr :lipas.user.permissions/admin?) :value (-> user :permissions :admin?) :on-change #(==> [::events/edit-user [:permissions :admin?] %])}] ;; Permission to all types? [lui/checkbox {:label (tr :lipas.user.permissions/all-types?) :value (-> user :permissions :all-types?) :on-change #(==> [::events/edit-user [:permissions :all-types?] %])}] ;; Permission to all cities? [lui/checkbox {:label (tr :lipas.user.permissions/all-cities?) :value (-> user :permissions :all-cities?) :on-change #(==> [::events/edit-user [:permissions :all-cities?] %])}] ;; Permission to individual spoorts-sites [lui/autocomplete {:items sites :label (tr :lipas.user.permissions/sports-sites) :value (-> user :permissions :sports-sites) :on-change #(==> [::events/edit-user [:permissions :sports-sites] %])}] ;; Permission to individual types [lui/autocomplete {:items types :label (tr :lipas.user.permissions/types) :value (-> user :permissions :types) :on-change #(==> [::events/edit-user [:permissions :types] %])}] ;; Permission to individual cities [lui/autocomplete {:items cities :label (tr :lipas.user.permissions/cities) :value (-> user :permissions :cities) :on-change #(==> [::events/edit-user [:permissions :cities] %])}]]] ;;; History [lui/form-card {:title (tr :lipas.user/history)} [lui/table-v2 {:items history :headers {:event {:label (tr :general/event)} :event-date {:label (tr :time/time)}}}]]]])) (defn color-picker [{:keys [value on-change]}] [:input {:type "color" :value value :on-change #(on-change (-> % .-target .-value))}]) (defn color-selector [] (let [new-colors (<== [::subs/selected-colors]) pick-color (fn [k1 k2 v] (==> [::events/select-color k1 k2 v])) types (<== [:lipas.ui.sports-sites.subs/all-types])] [mui/table [mui/table-head [mui/table-row [mui/table-cell "Type-code"] [mui/table-cell "Type-name"] [mui/table-cell "Geometry"] [mui/table-cell "Old symbol"] [mui/table-cell "New symbol"] [mui/table-cell "Old-fill"] [mui/table-cell "New-fill"] [mui/table-cell "Old-stroke"] [mui/table-cell "New-stroke"]]] (into [mui/table-body] (for [[type-code type] (sort-by first types) :let [shape (-> type-code types :geometry-type) fill (-> type-code styles/temp-symbols :fill) stroke (-> type-code styles/temp-symbols :stroke)]] [mui/table-row [mui/table-cell type-code] [mui/table-cell (-> type :name :fi)] [mui/table-cell shape] ;; Old symbol [mui/table-cell (condp = shape "Point" "Circle" shape)] ;; New symbol [mui/table-cell (condp = shape "Point" [lui/select {:items [{:label "Circle" :value "circle"} {:label "Square" :value "square"}] :value (or (-> type-code new-colors :symbol) "circle") :on-change (partial pick-color type-code :symbol)}] shape)] ;; Old fill [mui/table-cell [color-picker {:value fill :on-change #()}]] ;; New fill [mui/table-cell [mui/grid {:container true :wrap "nowrap"} [mui/grid {:item true} [color-picker {:value (-> (new-colors type-code) :fill) :on-change (partial pick-color type-code :fill)}]] [mui/grid {:item true} [mui/button {:size :small :on-click #(pick-color type-code :fill fill)} "reset"]]]] ;; Old stroke [mui/table-cell [color-picker {:value stroke :on-change #()}]] ;; New stroke [mui/table-cell [mui/grid {:container true :wrap "nowrap"} [mui/grid {:item true} [color-picker {:value (-> (new-colors type-code) :stroke) :on-change (partial pick-color type-code :stroke)}]] [mui/grid {:item true} [mui/button {:size :small :on-click #(pick-color type-code :stroke stroke)} "reset"]]]]]))])) (defn type-codes-view [] (let [types (<== [:lipas.ui.sports-sites.subs/type-table])] [mui/card {:square true} [mui/card-content [mui/typography {:variant "h5"} "Tyyppikoodit"] [lui/table {:hide-action-btn? true :headers [[:type-code "Tyyppikoodi"] [:name "PI:NAME:<NAME>END_PI"] [:main-category "Pääluokka"] [:sub-category "Alaluokka"] [:description "Kuvaus"] [:geometry-type "Geometria"]] :sort-fn :type-code :items types :on-select #(js/alert "Ei tee mitään vielä...")}]]])) (defn admin-panel [] (let [tr (<== [:lipas.ui.subs/translator]) status (<== [::subs/users-status]) users (<== [::subs/users-list]) users-filter (<== [::subs/users-filter]) selected-tab (<== [::subs/selected-tab])] [mui/grid {:container true} [mui/grid {:item true :xs 12} [mui/tool-bar [mui/tabs {:value selected-tab :on-change #(==> [::events/select-tab %2])} [mui/tab {:label (tr :lipas.admin/users)}] [mui/tab {:label "Symbolityökalu"}] [mui/tab {:label "Tyyppikoodit"}]]] (when (= 1 selected-tab) [:<> [color-selector] [mui/fab {:style {:position "sticky" :bottom "1em" :left "1em"} :variant "extended" :color "secondary" :on-click #(==> [::events/download-new-colors-excel])} [mui/icon "save"] "Lataa"]]) (when (= 0 selected-tab) [mui/card {:square true} [mui/card-content [mui/typography {:variant "h5"} (tr :lipas.admin/users)] ;; Full-screen user dialog [user-dialog tr] [mui/grid {:container true :spacing 32} ;; Add user button [mui/grid {:item true :style {:flex-grow 1}} [mui/fab {:color "secondary" :size "small" :style {:margin-top "1em"} :on-click #(==> [::events/edit-user [:email] "PI:EMAIL:<EMAIL>END_PI"])} [mui/icon "add"]]] ;; Status selector [mui/grid {:item true} [lui/select {:style {:width "150px"} :label "Status" :value status :items ["active" "archived"] :value-fn identity :label-fn identity :on-change #(==> [::events/select-status %])}]] ;; Users filter [mui/grid {:item true} [lui/text-field {:label (tr :search/search) :on-change #(==> [::events/filter-users %]) :value users-filter}]]] ;; Users table [lui/table {:headers [[:email (tr :lipas.user/email)] [:firstname (tr :lipas.user/firstname)] [:lastname (tr :lipas.user/lastname)] [:sports-sites (tr :lipas.user.permissions/sports-sites)] [:cities (tr :lipas.user.permissions/cities)] [:types (tr :lipas.user.permissions/types)]] :sort-fn :email :items users :on-select #(==> [::events/set-user-to-edit %])}]]]) (when (= 2 selected-tab) [type-codes-view])]])) (defn main [] (let [admin? (<== [:lipas.ui.user.subs/admin?])] (if admin? [admin-panel] (==> [:lipas.ui.events/navigate "/"]))))
[ { "context": "t [fd (select-api-version 520)\n key \\\"foo\\\"\n value \\\"bar\\\"]\n (with-open [db (open", "end": 1860, "score": 0.7748504281044006, "start": 1857, "tag": "KEY", "value": "foo" }, { "context": " (let [fd (select-api-version 520)\n key \\\"foo\\\"]\n (with-open [db (open fd)]\n (tr! db\n ", "end": 2436, "score": 0.9703758358955383, "start": 2433, "tag": "KEY", "value": "foo" }, { "context": "et [fd (select-api-version 520)\n key \\\"foo\\\"\n value [1 2 3]]\n (with-open [db (open fd", "end": 2569, "score": 0.9673874974250793, "start": 2566, "tag": "KEY", "value": "foo" }, { "context": " [fd (select-api-version 520)\n keys [\\\"foo\\\" \\\"baz\\\"]\n value \\\"bar\\\"]\n (with-open [db ", "end": 3967, "score": 0.8686540126800537, "start": 3962, "tag": "KEY", "value": "foo\\\"" }, { "context": "(select-api-version 520)\n keys [\\\"foo\\\" \\\"baz\\\"]\n value \\\"bar\\\"]\n (with-open [db (open fd)", "end": 3976, "score": 0.7491801977157593, "start": 3970, "tag": "KEY", "value": "baz\\\"]" }, { "context": " (let [fd (select-api-version 520)\n key \\\"foo\\\"]\n (with-open [db (open fd)]\n (tr! db (firs", "end": 10153, "score": 0.969831645488739, "start": 10150, "tag": "KEY", "value": "foo" } ]
src/clj_foundationdb/core.clj
tirkarthi/clj-foundationdb
16
(ns clj-foundationdb.core (:require [clojure.spec.alpha :as spec] [clj-foundationdb.utils :refer :all]) (:import (com.apple.foundationdb Database FDB Range KeySelector Transaction) (com.apple.foundationdb.tuple Tuple) (com.apple.foundationdb.subspace Subspace) (java.util List))) (def tr? #(instance? com.apple.foundationdb.Database %1)) ;; Refer https://github.com/apple/foundationdb/blob/e0c8175f3ccad92c582a3e70e9bcae58fff53633/bindings/java/src/main/com/apple/foundationdb/tuple/TupleUtil.java#L171 (def serializable? #(or (number? %1) (string? %1) (decimal? %1) (instance? List %1))) (defmacro tr! "Transaction macro to perform actions. Always use tr for actions inside each action since the transaction variable is bound to tr in the functions. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (set-val tr key value) (get-val tr key)))) ``` " [db & actions] `(.run ~db (reify java.util.function.Function (apply [this tr] ~@actions)))) (def ^:dynamic *subspace* nil) (defn make-subspace " Returns a key with name as prefix ``` (make-subspace [\"class\" \"intro\"] [\"algebra\"]) returns (\"class\" \"intro\" \"algebra\") ``` " [prefix key] (flatten (map vector [prefix key]))) (defmacro with-subspace " Sets and gets the keys with the given subspace key prefixed. This essentially executes with code binding the given prefix to *subspace*. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (clear-all tr) (with-subspace \"class\" (set-val tr key value) (get-val tr key)) (nil? (get-val tr key))))) ``` " [prefix & actions] `(binding [*subspace* ~prefix] ~@actions)) (defn get-val "Get the value for the given key. Accepts the below : :subspace - Subspace to be prefixed :coll - Boolean to indicate if the value needs to be deserialized as collection ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (get-val tr key)))) (let [fd (select-api-version 520) key \"foo\" value [1 2 3]] (with-open [db (open fd)] (tr! db (set-val tr key value) (get-val tr key) ;; 1 (get-val tr key :coll true)))) ;; [1 2 3] ``` " [tr key & {:keys [subspace coll] :or {subspace *subspace* coll false}}] (let [key (-> (if subspace (make-subspace subspace key) key) key->packed-tuple)] (if-let [value @(.get tr key)] (if coll (.getItems (Tuple/fromBytes value)) (.get (Tuple/fromBytes value) 0))))) (spec/fdef get-val :args (spec/cat :tr tr? :key serializable?) :ret (spec/nilable serializable?)) (defn set-val "Set a value for the key. Accepts the below : :subspace - Subspace to be prefixed ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (set-val tr key value)))) ``` " [tr key value & {:keys [subspace] :or {subspace *subspace*}}] (let [key (-> (if subspace (make-subspace subspace key) key) key->packed-tuple) value (key->packed-tuple value)] (.set tr key value))) (spec/fdef set-val :args (spec/cat :tr tr? :key serializable? :value serializable?) :ret (spec/nilable serializable?)) (defn set-keys "Set given keys with the value ``` (let [fd (select-api-version 520) keys [\"foo\" \"baz\"] value \"bar\"] (with-open [db (open fd)] (tr! db (set-keys tr keys value)))) ``` " [tr keys value] (let [keys (map #(key->packed-tuple %1) keys) value (key->packed-tuple value)] (doseq [key keys] (.set tr key value)))) (spec/fdef set-keys :args (spec/cat :tr tr? :key (spec/coll-of serializable?) :value serializable?)) (defn clear-key "Clear a key from the database ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (clear-key tr key)))) ``` " [tr key] (let [key (key->packed-tuple key)] (.clear tr key))) (spec/fdef clear-key :args (spec/cat :tr tr? :key serializable?)) (defn get-range-startswith "Get a range of key values as a vector that starts with prefix ``` (let [fd (select-api-version 520) prefix \"f\"] (with-open [db (open fd)] (tr! db (get-range-startswith tr key prefix)))) ``` " [tr prefix] (let [prefix (key->packed-tuple prefix) range-query (Range/startsWith prefix)] (->> (.getRange tr range-query) range->kv))) (spec/fdef get-range-startswith :args (spec/cat :tr tr? :prefix serializable?)) (defn watch " A key to watch and a callback function to be executed on change. It returns a future object that is realized when there is a change to key. Change in key value or clearing the key is noted as a change. A set statement with the old value is not a change. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (clear-key tr key) (watch tr key #(println \"key is set\")) (set-val tr key value) (watch tr key #(println \"key is changed to 1\")) (set-val tr key value) ;; Doesn't trigger watch (set-val tr key \"1\") (watch tr key #(println \"cleared key\")) (clear-key tr key)))) ``` key is set key is changed to 1 cleared key " [tr key callback] (let [key (key->packed-tuple key) watch (.watch tr key)] (future (do (.join watch) (callback))))) (spec/fdef watch :args (spec/cat :tr tr? :key serializable? :callback ifn?)) (defn get-range "Get a range of key values as a vector ``` (let [fd (select-api-version 520) begin \"foo\" end \"foo\"] (with-open [db (open fd)] (tr! db (get-range tr begin end)))) ``` " ([tr begin] (let [begin (Tuple/from (to-array (if (sequential? begin) begin [begin]))) range-query (.getRange tr (.range begin))] (range->kv range-query))) ([tr begin end] (let [begin (key->packed-tuple begin) end (key->packed-tuple end) range-query (.getRange tr (Range. begin end))] (range->kv range-query)))) (spec/fdef get-range :args (spec/cat :tr tr? :begin serializable? :end serializable?)) ;; https://stackoverflow.com/a/21421524/2610955 ;; Refer : https://forums.foundationdb.org/t/how-to-clear-all-keys-in-foundationdb-using-java/351/2 (defn get-all "Get all key values as a vector" [tr] (let [begin (byte-array []) end (byte-array [0xFF]) range-query (.getRange tr (Range. begin end))] (range->kv range-query))) (spec/fdef get-all :args (spec/cat :tr tr?)) (defn clear-range "Clear a range of keys from the database. When only begin is given then the keys with starting with the tuple are cleared. When begin and end are specified then end is exclusive of the range to be cleared. ``` (let [fd (select-api-version 520) begin \"foo\"] (with-open [db (open fd)] (tr! db (clear-range tr begin)))) (let [fd (select-api-version 520) begin \"foo\" end \"foo\"] (with-open [db (open fd)] (tr! db (clear-range tr begin end)))) ``` " ([tr begin] (let [begin (key->tuple begin)] (.clear tr (.range begin)))) ([tr begin end] (let [begin (key->packed-tuple begin) end (key->packed-tuple end)] (.clear tr (Range. begin end))))) (spec/fdef clear-range :args (spec/cat :tr tr? :begin serializable? :end serializable?)) ;; https://stackoverflow.com/a/21421524/2610955 ;; Refer : https://forums.foundationdb.org/t/how-to-clear-all-keys-in-foundationdb-using-java/351/2 (defn clear-all "Clear all keys from the database" [tr] (let [begin (byte-array []) end (byte-array [0xFF])] (.clear tr (Range. begin end)))) (spec/fdef clear-all :args (spec/cat :tr tr?)) (defn last-less-than "Returns key and value pairs with keys less than the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (last-less-than tr key)))) ``` " ([tr key] (last-less-than tr key 1)) ([tr key limit] (let [key (KeySelector/lastLessThan (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef last-less-than :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn last-less-or-equal "Returns key and value pairs with keys less than or equal the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (last-less-or-equal tr key)))) ``` " ([tr key] (last-less-or-equal tr key 1)) ([tr key limit] (let [key (KeySelector/lastLessOrEqual (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef last-less-or-equal :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn first-greater-than "Returns key and value pairs with keys greater than the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (first-greater-than tr key)))) ``` " ([tr key] (first-greater-than tr key 1)) ([tr key limit] (let [key (KeySelector/firstGreaterThan (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef first-greater-than :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn first-greater-or-equal "Returns key and value pairs with keys greater than or equal to the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (first-greater-or-equal tr key)))) ``` " ([tr key] (first-greater-or-equal tr key 1)) ([tr key limit] (let [key (KeySelector/firstGreaterOrEqual (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef first-greater-or-equal :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?)))
119345
(ns clj-foundationdb.core (:require [clojure.spec.alpha :as spec] [clj-foundationdb.utils :refer :all]) (:import (com.apple.foundationdb Database FDB Range KeySelector Transaction) (com.apple.foundationdb.tuple Tuple) (com.apple.foundationdb.subspace Subspace) (java.util List))) (def tr? #(instance? com.apple.foundationdb.Database %1)) ;; Refer https://github.com/apple/foundationdb/blob/e0c8175f3ccad92c582a3e70e9bcae58fff53633/bindings/java/src/main/com/apple/foundationdb/tuple/TupleUtil.java#L171 (def serializable? #(or (number? %1) (string? %1) (decimal? %1) (instance? List %1))) (defmacro tr! "Transaction macro to perform actions. Always use tr for actions inside each action since the transaction variable is bound to tr in the functions. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (set-val tr key value) (get-val tr key)))) ``` " [db & actions] `(.run ~db (reify java.util.function.Function (apply [this tr] ~@actions)))) (def ^:dynamic *subspace* nil) (defn make-subspace " Returns a key with name as prefix ``` (make-subspace [\"class\" \"intro\"] [\"algebra\"]) returns (\"class\" \"intro\" \"algebra\") ``` " [prefix key] (flatten (map vector [prefix key]))) (defmacro with-subspace " Sets and gets the keys with the given subspace key prefixed. This essentially executes with code binding the given prefix to *subspace*. ``` (let [fd (select-api-version 520) key \"<KEY>\" value \"bar\"] (with-open [db (open fd)] (tr! db (clear-all tr) (with-subspace \"class\" (set-val tr key value) (get-val tr key)) (nil? (get-val tr key))))) ``` " [prefix & actions] `(binding [*subspace* ~prefix] ~@actions)) (defn get-val "Get the value for the given key. Accepts the below : :subspace - Subspace to be prefixed :coll - Boolean to indicate if the value needs to be deserialized as collection ``` (let [fd (select-api-version 520) key \"<KEY>\"] (with-open [db (open fd)] (tr! db (get-val tr key)))) (let [fd (select-api-version 520) key \"<KEY>\" value [1 2 3]] (with-open [db (open fd)] (tr! db (set-val tr key value) (get-val tr key) ;; 1 (get-val tr key :coll true)))) ;; [1 2 3] ``` " [tr key & {:keys [subspace coll] :or {subspace *subspace* coll false}}] (let [key (-> (if subspace (make-subspace subspace key) key) key->packed-tuple)] (if-let [value @(.get tr key)] (if coll (.getItems (Tuple/fromBytes value)) (.get (Tuple/fromBytes value) 0))))) (spec/fdef get-val :args (spec/cat :tr tr? :key serializable?) :ret (spec/nilable serializable?)) (defn set-val "Set a value for the key. Accepts the below : :subspace - Subspace to be prefixed ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (set-val tr key value)))) ``` " [tr key value & {:keys [subspace] :or {subspace *subspace*}}] (let [key (-> (if subspace (make-subspace subspace key) key) key->packed-tuple) value (key->packed-tuple value)] (.set tr key value))) (spec/fdef set-val :args (spec/cat :tr tr? :key serializable? :value serializable?) :ret (spec/nilable serializable?)) (defn set-keys "Set given keys with the value ``` (let [fd (select-api-version 520) keys [\"<KEY> \"<KEY> value \"bar\"] (with-open [db (open fd)] (tr! db (set-keys tr keys value)))) ``` " [tr keys value] (let [keys (map #(key->packed-tuple %1) keys) value (key->packed-tuple value)] (doseq [key keys] (.set tr key value)))) (spec/fdef set-keys :args (spec/cat :tr tr? :key (spec/coll-of serializable?) :value serializable?)) (defn clear-key "Clear a key from the database ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (clear-key tr key)))) ``` " [tr key] (let [key (key->packed-tuple key)] (.clear tr key))) (spec/fdef clear-key :args (spec/cat :tr tr? :key serializable?)) (defn get-range-startswith "Get a range of key values as a vector that starts with prefix ``` (let [fd (select-api-version 520) prefix \"f\"] (with-open [db (open fd)] (tr! db (get-range-startswith tr key prefix)))) ``` " [tr prefix] (let [prefix (key->packed-tuple prefix) range-query (Range/startsWith prefix)] (->> (.getRange tr range-query) range->kv))) (spec/fdef get-range-startswith :args (spec/cat :tr tr? :prefix serializable?)) (defn watch " A key to watch and a callback function to be executed on change. It returns a future object that is realized when there is a change to key. Change in key value or clearing the key is noted as a change. A set statement with the old value is not a change. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (clear-key tr key) (watch tr key #(println \"key is set\")) (set-val tr key value) (watch tr key #(println \"key is changed to 1\")) (set-val tr key value) ;; Doesn't trigger watch (set-val tr key \"1\") (watch tr key #(println \"cleared key\")) (clear-key tr key)))) ``` key is set key is changed to 1 cleared key " [tr key callback] (let [key (key->packed-tuple key) watch (.watch tr key)] (future (do (.join watch) (callback))))) (spec/fdef watch :args (spec/cat :tr tr? :key serializable? :callback ifn?)) (defn get-range "Get a range of key values as a vector ``` (let [fd (select-api-version 520) begin \"foo\" end \"foo\"] (with-open [db (open fd)] (tr! db (get-range tr begin end)))) ``` " ([tr begin] (let [begin (Tuple/from (to-array (if (sequential? begin) begin [begin]))) range-query (.getRange tr (.range begin))] (range->kv range-query))) ([tr begin end] (let [begin (key->packed-tuple begin) end (key->packed-tuple end) range-query (.getRange tr (Range. begin end))] (range->kv range-query)))) (spec/fdef get-range :args (spec/cat :tr tr? :begin serializable? :end serializable?)) ;; https://stackoverflow.com/a/21421524/2610955 ;; Refer : https://forums.foundationdb.org/t/how-to-clear-all-keys-in-foundationdb-using-java/351/2 (defn get-all "Get all key values as a vector" [tr] (let [begin (byte-array []) end (byte-array [0xFF]) range-query (.getRange tr (Range. begin end))] (range->kv range-query))) (spec/fdef get-all :args (spec/cat :tr tr?)) (defn clear-range "Clear a range of keys from the database. When only begin is given then the keys with starting with the tuple are cleared. When begin and end are specified then end is exclusive of the range to be cleared. ``` (let [fd (select-api-version 520) begin \"foo\"] (with-open [db (open fd)] (tr! db (clear-range tr begin)))) (let [fd (select-api-version 520) begin \"foo\" end \"foo\"] (with-open [db (open fd)] (tr! db (clear-range tr begin end)))) ``` " ([tr begin] (let [begin (key->tuple begin)] (.clear tr (.range begin)))) ([tr begin end] (let [begin (key->packed-tuple begin) end (key->packed-tuple end)] (.clear tr (Range. begin end))))) (spec/fdef clear-range :args (spec/cat :tr tr? :begin serializable? :end serializable?)) ;; https://stackoverflow.com/a/21421524/2610955 ;; Refer : https://forums.foundationdb.org/t/how-to-clear-all-keys-in-foundationdb-using-java/351/2 (defn clear-all "Clear all keys from the database" [tr] (let [begin (byte-array []) end (byte-array [0xFF])] (.clear tr (Range. begin end)))) (spec/fdef clear-all :args (spec/cat :tr tr?)) (defn last-less-than "Returns key and value pairs with keys less than the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (last-less-than tr key)))) ``` " ([tr key] (last-less-than tr key 1)) ([tr key limit] (let [key (KeySelector/lastLessThan (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef last-less-than :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn last-less-or-equal "Returns key and value pairs with keys less than or equal the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (last-less-or-equal tr key)))) ``` " ([tr key] (last-less-or-equal tr key 1)) ([tr key limit] (let [key (KeySelector/lastLessOrEqual (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef last-less-or-equal :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn first-greater-than "Returns key and value pairs with keys greater than the given key for the given limit ``` (let [fd (select-api-version 520) key \"<KEY>\"] (with-open [db (open fd)] (tr! db (first-greater-than tr key)))) ``` " ([tr key] (first-greater-than tr key 1)) ([tr key limit] (let [key (KeySelector/firstGreaterThan (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef first-greater-than :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn first-greater-or-equal "Returns key and value pairs with keys greater than or equal to the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (first-greater-or-equal tr key)))) ``` " ([tr key] (first-greater-or-equal tr key 1)) ([tr key limit] (let [key (KeySelector/firstGreaterOrEqual (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef first-greater-or-equal :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?)))
true
(ns clj-foundationdb.core (:require [clojure.spec.alpha :as spec] [clj-foundationdb.utils :refer :all]) (:import (com.apple.foundationdb Database FDB Range KeySelector Transaction) (com.apple.foundationdb.tuple Tuple) (com.apple.foundationdb.subspace Subspace) (java.util List))) (def tr? #(instance? com.apple.foundationdb.Database %1)) ;; Refer https://github.com/apple/foundationdb/blob/e0c8175f3ccad92c582a3e70e9bcae58fff53633/bindings/java/src/main/com/apple/foundationdb/tuple/TupleUtil.java#L171 (def serializable? #(or (number? %1) (string? %1) (decimal? %1) (instance? List %1))) (defmacro tr! "Transaction macro to perform actions. Always use tr for actions inside each action since the transaction variable is bound to tr in the functions. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (set-val tr key value) (get-val tr key)))) ``` " [db & actions] `(.run ~db (reify java.util.function.Function (apply [this tr] ~@actions)))) (def ^:dynamic *subspace* nil) (defn make-subspace " Returns a key with name as prefix ``` (make-subspace [\"class\" \"intro\"] [\"algebra\"]) returns (\"class\" \"intro\" \"algebra\") ``` " [prefix key] (flatten (map vector [prefix key]))) (defmacro with-subspace " Sets and gets the keys with the given subspace key prefixed. This essentially executes with code binding the given prefix to *subspace*. ``` (let [fd (select-api-version 520) key \"PI:KEY:<KEY>END_PI\" value \"bar\"] (with-open [db (open fd)] (tr! db (clear-all tr) (with-subspace \"class\" (set-val tr key value) (get-val tr key)) (nil? (get-val tr key))))) ``` " [prefix & actions] `(binding [*subspace* ~prefix] ~@actions)) (defn get-val "Get the value for the given key. Accepts the below : :subspace - Subspace to be prefixed :coll - Boolean to indicate if the value needs to be deserialized as collection ``` (let [fd (select-api-version 520) key \"PI:KEY:<KEY>END_PI\"] (with-open [db (open fd)] (tr! db (get-val tr key)))) (let [fd (select-api-version 520) key \"PI:KEY:<KEY>END_PI\" value [1 2 3]] (with-open [db (open fd)] (tr! db (set-val tr key value) (get-val tr key) ;; 1 (get-val tr key :coll true)))) ;; [1 2 3] ``` " [tr key & {:keys [subspace coll] :or {subspace *subspace* coll false}}] (let [key (-> (if subspace (make-subspace subspace key) key) key->packed-tuple)] (if-let [value @(.get tr key)] (if coll (.getItems (Tuple/fromBytes value)) (.get (Tuple/fromBytes value) 0))))) (spec/fdef get-val :args (spec/cat :tr tr? :key serializable?) :ret (spec/nilable serializable?)) (defn set-val "Set a value for the key. Accepts the below : :subspace - Subspace to be prefixed ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (set-val tr key value)))) ``` " [tr key value & {:keys [subspace] :or {subspace *subspace*}}] (let [key (-> (if subspace (make-subspace subspace key) key) key->packed-tuple) value (key->packed-tuple value)] (.set tr key value))) (spec/fdef set-val :args (spec/cat :tr tr? :key serializable? :value serializable?) :ret (spec/nilable serializable?)) (defn set-keys "Set given keys with the value ``` (let [fd (select-api-version 520) keys [\"PI:KEY:<KEY>END_PI \"PI:KEY:<KEY>END_PI value \"bar\"] (with-open [db (open fd)] (tr! db (set-keys tr keys value)))) ``` " [tr keys value] (let [keys (map #(key->packed-tuple %1) keys) value (key->packed-tuple value)] (doseq [key keys] (.set tr key value)))) (spec/fdef set-keys :args (spec/cat :tr tr? :key (spec/coll-of serializable?) :value serializable?)) (defn clear-key "Clear a key from the database ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (clear-key tr key)))) ``` " [tr key] (let [key (key->packed-tuple key)] (.clear tr key))) (spec/fdef clear-key :args (spec/cat :tr tr? :key serializable?)) (defn get-range-startswith "Get a range of key values as a vector that starts with prefix ``` (let [fd (select-api-version 520) prefix \"f\"] (with-open [db (open fd)] (tr! db (get-range-startswith tr key prefix)))) ``` " [tr prefix] (let [prefix (key->packed-tuple prefix) range-query (Range/startsWith prefix)] (->> (.getRange tr range-query) range->kv))) (spec/fdef get-range-startswith :args (spec/cat :tr tr? :prefix serializable?)) (defn watch " A key to watch and a callback function to be executed on change. It returns a future object that is realized when there is a change to key. Change in key value or clearing the key is noted as a change. A set statement with the old value is not a change. ``` (let [fd (select-api-version 520) key \"foo\" value \"bar\"] (with-open [db (open fd)] (tr! db (clear-key tr key) (watch tr key #(println \"key is set\")) (set-val tr key value) (watch tr key #(println \"key is changed to 1\")) (set-val tr key value) ;; Doesn't trigger watch (set-val tr key \"1\") (watch tr key #(println \"cleared key\")) (clear-key tr key)))) ``` key is set key is changed to 1 cleared key " [tr key callback] (let [key (key->packed-tuple key) watch (.watch tr key)] (future (do (.join watch) (callback))))) (spec/fdef watch :args (spec/cat :tr tr? :key serializable? :callback ifn?)) (defn get-range "Get a range of key values as a vector ``` (let [fd (select-api-version 520) begin \"foo\" end \"foo\"] (with-open [db (open fd)] (tr! db (get-range tr begin end)))) ``` " ([tr begin] (let [begin (Tuple/from (to-array (if (sequential? begin) begin [begin]))) range-query (.getRange tr (.range begin))] (range->kv range-query))) ([tr begin end] (let [begin (key->packed-tuple begin) end (key->packed-tuple end) range-query (.getRange tr (Range. begin end))] (range->kv range-query)))) (spec/fdef get-range :args (spec/cat :tr tr? :begin serializable? :end serializable?)) ;; https://stackoverflow.com/a/21421524/2610955 ;; Refer : https://forums.foundationdb.org/t/how-to-clear-all-keys-in-foundationdb-using-java/351/2 (defn get-all "Get all key values as a vector" [tr] (let [begin (byte-array []) end (byte-array [0xFF]) range-query (.getRange tr (Range. begin end))] (range->kv range-query))) (spec/fdef get-all :args (spec/cat :tr tr?)) (defn clear-range "Clear a range of keys from the database. When only begin is given then the keys with starting with the tuple are cleared. When begin and end are specified then end is exclusive of the range to be cleared. ``` (let [fd (select-api-version 520) begin \"foo\"] (with-open [db (open fd)] (tr! db (clear-range tr begin)))) (let [fd (select-api-version 520) begin \"foo\" end \"foo\"] (with-open [db (open fd)] (tr! db (clear-range tr begin end)))) ``` " ([tr begin] (let [begin (key->tuple begin)] (.clear tr (.range begin)))) ([tr begin end] (let [begin (key->packed-tuple begin) end (key->packed-tuple end)] (.clear tr (Range. begin end))))) (spec/fdef clear-range :args (spec/cat :tr tr? :begin serializable? :end serializable?)) ;; https://stackoverflow.com/a/21421524/2610955 ;; Refer : https://forums.foundationdb.org/t/how-to-clear-all-keys-in-foundationdb-using-java/351/2 (defn clear-all "Clear all keys from the database" [tr] (let [begin (byte-array []) end (byte-array [0xFF])] (.clear tr (Range. begin end)))) (spec/fdef clear-all :args (spec/cat :tr tr?)) (defn last-less-than "Returns key and value pairs with keys less than the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (last-less-than tr key)))) ``` " ([tr key] (last-less-than tr key 1)) ([tr key limit] (let [key (KeySelector/lastLessThan (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef last-less-than :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn last-less-or-equal "Returns key and value pairs with keys less than or equal the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (last-less-or-equal tr key)))) ``` " ([tr key] (last-less-or-equal tr key 1)) ([tr key limit] (let [key (KeySelector/lastLessOrEqual (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef last-less-or-equal :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn first-greater-than "Returns key and value pairs with keys greater than the given key for the given limit ``` (let [fd (select-api-version 520) key \"PI:KEY:<KEY>END_PI\"] (with-open [db (open fd)] (tr! db (first-greater-than tr key)))) ``` " ([tr key] (first-greater-than tr key 1)) ([tr key limit] (let [key (KeySelector/firstGreaterThan (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef first-greater-than :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?))) (defn first-greater-or-equal "Returns key and value pairs with keys greater than or equal to the given key for the given limit ``` (let [fd (select-api-version 520) key \"foo\"] (with-open [db (open fd)] (tr! db (first-greater-or-equal tr key)))) ``` " ([tr key] (first-greater-or-equal tr key 1)) ([tr key limit] (let [key (KeySelector/firstGreaterOrEqual (key->packed-tuple key)) end (.add key limit) range-query (.getRange tr key end)] (range->kv range-query)))) (spec/fdef first-greater-or-equal :args (spec/cat :tr tr? :key serializable? :limit (spec/? pos-int?)) :ret (spec/coll-of (spec/tuple serializable? serializable?)))
[ { "context": "lojure.\"))\n args))\n\n;; https://github.com/bhb/expound/issues/8\n(deftest expound-output-ends-in-", "end": 1341, "score": 0.9994348883628845, "start": 1338, "tag": "USERNAME", "value": "bhb" }, { "context": " (expound/expound-str :and-spec/names [\"bob\" \"sally\" \"\" 1])))))\n\n(s/def :coll-of-spec/big-int-coll (s", "end": 7628, "score": 0.9948887825012207, "start": 7623, "tag": "NAME", "value": "sally" }, { "context": "= (pf \"-- Spec failed --------------------\n\n {\\\"Sally\\\" \\\"30\\\"}\n ^^^^\n\nshould satisfy\n\n pos-", "end": 16098, "score": 0.6311385035514832, "start": 16094, "tag": "NAME", "value": "ally" }, { "context": " (expound/expound-str :map-of-spec/name->age {\"Sally\" \"30\"})))\n (is (= (pf \"-- Spec failed ----------", "end": 16410, "score": 0.9701312184333801, "start": 16405, "tag": "NAME", "value": "Sally" } ]
data/test/clojure/84c700e06159320f16617b4e09ac4babe4c7a11dalpha_test.cljc
harshp8l/deep-learning-lang-detection
84
(ns expound.alpha-test (:require #?@(:clj ;; just to include the specs [[clojure.core.specs.alpha] [ring.core.spec] [onyx.spec]]) [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.string :as string] [clojure.test :as ct :refer [is testing deftest use-fixtures]] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [com.gfredericks.test.chuck.properties :as properties] [com.stuartsierra.dependency :as deps] [expound.alpha :as expound] [expound.printer :as printer] [expound.test-utils :as test-utils] #?(:clj [orchestra.spec.test :as orch.st] :cljs [orchestra-cljs.spec.test :as orch.st]))) (use-fixtures :once test-utils/check-spec-assertions test-utils/instrument-all) (def any-printable-wo-nan (gen/such-that (complement test-utils/contains-nan?) gen/any-printable)) (defn pf "Fixes platform-specific namespaces and also formats using printf syntax" [s & args] (apply printer/format #?(:cljs (string/replace s "pf." "cljs.") :clj (string/replace s "pf." "clojure.")) args)) ;; https://github.com/bhb/expound/issues/8 (deftest expound-output-ends-in-newline (is (= "\n" (str (last (expound/expound-str string? 1))))) (is (= "\n" (str (last (expound/expound-str string? "")))))) (deftest expound-prints-expound-str (is (= (expound/expound-str string? 1) (with-out-str (expound/expound string? 1))))) (deftest pprint-fn (is (= "string?" (expound/pprint-fn (::s/spec (s/explain-data string? 1))))) (is (= "expound.alpha/expound" (expound/pprint-fn expound/expound)))) (deftest predicate-spec (is (= (pf "-- Spec failed -------------------- 1 should satisfy string? ------------------------- Detected 1 error\n") (expound/expound-str string? 1)))) (s/def :simple-type-based-spec/str string?) (deftest simple-type-based-spec (testing "valid value" (is (= "Success!\n" (expound/expound-str :simple-type-based-spec/str "")))) (testing "invalid value" (is (= (pf "-- Spec failed -------------------- 1 should satisfy string? -- Relevant specs ------- :simple-type-based-spec/str: pf.core/string? ------------------------- Detected 1 error\n") (expound/expound-str :simple-type-based-spec/str 1))))) (s/def :set-based-spec/tag #{:foo :bar}) (s/def :set-based-spec/nilable-tag (s/nilable :set-based-spec/tag)) (s/def :set-based-spec/set-of-one #{:foobar}) (deftest set-based-spec (testing "prints valid options" (is (= "-- Spec failed -------------------- :baz should be one of: `:bar`,`:foo` -- Relevant specs ------- :set-based-spec/tag: #{:bar :foo} ------------------------- Detected 1 error\n" (expound/expound-str :set-based-spec/tag :baz)))) ;; FIXME - we should fix nilable and or specs better so they are clearly grouped (testing "nilable version" (is (= (pf "-- Spec failed -------------------- :baz should be one of: `:bar`,`:foo` -- Relevant specs ------- :set-based-spec/tag: #{:bar :foo} :set-based-spec/nilable-tag: (pf.spec.alpha/nilable :set-based-spec/tag) -- Spec failed -------------------- :baz should satisfy nil? -- Relevant specs ------- :set-based-spec/nilable-tag: (pf.spec.alpha/nilable :set-based-spec/tag) ------------------------- Detected 2 errors\n") (expound/expound-str :set-based-spec/nilable-tag :baz)))) (testing "single element spec" (is (= (pf "-- Spec failed -------------------- :baz should be: `:foobar` -- Relevant specs ------- :set-based-spec/set-of-one: #{:foobar} ------------------------- Detected 1 error\n") (expound/expound-str :set-based-spec/set-of-one :baz))))) (s/def :nested-type-based-spec/str string?) (s/def :nested-type-based-spec/strs (s/coll-of :nested-type-based-spec/str)) (deftest nested-type-based-spec (is (= (pf "-- Spec failed -------------------- [... ... 33] ^^ should satisfy string? -- Relevant specs ------- :nested-type-based-spec/str: pf.core/string? :nested-type-based-spec/strs: (pf.spec.alpha/coll-of :nested-type-based-spec/str) ------------------------- Detected 1 error\n") (expound/expound-str :nested-type-based-spec/strs ["one" "two" 33])))) (s/def :nested-type-based-spec-special-summary-string/int int?) (s/def :nested-type-based-spec-special-summary-string/ints (s/coll-of :nested-type-based-spec-special-summary-string/int)) (deftest nested-type-based-spec-special-summary-string (is (= (pf "-- Spec failed -------------------- [... ... \"...\"] ^^^^^ should satisfy int? -- Relevant specs ------- :nested-type-based-spec-special-summary-string/int: pf.core/int? :nested-type-based-spec-special-summary-string/ints: (pf.spec.alpha/coll-of :nested-type-based-spec-special-summary-string/int) ------------------------- Detected 1 error\n") (expound/expound-str :nested-type-based-spec-special-summary-string/ints [1 2 "..."])))) (s/def :or-spec/str-or-int (s/or :int int? :str string?)) (s/def :or-spec/vals (s/coll-of :or-spec/str-or-int)) (deftest or-spec (testing "simple value" (is (= (pf "-- Spec failed -------------------- :kw should satisfy int? or string? -- Relevant specs ------- :or-spec/str-or-int: (pf.spec.alpha/or :int pf.core/int? :str pf.core/string?) ------------------------- Detected 1 error\n") (expound/expound-str :or-spec/str-or-int :kw)))) (testing "collection of values" (is (= (pf "-- Spec failed -------------------- [... ... :kw ...] ^^^ should satisfy int? or string? -- Relevant specs ------- :or-spec/str-or-int: (pf.spec.alpha/or :int pf.core/int? :str pf.core/string?) :or-spec/vals: (pf.spec.alpha/coll-of :or-spec/str-or-int) ------------------------- Detected 1 error\n") (expound/expound-str :or-spec/vals [0 "hi" :kw "bye"]))))) (s/def :and-spec/name (s/and string? #(pos? (count %)))) (s/def :and-spec/names (s/coll-of :and-spec/name)) (deftest and-spec (testing "simple value" (is (= (pf "-- Spec failed -------------------- \"\" should satisfy %s -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) ------------------------- Detected 1 error\n" #?(:cljs "(fn [%] (pos? (count %)))" :clj "(fn [%] (pos? (count %)))")) (expound/expound-str :and-spec/name "")))) (testing "shows both failures in order" (is (= (pf "-- Spec failed -------------------- [... ... \"\" ...] ^^ should satisfy %s -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) :and-spec/names: (pf.spec.alpha/coll-of :and-spec/name) -- Spec failed -------------------- [... ... ... 1] ^ should satisfy string? -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) :and-spec/names: (pf.spec.alpha/coll-of :and-spec/name) ------------------------- Detected 2 errors\n" #?(:cljs "(fn [%] (pos? (count %)))" :clj "(fn [%] (pos? (count %)))")) (expound/expound-str :and-spec/names ["bob" "sally" "" 1]))))) (s/def :coll-of-spec/big-int-coll (s/coll-of int? :min-count 10)) (deftest coll-of-spec (testing "min count" (is (= (pf "-- Spec failed -------------------- [] should satisfy (<= 10 (count %%) %s) -- Relevant specs ------- :coll-of-spec/big-int-coll: (pf.spec.alpha/coll-of pf.core/int? :min-count 10) ------------------------- Detected 1 error\n" #?(:cljs "9007199254740991" :clj "Integer/MAX_VALUE")) (expound/expound-str :coll-of-spec/big-int-coll []))))) (s/def :cat-spec/kw (s/cat :k keyword? :v any?)) (deftest cat-spec (testing "too few elements" (is (= (pf "-- Syntax error ------------------- [] should have additional elements. The next element is named `:k` and satisfies keyword? -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw []))) (is (= (pf "-- Syntax error ------------------- [:foo] should have additional elements. The next element is named `:v` and satisfies any? -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw [:foo])))) (testing "too many elements" (is (= (pf "-- Syntax error ------------------- Value has extra input [... ... :bar ...] ^^^^ -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw [:foo 1 :bar :baz]))))) (s/def :keys-spec/name string?) (s/def :keys-spec/age int?) (s/def :keys-spec/user (s/keys :req [:keys-spec/name] :req-un [:keys-spec/age])) (deftest keys-spec (testing "missing keys" (is (= (pf "-- Spec failed -------------------- {} should contain keys: `:keys-spec/name`,`:age` -- Relevant specs ------- :keys-spec/user: %s ------------------------- Detected 1 error\n" #?(:cljs "(cljs.spec.alpha/keys :req [:keys-spec/name] :req-un [:keys-spec/age])" :clj "(clojure.spec.alpha/keys\n :req\n [:keys-spec/name]\n :req-un\n [:keys-spec/age])")) (expound/expound-str :keys-spec/user {})))) (testing "invalid key" (is (= (pf "-- Spec failed -------------------- {:age ..., :keys-spec/name :bob} ^^^^ should satisfy string? -- Relevant specs ------- :keys-spec/name: pf.core/string? :keys-spec/user: %s ------------------------- Detected 1 error\n" #?(:cljs "(cljs.spec.alpha/keys :req [:keys-spec/name] :req-un [:keys-spec/age])" :clj "(clojure.spec.alpha/keys\n :req\n [:keys-spec/name]\n :req-un\n [:keys-spec/age])")) (expound/expound-str :keys-spec/user {:age 1 :keys-spec/name :bob}))))) (s/def :multi-spec/value string?) (s/def :multi-spec/children vector?) (defmulti el-type :multi-spec/el-type) (defmethod el-type :text [x] (s/keys :req [:multi-spec/value])) (defmethod el-type :group [x] (s/keys :req [:multi-spec/children])) (s/def :multi-spec/el (s/multi-spec el-type :multi-spec/el-type)) (deftest multi-spec (testing "missing dispatch key" (is (= (pf "-- Missing spec ------------------- Cannot find spec for {} Spec multimethod: `expound.alpha-test/el-type` Dispatch function: `:multi-spec/el-type` Dispatch value: `nil` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {})))) (testing "invalid dispatch value" (is (= (pf "-- Missing spec ------------------- Cannot find spec for {:multi-spec/el-type :image} Spec multimethod: `expound.alpha-test/el-type` Dispatch function: `:multi-spec/el-type` Dispatch value: `:image` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {:multi-spec/el-type :image})))) (testing "valid dispatch value, but other error" (is (= (pf "-- Spec failed -------------------- {:multi-spec/el-type :text} should contain keys: `:multi-spec/value` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {:multi-spec/el-type :text}))))) (s/def :recursive-spec/tag #{:text :group}) (s/def :recursive-spec/on-tap (s/coll-of map? :kind vector?)) (s/def :recursive-spec/props (s/keys :opt-un [:recursive-spec/on-tap])) (s/def :recursive-spec/el (s/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])) (s/def :recursive-spec/children (s/coll-of (s/nilable :recursive-spec/el) :kind vector?)) (deftest recursive-spec (testing "only shows problem with data at 'leaves' (not problems with all parents in tree)" (is (= (pf "-- Spec failed -------------------- {:tag ..., :children [{:tag ..., :children [{:tag ..., :props {:on-tap {}}}]}]} ^^ should satisfy vector? -- Relevant specs ------- %s ------------------------- Detected 1 error\n" #?(:cljs ":recursive-spec/on-tap: (cljs.spec.alpha/coll-of cljs.core/map? :kind cljs.core/vector?) :recursive-spec/props: (cljs.spec.alpha/keys :opt-un [:recursive-spec/on-tap]) :recursive-spec/children: (cljs.spec.alpha/coll-of (cljs.spec.alpha/nilable :recursive-spec/el) :kind cljs.core/vector?) :recursive-spec/el: (cljs.spec.alpha/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])" :clj ":recursive-spec/on-tap: (clojure.spec.alpha/coll-of clojure.core/map? :kind clojure.core/vector?) :recursive-spec/props: (clojure.spec.alpha/keys :opt-un [:recursive-spec/on-tap]) :recursive-spec/children: (clojure.spec.alpha/coll-of (clojure.spec.alpha/nilable :recursive-spec/el) :kind clojure.core/vector?) :recursive-spec/el: (clojure.spec.alpha/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])")) (expound/expound-str :recursive-spec/el {:tag :group :children [{:tag :group :children [{:tag :group :props {:on-tap {}}}]}]}))))) (s/def :cat-wrapped-in-or-spec/kv (s/and sequential? (s/cat :k keyword? :v any?))) (s/def :cat-wrapped-in-or-spec/type #{:text}) (s/def :cat-wrapped-in-or-spec/kv-or-string (s/or :map (s/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv)) (deftest cat-wrapped-in-or-spec ;; FIXME - make multiple types of specs on the same value display as single error (is (= (pf "-- Spec failed -------------------- {\"foo\" \"hi\"} should contain keys: `:cat-wrapped-in-or-spec/type` -- Relevant specs ------- :cat-wrapped-in-or-spec/kv-or-string: (pf.spec.alpha/or :map (pf.spec.alpha/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv) -- Spec failed -------------------- {\"foo\" \"hi\"} should satisfy sequential? -- Relevant specs ------- :cat-wrapped-in-or-spec/kv: (pf.spec.alpha/and pf.core/sequential? (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?)) :cat-wrapped-in-or-spec/kv-or-string: (pf.spec.alpha/or :map (pf.spec.alpha/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv) ------------------------- Detected 2 errors\n") (expound/expound-str :cat-wrapped-in-or-spec/kv-or-string {"foo" "hi"})))) (s/def :map-of-spec/name string?) (s/def :map-of-spec/age pos-int?) (s/def :map-of-spec/name->age (s/map-of :map-of-spec/name :map-of-spec/age)) (deftest map-of-spec (is (= (pf "-- Spec failed -------------------- {\"Sally\" \"30\"} ^^^^ should satisfy pos-int? -- Relevant specs ------- :map-of-spec/age: pf.core/pos-int? :map-of-spec/name->age: (pf.spec.alpha/map-of :map-of-spec/name :map-of-spec/age) ------------------------- Detected 1 error\n") (expound/expound-str :map-of-spec/name->age {"Sally" "30"}))) (is (= (pf "-- Spec failed -------------------- {:sally ...} ^^^^^^ should satisfy string? -- Relevant specs ------- :map-of-spec/name: pf.core/string? :map-of-spec/name->age: (pf.spec.alpha/map-of :map-of-spec/name :map-of-spec/age) ------------------------- Detected 1 error\n") (expound/expound-str :map-of-spec/name->age {:sally 30})))) ;; I want to do something like ;; (s/def :specs.coll-of/into #{[] '() #{}}) ;; but Clojure (not Clojurescript) won't allow ;; this. As a workaround, I'll just use vectors instead ;; of vectors and lists. ;; TODO - force a specific type of into/kind one for each test ;; (one for vectors, one for lists, etc) (s/def :specs.coll-of/into #{[] #{}}) (s/def :specs.coll-of/kind #{vector? list? set?}) (s/def :specs.coll-of/count pos-int?) (s/def :specs.coll-of/max-count pos-int?) (s/def :specs.coll-of/min-count pos-int?) (s/def :specs.coll-of/distinct boolean?) (s/def :specs/every-args (s/keys :req-un [:specs.coll-of/into :specs.coll-of/kind :specs.coll-of/count :specs.coll-of/max-count :specs.coll-of/min-count :specs.coll-of/distinct])) (defn apply-coll-of [spec {:keys [into kind count max-count min-count distinct gen-max gen-into gen] :as opts}] (s/coll-of spec :into into :min-count min-count :max-count max-count :distinct distinct)) (defn apply-map-of [spec1 spec2 {:keys [into kind count max-count min-count distinct gen-max gen-into gen] :as opts}] (s/map-of spec1 spec2 :into into :min-count min-count :max-count max-count :distinct distinct)) ;; Since CLJS prints out entire source of a function when ;; it pretty-prints a failure, the output becomes much nicer if ;; we wrap each function in a simple spec (s/def :specs/string string?) (s/def :specs/vector vector?) (s/def :specs/int int?) (s/def :specs/boolean boolean?) (s/def :specs/keyword keyword?) (s/def :specs/map map?) (s/def :specs/symbol symbol?) (s/def :specs/pos-int pos-int?) (s/def :specs/neg-int neg-int?) (s/def :specs/zero #(and (number? %) (zero? %))) (def simple-spec-gen (gen/one-of [(gen/elements [:specs/string :specs/vector :specs/int :specs/boolean :specs/keyword :specs/map :specs/symbol :specs/pos-int :specs/neg-int :specs/zero]) (gen/set gen/simple-type-printable)])) (deftest generated-simple-spec (checking "simple spec" 30 [simple-spec simple-spec-gen :let [sp-form (s/form simple-spec)] form gen/any-printable] (expound/expound-str simple-spec form))) #_(deftest generated-coll-of-specs (checking "'coll-of' spec" 30 [simple-spec simple-spec-gen every-args (s/gen :specs/every-args) :let [spec (apply-coll-of simple-spec every-args)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) #_(deftest generated-and-specs (checking "'and' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen :let [spec (s/and simple-spec1 simple-spec2)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) #_(deftest generated-or-specs (checking "'or' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen :let [spec (s/or :or1 simple-spec1 :or2 simple-spec2)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) (deftest generated-map-of-specs (checking "'map-of' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen simple-spec3 simple-spec-gen every-args1 (s/gen :specs/every-args) every-args2 (s/gen :specs/every-args) :let [spec (apply-map-of simple-spec1 (apply-map-of simple-spec2 simple-spec3 every-args1) every-args2) sp-form (s/form spec)] form any-printable-wo-nan] (expound/expound-str spec form))) ;; TODO - keys ;; TODO - cat + alt, + ? * ;; TODO - nilable ;; TODO - test coll-of that is a set . can i should a bad element of a set? #_(deftest compare-paths-test (checking "path to a key comes before a path to a value" 10 [m (gen/map gen/simple-type-printable gen/simple-type-printable) k gen/simple-type-printable] (is (= -1 (expound/compare-paths [(expound/->KeyPathSegment k)] [k]))) (is (= 1 (expound/compare-paths [k] [(expound/->KeyPathSegment k)]))))) (s/def :test-assert/name string?) (deftest test-assert (testing "assertion passes" (is (= "hello" (s/assert :test-assert/name "hello")))) (testing "assertion fails" #?(:cljs (try (binding [s/*explain-out* expound/printer] (s/assert :test-assert/name :hello)) (catch :default e (is (= "Spec assertion failed\n-- Spec failed -------------------- :hello should satisfy string? ------------------------- Detected 1 error\n" (.-message e))))) :clj (try (binding [s/*explain-out* expound/printer] (s/assert :test-assert/name :hello)) (catch Exception e (is (= "Spec assertion failed -- Spec failed -------------------- :hello should satisfy string? ------------------------- Detected 1 error\n" ;; FIXME - move assertion out of catch, similar to instrument tests (:cause (Throwable->map e))))))))) (s/def :test-explain-str/name string?) (deftest test-explain-str (is (= (pf "-- Spec failed -------------------- :hello should satisfy string? -- Relevant specs ------- :test-assert/name: pf.core/string? ------------------------- Detected 1 error\n") (binding [s/*explain-out* expound/printer] (s/explain-str :test-assert/name :hello))))) (s/def :test-instrument/name string?) (s/fdef test-instrument-adder :args (s/cat :x int? :y int?) :fn #(> (:ret %) (-> % :args :x)) :ret pos-int?) (defn test-instrument-adder [x y] (+ x y)) (defn no-linum [s] (string/replace s #".cljc:\d+" ".cljc:LINUM")) (deftest test-instrument (st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-args-spec-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-args-syntax-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Syntax error ------------------- Function arguments (1) should have additional elements. The next element is named `:y` and satisfies int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Syntax error ------------------- Function arguments (1) should have additional elements. The next element is named `:y` and satisfies int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-ret-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Return value -3 should satisfy pos-int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder -1 -2)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Return value -3 should satisfy pos-int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder -1 -2)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-fn-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments and return value {:ret 1, :args {:x 1, :y 0}} should satisfy (fn [%] (> (:ret %) (-> % :args :x))) ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1 0)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments and return value {:ret 1, :args {:x 1, :y 0}} should satisfy (fn [%] (> (:ret %) (-> % :args :x))) ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1 0)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-custom-value-printer (st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" :x) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" :x) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (st/unstrument `test-instrument-adder)) (s/def :custom-printer/strings (s/coll-of string?)) (deftest custom-printer (testing "custom value printer" (is (= (pf "-- Spec failed -------------------- <HIDDEN> should satisfy string? -- Relevant specs ------- :custom-printer/strings: (pf.spec.alpha/coll-of pf.core/string?) ------------------------- Detected 1 error ") (binding [s/*explain-out* (expound/custom-printer {:value-str-fn (fn [spec-name form path val] "<HIDDEN>")})] (s/explain-str :custom-printer/strings ["a" "b" :c]))))) (testing "modified version of the included value printer" (testing "custom value printer" (is (= (pf "-- Spec failed -------------------- [\"a\" \"b\" :c] ^^ should satisfy string? -- Relevant specs ------- :custom-printer/strings: (pf.spec.alpha/coll-of pf.core/string?) ------------------------- Detected 1 error ") (binding [s/*explain-out* (expound/custom-printer {:value-str-fn (partial expound/value-in-context {:show-valid-values? true})})] (s/explain-str :custom-printer/strings ["a" "b" :c]))))))) (defn spec-dependencies [spec] (->> spec s/form (tree-seq coll? seq) (filter #(and (s/get-spec %) (not= spec %))) distinct)) (defn topo-sort [specs] (deps/topo-sort (reduce (fn [gr spec] (reduce (fn [g d] ;; If this creates a circular reference, then ;; just skip it. (if (deps/depends? g d spec) g (deps/depend g spec d))) gr (spec-dependencies spec))) (deps/graph) specs))) (s/def :alt-spec/int-or-str (s/alt :int int? :string string?)) (deftest alt-spec (is (= (pf "-- Spec failed -------------------- [:hi] ^^^ should satisfy int? or string? -- Relevant specs ------- :alt-spec/int-or-str: %s ------------------------- Detected 1 error\n" #?(:clj "(clojure.spec.alpha/alt :int clojure.core/int? :string clojure.core/string?)" :cljs "(cljs.spec.alpha/alt :int cljs.core/int? :string cljs.core/string?)")) (expound/expound-str :alt-spec/int-or-str [:hi])))) #?(:clj (def spec-gen (gen/elements (->> (s/registry) (map key) topo-sort (filter keyword?))))) #?(:clj (deftest clojure-spec-tests (checking "for any core spec and any data, explain-str returns a string" ;; At 50, it might find a bug in failures for the ;; :ring/handler spec, but keep it plugged in, since it ;; takes a long time to shrink 25 [spec spec-gen form gen/any-printable] (when-not (some #{"clojure.spec.alpha/fspec"} (->> spec s/form (tree-seq coll? identity) (map str))) (expound/expound-str spec form)))))
30190
(ns expound.alpha-test (:require #?@(:clj ;; just to include the specs [[clojure.core.specs.alpha] [ring.core.spec] [onyx.spec]]) [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.string :as string] [clojure.test :as ct :refer [is testing deftest use-fixtures]] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [com.gfredericks.test.chuck.properties :as properties] [com.stuartsierra.dependency :as deps] [expound.alpha :as expound] [expound.printer :as printer] [expound.test-utils :as test-utils] #?(:clj [orchestra.spec.test :as orch.st] :cljs [orchestra-cljs.spec.test :as orch.st]))) (use-fixtures :once test-utils/check-spec-assertions test-utils/instrument-all) (def any-printable-wo-nan (gen/such-that (complement test-utils/contains-nan?) gen/any-printable)) (defn pf "Fixes platform-specific namespaces and also formats using printf syntax" [s & args] (apply printer/format #?(:cljs (string/replace s "pf." "cljs.") :clj (string/replace s "pf." "clojure.")) args)) ;; https://github.com/bhb/expound/issues/8 (deftest expound-output-ends-in-newline (is (= "\n" (str (last (expound/expound-str string? 1))))) (is (= "\n" (str (last (expound/expound-str string? "")))))) (deftest expound-prints-expound-str (is (= (expound/expound-str string? 1) (with-out-str (expound/expound string? 1))))) (deftest pprint-fn (is (= "string?" (expound/pprint-fn (::s/spec (s/explain-data string? 1))))) (is (= "expound.alpha/expound" (expound/pprint-fn expound/expound)))) (deftest predicate-spec (is (= (pf "-- Spec failed -------------------- 1 should satisfy string? ------------------------- Detected 1 error\n") (expound/expound-str string? 1)))) (s/def :simple-type-based-spec/str string?) (deftest simple-type-based-spec (testing "valid value" (is (= "Success!\n" (expound/expound-str :simple-type-based-spec/str "")))) (testing "invalid value" (is (= (pf "-- Spec failed -------------------- 1 should satisfy string? -- Relevant specs ------- :simple-type-based-spec/str: pf.core/string? ------------------------- Detected 1 error\n") (expound/expound-str :simple-type-based-spec/str 1))))) (s/def :set-based-spec/tag #{:foo :bar}) (s/def :set-based-spec/nilable-tag (s/nilable :set-based-spec/tag)) (s/def :set-based-spec/set-of-one #{:foobar}) (deftest set-based-spec (testing "prints valid options" (is (= "-- Spec failed -------------------- :baz should be one of: `:bar`,`:foo` -- Relevant specs ------- :set-based-spec/tag: #{:bar :foo} ------------------------- Detected 1 error\n" (expound/expound-str :set-based-spec/tag :baz)))) ;; FIXME - we should fix nilable and or specs better so they are clearly grouped (testing "nilable version" (is (= (pf "-- Spec failed -------------------- :baz should be one of: `:bar`,`:foo` -- Relevant specs ------- :set-based-spec/tag: #{:bar :foo} :set-based-spec/nilable-tag: (pf.spec.alpha/nilable :set-based-spec/tag) -- Spec failed -------------------- :baz should satisfy nil? -- Relevant specs ------- :set-based-spec/nilable-tag: (pf.spec.alpha/nilable :set-based-spec/tag) ------------------------- Detected 2 errors\n") (expound/expound-str :set-based-spec/nilable-tag :baz)))) (testing "single element spec" (is (= (pf "-- Spec failed -------------------- :baz should be: `:foobar` -- Relevant specs ------- :set-based-spec/set-of-one: #{:foobar} ------------------------- Detected 1 error\n") (expound/expound-str :set-based-spec/set-of-one :baz))))) (s/def :nested-type-based-spec/str string?) (s/def :nested-type-based-spec/strs (s/coll-of :nested-type-based-spec/str)) (deftest nested-type-based-spec (is (= (pf "-- Spec failed -------------------- [... ... 33] ^^ should satisfy string? -- Relevant specs ------- :nested-type-based-spec/str: pf.core/string? :nested-type-based-spec/strs: (pf.spec.alpha/coll-of :nested-type-based-spec/str) ------------------------- Detected 1 error\n") (expound/expound-str :nested-type-based-spec/strs ["one" "two" 33])))) (s/def :nested-type-based-spec-special-summary-string/int int?) (s/def :nested-type-based-spec-special-summary-string/ints (s/coll-of :nested-type-based-spec-special-summary-string/int)) (deftest nested-type-based-spec-special-summary-string (is (= (pf "-- Spec failed -------------------- [... ... \"...\"] ^^^^^ should satisfy int? -- Relevant specs ------- :nested-type-based-spec-special-summary-string/int: pf.core/int? :nested-type-based-spec-special-summary-string/ints: (pf.spec.alpha/coll-of :nested-type-based-spec-special-summary-string/int) ------------------------- Detected 1 error\n") (expound/expound-str :nested-type-based-spec-special-summary-string/ints [1 2 "..."])))) (s/def :or-spec/str-or-int (s/or :int int? :str string?)) (s/def :or-spec/vals (s/coll-of :or-spec/str-or-int)) (deftest or-spec (testing "simple value" (is (= (pf "-- Spec failed -------------------- :kw should satisfy int? or string? -- Relevant specs ------- :or-spec/str-or-int: (pf.spec.alpha/or :int pf.core/int? :str pf.core/string?) ------------------------- Detected 1 error\n") (expound/expound-str :or-spec/str-or-int :kw)))) (testing "collection of values" (is (= (pf "-- Spec failed -------------------- [... ... :kw ...] ^^^ should satisfy int? or string? -- Relevant specs ------- :or-spec/str-or-int: (pf.spec.alpha/or :int pf.core/int? :str pf.core/string?) :or-spec/vals: (pf.spec.alpha/coll-of :or-spec/str-or-int) ------------------------- Detected 1 error\n") (expound/expound-str :or-spec/vals [0 "hi" :kw "bye"]))))) (s/def :and-spec/name (s/and string? #(pos? (count %)))) (s/def :and-spec/names (s/coll-of :and-spec/name)) (deftest and-spec (testing "simple value" (is (= (pf "-- Spec failed -------------------- \"\" should satisfy %s -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) ------------------------- Detected 1 error\n" #?(:cljs "(fn [%] (pos? (count %)))" :clj "(fn [%] (pos? (count %)))")) (expound/expound-str :and-spec/name "")))) (testing "shows both failures in order" (is (= (pf "-- Spec failed -------------------- [... ... \"\" ...] ^^ should satisfy %s -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) :and-spec/names: (pf.spec.alpha/coll-of :and-spec/name) -- Spec failed -------------------- [... ... ... 1] ^ should satisfy string? -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) :and-spec/names: (pf.spec.alpha/coll-of :and-spec/name) ------------------------- Detected 2 errors\n" #?(:cljs "(fn [%] (pos? (count %)))" :clj "(fn [%] (pos? (count %)))")) (expound/expound-str :and-spec/names ["bob" "<NAME>" "" 1]))))) (s/def :coll-of-spec/big-int-coll (s/coll-of int? :min-count 10)) (deftest coll-of-spec (testing "min count" (is (= (pf "-- Spec failed -------------------- [] should satisfy (<= 10 (count %%) %s) -- Relevant specs ------- :coll-of-spec/big-int-coll: (pf.spec.alpha/coll-of pf.core/int? :min-count 10) ------------------------- Detected 1 error\n" #?(:cljs "9007199254740991" :clj "Integer/MAX_VALUE")) (expound/expound-str :coll-of-spec/big-int-coll []))))) (s/def :cat-spec/kw (s/cat :k keyword? :v any?)) (deftest cat-spec (testing "too few elements" (is (= (pf "-- Syntax error ------------------- [] should have additional elements. The next element is named `:k` and satisfies keyword? -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw []))) (is (= (pf "-- Syntax error ------------------- [:foo] should have additional elements. The next element is named `:v` and satisfies any? -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw [:foo])))) (testing "too many elements" (is (= (pf "-- Syntax error ------------------- Value has extra input [... ... :bar ...] ^^^^ -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw [:foo 1 :bar :baz]))))) (s/def :keys-spec/name string?) (s/def :keys-spec/age int?) (s/def :keys-spec/user (s/keys :req [:keys-spec/name] :req-un [:keys-spec/age])) (deftest keys-spec (testing "missing keys" (is (= (pf "-- Spec failed -------------------- {} should contain keys: `:keys-spec/name`,`:age` -- Relevant specs ------- :keys-spec/user: %s ------------------------- Detected 1 error\n" #?(:cljs "(cljs.spec.alpha/keys :req [:keys-spec/name] :req-un [:keys-spec/age])" :clj "(clojure.spec.alpha/keys\n :req\n [:keys-spec/name]\n :req-un\n [:keys-spec/age])")) (expound/expound-str :keys-spec/user {})))) (testing "invalid key" (is (= (pf "-- Spec failed -------------------- {:age ..., :keys-spec/name :bob} ^^^^ should satisfy string? -- Relevant specs ------- :keys-spec/name: pf.core/string? :keys-spec/user: %s ------------------------- Detected 1 error\n" #?(:cljs "(cljs.spec.alpha/keys :req [:keys-spec/name] :req-un [:keys-spec/age])" :clj "(clojure.spec.alpha/keys\n :req\n [:keys-spec/name]\n :req-un\n [:keys-spec/age])")) (expound/expound-str :keys-spec/user {:age 1 :keys-spec/name :bob}))))) (s/def :multi-spec/value string?) (s/def :multi-spec/children vector?) (defmulti el-type :multi-spec/el-type) (defmethod el-type :text [x] (s/keys :req [:multi-spec/value])) (defmethod el-type :group [x] (s/keys :req [:multi-spec/children])) (s/def :multi-spec/el (s/multi-spec el-type :multi-spec/el-type)) (deftest multi-spec (testing "missing dispatch key" (is (= (pf "-- Missing spec ------------------- Cannot find spec for {} Spec multimethod: `expound.alpha-test/el-type` Dispatch function: `:multi-spec/el-type` Dispatch value: `nil` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {})))) (testing "invalid dispatch value" (is (= (pf "-- Missing spec ------------------- Cannot find spec for {:multi-spec/el-type :image} Spec multimethod: `expound.alpha-test/el-type` Dispatch function: `:multi-spec/el-type` Dispatch value: `:image` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {:multi-spec/el-type :image})))) (testing "valid dispatch value, but other error" (is (= (pf "-- Spec failed -------------------- {:multi-spec/el-type :text} should contain keys: `:multi-spec/value` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {:multi-spec/el-type :text}))))) (s/def :recursive-spec/tag #{:text :group}) (s/def :recursive-spec/on-tap (s/coll-of map? :kind vector?)) (s/def :recursive-spec/props (s/keys :opt-un [:recursive-spec/on-tap])) (s/def :recursive-spec/el (s/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])) (s/def :recursive-spec/children (s/coll-of (s/nilable :recursive-spec/el) :kind vector?)) (deftest recursive-spec (testing "only shows problem with data at 'leaves' (not problems with all parents in tree)" (is (= (pf "-- Spec failed -------------------- {:tag ..., :children [{:tag ..., :children [{:tag ..., :props {:on-tap {}}}]}]} ^^ should satisfy vector? -- Relevant specs ------- %s ------------------------- Detected 1 error\n" #?(:cljs ":recursive-spec/on-tap: (cljs.spec.alpha/coll-of cljs.core/map? :kind cljs.core/vector?) :recursive-spec/props: (cljs.spec.alpha/keys :opt-un [:recursive-spec/on-tap]) :recursive-spec/children: (cljs.spec.alpha/coll-of (cljs.spec.alpha/nilable :recursive-spec/el) :kind cljs.core/vector?) :recursive-spec/el: (cljs.spec.alpha/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])" :clj ":recursive-spec/on-tap: (clojure.spec.alpha/coll-of clojure.core/map? :kind clojure.core/vector?) :recursive-spec/props: (clojure.spec.alpha/keys :opt-un [:recursive-spec/on-tap]) :recursive-spec/children: (clojure.spec.alpha/coll-of (clojure.spec.alpha/nilable :recursive-spec/el) :kind clojure.core/vector?) :recursive-spec/el: (clojure.spec.alpha/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])")) (expound/expound-str :recursive-spec/el {:tag :group :children [{:tag :group :children [{:tag :group :props {:on-tap {}}}]}]}))))) (s/def :cat-wrapped-in-or-spec/kv (s/and sequential? (s/cat :k keyword? :v any?))) (s/def :cat-wrapped-in-or-spec/type #{:text}) (s/def :cat-wrapped-in-or-spec/kv-or-string (s/or :map (s/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv)) (deftest cat-wrapped-in-or-spec ;; FIXME - make multiple types of specs on the same value display as single error (is (= (pf "-- Spec failed -------------------- {\"foo\" \"hi\"} should contain keys: `:cat-wrapped-in-or-spec/type` -- Relevant specs ------- :cat-wrapped-in-or-spec/kv-or-string: (pf.spec.alpha/or :map (pf.spec.alpha/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv) -- Spec failed -------------------- {\"foo\" \"hi\"} should satisfy sequential? -- Relevant specs ------- :cat-wrapped-in-or-spec/kv: (pf.spec.alpha/and pf.core/sequential? (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?)) :cat-wrapped-in-or-spec/kv-or-string: (pf.spec.alpha/or :map (pf.spec.alpha/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv) ------------------------- Detected 2 errors\n") (expound/expound-str :cat-wrapped-in-or-spec/kv-or-string {"foo" "hi"})))) (s/def :map-of-spec/name string?) (s/def :map-of-spec/age pos-int?) (s/def :map-of-spec/name->age (s/map-of :map-of-spec/name :map-of-spec/age)) (deftest map-of-spec (is (= (pf "-- Spec failed -------------------- {\"S<NAME>\" \"30\"} ^^^^ should satisfy pos-int? -- Relevant specs ------- :map-of-spec/age: pf.core/pos-int? :map-of-spec/name->age: (pf.spec.alpha/map-of :map-of-spec/name :map-of-spec/age) ------------------------- Detected 1 error\n") (expound/expound-str :map-of-spec/name->age {"<NAME>" "30"}))) (is (= (pf "-- Spec failed -------------------- {:sally ...} ^^^^^^ should satisfy string? -- Relevant specs ------- :map-of-spec/name: pf.core/string? :map-of-spec/name->age: (pf.spec.alpha/map-of :map-of-spec/name :map-of-spec/age) ------------------------- Detected 1 error\n") (expound/expound-str :map-of-spec/name->age {:sally 30})))) ;; I want to do something like ;; (s/def :specs.coll-of/into #{[] '() #{}}) ;; but Clojure (not Clojurescript) won't allow ;; this. As a workaround, I'll just use vectors instead ;; of vectors and lists. ;; TODO - force a specific type of into/kind one for each test ;; (one for vectors, one for lists, etc) (s/def :specs.coll-of/into #{[] #{}}) (s/def :specs.coll-of/kind #{vector? list? set?}) (s/def :specs.coll-of/count pos-int?) (s/def :specs.coll-of/max-count pos-int?) (s/def :specs.coll-of/min-count pos-int?) (s/def :specs.coll-of/distinct boolean?) (s/def :specs/every-args (s/keys :req-un [:specs.coll-of/into :specs.coll-of/kind :specs.coll-of/count :specs.coll-of/max-count :specs.coll-of/min-count :specs.coll-of/distinct])) (defn apply-coll-of [spec {:keys [into kind count max-count min-count distinct gen-max gen-into gen] :as opts}] (s/coll-of spec :into into :min-count min-count :max-count max-count :distinct distinct)) (defn apply-map-of [spec1 spec2 {:keys [into kind count max-count min-count distinct gen-max gen-into gen] :as opts}] (s/map-of spec1 spec2 :into into :min-count min-count :max-count max-count :distinct distinct)) ;; Since CLJS prints out entire source of a function when ;; it pretty-prints a failure, the output becomes much nicer if ;; we wrap each function in a simple spec (s/def :specs/string string?) (s/def :specs/vector vector?) (s/def :specs/int int?) (s/def :specs/boolean boolean?) (s/def :specs/keyword keyword?) (s/def :specs/map map?) (s/def :specs/symbol symbol?) (s/def :specs/pos-int pos-int?) (s/def :specs/neg-int neg-int?) (s/def :specs/zero #(and (number? %) (zero? %))) (def simple-spec-gen (gen/one-of [(gen/elements [:specs/string :specs/vector :specs/int :specs/boolean :specs/keyword :specs/map :specs/symbol :specs/pos-int :specs/neg-int :specs/zero]) (gen/set gen/simple-type-printable)])) (deftest generated-simple-spec (checking "simple spec" 30 [simple-spec simple-spec-gen :let [sp-form (s/form simple-spec)] form gen/any-printable] (expound/expound-str simple-spec form))) #_(deftest generated-coll-of-specs (checking "'coll-of' spec" 30 [simple-spec simple-spec-gen every-args (s/gen :specs/every-args) :let [spec (apply-coll-of simple-spec every-args)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) #_(deftest generated-and-specs (checking "'and' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen :let [spec (s/and simple-spec1 simple-spec2)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) #_(deftest generated-or-specs (checking "'or' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen :let [spec (s/or :or1 simple-spec1 :or2 simple-spec2)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) (deftest generated-map-of-specs (checking "'map-of' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen simple-spec3 simple-spec-gen every-args1 (s/gen :specs/every-args) every-args2 (s/gen :specs/every-args) :let [spec (apply-map-of simple-spec1 (apply-map-of simple-spec2 simple-spec3 every-args1) every-args2) sp-form (s/form spec)] form any-printable-wo-nan] (expound/expound-str spec form))) ;; TODO - keys ;; TODO - cat + alt, + ? * ;; TODO - nilable ;; TODO - test coll-of that is a set . can i should a bad element of a set? #_(deftest compare-paths-test (checking "path to a key comes before a path to a value" 10 [m (gen/map gen/simple-type-printable gen/simple-type-printable) k gen/simple-type-printable] (is (= -1 (expound/compare-paths [(expound/->KeyPathSegment k)] [k]))) (is (= 1 (expound/compare-paths [k] [(expound/->KeyPathSegment k)]))))) (s/def :test-assert/name string?) (deftest test-assert (testing "assertion passes" (is (= "hello" (s/assert :test-assert/name "hello")))) (testing "assertion fails" #?(:cljs (try (binding [s/*explain-out* expound/printer] (s/assert :test-assert/name :hello)) (catch :default e (is (= "Spec assertion failed\n-- Spec failed -------------------- :hello should satisfy string? ------------------------- Detected 1 error\n" (.-message e))))) :clj (try (binding [s/*explain-out* expound/printer] (s/assert :test-assert/name :hello)) (catch Exception e (is (= "Spec assertion failed -- Spec failed -------------------- :hello should satisfy string? ------------------------- Detected 1 error\n" ;; FIXME - move assertion out of catch, similar to instrument tests (:cause (Throwable->map e))))))))) (s/def :test-explain-str/name string?) (deftest test-explain-str (is (= (pf "-- Spec failed -------------------- :hello should satisfy string? -- Relevant specs ------- :test-assert/name: pf.core/string? ------------------------- Detected 1 error\n") (binding [s/*explain-out* expound/printer] (s/explain-str :test-assert/name :hello))))) (s/def :test-instrument/name string?) (s/fdef test-instrument-adder :args (s/cat :x int? :y int?) :fn #(> (:ret %) (-> % :args :x)) :ret pos-int?) (defn test-instrument-adder [x y] (+ x y)) (defn no-linum [s] (string/replace s #".cljc:\d+" ".cljc:LINUM")) (deftest test-instrument (st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-args-spec-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-args-syntax-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Syntax error ------------------- Function arguments (1) should have additional elements. The next element is named `:y` and satisfies int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Syntax error ------------------- Function arguments (1) should have additional elements. The next element is named `:y` and satisfies int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-ret-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Return value -3 should satisfy pos-int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder -1 -2)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Return value -3 should satisfy pos-int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder -1 -2)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-fn-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments and return value {:ret 1, :args {:x 1, :y 0}} should satisfy (fn [%] (> (:ret %) (-> % :args :x))) ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1 0)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments and return value {:ret 1, :args {:x 1, :y 0}} should satisfy (fn [%] (> (:ret %) (-> % :args :x))) ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1 0)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-custom-value-printer (st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" :x) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" :x) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (st/unstrument `test-instrument-adder)) (s/def :custom-printer/strings (s/coll-of string?)) (deftest custom-printer (testing "custom value printer" (is (= (pf "-- Spec failed -------------------- <HIDDEN> should satisfy string? -- Relevant specs ------- :custom-printer/strings: (pf.spec.alpha/coll-of pf.core/string?) ------------------------- Detected 1 error ") (binding [s/*explain-out* (expound/custom-printer {:value-str-fn (fn [spec-name form path val] "<HIDDEN>")})] (s/explain-str :custom-printer/strings ["a" "b" :c]))))) (testing "modified version of the included value printer" (testing "custom value printer" (is (= (pf "-- Spec failed -------------------- [\"a\" \"b\" :c] ^^ should satisfy string? -- Relevant specs ------- :custom-printer/strings: (pf.spec.alpha/coll-of pf.core/string?) ------------------------- Detected 1 error ") (binding [s/*explain-out* (expound/custom-printer {:value-str-fn (partial expound/value-in-context {:show-valid-values? true})})] (s/explain-str :custom-printer/strings ["a" "b" :c]))))))) (defn spec-dependencies [spec] (->> spec s/form (tree-seq coll? seq) (filter #(and (s/get-spec %) (not= spec %))) distinct)) (defn topo-sort [specs] (deps/topo-sort (reduce (fn [gr spec] (reduce (fn [g d] ;; If this creates a circular reference, then ;; just skip it. (if (deps/depends? g d spec) g (deps/depend g spec d))) gr (spec-dependencies spec))) (deps/graph) specs))) (s/def :alt-spec/int-or-str (s/alt :int int? :string string?)) (deftest alt-spec (is (= (pf "-- Spec failed -------------------- [:hi] ^^^ should satisfy int? or string? -- Relevant specs ------- :alt-spec/int-or-str: %s ------------------------- Detected 1 error\n" #?(:clj "(clojure.spec.alpha/alt :int clojure.core/int? :string clojure.core/string?)" :cljs "(cljs.spec.alpha/alt :int cljs.core/int? :string cljs.core/string?)")) (expound/expound-str :alt-spec/int-or-str [:hi])))) #?(:clj (def spec-gen (gen/elements (->> (s/registry) (map key) topo-sort (filter keyword?))))) #?(:clj (deftest clojure-spec-tests (checking "for any core spec and any data, explain-str returns a string" ;; At 50, it might find a bug in failures for the ;; :ring/handler spec, but keep it plugged in, since it ;; takes a long time to shrink 25 [spec spec-gen form gen/any-printable] (when-not (some #{"clojure.spec.alpha/fspec"} (->> spec s/form (tree-seq coll? identity) (map str))) (expound/expound-str spec form)))))
true
(ns expound.alpha-test (:require #?@(:clj ;; just to include the specs [[clojure.core.specs.alpha] [ring.core.spec] [onyx.spec]]) [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.string :as string] [clojure.test :as ct :refer [is testing deftest use-fixtures]] [clojure.test.check.generators :as gen] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [com.gfredericks.test.chuck.properties :as properties] [com.stuartsierra.dependency :as deps] [expound.alpha :as expound] [expound.printer :as printer] [expound.test-utils :as test-utils] #?(:clj [orchestra.spec.test :as orch.st] :cljs [orchestra-cljs.spec.test :as orch.st]))) (use-fixtures :once test-utils/check-spec-assertions test-utils/instrument-all) (def any-printable-wo-nan (gen/such-that (complement test-utils/contains-nan?) gen/any-printable)) (defn pf "Fixes platform-specific namespaces and also formats using printf syntax" [s & args] (apply printer/format #?(:cljs (string/replace s "pf." "cljs.") :clj (string/replace s "pf." "clojure.")) args)) ;; https://github.com/bhb/expound/issues/8 (deftest expound-output-ends-in-newline (is (= "\n" (str (last (expound/expound-str string? 1))))) (is (= "\n" (str (last (expound/expound-str string? "")))))) (deftest expound-prints-expound-str (is (= (expound/expound-str string? 1) (with-out-str (expound/expound string? 1))))) (deftest pprint-fn (is (= "string?" (expound/pprint-fn (::s/spec (s/explain-data string? 1))))) (is (= "expound.alpha/expound" (expound/pprint-fn expound/expound)))) (deftest predicate-spec (is (= (pf "-- Spec failed -------------------- 1 should satisfy string? ------------------------- Detected 1 error\n") (expound/expound-str string? 1)))) (s/def :simple-type-based-spec/str string?) (deftest simple-type-based-spec (testing "valid value" (is (= "Success!\n" (expound/expound-str :simple-type-based-spec/str "")))) (testing "invalid value" (is (= (pf "-- Spec failed -------------------- 1 should satisfy string? -- Relevant specs ------- :simple-type-based-spec/str: pf.core/string? ------------------------- Detected 1 error\n") (expound/expound-str :simple-type-based-spec/str 1))))) (s/def :set-based-spec/tag #{:foo :bar}) (s/def :set-based-spec/nilable-tag (s/nilable :set-based-spec/tag)) (s/def :set-based-spec/set-of-one #{:foobar}) (deftest set-based-spec (testing "prints valid options" (is (= "-- Spec failed -------------------- :baz should be one of: `:bar`,`:foo` -- Relevant specs ------- :set-based-spec/tag: #{:bar :foo} ------------------------- Detected 1 error\n" (expound/expound-str :set-based-spec/tag :baz)))) ;; FIXME - we should fix nilable and or specs better so they are clearly grouped (testing "nilable version" (is (= (pf "-- Spec failed -------------------- :baz should be one of: `:bar`,`:foo` -- Relevant specs ------- :set-based-spec/tag: #{:bar :foo} :set-based-spec/nilable-tag: (pf.spec.alpha/nilable :set-based-spec/tag) -- Spec failed -------------------- :baz should satisfy nil? -- Relevant specs ------- :set-based-spec/nilable-tag: (pf.spec.alpha/nilable :set-based-spec/tag) ------------------------- Detected 2 errors\n") (expound/expound-str :set-based-spec/nilable-tag :baz)))) (testing "single element spec" (is (= (pf "-- Spec failed -------------------- :baz should be: `:foobar` -- Relevant specs ------- :set-based-spec/set-of-one: #{:foobar} ------------------------- Detected 1 error\n") (expound/expound-str :set-based-spec/set-of-one :baz))))) (s/def :nested-type-based-spec/str string?) (s/def :nested-type-based-spec/strs (s/coll-of :nested-type-based-spec/str)) (deftest nested-type-based-spec (is (= (pf "-- Spec failed -------------------- [... ... 33] ^^ should satisfy string? -- Relevant specs ------- :nested-type-based-spec/str: pf.core/string? :nested-type-based-spec/strs: (pf.spec.alpha/coll-of :nested-type-based-spec/str) ------------------------- Detected 1 error\n") (expound/expound-str :nested-type-based-spec/strs ["one" "two" 33])))) (s/def :nested-type-based-spec-special-summary-string/int int?) (s/def :nested-type-based-spec-special-summary-string/ints (s/coll-of :nested-type-based-spec-special-summary-string/int)) (deftest nested-type-based-spec-special-summary-string (is (= (pf "-- Spec failed -------------------- [... ... \"...\"] ^^^^^ should satisfy int? -- Relevant specs ------- :nested-type-based-spec-special-summary-string/int: pf.core/int? :nested-type-based-spec-special-summary-string/ints: (pf.spec.alpha/coll-of :nested-type-based-spec-special-summary-string/int) ------------------------- Detected 1 error\n") (expound/expound-str :nested-type-based-spec-special-summary-string/ints [1 2 "..."])))) (s/def :or-spec/str-or-int (s/or :int int? :str string?)) (s/def :or-spec/vals (s/coll-of :or-spec/str-or-int)) (deftest or-spec (testing "simple value" (is (= (pf "-- Spec failed -------------------- :kw should satisfy int? or string? -- Relevant specs ------- :or-spec/str-or-int: (pf.spec.alpha/or :int pf.core/int? :str pf.core/string?) ------------------------- Detected 1 error\n") (expound/expound-str :or-spec/str-or-int :kw)))) (testing "collection of values" (is (= (pf "-- Spec failed -------------------- [... ... :kw ...] ^^^ should satisfy int? or string? -- Relevant specs ------- :or-spec/str-or-int: (pf.spec.alpha/or :int pf.core/int? :str pf.core/string?) :or-spec/vals: (pf.spec.alpha/coll-of :or-spec/str-or-int) ------------------------- Detected 1 error\n") (expound/expound-str :or-spec/vals [0 "hi" :kw "bye"]))))) (s/def :and-spec/name (s/and string? #(pos? (count %)))) (s/def :and-spec/names (s/coll-of :and-spec/name)) (deftest and-spec (testing "simple value" (is (= (pf "-- Spec failed -------------------- \"\" should satisfy %s -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) ------------------------- Detected 1 error\n" #?(:cljs "(fn [%] (pos? (count %)))" :clj "(fn [%] (pos? (count %)))")) (expound/expound-str :and-spec/name "")))) (testing "shows both failures in order" (is (= (pf "-- Spec failed -------------------- [... ... \"\" ...] ^^ should satisfy %s -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) :and-spec/names: (pf.spec.alpha/coll-of :and-spec/name) -- Spec failed -------------------- [... ... ... 1] ^ should satisfy string? -- Relevant specs ------- :and-spec/name: (pf.spec.alpha/and pf.core/string? (pf.core/fn [%%] (pf.core/pos? (pf.core/count %%)))) :and-spec/names: (pf.spec.alpha/coll-of :and-spec/name) ------------------------- Detected 2 errors\n" #?(:cljs "(fn [%] (pos? (count %)))" :clj "(fn [%] (pos? (count %)))")) (expound/expound-str :and-spec/names ["bob" "PI:NAME:<NAME>END_PI" "" 1]))))) (s/def :coll-of-spec/big-int-coll (s/coll-of int? :min-count 10)) (deftest coll-of-spec (testing "min count" (is (= (pf "-- Spec failed -------------------- [] should satisfy (<= 10 (count %%) %s) -- Relevant specs ------- :coll-of-spec/big-int-coll: (pf.spec.alpha/coll-of pf.core/int? :min-count 10) ------------------------- Detected 1 error\n" #?(:cljs "9007199254740991" :clj "Integer/MAX_VALUE")) (expound/expound-str :coll-of-spec/big-int-coll []))))) (s/def :cat-spec/kw (s/cat :k keyword? :v any?)) (deftest cat-spec (testing "too few elements" (is (= (pf "-- Syntax error ------------------- [] should have additional elements. The next element is named `:k` and satisfies keyword? -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw []))) (is (= (pf "-- Syntax error ------------------- [:foo] should have additional elements. The next element is named `:v` and satisfies any? -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw [:foo])))) (testing "too many elements" (is (= (pf "-- Syntax error ------------------- Value has extra input [... ... :bar ...] ^^^^ -- Relevant specs ------- :cat-spec/kw: (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?) ------------------------- Detected 1 error\n") (expound/expound-str :cat-spec/kw [:foo 1 :bar :baz]))))) (s/def :keys-spec/name string?) (s/def :keys-spec/age int?) (s/def :keys-spec/user (s/keys :req [:keys-spec/name] :req-un [:keys-spec/age])) (deftest keys-spec (testing "missing keys" (is (= (pf "-- Spec failed -------------------- {} should contain keys: `:keys-spec/name`,`:age` -- Relevant specs ------- :keys-spec/user: %s ------------------------- Detected 1 error\n" #?(:cljs "(cljs.spec.alpha/keys :req [:keys-spec/name] :req-un [:keys-spec/age])" :clj "(clojure.spec.alpha/keys\n :req\n [:keys-spec/name]\n :req-un\n [:keys-spec/age])")) (expound/expound-str :keys-spec/user {})))) (testing "invalid key" (is (= (pf "-- Spec failed -------------------- {:age ..., :keys-spec/name :bob} ^^^^ should satisfy string? -- Relevant specs ------- :keys-spec/name: pf.core/string? :keys-spec/user: %s ------------------------- Detected 1 error\n" #?(:cljs "(cljs.spec.alpha/keys :req [:keys-spec/name] :req-un [:keys-spec/age])" :clj "(clojure.spec.alpha/keys\n :req\n [:keys-spec/name]\n :req-un\n [:keys-spec/age])")) (expound/expound-str :keys-spec/user {:age 1 :keys-spec/name :bob}))))) (s/def :multi-spec/value string?) (s/def :multi-spec/children vector?) (defmulti el-type :multi-spec/el-type) (defmethod el-type :text [x] (s/keys :req [:multi-spec/value])) (defmethod el-type :group [x] (s/keys :req [:multi-spec/children])) (s/def :multi-spec/el (s/multi-spec el-type :multi-spec/el-type)) (deftest multi-spec (testing "missing dispatch key" (is (= (pf "-- Missing spec ------------------- Cannot find spec for {} Spec multimethod: `expound.alpha-test/el-type` Dispatch function: `:multi-spec/el-type` Dispatch value: `nil` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {})))) (testing "invalid dispatch value" (is (= (pf "-- Missing spec ------------------- Cannot find spec for {:multi-spec/el-type :image} Spec multimethod: `expound.alpha-test/el-type` Dispatch function: `:multi-spec/el-type` Dispatch value: `:image` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {:multi-spec/el-type :image})))) (testing "valid dispatch value, but other error" (is (= (pf "-- Spec failed -------------------- {:multi-spec/el-type :text} should contain keys: `:multi-spec/value` -- Relevant specs ------- :multi-spec/el: (pf.spec.alpha/multi-spec expound.alpha-test/el-type :multi-spec/el-type) ------------------------- Detected 1 error\n") (expound/expound-str :multi-spec/el {:multi-spec/el-type :text}))))) (s/def :recursive-spec/tag #{:text :group}) (s/def :recursive-spec/on-tap (s/coll-of map? :kind vector?)) (s/def :recursive-spec/props (s/keys :opt-un [:recursive-spec/on-tap])) (s/def :recursive-spec/el (s/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])) (s/def :recursive-spec/children (s/coll-of (s/nilable :recursive-spec/el) :kind vector?)) (deftest recursive-spec (testing "only shows problem with data at 'leaves' (not problems with all parents in tree)" (is (= (pf "-- Spec failed -------------------- {:tag ..., :children [{:tag ..., :children [{:tag ..., :props {:on-tap {}}}]}]} ^^ should satisfy vector? -- Relevant specs ------- %s ------------------------- Detected 1 error\n" #?(:cljs ":recursive-spec/on-tap: (cljs.spec.alpha/coll-of cljs.core/map? :kind cljs.core/vector?) :recursive-spec/props: (cljs.spec.alpha/keys :opt-un [:recursive-spec/on-tap]) :recursive-spec/children: (cljs.spec.alpha/coll-of (cljs.spec.alpha/nilable :recursive-spec/el) :kind cljs.core/vector?) :recursive-spec/el: (cljs.spec.alpha/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])" :clj ":recursive-spec/on-tap: (clojure.spec.alpha/coll-of clojure.core/map? :kind clojure.core/vector?) :recursive-spec/props: (clojure.spec.alpha/keys :opt-un [:recursive-spec/on-tap]) :recursive-spec/children: (clojure.spec.alpha/coll-of (clojure.spec.alpha/nilable :recursive-spec/el) :kind clojure.core/vector?) :recursive-spec/el: (clojure.spec.alpha/keys :req-un [:recursive-spec/tag] :opt-un [:recursive-spec/props :recursive-spec/children])")) (expound/expound-str :recursive-spec/el {:tag :group :children [{:tag :group :children [{:tag :group :props {:on-tap {}}}]}]}))))) (s/def :cat-wrapped-in-or-spec/kv (s/and sequential? (s/cat :k keyword? :v any?))) (s/def :cat-wrapped-in-or-spec/type #{:text}) (s/def :cat-wrapped-in-or-spec/kv-or-string (s/or :map (s/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv)) (deftest cat-wrapped-in-or-spec ;; FIXME - make multiple types of specs on the same value display as single error (is (= (pf "-- Spec failed -------------------- {\"foo\" \"hi\"} should contain keys: `:cat-wrapped-in-or-spec/type` -- Relevant specs ------- :cat-wrapped-in-or-spec/kv-or-string: (pf.spec.alpha/or :map (pf.spec.alpha/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv) -- Spec failed -------------------- {\"foo\" \"hi\"} should satisfy sequential? -- Relevant specs ------- :cat-wrapped-in-or-spec/kv: (pf.spec.alpha/and pf.core/sequential? (pf.spec.alpha/cat :k pf.core/keyword? :v pf.core/any?)) :cat-wrapped-in-or-spec/kv-or-string: (pf.spec.alpha/or :map (pf.spec.alpha/keys :req [:cat-wrapped-in-or-spec/type]) :kv :cat-wrapped-in-or-spec/kv) ------------------------- Detected 2 errors\n") (expound/expound-str :cat-wrapped-in-or-spec/kv-or-string {"foo" "hi"})))) (s/def :map-of-spec/name string?) (s/def :map-of-spec/age pos-int?) (s/def :map-of-spec/name->age (s/map-of :map-of-spec/name :map-of-spec/age)) (deftest map-of-spec (is (= (pf "-- Spec failed -------------------- {\"SPI:NAME:<NAME>END_PI\" \"30\"} ^^^^ should satisfy pos-int? -- Relevant specs ------- :map-of-spec/age: pf.core/pos-int? :map-of-spec/name->age: (pf.spec.alpha/map-of :map-of-spec/name :map-of-spec/age) ------------------------- Detected 1 error\n") (expound/expound-str :map-of-spec/name->age {"PI:NAME:<NAME>END_PI" "30"}))) (is (= (pf "-- Spec failed -------------------- {:sally ...} ^^^^^^ should satisfy string? -- Relevant specs ------- :map-of-spec/name: pf.core/string? :map-of-spec/name->age: (pf.spec.alpha/map-of :map-of-spec/name :map-of-spec/age) ------------------------- Detected 1 error\n") (expound/expound-str :map-of-spec/name->age {:sally 30})))) ;; I want to do something like ;; (s/def :specs.coll-of/into #{[] '() #{}}) ;; but Clojure (not Clojurescript) won't allow ;; this. As a workaround, I'll just use vectors instead ;; of vectors and lists. ;; TODO - force a specific type of into/kind one for each test ;; (one for vectors, one for lists, etc) (s/def :specs.coll-of/into #{[] #{}}) (s/def :specs.coll-of/kind #{vector? list? set?}) (s/def :specs.coll-of/count pos-int?) (s/def :specs.coll-of/max-count pos-int?) (s/def :specs.coll-of/min-count pos-int?) (s/def :specs.coll-of/distinct boolean?) (s/def :specs/every-args (s/keys :req-un [:specs.coll-of/into :specs.coll-of/kind :specs.coll-of/count :specs.coll-of/max-count :specs.coll-of/min-count :specs.coll-of/distinct])) (defn apply-coll-of [spec {:keys [into kind count max-count min-count distinct gen-max gen-into gen] :as opts}] (s/coll-of spec :into into :min-count min-count :max-count max-count :distinct distinct)) (defn apply-map-of [spec1 spec2 {:keys [into kind count max-count min-count distinct gen-max gen-into gen] :as opts}] (s/map-of spec1 spec2 :into into :min-count min-count :max-count max-count :distinct distinct)) ;; Since CLJS prints out entire source of a function when ;; it pretty-prints a failure, the output becomes much nicer if ;; we wrap each function in a simple spec (s/def :specs/string string?) (s/def :specs/vector vector?) (s/def :specs/int int?) (s/def :specs/boolean boolean?) (s/def :specs/keyword keyword?) (s/def :specs/map map?) (s/def :specs/symbol symbol?) (s/def :specs/pos-int pos-int?) (s/def :specs/neg-int neg-int?) (s/def :specs/zero #(and (number? %) (zero? %))) (def simple-spec-gen (gen/one-of [(gen/elements [:specs/string :specs/vector :specs/int :specs/boolean :specs/keyword :specs/map :specs/symbol :specs/pos-int :specs/neg-int :specs/zero]) (gen/set gen/simple-type-printable)])) (deftest generated-simple-spec (checking "simple spec" 30 [simple-spec simple-spec-gen :let [sp-form (s/form simple-spec)] form gen/any-printable] (expound/expound-str simple-spec form))) #_(deftest generated-coll-of-specs (checking "'coll-of' spec" 30 [simple-spec simple-spec-gen every-args (s/gen :specs/every-args) :let [spec (apply-coll-of simple-spec every-args)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) #_(deftest generated-and-specs (checking "'and' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen :let [spec (s/and simple-spec1 simple-spec2)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) #_(deftest generated-or-specs (checking "'or' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen :let [spec (s/or :or1 simple-spec1 :or2 simple-spec2)] :let [sp-form (s/form spec)] form gen/any-printable] (expound/expound-str spec form))) (deftest generated-map-of-specs (checking "'map-of' spec" 30 [simple-spec1 simple-spec-gen simple-spec2 simple-spec-gen simple-spec3 simple-spec-gen every-args1 (s/gen :specs/every-args) every-args2 (s/gen :specs/every-args) :let [spec (apply-map-of simple-spec1 (apply-map-of simple-spec2 simple-spec3 every-args1) every-args2) sp-form (s/form spec)] form any-printable-wo-nan] (expound/expound-str spec form))) ;; TODO - keys ;; TODO - cat + alt, + ? * ;; TODO - nilable ;; TODO - test coll-of that is a set . can i should a bad element of a set? #_(deftest compare-paths-test (checking "path to a key comes before a path to a value" 10 [m (gen/map gen/simple-type-printable gen/simple-type-printable) k gen/simple-type-printable] (is (= -1 (expound/compare-paths [(expound/->KeyPathSegment k)] [k]))) (is (= 1 (expound/compare-paths [k] [(expound/->KeyPathSegment k)]))))) (s/def :test-assert/name string?) (deftest test-assert (testing "assertion passes" (is (= "hello" (s/assert :test-assert/name "hello")))) (testing "assertion fails" #?(:cljs (try (binding [s/*explain-out* expound/printer] (s/assert :test-assert/name :hello)) (catch :default e (is (= "Spec assertion failed\n-- Spec failed -------------------- :hello should satisfy string? ------------------------- Detected 1 error\n" (.-message e))))) :clj (try (binding [s/*explain-out* expound/printer] (s/assert :test-assert/name :hello)) (catch Exception e (is (= "Spec assertion failed -- Spec failed -------------------- :hello should satisfy string? ------------------------- Detected 1 error\n" ;; FIXME - move assertion out of catch, similar to instrument tests (:cause (Throwable->map e))))))))) (s/def :test-explain-str/name string?) (deftest test-explain-str (is (= (pf "-- Spec failed -------------------- :hello should satisfy string? -- Relevant specs ------- :test-assert/name: pf.core/string? ------------------------- Detected 1 error\n") (binding [s/*explain-out* expound/printer] (s/explain-str :test-assert/name :hello))))) (s/def :test-instrument/name string?) (s/fdef test-instrument-adder :args (s/cat :x int? :y int?) :fn #(> (:ret %) (-> % :args :x)) :ret pos-int?) (defn test-instrument-adder [x y] (+ x y)) (defn no-linum [s] (string/replace s #".cljc:\d+" ".cljc:LINUM")) (deftest test-instrument (st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-args-spec-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" ...) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-args-syntax-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Syntax error ------------------- Function arguments (1) should have additional elements. The next element is named `:y` and satisfies int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Syntax error ------------------- Function arguments (1) should have additional elements. The next element is named `:y` and satisfies int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-ret-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Return value -3 should satisfy pos-int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder -1 -2)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Return value -3 should satisfy pos-int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder -1 -2)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-orchestra-fn-failure (orch.st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments and return value {:ret 1, :args {:x 1, :y 0}} should satisfy (fn [%] (> (:ret %) (-> % :args :x))) ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1 0)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments and return value {:ret 1, :args {:x 1, :y 0}} should satisfy (fn [%] (> (:ret %) (-> % :args :x))) ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* expound/printer] (test-instrument-adder 1 0)) (catch Exception e e)))))))) (orch.st/unstrument `test-instrument-adder)) (deftest test-instrument-with-custom-value-printer (st/instrument `test-instrument-adder) #?(:cljs (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: <filename missing>:<line number missing> -- Spec failed -------------------- Function arguments (\"\" :x) ^^ should satisfy int? ------------------------- Detected 1 error\n" (.-message (try (binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})] (test-instrument-adder "" :x)) (catch :default e e))))) :clj (is (= "Call to #'expound.alpha-test/test-instrument-adder did not conform to spec: alpha_test.cljc:LINUM -- Spec failed -------------------- Function arguments (\"\" :x) ^^ should satisfy int? ------------------------- Detected 1 error\n" (no-linum (:cause (Throwable->map (try (binding [s/*explain-out* (expound/custom-printer {:show-valid-values? true})] (test-instrument-adder "" :x)) (catch Exception e e)))))))) (st/unstrument `test-instrument-adder)) (s/def :custom-printer/strings (s/coll-of string?)) (deftest custom-printer (testing "custom value printer" (is (= (pf "-- Spec failed -------------------- <HIDDEN> should satisfy string? -- Relevant specs ------- :custom-printer/strings: (pf.spec.alpha/coll-of pf.core/string?) ------------------------- Detected 1 error ") (binding [s/*explain-out* (expound/custom-printer {:value-str-fn (fn [spec-name form path val] "<HIDDEN>")})] (s/explain-str :custom-printer/strings ["a" "b" :c]))))) (testing "modified version of the included value printer" (testing "custom value printer" (is (= (pf "-- Spec failed -------------------- [\"a\" \"b\" :c] ^^ should satisfy string? -- Relevant specs ------- :custom-printer/strings: (pf.spec.alpha/coll-of pf.core/string?) ------------------------- Detected 1 error ") (binding [s/*explain-out* (expound/custom-printer {:value-str-fn (partial expound/value-in-context {:show-valid-values? true})})] (s/explain-str :custom-printer/strings ["a" "b" :c]))))))) (defn spec-dependencies [spec] (->> spec s/form (tree-seq coll? seq) (filter #(and (s/get-spec %) (not= spec %))) distinct)) (defn topo-sort [specs] (deps/topo-sort (reduce (fn [gr spec] (reduce (fn [g d] ;; If this creates a circular reference, then ;; just skip it. (if (deps/depends? g d spec) g (deps/depend g spec d))) gr (spec-dependencies spec))) (deps/graph) specs))) (s/def :alt-spec/int-or-str (s/alt :int int? :string string?)) (deftest alt-spec (is (= (pf "-- Spec failed -------------------- [:hi] ^^^ should satisfy int? or string? -- Relevant specs ------- :alt-spec/int-or-str: %s ------------------------- Detected 1 error\n" #?(:clj "(clojure.spec.alpha/alt :int clojure.core/int? :string clojure.core/string?)" :cljs "(cljs.spec.alpha/alt :int cljs.core/int? :string cljs.core/string?)")) (expound/expound-str :alt-spec/int-or-str [:hi])))) #?(:clj (def spec-gen (gen/elements (->> (s/registry) (map key) topo-sort (filter keyword?))))) #?(:clj (deftest clojure-spec-tests (checking "for any core spec and any data, explain-str returns a string" ;; At 50, it might find a bug in failures for the ;; :ring/handler spec, but keep it plugged in, since it ;; takes a long time to shrink 25 [spec spec-gen form gen/any-printable] (when-not (some #{"clojure.spec.alpha/fspec"} (->> spec s/form (tree-seq coll? identity) (map str))) (expound/expound-str spec form)))))
[ { "context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998803734779358, "start": 25, "tag": "NAME", "value": "Esko Luontola" }, { "context": "\"schema is missing\")\n (assert database-username \"username is missing\")\n (assert database-password \"password is missin", "end": 654, "score": 0.9891147017478943, "start": 635, "tag": "USERNAME", "value": "username is missing" }, { "context": "sername is missing\")\n (assert database-password \"password is missing\")\n (assert database-ssl-mode \"ssl mode is missin", "end": 705, "score": 0.9987629055976868, "start": 686, "tag": "PASSWORD", "value": "password is missing" } ]
src/territory_bro/gis/qgis.clj
orfjackal/territory-bro
2
;; 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.gis.qgis (:require [clojure.java.io :as io] [clojure.string :as str])) (def project-template (io/resource "template-territories.qgs")) (defn generate-project [{:keys [database-host database-name database-schema database-username database-password database-ssl-mode]}] (assert database-host "host is missing") (assert database-name "db name is missing") (assert database-schema "schema is missing") (assert database-username "username is missing") (assert database-password "password is missing") (assert database-ssl-mode "ssl mode is missing") (-> (slurp project-template :encoding "UTF-8") (str/replace "HOST_GOES_HERE" database-host) (str/replace "DBNAME_GOES_HERE" database-name) (str/replace "SCHEMA_GOES_HERE" database-schema) (str/replace "USERNAME_GOES_HERE" database-username) (str/replace "PASSWORD_GOES_HERE" database-password) (str/replace "SSLMODE_GOES_HERE" database-ssl-mode))) (defn project-file-name [name] (let [name (-> name (str/replace #"[<>:\"/\\|?*]" "") ; not allowed in Windows file names (str/replace #"\s+" " ")) name (if (str/blank? name) "territories" name)] (str name ".qgs")))
61928
;; 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.gis.qgis (:require [clojure.java.io :as io] [clojure.string :as str])) (def project-template (io/resource "template-territories.qgs")) (defn generate-project [{:keys [database-host database-name database-schema database-username database-password database-ssl-mode]}] (assert database-host "host is missing") (assert database-name "db name is missing") (assert database-schema "schema is missing") (assert database-username "username is missing") (assert database-password "<PASSWORD>") (assert database-ssl-mode "ssl mode is missing") (-> (slurp project-template :encoding "UTF-8") (str/replace "HOST_GOES_HERE" database-host) (str/replace "DBNAME_GOES_HERE" database-name) (str/replace "SCHEMA_GOES_HERE" database-schema) (str/replace "USERNAME_GOES_HERE" database-username) (str/replace "PASSWORD_GOES_HERE" database-password) (str/replace "SSLMODE_GOES_HERE" database-ssl-mode))) (defn project-file-name [name] (let [name (-> name (str/replace #"[<>:\"/\\|?*]" "") ; not allowed in Windows file names (str/replace #"\s+" " ")) name (if (str/blank? name) "territories" name)] (str name ".qgs")))
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.gis.qgis (:require [clojure.java.io :as io] [clojure.string :as str])) (def project-template (io/resource "template-territories.qgs")) (defn generate-project [{:keys [database-host database-name database-schema database-username database-password database-ssl-mode]}] (assert database-host "host is missing") (assert database-name "db name is missing") (assert database-schema "schema is missing") (assert database-username "username is missing") (assert database-password "PI:PASSWORD:<PASSWORD>END_PI") (assert database-ssl-mode "ssl mode is missing") (-> (slurp project-template :encoding "UTF-8") (str/replace "HOST_GOES_HERE" database-host) (str/replace "DBNAME_GOES_HERE" database-name) (str/replace "SCHEMA_GOES_HERE" database-schema) (str/replace "USERNAME_GOES_HERE" database-username) (str/replace "PASSWORD_GOES_HERE" database-password) (str/replace "SSLMODE_GOES_HERE" database-ssl-mode))) (defn project-file-name [name] (let [name (-> name (str/replace #"[<>:\"/\\|?*]" "") ; not allowed in Windows file names (str/replace #"\s+" " ")) name (if (str/blank? name) "territories" name)] (str name ".qgs")))
[ { "context": ";; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and\n;; distributi", "end": 36, "score": 0.9998700618743896, "start": 18, "tag": "NAME", "value": "Stephen C. Gilardi" }, { "context": ";\n;; clojure.contrib.condition.example.clj\n;;\n;; scgilardi (gmail)\n;; Created 09 June 2009\n\n(ns clojure.con", "end": 534, "score": 0.9846110343933105, "start": 525, "tag": "USERNAME", "value": "scgilardi" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/condition/example.clj
allertonm/Couverjure
3
;; Copyright (c) Stephen C. Gilardi. 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. ;; ;; clojure.contrib.condition.example.clj ;; ;; scgilardi (gmail) ;; Created 09 June 2009 (ns clojure.contrib.condition.example (:use (clojure.contrib [condition :only (handler-case print-stack-trace raise *condition*)]))) (defn func [x y] "Raises an exception if x is negative" (when (neg? x) (raise :type :illegal-argument :arg 'x :value x)) (+ x y)) (defn main [] ;; simple handler (handler-case :type (println (func 3 4)) (println (func -5 10)) (handle :illegal-argument (print-stack-trace *condition*)) (println 3)) ;; multiple handlers (handler-case :type (println (func 4 1)) (println (func -3 22)) (handle :overflow (print-stack-trace *condition*)) (handle :illegal-argument (print-stack-trace *condition*))) ;; nested handlers (handler-case :type (handler-case :type nil nil (println 1) (println 2) (println 3) (println (func 8 2)) (println (func -6 17)) ;; no handler for :illegal-argument (handle :overflow (println "nested") (print-stack-trace *condition*))) (println (func 3 4)) (println (func -5 10)) (handle :illegal-argument (println "outer") (print-stack-trace *condition*))))
10425
;; 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. ;; ;; clojure.contrib.condition.example.clj ;; ;; scgilardi (gmail) ;; Created 09 June 2009 (ns clojure.contrib.condition.example (:use (clojure.contrib [condition :only (handler-case print-stack-trace raise *condition*)]))) (defn func [x y] "Raises an exception if x is negative" (when (neg? x) (raise :type :illegal-argument :arg 'x :value x)) (+ x y)) (defn main [] ;; simple handler (handler-case :type (println (func 3 4)) (println (func -5 10)) (handle :illegal-argument (print-stack-trace *condition*)) (println 3)) ;; multiple handlers (handler-case :type (println (func 4 1)) (println (func -3 22)) (handle :overflow (print-stack-trace *condition*)) (handle :illegal-argument (print-stack-trace *condition*))) ;; nested handlers (handler-case :type (handler-case :type nil nil (println 1) (println 2) (println 3) (println (func 8 2)) (println (func -6 17)) ;; no handler for :illegal-argument (handle :overflow (println "nested") (print-stack-trace *condition*))) (println (func 3 4)) (println (func -5 10)) (handle :illegal-argument (println "outer") (print-stack-trace *condition*))))
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. ;; ;; clojure.contrib.condition.example.clj ;; ;; scgilardi (gmail) ;; Created 09 June 2009 (ns clojure.contrib.condition.example (:use (clojure.contrib [condition :only (handler-case print-stack-trace raise *condition*)]))) (defn func [x y] "Raises an exception if x is negative" (when (neg? x) (raise :type :illegal-argument :arg 'x :value x)) (+ x y)) (defn main [] ;; simple handler (handler-case :type (println (func 3 4)) (println (func -5 10)) (handle :illegal-argument (print-stack-trace *condition*)) (println 3)) ;; multiple handlers (handler-case :type (println (func 4 1)) (println (func -3 22)) (handle :overflow (print-stack-trace *condition*)) (handle :illegal-argument (print-stack-trace *condition*))) ;; nested handlers (handler-case :type (handler-case :type nil nil (println 1) (println 2) (println 3) (println (func 8 2)) (println (func -6 17)) ;; no handler for :illegal-argument (handle :overflow (println "nested") (print-stack-trace *condition*))) (println (func 3 4)) (println (func -5 10)) (handle :illegal-argument (println "outer") (print-stack-trace *condition*))))
[ { "context": "; Written by Raju\n; Run using following command\n; clojure fiboSerie", "end": 17, "score": 0.9998443722724915, "start": 13, "tag": "NAME", "value": "Raju" } ]
Chapter09/fiboSeries.clj
PacktPublishing/Learning-Functional-Data-Structures-and-Algorithms
31
; Written by Raju ; Run using following command ; clojure fiboSeries.clj ;Fibonacci Series in Clojure (defn fiboSeries [x y] (lazy-seq (cons x (fiboSeries y (+ x y))))) (println (take 5 (fiboSeries 0 1))) (println (take 5 (fiboSeries 1 1)))
45216
; Written by <NAME> ; Run using following command ; clojure fiboSeries.clj ;Fibonacci Series in Clojure (defn fiboSeries [x y] (lazy-seq (cons x (fiboSeries y (+ x y))))) (println (take 5 (fiboSeries 0 1))) (println (take 5 (fiboSeries 1 1)))
true
; Written by PI:NAME:<NAME>END_PI ; Run using following command ; clojure fiboSeries.clj ;Fibonacci Series in Clojure (defn fiboSeries [x y] (lazy-seq (cons x (fiboSeries y (+ x y))))) (println (take 5 (fiboSeries 0 1))) (println (take 5 (fiboSeries 1 1)))
[ { "context": "ethod-def\n {:oid \"M01\"\n :name \"foo\"\n :type :other\n :odm/descript", "end": 644, "score": 0.7888591885566711, "start": 641, "tag": "NAME", "value": "foo" } ]
data/train/clojure/a3d9b950460247d5f435247ee42a7e0c471502cfmethod_def_test.cljc
harshp8l/deep-learning-lang-detection
84
(ns odm.method-def-test (:require #?@(:clj [[clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :refer :all] [odm-spec.test-util :refer [given-problems]]] :cljs [[cljs.spec.alpha :as s] [cljs.spec.test.alpha :as st] [cljs.test :refer-macros [deftest testing is are]] [odm-spec.test-util :refer-macros [given-problems]]]) [odm.method-def])) (st/instrument) (deftest method-def-test (testing "Valid method definitions" (are [x] (s/valid? :odm/method-def x) #:odm.method-def {:oid "M01" :name "foo" :type :other :odm/description [{:lang-tag "de" :text "bar"}]})) (testing "Generator available" (is (doall (s/exercise :odm/method-def 1)))))
31033
(ns odm.method-def-test (:require #?@(:clj [[clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :refer :all] [odm-spec.test-util :refer [given-problems]]] :cljs [[cljs.spec.alpha :as s] [cljs.spec.test.alpha :as st] [cljs.test :refer-macros [deftest testing is are]] [odm-spec.test-util :refer-macros [given-problems]]]) [odm.method-def])) (st/instrument) (deftest method-def-test (testing "Valid method definitions" (are [x] (s/valid? :odm/method-def x) #:odm.method-def {:oid "M01" :name "<NAME>" :type :other :odm/description [{:lang-tag "de" :text "bar"}]})) (testing "Generator available" (is (doall (s/exercise :odm/method-def 1)))))
true
(ns odm.method-def-test (:require #?@(:clj [[clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :refer :all] [odm-spec.test-util :refer [given-problems]]] :cljs [[cljs.spec.alpha :as s] [cljs.spec.test.alpha :as st] [cljs.test :refer-macros [deftest testing is are]] [odm-spec.test-util :refer-macros [given-problems]]]) [odm.method-def])) (st/instrument) (deftest method-def-test (testing "Valid method definitions" (are [x] (s/valid? :odm/method-def x) #:odm.method-def {:oid "M01" :name "PI:NAME:<NAME>END_PI" :type :other :odm/description [{:lang-tag "de" :text "bar"}]})) (testing "Generator available" (is (doall (s/exercise :odm/method-def 1)))))
[ { "context": " :family \"Doe\"}]}))\n \"Doe, \")))\n\n (testing \"with one given name\"\n (i", "end": 3451, "score": 0.9471195340156555, "start": 3448, "tag": "NAME", "value": "Doe" }, { "context": "amily \"Doe\"\n :given [\"John\"]}]}))\n \"Doe, John\")))\n\n (testing ", "end": 3833, "score": 0.9992964863777161, "start": 3829, "tag": "NAME", "value": "John" }, { "context": " :given [\"John\"]}]}))\n \"Doe, John\")))\n\n (testing \"with two given names\"\n (g", "end": 3864, "score": 0.8745677471160889, "start": 3855, "tag": "NAME", "value": "Doe, John" }, { "context": " :family \"Doe\"\n :given [\"John\" \"Foo\"]}]})\n ::anom/category := ::anom/inc", "end": 4196, "score": 0.998895525932312, "start": 4192, "tag": "NAME", "value": "John" }, { "context": "amily \"Doe\"\n :given [\"John\" \"Foo\"]}]})\n ::anom/category := ::anom/incorrect", "end": 4202, "score": 0.895579993724823, "start": 4199, "tag": "NAME", "value": "Foo" } ]
modules/fhir-path/test/blaze/fhir_path_test.clj
samply/blaze
50
(ns blaze.fhir-path-test "See: http://hl7.org/fhirpath/index.html" (:refer-clojure :exclude [eval]) (:require [blaze.fhir-path :as fhir-path] [blaze.fhir-path-spec] [blaze.fhir.spec :as fhir-spec] [blaze.fhir.spec.type] [blaze.fhir.spec.type.system :as system] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [are deftest is testing]] [cognitect.anomalies :as anom] [juxt.iota :refer [given]] [taoensso.timbre :as log])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def ^:private resolver (reify fhir-path/Resolver (-resolve [_ _]))) (defn- eval ([expr resource] (eval expr resolver resource)) ([expr resolver resource] (fhir-path/eval resolver (fhir-path/compile expr) resource))) ;; 3. Path selection (deftest path-selection-test (testing "Resource.id" (are [x] (= x (first (eval "Resource.id" {:fhir/type :fhir/Patient :id x}))) "id-161533" "id-161537")) (testing "Patient.id" (are [x] (= x (first (eval "Patient.id" {:fhir/type :fhir/Patient :id x}))) "id-161533" "id-161537")) (testing "Patient.active" (testing "value" (are [x] (= x (first (eval "Patient.active" {:fhir/type :fhir/Patient :id "foo" :active x}))) true false)) (testing "type" (are [x] (= :fhir/boolean (fhir-spec/fhir-type (first (eval "Patient.active" {:fhir/type :fhir/Patient :id "foo" :active x})))) true false))) (testing "(Observation.value as boolean)" (are [x] (= x (first (eval "(Observation.value as boolean)" {:fhir/type :fhir/Observation :id "foo" :value x}))) true false))) ;; 4. Expressions ;; 4.1 Literals (deftest boolean-test (is (true? (first (eval "true" "foo")))) (is (false? (first (eval "false" "foo"))))) (deftest string-test (is (= "bar" (first (eval "'bar'" "foo"))))) (deftest integer-test (is (= 0 (first (eval "0" "foo"))))) (deftest decimal-test (is (= 0.1M (first (eval "0.1" "foo"))))) (deftest date-test (are [expr date] (= date (first (eval expr "foo"))) "@2020" (system/date 2020) "@2020-01" (system/date 2020 1) "@2020-01-02" (system/date 2020 1 2))) (deftest date-time-test (are [expr date-time] (= date-time (first (eval expr "foo"))) "@2020T" (system/date-time 2020) "@2020-01T" (system/date-time 2020 1) "@2020-01-02T" (system/date-time 2020 1 2) "@2020-01-02T03" (system/date-time 2020 1 2 3))) ;; 4.5. Singleton Evaluation of Collections (deftest singleton-test (testing "string concatenation" (testing "with no given name" (is (= (first (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"}]})) "Doe, "))) (testing "with one given name" (is (= (first (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe" :given ["John"]}]})) "Doe, John"))) (testing "with two given names" (given (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe" :given ["John" "Foo"]}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[\"John\" \"Foo\"]` as singleton")) (testing "with non-convertible type" (given (eval "Patient.name.family + ', ' + Patient.name" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[{:fhir/type :fhir/HumanName, :family \"Doe\"}]` as singleton"))) (testing "and expression" (testing "with one telecom" (is (= (first (eval "Patient.active and Patient.gender and Patient.telecom" {:fhir/type :fhir/Patient :id "foo" :active true :gender #fhir/code"female" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "foo"}]})) true))) (testing "with two telecoms" (given (eval "Patient.active and Patient.gender and Patient.telecom" {:fhir/type :fhir/Patient :id "foo" :active true :gender #fhir/code"female" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "foo"} {:fhir/type :fhir/ContactPoint :use #fhir/code"work" :value "bar"}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[{:fhir/type :fhir/ContactPoint, :use #fhir/code\"home\", :value \"foo\"} {:fhir/type :fhir/ContactPoint, :use #fhir/code\"work\", :value \"bar\"}]` as singleton")))) ;; 5. Functions (deftest resolve-function-test (let [resolver (reify fhir-path/Resolver (-resolve [_ uri] (when (= "reference-180039" uri) {:fhir/type :fhir/Patient :id "id-164737"})))] (given (eval "Specimen.subject.where(resolve() is Patient)" resolver {:fhir/type :fhir/Specimen :id "id-175250" :subject #fhir/Reference{:reference "reference-180039"}}) [0 :reference] := "reference-180039"))) ;; 5.1. Existence ;; 5.1.2. exists([criteria : expression]) : Boolean (deftest exists-function-test (is (false? (first (eval "Patient.deceased.exists()" {:fhir/type :fhir/Patient :id "id-182007"})))) (is (true? (first (eval "Patient.deceased.exists()" {:fhir/type :fhir/Patient :id "id-182007" :deceased true}))))) ;; 5.2. Filtering and projection ;; 5.2.1. where(criteria : expression) : collection (deftest where-function-test (testing "missing criteria" (given (fhir-path/compile "Patient.telecom.where()") ::anom/category := ::anom/incorrect ::anom/message := "missing criteria in `where` function in expression `Patient.telecom.where()`")) (testing "returns one matching item" (given (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]}) [0 :use] := #fhir/code"home" [0 :value] := "value-170758")) (testing "returns two matching items" (given (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"} {:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-145928"}]}) [0 :use] := #fhir/code"home" [0 :value] := "value-170758" [1 :use] := #fhir/code"home" [1 :value] := "value-145928")) (testing "returns empty collection on non-matching item" (is (empty? (eval "Patient.telecom.where(use = 'work')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]})))) (testing "returns empty collection on empty criteria result" (is (empty? (eval "Patient.telecom.where({})" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]})))) (testing "returns empty collection on empty input" (is (empty? (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953"})))) (testing "return error on multiple criteria result" (given (eval "Patient.address.where(line)" {:fhir/type :fhir/Patient :id "id-162953" :address [{:fhir/type :fhir/Address :line ["a" "b"]}]}) ::anom/category := ::anom/incorrect ::anom/message := "multiple result items `[\"a\" \"b\"]` while evaluating where function criteria")) (testing "return error on non-boolean criteria result" (given (eval "Patient.telecom.where(use)" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]}) ::anom/category := ::anom/incorrect ::anom/message := "non-boolean result `#fhir/code\"home\"` of type `:fhir/code` while evaluating where function criteria"))) ;; 5.2.4. ofType(type : type specifier) : collection (deftest of-type-function-test (testing "returns two matching items" (given (eval "Observation.component.value.ofType(Quantity)" {:fhir/type :fhir/Observation :component [{:fhir/type :fhir.Observation/component :value #fhir/Quantity{:value 150M}} {:fhir/type :fhir.Observation/component :value #fhir/Quantity{:value 100M}}]}) [0 :value] := 150M [1 :value] := 100M))) ;; 5.3. Subsetting ;; 5.3.1. [ index : Integer ] : collection (deftest indexer-test (is (= (eval "Bundle.entry[0].resource" {:fhir/type :fhir/Bundle :id "id-110914" :entry [{:fhir/type :fhir.Bundle/entry :resource {:fhir/type :fhir/Patient :id "id-111004"}}]}) [{:fhir/type :fhir/Patient :id "id-111004"}]))) ;; 5.4. Combining ;; 5.4.1. union(other : collection) (deftest union-test (let [patient {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"} {:fhir/type :fhir/HumanName :family "Bolton"}]}] (are [expr res] (= res (eval expr patient)) "{} | {}" [] "1 | {}" [1] "{} | 1" [1] "1 | 1" [1] "Patient.name.family | {}" ["Doe" "Bolton"] "Patient.name.family | 'Wade'" ["Wade" "Doe" "Bolton"] "{} | Patient.name.family" ["Doe" "Bolton"] "'Wade' | Patient.name.family" ["Wade" "Doe" "Bolton"] "Patient.name.family | Patient.name.family" ["Doe" "Bolton"])) (is (= (eval "Patient.gender | Patient.birthDate" {:fhir/type :fhir/Patient :id "id-162953" :gender #fhir/code"female" :birthDate #fhir/date"2020"}) [#fhir/code"female" #fhir/date"2020"]))) ;; 6. Operations ;; 6.1. Equality ;; 6.1.1. = (Equals) (deftest equals-test (testing "propagates empty collections" (testing "both empty" (is (empty? (eval "{} = {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "left empty" (is (empty? (eval "{} = Patient.id" {:fhir/type :fhir/Patient :id "foo"})))) (testing "right empty" (is (empty? (eval "Patient.id = {}" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "string comparison" (is (true? (first (eval "Patient.id = 'foo'" {:fhir/type :fhir/Patient :id "foo"})))) (is (false? (first (eval "Patient.id = 'bar'" {:fhir/type :fhir/Patient :id "foo"})))))) ;; 6.1.3. != (Not Equals) (deftest not-equals-test (testing "propagates empty collections" (testing "both empty" (is (empty? (eval "{} != {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "left empty" (is (empty? (eval "{} != Patient.id" {:fhir/type :fhir/Patient :id "foo"})))) (testing "right empty" (is (empty? (eval "Patient.id != {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "string comparison" (is (true? (first (eval "Patient.id != 'bar'" {:fhir/type :fhir/Patient :id "foo"})))) (is (false? (first (eval "Patient.id != 'foo'" {:fhir/type :fhir/Patient :id "foo"}))))))) ;; 6.3. Types ;; 6.3.1. is type specifier (deftest is-type-specifier-test (testing "single item with matching type returns true" (is (true? (first (eval "Patient.birthDate is date" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns false" (is (false? (first (eval "Patient.birthDate is string" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate is string" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier is string" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "is type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.3.3 as type specifier (deftest as-type-specifier-test (testing "single item with matching type returns the item" (is (= #fhir/date"2020" (first (eval "Patient.birthDate as date" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns an empty collection" (is (empty? (first (eval "Patient.birthDate as string" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate as string" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier as string" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "as type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.3.4 as(type : type specifier) (deftest as-function-test (testing "single item with matching type returns the item" (is (= #fhir/date"2020" (first (eval "Patient.birthDate.as(date)" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns an empty collection" (is (empty? (first (eval "Patient.birthDate.as(string)" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate.as(string)" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier.as(string)" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "as type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.5. Boolean logic ;; 6.5.1. and (deftest and-test (are [expr pred] (pred (first (eval expr {:fhir/type :fhir/Patient :id "id-162953" :gender #fhir/code"male" :birthDate #fhir/date"2020"}))) "Patient.gender = 'male' and Patient.birthDate = @2020" true? "Patient.gender = 'male' and Patient.birthDate = @2021" false? "Patient.gender = 'female' and Patient.birthDate = @2020" false? "Patient.gender = 'female' and Patient.birthDate = @2021" false?))
23017
(ns blaze.fhir-path-test "See: http://hl7.org/fhirpath/index.html" (:refer-clojure :exclude [eval]) (:require [blaze.fhir-path :as fhir-path] [blaze.fhir-path-spec] [blaze.fhir.spec :as fhir-spec] [blaze.fhir.spec.type] [blaze.fhir.spec.type.system :as system] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [are deftest is testing]] [cognitect.anomalies :as anom] [juxt.iota :refer [given]] [taoensso.timbre :as log])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def ^:private resolver (reify fhir-path/Resolver (-resolve [_ _]))) (defn- eval ([expr resource] (eval expr resolver resource)) ([expr resolver resource] (fhir-path/eval resolver (fhir-path/compile expr) resource))) ;; 3. Path selection (deftest path-selection-test (testing "Resource.id" (are [x] (= x (first (eval "Resource.id" {:fhir/type :fhir/Patient :id x}))) "id-161533" "id-161537")) (testing "Patient.id" (are [x] (= x (first (eval "Patient.id" {:fhir/type :fhir/Patient :id x}))) "id-161533" "id-161537")) (testing "Patient.active" (testing "value" (are [x] (= x (first (eval "Patient.active" {:fhir/type :fhir/Patient :id "foo" :active x}))) true false)) (testing "type" (are [x] (= :fhir/boolean (fhir-spec/fhir-type (first (eval "Patient.active" {:fhir/type :fhir/Patient :id "foo" :active x})))) true false))) (testing "(Observation.value as boolean)" (are [x] (= x (first (eval "(Observation.value as boolean)" {:fhir/type :fhir/Observation :id "foo" :value x}))) true false))) ;; 4. Expressions ;; 4.1 Literals (deftest boolean-test (is (true? (first (eval "true" "foo")))) (is (false? (first (eval "false" "foo"))))) (deftest string-test (is (= "bar" (first (eval "'bar'" "foo"))))) (deftest integer-test (is (= 0 (first (eval "0" "foo"))))) (deftest decimal-test (is (= 0.1M (first (eval "0.1" "foo"))))) (deftest date-test (are [expr date] (= date (first (eval expr "foo"))) "@2020" (system/date 2020) "@2020-01" (system/date 2020 1) "@2020-01-02" (system/date 2020 1 2))) (deftest date-time-test (are [expr date-time] (= date-time (first (eval expr "foo"))) "@2020T" (system/date-time 2020) "@2020-01T" (system/date-time 2020 1) "@2020-01-02T" (system/date-time 2020 1 2) "@2020-01-02T03" (system/date-time 2020 1 2 3))) ;; 4.5. Singleton Evaluation of Collections (deftest singleton-test (testing "string concatenation" (testing "with no given name" (is (= (first (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"}]})) "<NAME>, "))) (testing "with one given name" (is (= (first (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe" :given ["<NAME>"]}]})) "<NAME>"))) (testing "with two given names" (given (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe" :given ["<NAME>" "<NAME>"]}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[\"John\" \"Foo\"]` as singleton")) (testing "with non-convertible type" (given (eval "Patient.name.family + ', ' + Patient.name" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[{:fhir/type :fhir/HumanName, :family \"Doe\"}]` as singleton"))) (testing "and expression" (testing "with one telecom" (is (= (first (eval "Patient.active and Patient.gender and Patient.telecom" {:fhir/type :fhir/Patient :id "foo" :active true :gender #fhir/code"female" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "foo"}]})) true))) (testing "with two telecoms" (given (eval "Patient.active and Patient.gender and Patient.telecom" {:fhir/type :fhir/Patient :id "foo" :active true :gender #fhir/code"female" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "foo"} {:fhir/type :fhir/ContactPoint :use #fhir/code"work" :value "bar"}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[{:fhir/type :fhir/ContactPoint, :use #fhir/code\"home\", :value \"foo\"} {:fhir/type :fhir/ContactPoint, :use #fhir/code\"work\", :value \"bar\"}]` as singleton")))) ;; 5. Functions (deftest resolve-function-test (let [resolver (reify fhir-path/Resolver (-resolve [_ uri] (when (= "reference-180039" uri) {:fhir/type :fhir/Patient :id "id-164737"})))] (given (eval "Specimen.subject.where(resolve() is Patient)" resolver {:fhir/type :fhir/Specimen :id "id-175250" :subject #fhir/Reference{:reference "reference-180039"}}) [0 :reference] := "reference-180039"))) ;; 5.1. Existence ;; 5.1.2. exists([criteria : expression]) : Boolean (deftest exists-function-test (is (false? (first (eval "Patient.deceased.exists()" {:fhir/type :fhir/Patient :id "id-182007"})))) (is (true? (first (eval "Patient.deceased.exists()" {:fhir/type :fhir/Patient :id "id-182007" :deceased true}))))) ;; 5.2. Filtering and projection ;; 5.2.1. where(criteria : expression) : collection (deftest where-function-test (testing "missing criteria" (given (fhir-path/compile "Patient.telecom.where()") ::anom/category := ::anom/incorrect ::anom/message := "missing criteria in `where` function in expression `Patient.telecom.where()`")) (testing "returns one matching item" (given (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]}) [0 :use] := #fhir/code"home" [0 :value] := "value-170758")) (testing "returns two matching items" (given (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"} {:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-145928"}]}) [0 :use] := #fhir/code"home" [0 :value] := "value-170758" [1 :use] := #fhir/code"home" [1 :value] := "value-145928")) (testing "returns empty collection on non-matching item" (is (empty? (eval "Patient.telecom.where(use = 'work')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]})))) (testing "returns empty collection on empty criteria result" (is (empty? (eval "Patient.telecom.where({})" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]})))) (testing "returns empty collection on empty input" (is (empty? (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953"})))) (testing "return error on multiple criteria result" (given (eval "Patient.address.where(line)" {:fhir/type :fhir/Patient :id "id-162953" :address [{:fhir/type :fhir/Address :line ["a" "b"]}]}) ::anom/category := ::anom/incorrect ::anom/message := "multiple result items `[\"a\" \"b\"]` while evaluating where function criteria")) (testing "return error on non-boolean criteria result" (given (eval "Patient.telecom.where(use)" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]}) ::anom/category := ::anom/incorrect ::anom/message := "non-boolean result `#fhir/code\"home\"` of type `:fhir/code` while evaluating where function criteria"))) ;; 5.2.4. ofType(type : type specifier) : collection (deftest of-type-function-test (testing "returns two matching items" (given (eval "Observation.component.value.ofType(Quantity)" {:fhir/type :fhir/Observation :component [{:fhir/type :fhir.Observation/component :value #fhir/Quantity{:value 150M}} {:fhir/type :fhir.Observation/component :value #fhir/Quantity{:value 100M}}]}) [0 :value] := 150M [1 :value] := 100M))) ;; 5.3. Subsetting ;; 5.3.1. [ index : Integer ] : collection (deftest indexer-test (is (= (eval "Bundle.entry[0].resource" {:fhir/type :fhir/Bundle :id "id-110914" :entry [{:fhir/type :fhir.Bundle/entry :resource {:fhir/type :fhir/Patient :id "id-111004"}}]}) [{:fhir/type :fhir/Patient :id "id-111004"}]))) ;; 5.4. Combining ;; 5.4.1. union(other : collection) (deftest union-test (let [patient {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"} {:fhir/type :fhir/HumanName :family "Bolton"}]}] (are [expr res] (= res (eval expr patient)) "{} | {}" [] "1 | {}" [1] "{} | 1" [1] "1 | 1" [1] "Patient.name.family | {}" ["Doe" "Bolton"] "Patient.name.family | 'Wade'" ["Wade" "Doe" "Bolton"] "{} | Patient.name.family" ["Doe" "Bolton"] "'Wade' | Patient.name.family" ["Wade" "Doe" "Bolton"] "Patient.name.family | Patient.name.family" ["Doe" "Bolton"])) (is (= (eval "Patient.gender | Patient.birthDate" {:fhir/type :fhir/Patient :id "id-162953" :gender #fhir/code"female" :birthDate #fhir/date"2020"}) [#fhir/code"female" #fhir/date"2020"]))) ;; 6. Operations ;; 6.1. Equality ;; 6.1.1. = (Equals) (deftest equals-test (testing "propagates empty collections" (testing "both empty" (is (empty? (eval "{} = {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "left empty" (is (empty? (eval "{} = Patient.id" {:fhir/type :fhir/Patient :id "foo"})))) (testing "right empty" (is (empty? (eval "Patient.id = {}" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "string comparison" (is (true? (first (eval "Patient.id = 'foo'" {:fhir/type :fhir/Patient :id "foo"})))) (is (false? (first (eval "Patient.id = 'bar'" {:fhir/type :fhir/Patient :id "foo"})))))) ;; 6.1.3. != (Not Equals) (deftest not-equals-test (testing "propagates empty collections" (testing "both empty" (is (empty? (eval "{} != {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "left empty" (is (empty? (eval "{} != Patient.id" {:fhir/type :fhir/Patient :id "foo"})))) (testing "right empty" (is (empty? (eval "Patient.id != {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "string comparison" (is (true? (first (eval "Patient.id != 'bar'" {:fhir/type :fhir/Patient :id "foo"})))) (is (false? (first (eval "Patient.id != 'foo'" {:fhir/type :fhir/Patient :id "foo"}))))))) ;; 6.3. Types ;; 6.3.1. is type specifier (deftest is-type-specifier-test (testing "single item with matching type returns true" (is (true? (first (eval "Patient.birthDate is date" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns false" (is (false? (first (eval "Patient.birthDate is string" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate is string" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier is string" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "is type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.3.3 as type specifier (deftest as-type-specifier-test (testing "single item with matching type returns the item" (is (= #fhir/date"2020" (first (eval "Patient.birthDate as date" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns an empty collection" (is (empty? (first (eval "Patient.birthDate as string" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate as string" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier as string" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "as type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.3.4 as(type : type specifier) (deftest as-function-test (testing "single item with matching type returns the item" (is (= #fhir/date"2020" (first (eval "Patient.birthDate.as(date)" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns an empty collection" (is (empty? (first (eval "Patient.birthDate.as(string)" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate.as(string)" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier.as(string)" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "as type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.5. Boolean logic ;; 6.5.1. and (deftest and-test (are [expr pred] (pred (first (eval expr {:fhir/type :fhir/Patient :id "id-162953" :gender #fhir/code"male" :birthDate #fhir/date"2020"}))) "Patient.gender = 'male' and Patient.birthDate = @2020" true? "Patient.gender = 'male' and Patient.birthDate = @2021" false? "Patient.gender = 'female' and Patient.birthDate = @2020" false? "Patient.gender = 'female' and Patient.birthDate = @2021" false?))
true
(ns blaze.fhir-path-test "See: http://hl7.org/fhirpath/index.html" (:refer-clojure :exclude [eval]) (:require [blaze.fhir-path :as fhir-path] [blaze.fhir-path-spec] [blaze.fhir.spec :as fhir-spec] [blaze.fhir.spec.type] [blaze.fhir.spec.type.system :as system] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [are deftest is testing]] [cognitect.anomalies :as anom] [juxt.iota :refer [given]] [taoensso.timbre :as log])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def ^:private resolver (reify fhir-path/Resolver (-resolve [_ _]))) (defn- eval ([expr resource] (eval expr resolver resource)) ([expr resolver resource] (fhir-path/eval resolver (fhir-path/compile expr) resource))) ;; 3. Path selection (deftest path-selection-test (testing "Resource.id" (are [x] (= x (first (eval "Resource.id" {:fhir/type :fhir/Patient :id x}))) "id-161533" "id-161537")) (testing "Patient.id" (are [x] (= x (first (eval "Patient.id" {:fhir/type :fhir/Patient :id x}))) "id-161533" "id-161537")) (testing "Patient.active" (testing "value" (are [x] (= x (first (eval "Patient.active" {:fhir/type :fhir/Patient :id "foo" :active x}))) true false)) (testing "type" (are [x] (= :fhir/boolean (fhir-spec/fhir-type (first (eval "Patient.active" {:fhir/type :fhir/Patient :id "foo" :active x})))) true false))) (testing "(Observation.value as boolean)" (are [x] (= x (first (eval "(Observation.value as boolean)" {:fhir/type :fhir/Observation :id "foo" :value x}))) true false))) ;; 4. Expressions ;; 4.1 Literals (deftest boolean-test (is (true? (first (eval "true" "foo")))) (is (false? (first (eval "false" "foo"))))) (deftest string-test (is (= "bar" (first (eval "'bar'" "foo"))))) (deftest integer-test (is (= 0 (first (eval "0" "foo"))))) (deftest decimal-test (is (= 0.1M (first (eval "0.1" "foo"))))) (deftest date-test (are [expr date] (= date (first (eval expr "foo"))) "@2020" (system/date 2020) "@2020-01" (system/date 2020 1) "@2020-01-02" (system/date 2020 1 2))) (deftest date-time-test (are [expr date-time] (= date-time (first (eval expr "foo"))) "@2020T" (system/date-time 2020) "@2020-01T" (system/date-time 2020 1) "@2020-01-02T" (system/date-time 2020 1 2) "@2020-01-02T03" (system/date-time 2020 1 2 3))) ;; 4.5. Singleton Evaluation of Collections (deftest singleton-test (testing "string concatenation" (testing "with no given name" (is (= (first (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"}]})) "PI:NAME:<NAME>END_PI, "))) (testing "with one given name" (is (= (first (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe" :given ["PI:NAME:<NAME>END_PI"]}]})) "PI:NAME:<NAME>END_PI"))) (testing "with two given names" (given (eval "Patient.name.family + ', ' + Patient.name.given" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe" :given ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[\"John\" \"Foo\"]` as singleton")) (testing "with non-convertible type" (given (eval "Patient.name.family + ', ' + Patient.name" {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[{:fhir/type :fhir/HumanName, :family \"Doe\"}]` as singleton"))) (testing "and expression" (testing "with one telecom" (is (= (first (eval "Patient.active and Patient.gender and Patient.telecom" {:fhir/type :fhir/Patient :id "foo" :active true :gender #fhir/code"female" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "foo"}]})) true))) (testing "with two telecoms" (given (eval "Patient.active and Patient.gender and Patient.telecom" {:fhir/type :fhir/Patient :id "foo" :active true :gender #fhir/code"female" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "foo"} {:fhir/type :fhir/ContactPoint :use #fhir/code"work" :value "bar"}]}) ::anom/category := ::anom/incorrect ::anom/message := "unable to evaluate `[{:fhir/type :fhir/ContactPoint, :use #fhir/code\"home\", :value \"foo\"} {:fhir/type :fhir/ContactPoint, :use #fhir/code\"work\", :value \"bar\"}]` as singleton")))) ;; 5. Functions (deftest resolve-function-test (let [resolver (reify fhir-path/Resolver (-resolve [_ uri] (when (= "reference-180039" uri) {:fhir/type :fhir/Patient :id "id-164737"})))] (given (eval "Specimen.subject.where(resolve() is Patient)" resolver {:fhir/type :fhir/Specimen :id "id-175250" :subject #fhir/Reference{:reference "reference-180039"}}) [0 :reference] := "reference-180039"))) ;; 5.1. Existence ;; 5.1.2. exists([criteria : expression]) : Boolean (deftest exists-function-test (is (false? (first (eval "Patient.deceased.exists()" {:fhir/type :fhir/Patient :id "id-182007"})))) (is (true? (first (eval "Patient.deceased.exists()" {:fhir/type :fhir/Patient :id "id-182007" :deceased true}))))) ;; 5.2. Filtering and projection ;; 5.2.1. where(criteria : expression) : collection (deftest where-function-test (testing "missing criteria" (given (fhir-path/compile "Patient.telecom.where()") ::anom/category := ::anom/incorrect ::anom/message := "missing criteria in `where` function in expression `Patient.telecom.where()`")) (testing "returns one matching item" (given (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]}) [0 :use] := #fhir/code"home" [0 :value] := "value-170758")) (testing "returns two matching items" (given (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"} {:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-145928"}]}) [0 :use] := #fhir/code"home" [0 :value] := "value-170758" [1 :use] := #fhir/code"home" [1 :value] := "value-145928")) (testing "returns empty collection on non-matching item" (is (empty? (eval "Patient.telecom.where(use = 'work')" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]})))) (testing "returns empty collection on empty criteria result" (is (empty? (eval "Patient.telecom.where({})" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]})))) (testing "returns empty collection on empty input" (is (empty? (eval "Patient.telecom.where(use = 'home')" {:fhir/type :fhir/Patient :id "id-162953"})))) (testing "return error on multiple criteria result" (given (eval "Patient.address.where(line)" {:fhir/type :fhir/Patient :id "id-162953" :address [{:fhir/type :fhir/Address :line ["a" "b"]}]}) ::anom/category := ::anom/incorrect ::anom/message := "multiple result items `[\"a\" \"b\"]` while evaluating where function criteria")) (testing "return error on non-boolean criteria result" (given (eval "Patient.telecom.where(use)" {:fhir/type :fhir/Patient :id "id-162953" :telecom [{:fhir/type :fhir/ContactPoint :use #fhir/code"home" :value "value-170758"}]}) ::anom/category := ::anom/incorrect ::anom/message := "non-boolean result `#fhir/code\"home\"` of type `:fhir/code` while evaluating where function criteria"))) ;; 5.2.4. ofType(type : type specifier) : collection (deftest of-type-function-test (testing "returns two matching items" (given (eval "Observation.component.value.ofType(Quantity)" {:fhir/type :fhir/Observation :component [{:fhir/type :fhir.Observation/component :value #fhir/Quantity{:value 150M}} {:fhir/type :fhir.Observation/component :value #fhir/Quantity{:value 100M}}]}) [0 :value] := 150M [1 :value] := 100M))) ;; 5.3. Subsetting ;; 5.3.1. [ index : Integer ] : collection (deftest indexer-test (is (= (eval "Bundle.entry[0].resource" {:fhir/type :fhir/Bundle :id "id-110914" :entry [{:fhir/type :fhir.Bundle/entry :resource {:fhir/type :fhir/Patient :id "id-111004"}}]}) [{:fhir/type :fhir/Patient :id "id-111004"}]))) ;; 5.4. Combining ;; 5.4.1. union(other : collection) (deftest union-test (let [patient {:fhir/type :fhir/Patient :id "foo" :name [{:fhir/type :fhir/HumanName :family "Doe"} {:fhir/type :fhir/HumanName :family "Bolton"}]}] (are [expr res] (= res (eval expr patient)) "{} | {}" [] "1 | {}" [1] "{} | 1" [1] "1 | 1" [1] "Patient.name.family | {}" ["Doe" "Bolton"] "Patient.name.family | 'Wade'" ["Wade" "Doe" "Bolton"] "{} | Patient.name.family" ["Doe" "Bolton"] "'Wade' | Patient.name.family" ["Wade" "Doe" "Bolton"] "Patient.name.family | Patient.name.family" ["Doe" "Bolton"])) (is (= (eval "Patient.gender | Patient.birthDate" {:fhir/type :fhir/Patient :id "id-162953" :gender #fhir/code"female" :birthDate #fhir/date"2020"}) [#fhir/code"female" #fhir/date"2020"]))) ;; 6. Operations ;; 6.1. Equality ;; 6.1.1. = (Equals) (deftest equals-test (testing "propagates empty collections" (testing "both empty" (is (empty? (eval "{} = {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "left empty" (is (empty? (eval "{} = Patient.id" {:fhir/type :fhir/Patient :id "foo"})))) (testing "right empty" (is (empty? (eval "Patient.id = {}" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "string comparison" (is (true? (first (eval "Patient.id = 'foo'" {:fhir/type :fhir/Patient :id "foo"})))) (is (false? (first (eval "Patient.id = 'bar'" {:fhir/type :fhir/Patient :id "foo"})))))) ;; 6.1.3. != (Not Equals) (deftest not-equals-test (testing "propagates empty collections" (testing "both empty" (is (empty? (eval "{} != {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "left empty" (is (empty? (eval "{} != Patient.id" {:fhir/type :fhir/Patient :id "foo"})))) (testing "right empty" (is (empty? (eval "Patient.id != {}" {:fhir/type :fhir/Patient :id "foo"})))) (testing "string comparison" (is (true? (first (eval "Patient.id != 'bar'" {:fhir/type :fhir/Patient :id "foo"})))) (is (false? (first (eval "Patient.id != 'foo'" {:fhir/type :fhir/Patient :id "foo"}))))))) ;; 6.3. Types ;; 6.3.1. is type specifier (deftest is-type-specifier-test (testing "single item with matching type returns true" (is (true? (first (eval "Patient.birthDate is date" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns false" (is (false? (first (eval "Patient.birthDate is string" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate is string" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier is string" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "is type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.3.3 as type specifier (deftest as-type-specifier-test (testing "single item with matching type returns the item" (is (= #fhir/date"2020" (first (eval "Patient.birthDate as date" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns an empty collection" (is (empty? (first (eval "Patient.birthDate as string" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate as string" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier as string" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "as type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.3.4 as(type : type specifier) (deftest as-function-test (testing "single item with matching type returns the item" (is (= #fhir/date"2020" (first (eval "Patient.birthDate.as(date)" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "single item with non-matching type returns an empty collection" (is (empty? (first (eval "Patient.birthDate.as(string)" {:fhir/type :fhir/Patient :id "foo" :birthDate #fhir/date"2020"}))))) (testing "empty collection returns empty collection" (is (empty? (first (eval "Patient.birthDate.as(string)" {:fhir/type :fhir/Patient :id "foo"}))))) (testing "multiple item returns an error" (given (eval "Patient.identifier.as(string)" {:fhir/type :fhir/Patient :id "id-162953" :identifier [#fhir/Identifier{:value "value-163922"} #fhir/Identifier{:value "value-163928"}]}) ::anom/category := ::anom/incorrect ::anom/message := "as type specifier with more than one item at the left side `[#fhir/Identifier{:value \"value-163922\"} #fhir/Identifier{:value \"value-163928\"}]`"))) ;; 6.5. Boolean logic ;; 6.5.1. and (deftest and-test (are [expr pred] (pred (first (eval expr {:fhir/type :fhir/Patient :id "id-162953" :gender #fhir/code"male" :birthDate #fhir/date"2020"}))) "Patient.gender = 'male' and Patient.birthDate = @2020" true? "Patient.gender = 'male' and Patient.birthDate = @2021" false? "Patient.gender = 'female' and Patient.birthDate = @2020" false? "Patient.gender = 'female' and Patient.birthDate = @2021" false?))
[ { "context": "sers\n (let [user (u/create {:name \"Test\" :email \"user@example.com\" :password \"s3cr3t\"})]\n\n (testing \"Authenticat", "end": 342, "score": 0.9999211430549622, "start": 326, "tag": "EMAIL", "value": "user@example.com" }, { "context": ":name \"Test\" :email \"user@example.com\" :password \"s3cr3t\"})]\n\n (testing \"Authenticates with valid token", "end": 361, "score": 0.9994938969612122, "start": 355, "tag": "PASSWORD", "value": "s3cr3t" }, { "context": " (is (nil? (auth/authenticate-token {} \"youhavetobekiddingme\"))))\n\n (testing \"Does not authentic", "end": 636, "score": 0.5144228339195251, "start": 633, "tag": "PASSWORD", "value": "eto" }, { "context": "is (nil? (auth/authenticate-token {} \"youhavetobekiddingme\"))))\n\n (testing \"Does not authenticate with ex", "end": 647, "score": 0.5836440324783325, "start": 639, "tag": "PASSWORD", "value": "iddingme" }, { "context": "rs\n; (let [user (u/create {:name \"User\" :email \"user@example.com\" :password \"s3cr3t\"})\n; admin (u/create {", "end": 1095, "score": 0.9999229311943054, "start": 1079, "tag": "EMAIL", "value": "user@example.com" }, { "context": ":name \"User\" :email \"user@example.com\" :password \"s3cr3t\"})\n; admin (u/create {:name \"Admin\" :emai", "end": 1114, "score": 0.9995092153549194, "start": 1108, "tag": "PASSWORD", "value": "s3cr3t" }, { "context": "\n; admin (u/create {:name \"Admin\" :email \"admin@example.com\" :password \"sup3rs3cr3t\" :restful-clojure.models.", "end": 1184, "score": 0.9999250173568726, "start": 1167, "tag": "EMAIL", "value": "admin@example.com" }, { "context": "ame \"Admin\" :email \"admin@example.com\" :password \"sup3rs3cr3t\" :restful-clojure.models.users/admin})]))", "end": 1208, "score": 0.9994889497756958, "start": 1197, "tag": "PASSWORD", "value": "sup3rs3cr3t" } ]
restful-clojure/test/restful_clojure/auth_test.clj
joaobertacchi/restful-clojure
65
(ns restful-clojure.auth-test (:use clojure.test restful-clojure.test-core) (:require [restful-clojure.auth :as auth] [restful-clojure.models.users :as u] [korma.core :as sql])) (use-fixtures :each with-rollback) (deftest authenticating-users (let [user (u/create {:name "Test" :email "user@example.com" :password "s3cr3t"})] (testing "Authenticates with valid token" (let [token (auth/make-token! (:id user))] (is (= user (auth/authenticate-token {} token))))) (testing "Does not authenticate with nonexistent token" (is (nil? (auth/authenticate-token {} "youhavetobekiddingme")))) (testing "Does not authenticate with expired token" (let [token (auth/make-token! (:id user)) sql (str "UPDATE auth_tokens " "SET created_at = NOW() - interval '7 hours' " "WHERE id = ?")] (sql/exec-raw [sql [token]]) (is (nil? (auth/authenticate-token {} token))))))) ; (detest authorizing-users ; (let [user (u/create {:name "User" :email "user@example.com" :password "s3cr3t"}) ; admin (u/create {:name "Admin" :email "admin@example.com" :password "sup3rs3cr3t" :restful-clojure.models.users/admin})]))
121847
(ns restful-clojure.auth-test (:use clojure.test restful-clojure.test-core) (:require [restful-clojure.auth :as auth] [restful-clojure.models.users :as u] [korma.core :as sql])) (use-fixtures :each with-rollback) (deftest authenticating-users (let [user (u/create {:name "Test" :email "<EMAIL>" :password "<PASSWORD>"})] (testing "Authenticates with valid token" (let [token (auth/make-token! (:id user))] (is (= user (auth/authenticate-token {} token))))) (testing "Does not authenticate with nonexistent token" (is (nil? (auth/authenticate-token {} "youhav<PASSWORD>bek<PASSWORD>")))) (testing "Does not authenticate with expired token" (let [token (auth/make-token! (:id user)) sql (str "UPDATE auth_tokens " "SET created_at = NOW() - interval '7 hours' " "WHERE id = ?")] (sql/exec-raw [sql [token]]) (is (nil? (auth/authenticate-token {} token))))))) ; (detest authorizing-users ; (let [user (u/create {:name "User" :email "<EMAIL>" :password "<PASSWORD>"}) ; admin (u/create {:name "Admin" :email "<EMAIL>" :password "<PASSWORD>" :restful-clojure.models.users/admin})]))
true
(ns restful-clojure.auth-test (:use clojure.test restful-clojure.test-core) (:require [restful-clojure.auth :as auth] [restful-clojure.models.users :as u] [korma.core :as sql])) (use-fixtures :each with-rollback) (deftest authenticating-users (let [user (u/create {:name "Test" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"})] (testing "Authenticates with valid token" (let [token (auth/make-token! (:id user))] (is (= user (auth/authenticate-token {} token))))) (testing "Does not authenticate with nonexistent token" (is (nil? (auth/authenticate-token {} "youhavPI:PASSWORD:<PASSWORD>END_PIbekPI:PASSWORD:<PASSWORD>END_PI")))) (testing "Does not authenticate with expired token" (let [token (auth/make-token! (:id user)) sql (str "UPDATE auth_tokens " "SET created_at = NOW() - interval '7 hours' " "WHERE id = ?")] (sql/exec-raw [sql [token]]) (is (nil? (auth/authenticate-token {} token))))))) ; (detest authorizing-users ; (let [user (u/create {:name "User" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}) ; admin (u/create {:name "Admin" :email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI" :restful-clojure.models.users/admin})]))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998311996459961, "start": 18, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/slackbot/routes/slash_command/stinkypinky.clj
chrisrink10/slackbot-clj
0
;; Copyright 2018 Chris Rink ;; ;; 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 slackbot.routes.slash-command.stinkypinky (:require [ring.util.response :as response] [slackbot.stinkypinky :as stinkypinky])) (def stinky-pinky-command-pattern #"(\S+)(?: ?(.*))") (defmulti handle-stinky-pinky (fn [{:keys [text]} _ _] (if-let [[_ command _] (re-matches stinky-pinky-command-pattern text)] command "help")) :default "help") (defmethod handle-stinky-pinky "set-answer" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ answer] (re-matches #"set-answer (\S+ \S+)" text)] (do (stinkypinky/set-answer tx token team_id channel_id user_id answer) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text "Stinky Pinky answers must be two rhyming words."} (response/response)))) (defmethod handle-stinky-pinky "set-clue" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ clue] (re-matches #"set-clue (.*)" text)] (do (stinkypinky/set-clue tx token team_id channel_id user_id clue) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text (str "Your Stinky Pinky clue didn't quite work. Try `/sp set-clue smelly finger`")} (response/response)))) (defmethod handle-stinky-pinky "set-hint" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ hint] (re-matches #"set-hint (\S+ \S+)" text)] (do (stinkypinky/set-hint tx token team_id channel_id user_id hint) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text (str "Stinky Pinky hints must be two rhyming words, " "like: `stink pink`, `stinky pinky`, `stinkity pinkity`, etc.")} (response/response)))) (defmethod handle-stinky-pinky "set-channel" [{:keys [team_id channel_id user_id]} tx token] (case (stinkypinky/set-channel tx token team_id channel_id user_id) :successfully-set-channel (-> (response/response nil) (response/status 204)) :channel-already-set (-> {:response_type "ephemeral" :text "This channel is already a Stinky Pinky channel."} (response/response)))) (defmethod handle-stinky-pinky "show-details" [{:keys [team_id channel_id]} tx token] (case (stinkypinky/show-details tx token team_id channel_id) :no-details (-> {:response_type "ephemeral" :text "No Stinky Pinky answer is set in the channel."} (response/response)) :details-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "show-guesses" [{:keys [team_id channel_id]} tx token] (case (stinkypinky/show-guesses tx token team_id channel_id) :no-guesses (-> {:response_type "ephemeral" :text "No Stinky Pinky guesses have been made in this channel."} (response/response)) :guesses-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "show-scores" [{:keys [team_id channel_id user_id]} tx token] (case (stinkypinky/show-scores tx token team_id channel_id user_id) :no-scores (-> {:response_type "ephemeral" :text "No Stinky Pinky scores found for this channel."} (response/response)) :scores-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "help" [_ _ _] (-> {:response_type "ephemeral" :text (->> [(str "Stinky Pinky is a word game. The game is played in rounds, " "each hosted by a single player. The host of the round will " "think of a pair of words that rhyme (like \"stinky pinky\"), " "for instance. The host will also think of a clue (like \"smelly " "finger\" for the previous answer). Other players enter a clue " "into the Stinky Pinky channel by guessing word pairs until the " "answer is guessed. The player which correctly guesses the pair " "hosts the next round. The game can continue ad nauseum or to a " "terminal score.") "Available `/sp` sub-commands are:" "- `set-answer [answer]` - if you are the host, set the answer for this round" "- `set-clue [clue]` - if you are the host, set the clue for this round" "- `set-hint [hint]` - if you are the host, _optionally_ set the hint for this round" "- `set-channel` - set the current channel as a Stinky Pinky channel and set you as the host of the first round" "- `show-details` - show the host, clue, and _optional_ hint" "- `show-guesses` - show the guesses players have made in the current channel's Stinky Pinky game" "- `show-scores` - show the scores for players in the current channel's Stinky Pinky game" "- `reset` - reset the scores and finish the game" "- `help` - show this text"] (interpose \newline) (apply str))} (response/response)))
101264
;; Copyright 2018 <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 slackbot.routes.slash-command.stinkypinky (:require [ring.util.response :as response] [slackbot.stinkypinky :as stinkypinky])) (def stinky-pinky-command-pattern #"(\S+)(?: ?(.*))") (defmulti handle-stinky-pinky (fn [{:keys [text]} _ _] (if-let [[_ command _] (re-matches stinky-pinky-command-pattern text)] command "help")) :default "help") (defmethod handle-stinky-pinky "set-answer" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ answer] (re-matches #"set-answer (\S+ \S+)" text)] (do (stinkypinky/set-answer tx token team_id channel_id user_id answer) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text "Stinky Pinky answers must be two rhyming words."} (response/response)))) (defmethod handle-stinky-pinky "set-clue" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ clue] (re-matches #"set-clue (.*)" text)] (do (stinkypinky/set-clue tx token team_id channel_id user_id clue) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text (str "Your Stinky Pinky clue didn't quite work. Try `/sp set-clue smelly finger`")} (response/response)))) (defmethod handle-stinky-pinky "set-hint" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ hint] (re-matches #"set-hint (\S+ \S+)" text)] (do (stinkypinky/set-hint tx token team_id channel_id user_id hint) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text (str "Stinky Pinky hints must be two rhyming words, " "like: `stink pink`, `stinky pinky`, `stinkity pinkity`, etc.")} (response/response)))) (defmethod handle-stinky-pinky "set-channel" [{:keys [team_id channel_id user_id]} tx token] (case (stinkypinky/set-channel tx token team_id channel_id user_id) :successfully-set-channel (-> (response/response nil) (response/status 204)) :channel-already-set (-> {:response_type "ephemeral" :text "This channel is already a Stinky Pinky channel."} (response/response)))) (defmethod handle-stinky-pinky "show-details" [{:keys [team_id channel_id]} tx token] (case (stinkypinky/show-details tx token team_id channel_id) :no-details (-> {:response_type "ephemeral" :text "No Stinky Pinky answer is set in the channel."} (response/response)) :details-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "show-guesses" [{:keys [team_id channel_id]} tx token] (case (stinkypinky/show-guesses tx token team_id channel_id) :no-guesses (-> {:response_type "ephemeral" :text "No Stinky Pinky guesses have been made in this channel."} (response/response)) :guesses-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "show-scores" [{:keys [team_id channel_id user_id]} tx token] (case (stinkypinky/show-scores tx token team_id channel_id user_id) :no-scores (-> {:response_type "ephemeral" :text "No Stinky Pinky scores found for this channel."} (response/response)) :scores-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "help" [_ _ _] (-> {:response_type "ephemeral" :text (->> [(str "Stinky Pinky is a word game. The game is played in rounds, " "each hosted by a single player. The host of the round will " "think of a pair of words that rhyme (like \"stinky pinky\"), " "for instance. The host will also think of a clue (like \"smelly " "finger\" for the previous answer). Other players enter a clue " "into the Stinky Pinky channel by guessing word pairs until the " "answer is guessed. The player which correctly guesses the pair " "hosts the next round. The game can continue ad nauseum or to a " "terminal score.") "Available `/sp` sub-commands are:" "- `set-answer [answer]` - if you are the host, set the answer for this round" "- `set-clue [clue]` - if you are the host, set the clue for this round" "- `set-hint [hint]` - if you are the host, _optionally_ set the hint for this round" "- `set-channel` - set the current channel as a Stinky Pinky channel and set you as the host of the first round" "- `show-details` - show the host, clue, and _optional_ hint" "- `show-guesses` - show the guesses players have made in the current channel's Stinky Pinky game" "- `show-scores` - show the scores for players in the current channel's Stinky Pinky game" "- `reset` - reset the scores and finish the game" "- `help` - show this text"] (interpose \newline) (apply str))} (response/response)))
true
;; Copyright 2018 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 slackbot.routes.slash-command.stinkypinky (:require [ring.util.response :as response] [slackbot.stinkypinky :as stinkypinky])) (def stinky-pinky-command-pattern #"(\S+)(?: ?(.*))") (defmulti handle-stinky-pinky (fn [{:keys [text]} _ _] (if-let [[_ command _] (re-matches stinky-pinky-command-pattern text)] command "help")) :default "help") (defmethod handle-stinky-pinky "set-answer" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ answer] (re-matches #"set-answer (\S+ \S+)" text)] (do (stinkypinky/set-answer tx token team_id channel_id user_id answer) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text "Stinky Pinky answers must be two rhyming words."} (response/response)))) (defmethod handle-stinky-pinky "set-clue" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ clue] (re-matches #"set-clue (.*)" text)] (do (stinkypinky/set-clue tx token team_id channel_id user_id clue) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text (str "Your Stinky Pinky clue didn't quite work. Try `/sp set-clue smelly finger`")} (response/response)))) (defmethod handle-stinky-pinky "set-hint" [{:keys [team_id channel_id user_id text]} tx token] (if-let [[_ hint] (re-matches #"set-hint (\S+ \S+)" text)] (do (stinkypinky/set-hint tx token team_id channel_id user_id hint) (-> (response/response nil) (response/status 204))) (-> {:response_type "ephemeral" :text (str "Stinky Pinky hints must be two rhyming words, " "like: `stink pink`, `stinky pinky`, `stinkity pinkity`, etc.")} (response/response)))) (defmethod handle-stinky-pinky "set-channel" [{:keys [team_id channel_id user_id]} tx token] (case (stinkypinky/set-channel tx token team_id channel_id user_id) :successfully-set-channel (-> (response/response nil) (response/status 204)) :channel-already-set (-> {:response_type "ephemeral" :text "This channel is already a Stinky Pinky channel."} (response/response)))) (defmethod handle-stinky-pinky "show-details" [{:keys [team_id channel_id]} tx token] (case (stinkypinky/show-details tx token team_id channel_id) :no-details (-> {:response_type "ephemeral" :text "No Stinky Pinky answer is set in the channel."} (response/response)) :details-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "show-guesses" [{:keys [team_id channel_id]} tx token] (case (stinkypinky/show-guesses tx token team_id channel_id) :no-guesses (-> {:response_type "ephemeral" :text "No Stinky Pinky guesses have been made in this channel."} (response/response)) :guesses-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "show-scores" [{:keys [team_id channel_id user_id]} tx token] (case (stinkypinky/show-scores tx token team_id channel_id user_id) :no-scores (-> {:response_type "ephemeral" :text "No Stinky Pinky scores found for this channel."} (response/response)) :scores-sent (-> (response/response nil) (response/status 204)))) (defmethod handle-stinky-pinky "help" [_ _ _] (-> {:response_type "ephemeral" :text (->> [(str "Stinky Pinky is a word game. The game is played in rounds, " "each hosted by a single player. The host of the round will " "think of a pair of words that rhyme (like \"stinky pinky\"), " "for instance. The host will also think of a clue (like \"smelly " "finger\" for the previous answer). Other players enter a clue " "into the Stinky Pinky channel by guessing word pairs until the " "answer is guessed. The player which correctly guesses the pair " "hosts the next round. The game can continue ad nauseum or to a " "terminal score.") "Available `/sp` sub-commands are:" "- `set-answer [answer]` - if you are the host, set the answer for this round" "- `set-clue [clue]` - if you are the host, set the clue for this round" "- `set-hint [hint]` - if you are the host, _optionally_ set the hint for this round" "- `set-channel` - set the current channel as a Stinky Pinky channel and set you as the host of the first round" "- `show-details` - show the host, clue, and _optional_ hint" "- `show-guesses` - show the guesses players have made in the current channel's Stinky Pinky game" "- `show-scores` - show the scores for players in the current channel's Stinky Pinky game" "- `reset` - reset the scores and finish the game" "- `help` - show this text"] (interpose \newline) (apply str))} (response/response)))
[ { "context": "(ns maximgb.re-service.core\n {:author \"Maxim Bazhenov\"})\n\n\n(defmacro def-re-service\n \"Defines a servic", "end": 54, "score": 0.9998569488525391, "start": 40, "tag": "NAME", "value": "Maxim Bazhenov" } ]
src/maximgb/re_service/core.clj
MaximGB/re-service
1
(ns maximgb.re-service.core {:author "Maxim Bazhenov"}) (defmacro def-re-service "Defines a service with the given `service-id`." [service-id] `(register-service ~service-id)) (defmacro def-re-service-command "Defines a command with the given `command-id` for service designated by `service-id`. Command recieves set of arguments defined in `args` vector and is implemented by given `fn-body`. If command is invoked during co-effect injection then the first argument will be co-effects map." [service-id command-id args & fn-body] `(register-service-command ~service-id ~command-id (fn ~args ~@fn-body))) (defmacro def-re-service-command-raw "Defines a raw service command. Command recieves set of arguments defined in `args` vector and is implemented by given `fn-body`. The difference from `(def-service-command)` is that `service-id` `command-id` will be passed as the first and the second arguments in the `args` vector." [service-id command-id args & fn-body] `(register-service-command-raw ~service-id ~command-id (fn ~args ~@fn-body)))
81971
(ns maximgb.re-service.core {:author "<NAME>"}) (defmacro def-re-service "Defines a service with the given `service-id`." [service-id] `(register-service ~service-id)) (defmacro def-re-service-command "Defines a command with the given `command-id` for service designated by `service-id`. Command recieves set of arguments defined in `args` vector and is implemented by given `fn-body`. If command is invoked during co-effect injection then the first argument will be co-effects map." [service-id command-id args & fn-body] `(register-service-command ~service-id ~command-id (fn ~args ~@fn-body))) (defmacro def-re-service-command-raw "Defines a raw service command. Command recieves set of arguments defined in `args` vector and is implemented by given `fn-body`. The difference from `(def-service-command)` is that `service-id` `command-id` will be passed as the first and the second arguments in the `args` vector." [service-id command-id args & fn-body] `(register-service-command-raw ~service-id ~command-id (fn ~args ~@fn-body)))
true
(ns maximgb.re-service.core {:author "PI:NAME:<NAME>END_PI"}) (defmacro def-re-service "Defines a service with the given `service-id`." [service-id] `(register-service ~service-id)) (defmacro def-re-service-command "Defines a command with the given `command-id` for service designated by `service-id`. Command recieves set of arguments defined in `args` vector and is implemented by given `fn-body`. If command is invoked during co-effect injection then the first argument will be co-effects map." [service-id command-id args & fn-body] `(register-service-command ~service-id ~command-id (fn ~args ~@fn-body))) (defmacro def-re-service-command-raw "Defines a raw service command. Command recieves set of arguments defined in `args` vector and is implemented by given `fn-body`. The difference from `(def-service-command)` is that `service-id` `command-id` will be passed as the first and the second arguments in the `args` vector." [service-id command-id args & fn-body] `(register-service-command-raw ~service-id ~command-id (fn ~args ~@fn-body)))
[ { "context": "/lawyerAssoc/\") n))\n\n(def lawyerAssocMap { \n\t:name fullname\n\t:profession profession\n\t:city city})\n\n(defrecord", "end": 344, "score": 0.9134289026260376, "start": 336, "tag": "NAME", "value": "fullname" }, { "context": "defmethod convert :lawyerAssoc [x type]\n(let [[_ _ firstName lastName] x]\n\t(->LawyerAssociates (str firstName ", "end": 582, "score": 0.9665108919143677, "start": 573, "tag": "NAME", "value": "firstName" }, { "context": "convert :lawyerAssoc [x type]\n(let [[_ _ firstName lastName] x]\n\t(->LawyerAssociates (str firstName \" \" lastN", "end": 591, "score": 0.9163031578063965, "start": 583, "tag": "NAME", "value": "lastName" } ]
src/clojsesame/integration/lawyer_assoc.clj
hotlib/datanest2rdf
0
(ns clojsesame.integration.lawyer_assoc (:require [clojsesame.vocabulary :refer :all] [clojsesame.sesame :refer :all])) (def lawyerAssocInfo {:filename "dumps/lawyer_associates-dump.csv" :type :lawyerAssoc}) (defn- lawyerAssocURI [{ n :name}] (createURI (str basicNamespace "/lawyerAssoc/") n)) (def lawyerAssocMap { :name fullname :profession profession :city city}) (defrecord LawyerAssociates [name profession] SesameRepository (store [x] (storeRecord lawyerAssocURI lawyerAssocMap x))) (defmethod convert :lawyerAssoc [x type] (let [[_ _ firstName lastName] x] (->LawyerAssociates (str firstName " " lastName) "lawyerAssociate")))
96187
(ns clojsesame.integration.lawyer_assoc (:require [clojsesame.vocabulary :refer :all] [clojsesame.sesame :refer :all])) (def lawyerAssocInfo {:filename "dumps/lawyer_associates-dump.csv" :type :lawyerAssoc}) (defn- lawyerAssocURI [{ n :name}] (createURI (str basicNamespace "/lawyerAssoc/") n)) (def lawyerAssocMap { :name <NAME> :profession profession :city city}) (defrecord LawyerAssociates [name profession] SesameRepository (store [x] (storeRecord lawyerAssocURI lawyerAssocMap x))) (defmethod convert :lawyerAssoc [x type] (let [[_ _ <NAME> <NAME>] x] (->LawyerAssociates (str firstName " " lastName) "lawyerAssociate")))
true
(ns clojsesame.integration.lawyer_assoc (:require [clojsesame.vocabulary :refer :all] [clojsesame.sesame :refer :all])) (def lawyerAssocInfo {:filename "dumps/lawyer_associates-dump.csv" :type :lawyerAssoc}) (defn- lawyerAssocURI [{ n :name}] (createURI (str basicNamespace "/lawyerAssoc/") n)) (def lawyerAssocMap { :name PI:NAME:<NAME>END_PI :profession profession :city city}) (defrecord LawyerAssociates [name profession] SesameRepository (store [x] (storeRecord lawyerAssocURI lawyerAssocMap x))) (defmethod convert :lawyerAssoc [x type] (let [[_ _ PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI] x] (->LawyerAssociates (str firstName " " lastName) "lawyerAssociate")))
[ { "context": "ons to various java SAM interfaces.\"\n :author \"Vladimir Tsanev\"}\n reactor-core.util.function\n (:import\n (ja", "end": 712, "score": 0.9998278617858887, "start": 697, "tag": "NAME", "value": "Vladimir Tsanev" } ]
src/reactor_core/util/function.clj
jaju/reactor-core-clojure
2
; ; Copyright 2018 the original author or authors. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns ^{:doc "Converters from clojure functions to various java SAM interfaces." :author "Vladimir Tsanev"} reactor-core.util.function (:import (java.util.function Consumer BiFunction Predicate Function LongFunction BiPredicate LongConsumer Supplier BooleanSupplier BiConsumer))) (defn as-predicate ^Predicate [p] (if (or (nil? p) (instance? Predicate p)) p (reify Predicate (test [_ t] (p t))))) (defn as-bi-predicate ^BiPredicate [p] (if (or (nil? p) (instance? BiPredicate p)) p (reify BiPredicate (test [_ t u] (p t u))))) (defn as-function ^Function [f] (if (or (nil? f) (instance? Function f)) f (reify Function (apply [_ t] (f t))))) (defn as-long-function ^LongFunction [f] (if (or (nil? f) (instance? LongFunction f)) f (reify LongFunction (apply [_ value] (f value))))) (defn ^BiFunction as-bi-function ^BiFunction [f] (if (or (nil? f) (instance? BiFunction f)) f (reify BiFunction (apply [_ t u] (f t u))))) (defn as-consumer ^Consumer [c] (if (or (nil? c) (instance? Consumer c)) c (reify Consumer (accept [_ t] (c t))))) (defn as-long-consumer ^LongConsumer [c] (if (or (nil? c) (instance? LongConsumer c)) c (reify LongConsumer (accept [_ value] (c value))))) (defn as-bi-consumer ^BiConsumer [c] (if (or (nil? c) (instance? BiConsumer c)) c (reify BiConsumer (accept [_ t u] (c t u))))) (defn as-runnable ^Runnable [r] (if (or (nil? r) (instance? Runnable r)) r (reify Runnable (run [_] (r))))) (defn as-callable ^Callable [c] (if (or (nil? c) (instance? Callable c)) c (reify Callable (call [_] (c))))) (defn as-supplier ^Supplier [s] (if (or (nil? s) (instance? Supplier s)) s (reify Supplier (get [_] (s))))) (defn as-boolean-supplier ^BooleanSupplier [s] (if (or (nil? s) (instance? BooleanSupplier s)) s (reify BooleanSupplier (getAsBoolean [_] (s)))))
34286
; ; Copyright 2018 the original author or authors. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns ^{:doc "Converters from clojure functions to various java SAM interfaces." :author "<NAME>"} reactor-core.util.function (:import (java.util.function Consumer BiFunction Predicate Function LongFunction BiPredicate LongConsumer Supplier BooleanSupplier BiConsumer))) (defn as-predicate ^Predicate [p] (if (or (nil? p) (instance? Predicate p)) p (reify Predicate (test [_ t] (p t))))) (defn as-bi-predicate ^BiPredicate [p] (if (or (nil? p) (instance? BiPredicate p)) p (reify BiPredicate (test [_ t u] (p t u))))) (defn as-function ^Function [f] (if (or (nil? f) (instance? Function f)) f (reify Function (apply [_ t] (f t))))) (defn as-long-function ^LongFunction [f] (if (or (nil? f) (instance? LongFunction f)) f (reify LongFunction (apply [_ value] (f value))))) (defn ^BiFunction as-bi-function ^BiFunction [f] (if (or (nil? f) (instance? BiFunction f)) f (reify BiFunction (apply [_ t u] (f t u))))) (defn as-consumer ^Consumer [c] (if (or (nil? c) (instance? Consumer c)) c (reify Consumer (accept [_ t] (c t))))) (defn as-long-consumer ^LongConsumer [c] (if (or (nil? c) (instance? LongConsumer c)) c (reify LongConsumer (accept [_ value] (c value))))) (defn as-bi-consumer ^BiConsumer [c] (if (or (nil? c) (instance? BiConsumer c)) c (reify BiConsumer (accept [_ t u] (c t u))))) (defn as-runnable ^Runnable [r] (if (or (nil? r) (instance? Runnable r)) r (reify Runnable (run [_] (r))))) (defn as-callable ^Callable [c] (if (or (nil? c) (instance? Callable c)) c (reify Callable (call [_] (c))))) (defn as-supplier ^Supplier [s] (if (or (nil? s) (instance? Supplier s)) s (reify Supplier (get [_] (s))))) (defn as-boolean-supplier ^BooleanSupplier [s] (if (or (nil? s) (instance? BooleanSupplier s)) s (reify BooleanSupplier (getAsBoolean [_] (s)))))
true
; ; Copyright 2018 the original author or authors. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns ^{:doc "Converters from clojure functions to various java SAM interfaces." :author "PI:NAME:<NAME>END_PI"} reactor-core.util.function (:import (java.util.function Consumer BiFunction Predicate Function LongFunction BiPredicate LongConsumer Supplier BooleanSupplier BiConsumer))) (defn as-predicate ^Predicate [p] (if (or (nil? p) (instance? Predicate p)) p (reify Predicate (test [_ t] (p t))))) (defn as-bi-predicate ^BiPredicate [p] (if (or (nil? p) (instance? BiPredicate p)) p (reify BiPredicate (test [_ t u] (p t u))))) (defn as-function ^Function [f] (if (or (nil? f) (instance? Function f)) f (reify Function (apply [_ t] (f t))))) (defn as-long-function ^LongFunction [f] (if (or (nil? f) (instance? LongFunction f)) f (reify LongFunction (apply [_ value] (f value))))) (defn ^BiFunction as-bi-function ^BiFunction [f] (if (or (nil? f) (instance? BiFunction f)) f (reify BiFunction (apply [_ t u] (f t u))))) (defn as-consumer ^Consumer [c] (if (or (nil? c) (instance? Consumer c)) c (reify Consumer (accept [_ t] (c t))))) (defn as-long-consumer ^LongConsumer [c] (if (or (nil? c) (instance? LongConsumer c)) c (reify LongConsumer (accept [_ value] (c value))))) (defn as-bi-consumer ^BiConsumer [c] (if (or (nil? c) (instance? BiConsumer c)) c (reify BiConsumer (accept [_ t u] (c t u))))) (defn as-runnable ^Runnable [r] (if (or (nil? r) (instance? Runnable r)) r (reify Runnable (run [_] (r))))) (defn as-callable ^Callable [c] (if (or (nil? c) (instance? Callable c)) c (reify Callable (call [_] (c))))) (defn as-supplier ^Supplier [s] (if (or (nil? s) (instance? Supplier s)) s (reify Supplier (get [_] (s))))) (defn as-boolean-supplier ^BooleanSupplier [s] (if (or (nil? s) (instance? BooleanSupplier s)) s (reify BooleanSupplier (getAsBoolean [_] (s)))))
[ { "context": "esses) using standard sim tools.\"\r\n :author \"Lucy Bridges\"}\r\n simulator.simulations.normal\r\n (:use simula", "end": 128, "score": 0.9998748898506165, "start": 116, "tag": "NAME", "value": "Lucy Bridges" } ]
src/patient-simulator/sims/normal.clj
connectedhealthcities/anytown
0
(ns ^{:doc "A simulator of normal patients (having no chronic illnesses) using standard sim tools." :author "Lucy Bridges"} simulator.simulations.normal (:use simulator.simulation [simulator.utils :only (rand-range)] [simulator.simulation utils standard] simulator.simulation.coding.read simulator.pathways simulator.pathways.utils simulator.time)) ) (simple-node alcohol-screening-entry nil :new-patient-registration) ;; done (simple-node new-patient-screening-entry nil :new-patient-registration) ;; done (simple-node smoking-cessation-advice-entry nil :new-patient-registration) ;; done (simple-node bmi-entry nil :new-patient-registration) ;; done (simple-node weight-entry nil :new-patient-registration) ;; done (simple-node height-entry nil :new-patient-registration) ;; done (simple-node systolic-bp-entry nil :new-patient-registration) ;; done (simple-node diastolic-bp-entry nil :new-patient-registration) ;; done (simple-node new-patient-registration (children (possibilities systolic-bp-entry 8/10 diastolic-bp-entry 8/10 height-entry 7/10 weight-entry 7/10 bmi-entry 9/10 new-patient-screening-entry 9/10 alcohol-screening-entry 6/10 smoking-cessation-advice-entry 3/10) 1 0) :new-patient-registration) (repeating-node random-admin-event #(years 0 4) nil :random-admin-event) (repeating-node random-medication-event #(years 0 5) nil :random-medication-event) (repeating-node random-measurements #(years 0 8) nil :random-measurements) (repeating-node random-blood-test #(years 0 10) nil :random-blood-test) (lifeline-fn birth 0 new-patient-registration #(years 15 35) random-admin-event #(years 5 10) random-medication-event #(years 5 10) random-measurements #(years 5 10) random-blood-test #(years 5 10) death #(years-normal 80 10)) (patient-fn #(random-patient [1965 20] ethnicity-all ["gp"])) (journal-formatter default-journal-formatter) (patient-formatter default-patient-formatter) (journal-map (merge { :random-admin-event general-admin :random-medication-event general-medications :random-blood-test general-blood-tests :random-measurements general-measurements :bmi-entry (measurement-entry bmi #(nd 23 5) "kg/m^2") :alcohol-screening-entry (measurement-entry alcohol-screening #(nd 2 1/12) "/12") :new-patient-screening-entry (entry new-patient-screening) :smoking-cessation-advice-entry (entry smoking-cessation-advice) :weight-entry (measurement-entry weight #(nd 90 40/150) "kg") :height-entry (measurement-entry height #(nd 185 120/250) "cm") :systolic-bp-entry (measurement-entry systolic-bp #(rand-range 80 130) "mmHg") :diastolic-bp-entry (measurement-entry diastolic-bp #(rand-range 40 85) "mmHg") :born nil :died nil }))
121311
(ns ^{:doc "A simulator of normal patients (having no chronic illnesses) using standard sim tools." :author "<NAME>"} simulator.simulations.normal (:use simulator.simulation [simulator.utils :only (rand-range)] [simulator.simulation utils standard] simulator.simulation.coding.read simulator.pathways simulator.pathways.utils simulator.time)) ) (simple-node alcohol-screening-entry nil :new-patient-registration) ;; done (simple-node new-patient-screening-entry nil :new-patient-registration) ;; done (simple-node smoking-cessation-advice-entry nil :new-patient-registration) ;; done (simple-node bmi-entry nil :new-patient-registration) ;; done (simple-node weight-entry nil :new-patient-registration) ;; done (simple-node height-entry nil :new-patient-registration) ;; done (simple-node systolic-bp-entry nil :new-patient-registration) ;; done (simple-node diastolic-bp-entry nil :new-patient-registration) ;; done (simple-node new-patient-registration (children (possibilities systolic-bp-entry 8/10 diastolic-bp-entry 8/10 height-entry 7/10 weight-entry 7/10 bmi-entry 9/10 new-patient-screening-entry 9/10 alcohol-screening-entry 6/10 smoking-cessation-advice-entry 3/10) 1 0) :new-patient-registration) (repeating-node random-admin-event #(years 0 4) nil :random-admin-event) (repeating-node random-medication-event #(years 0 5) nil :random-medication-event) (repeating-node random-measurements #(years 0 8) nil :random-measurements) (repeating-node random-blood-test #(years 0 10) nil :random-blood-test) (lifeline-fn birth 0 new-patient-registration #(years 15 35) random-admin-event #(years 5 10) random-medication-event #(years 5 10) random-measurements #(years 5 10) random-blood-test #(years 5 10) death #(years-normal 80 10)) (patient-fn #(random-patient [1965 20] ethnicity-all ["gp"])) (journal-formatter default-journal-formatter) (patient-formatter default-patient-formatter) (journal-map (merge { :random-admin-event general-admin :random-medication-event general-medications :random-blood-test general-blood-tests :random-measurements general-measurements :bmi-entry (measurement-entry bmi #(nd 23 5) "kg/m^2") :alcohol-screening-entry (measurement-entry alcohol-screening #(nd 2 1/12) "/12") :new-patient-screening-entry (entry new-patient-screening) :smoking-cessation-advice-entry (entry smoking-cessation-advice) :weight-entry (measurement-entry weight #(nd 90 40/150) "kg") :height-entry (measurement-entry height #(nd 185 120/250) "cm") :systolic-bp-entry (measurement-entry systolic-bp #(rand-range 80 130) "mmHg") :diastolic-bp-entry (measurement-entry diastolic-bp #(rand-range 40 85) "mmHg") :born nil :died nil }))
true
(ns ^{:doc "A simulator of normal patients (having no chronic illnesses) using standard sim tools." :author "PI:NAME:<NAME>END_PI"} simulator.simulations.normal (:use simulator.simulation [simulator.utils :only (rand-range)] [simulator.simulation utils standard] simulator.simulation.coding.read simulator.pathways simulator.pathways.utils simulator.time)) ) (simple-node alcohol-screening-entry nil :new-patient-registration) ;; done (simple-node new-patient-screening-entry nil :new-patient-registration) ;; done (simple-node smoking-cessation-advice-entry nil :new-patient-registration) ;; done (simple-node bmi-entry nil :new-patient-registration) ;; done (simple-node weight-entry nil :new-patient-registration) ;; done (simple-node height-entry nil :new-patient-registration) ;; done (simple-node systolic-bp-entry nil :new-patient-registration) ;; done (simple-node diastolic-bp-entry nil :new-patient-registration) ;; done (simple-node new-patient-registration (children (possibilities systolic-bp-entry 8/10 diastolic-bp-entry 8/10 height-entry 7/10 weight-entry 7/10 bmi-entry 9/10 new-patient-screening-entry 9/10 alcohol-screening-entry 6/10 smoking-cessation-advice-entry 3/10) 1 0) :new-patient-registration) (repeating-node random-admin-event #(years 0 4) nil :random-admin-event) (repeating-node random-medication-event #(years 0 5) nil :random-medication-event) (repeating-node random-measurements #(years 0 8) nil :random-measurements) (repeating-node random-blood-test #(years 0 10) nil :random-blood-test) (lifeline-fn birth 0 new-patient-registration #(years 15 35) random-admin-event #(years 5 10) random-medication-event #(years 5 10) random-measurements #(years 5 10) random-blood-test #(years 5 10) death #(years-normal 80 10)) (patient-fn #(random-patient [1965 20] ethnicity-all ["gp"])) (journal-formatter default-journal-formatter) (patient-formatter default-patient-formatter) (journal-map (merge { :random-admin-event general-admin :random-medication-event general-medications :random-blood-test general-blood-tests :random-measurements general-measurements :bmi-entry (measurement-entry bmi #(nd 23 5) "kg/m^2") :alcohol-screening-entry (measurement-entry alcohol-screening #(nd 2 1/12) "/12") :new-patient-screening-entry (entry new-patient-screening) :smoking-cessation-advice-entry (entry smoking-cessation-advice) :weight-entry (measurement-entry weight #(nd 90 40/150) "kg") :height-entry (measurement-entry height #(nd 185 120/250) "cm") :systolic-bp-entry (measurement-entry systolic-bp #(rand-range 80 130) "mmHg") :diastolic-bp-entry (measurement-entry diastolic-bp #(rand-range 40 85) "mmHg") :born nil :died nil }))
[ { "context": "nCall \"HelloWorld\"\n\n [:String \"Johnny\"]]]])\n\n (ast-to-ir [:FunDef {:args [], :fn-name ", "end": 14809, "score": 0.8082499504089355, "start": 14803, "tag": "NAME", "value": "Johnny" }, { "context": "ype :string}\n [:FunCall \"Hello\" [:String \"Johnny\"]]]])\n emit/emit-and-run!)\n\n\n ;; make-fn fr", "end": 16143, "score": 0.8037802577018738, "start": 16137, "tag": "NAME", "value": "Johnny" }, { "context": "t [:string] :string]]]},)\n\n\n (TestConcat/invoke \"Johnny Von Neuman\")\n\n (emit/make-fn {:class-name \"MA1\"\n ", "end": 16671, "score": 0.9998305439949036, "start": 16654, "tag": "NAME", "value": "Johnny Von Neuman" }, { "context": " :body\n [[:string {:value \"Johnny\"}]\n [:call-fn\n ", "end": 16839, "score": 0.9998019337654114, "start": 16833, "tag": "NAME", "value": "Johnny" } ]
src/lasm/ast.clj
nabacg/lasm
0
(ns lasm.ast (:require [clojure.string :as string] [clojure.reflect :as reflect])) (defn error [expr & [msg ]] (throw (ex-info (str "Invalid-expression: " msg) {:expr expr :msg msg}))) (defn errorf [msg & args] (throw (ex-info (apply format msg args) {:msg msg :args args}))) (defmulti ast-to-ir (fn [expr _] (first expr))) (defn args-to-locals [args] (vec (mapcat identity (map-indexed (fn [i {:keys [id type]}] [[:arg {:value i}] [:def-local {:var-id id :var-type type}]]) args)))) (defn map-ast-to-ir [env exprs] (reduce (fn [[env irs] expr] (let [[env' ir] (ast-to-ir expr env)] [env' (into irs ir)])) [env []] exprs)) (defn ops-to-ir [ops tenv] (vec (mapcat #(second (ast-to-ir % tenv)) ops))) (defmethod ast-to-ir :AddInt [[_ & ops] tenv] [tenv (conj (ops-to-ir ops tenv) [:add-int])]) (defmethod ast-to-ir :SubInt [[_ & ops] tenv] [tenv (conj (ops-to-ir ops tenv) [:sub-int])]) (defmethod ast-to-ir :MulInt [[_ & ops] tenv] [tenv (conj (vec (mapcat #(second (ast-to-ir % tenv)) ops)) [:mul-int])]) (defmethod ast-to-ir :DivInt [[_ & ops] tenv] [tenv (conj (mapv #(first (second (ast-to-ir % tenv))) ops) [:div-int])]) (defmethod ast-to-ir :String [[_ str-val] env] [env [[:string {:value str-val}]]]) (defmethod ast-to-ir :Int [[_ int-val] env] [env [[:int {:value int-val}]]]) (defmethod ast-to-ir :VarRef [[_ {:keys [var-id var-type]}] env] (let [declared-type var-type var-type (env var-id)] (cond (and (nil? declared-type) (nil? var-type)) (errorf "Unknown variable found %s" var-id) (and declared-type var-type (not= declared-type var-type)) (errorf "Incompatible variable types found, declared-type: %s vs env-type: %s" declared-type var-type) :else [env [[:ref-local {:var-id var-id ;; if at least one type is not empty, use it for var-type :var-type (or var-type declared-type)}]]]))) (defmethod ast-to-ir :VarDef [[_ {:keys [var-id var-type]} val-expr] tenv] (let [[_ val-ir] (ast-to-ir val-expr tenv)] [(assoc tenv var-id var-type) (conj val-ir [:def-local {:var-id var-id :var-type var-type}])])) (defn resolve-cmp-type [arg0 arg1 tenv] ;;TODO Implement me :int) (defmethod ast-to-ir :If [[_ pred truthy-expr falsy-expr] tenv] (let [[_ truthy-ir] (ast-to-ir truthy-expr tenv) [_ falsy-ir] (ast-to-ir falsy-expr tenv) [cmp-op arg0 arg1] pred cmp-type (resolve-cmp-type truthy-expr falsy-expr tenv) [_ arg0] (ast-to-ir arg0 tenv) [_ arg1] (ast-to-ir arg1 tenv) truthy-lbl (name (gensym "truthy_lbl_")) exit-lbl (name (gensym "exit_lbl"))] [tenv (vec (concat arg0 arg1 [[:jump-cmp {:value truthy-lbl :compare-op cmp-op :compare-type cmp-type}]] falsy-ir [[:jump {:value exit-lbl}]] [[:label {:value truthy-lbl}]] truthy-ir [[:label {:value exit-lbl}]]))])) (defn jvm-type-to-ir [java-type-sym] (let [type-name (name java-type-sym)] ;; TODO this should really be a check on whether this is a simple type by (#{int float long double char} ) etc. (if (string/includes? type-name ".") [:class type-name] (keyword type-name)))) (defn ast-expr-to-ir-type [[expr-type & exprs] tenv] (case expr-type ;; TODO this clearly needs loads of work :Int :int ;; this solves fuzzy-type-equals actually, but only for strings :String [:class "java.lang.String"] :AddInt :int :SubInt :int :MulInt :int :DivInt :int :VarRef (if-let [var-type (tenv (:var-id (first exprs)))] var-type) :FunCall (if-let [{:keys [return-type]} (tenv (first exprs))] return-type))) (defn can-conform-types? [param-class arg-expr tenv] (assert (symbol? param-class) "Param-class needs to be a symbol") (let [arg-type (ast-expr-to-ir-type arg-expr tenv)] (cond (= param-class arg-type) true (and (vector? arg-type) (= :class (first arg-type))) (let [[_ class-name] arg-type java-class (Class/forName class-name)] (or (= class-name (name param-class)) (contains? (:bases (reflect/reflect java-class)) param-class))) (= (name param-class) (name arg-type)) true))) (comment ;; TODO START HERE ;; this works (can-conform-types? (symbol "java.lang.CharSequence") [:String "aa"] {}) ;; this doesn (can-conform-types? (symbol "java.lang.CharSequence") [:FunCall "Main"] { "Main" {:args [:string] :return-type :string}}) ;; but this would, if that's how we store types in tevn (can-conform-types? (symbol "java.lang.CharSequence") [:FunCall "Main"] { "Main" {:args [:class "java.lang.String"] :return-type [:class "java.lang.String"]}}) (reflect/reflect (class "java.lang.String")) (reflect/reflect String :ancestors true) (reflect/reflect String)) (defn lookup-interop-method-signature [class-name method-name call-arg-exprs static? tenv] ;; because of the way we put 'this' as first argument ;; our call-args for non static will always have 1 more arg than ;; their corresponding java signature, so we need to (dec (count call-arg-expr)) (let [call-arg-count (if static? (count call-arg-exprs) (dec (count call-arg-exprs))) matching-methods (->> (reflect/reflect (Class/forName class-name)) :members (filter (comp #{(symbol method-name)} :name)) ;;TODO also use args-maybe? to filter results on matching arity and parameter types! (filter (fn [{:keys [parameter-types]}] (and (= (count parameter-types) call-arg-count) (every? true? (map (fn [param arg-e] (can-conform-types? param arg-e tenv)) parameter-types call-arg-exprs))))) (map (fn [{:keys [return-type parameter-types name]}] {:return-type (jvm-type-to-ir return-type) :args (mapv jvm-type-to-ir parameter-types) :name (clojure.core/name name)})) ;; TODO check how many matches we found and throw an error if there is ambiguity )] (when (not= (count matching-methods) 1) (throw (ex-info "Ambiguous Interop Method signature, found more then 1 match or no matches at all" {:class-name class-name :method-name method-name :call-arg-exprs call-arg-exprs :static? static? :matching-methods matching-methods}))) (first matching-methods))) (comment ;; TODO needs a lot of work this (lookup-interop-method-signature "java.lang.Math" "abs" [[:FunCall "f" [:IntExpr 2]]] true {"f" {:args [:int] :return-type :int}}) (lookup-interop-method-signature "java.lang.String" "concat" (list [:String " Hello" ] [:VarRef {:var-id "x"}]) false {"x" [:class "java.lang.String"]}) (lookup-interop-method-signature "java.lang.String" "replace" (list [:FunCall "Main"] [:String " Hello" ] [:VarRef {:var-id "x"}]) false {"x" :string "Main" {:args [[:class "java.lang.String"]] :return-type [:class "java.lang.String"]}}) (->> (reflect/reflect String) :members (filter (fn [{:keys [name]}] (= name 'replace)))) ;; TODO How about that? {:return-type [:class "java.lang.String"], :args [:char :char], :name "replace"} ) (defmethod ast-to-ir :InteropCall [[_ {:keys [class-name method-name static?]} & method-args] tenv] #_(println ":InteropCall=" [class-name method-name static?] " method-args = " method-args " tenv= " tenv) (let [{:keys [args return-type] :as env-type} (tenv method-name) ;; TODO should interop take a map with params instead positional? jvm-type (lookup-interop-method-signature class-name method-name method-args static? tenv) [_ args-ir] (map-ast-to-ir tenv method-args) ir-op (if static? :static-interop-call :interop-call) {:keys [return-type args]} (merge-with #(or %1 %2) jvm-type env-type )] #_ (println "env-type= " env-type " jvm-type= " jvm-type) #_ (println "class-name=" class-name " method-name=" method-name "args=" method-args) (if (or env-type jvm-type) [tenv (conj (vec args-ir) ;; in case args-ir is empty, thus '() [ir-op [(keyword (str class-name "/" method-name)) args return-type]])] (errorf "Unknown method signature for class/method: %s/%s" class-name method-name)))) (defmethod ast-to-ir :FunCall [[_ fn-name & fn-args] tenv] (if-let [fn-type (tenv fn-name)] (let [{:keys [args return-type special-form]} fn-type [_ args-ir] (map-ast-to-ir tenv fn-args) ] [tenv (cond (and special-form (empty? args-ir)) [special-form] special-form (conj args-ir [special-form]) (empty? args-ir) [[:call-fn [(keyword fn-name "invoke") args return-type]]] :else (conj args-ir [:call-fn [(keyword fn-name "invoke") args return-type]]))]) (errorf "Unknown function signature for fn-name: %s" fn-name fn-args))) (defmethod ast-to-ir :FunDef [[_ {:keys [args return-type fn-name]} & body] tenv] ;; (println [args return-type fn-name] body ) (let [arg-types (mapv :type args) tenv' (assoc tenv fn-name {:args arg-types :return-type return-type}) tenv-with-params (into tenv' (map (juxt :id :type) args)) [tenv'' body-irs] (map-ast-to-ir tenv-with-params body)] [tenv' [{:class-name fn-name :args arg-types :return-type return-type :body (into (args-to-locals args) body-irs)}]])) (defn init-tenv [] {"printstr" {:args [[:class "java.lang.String"]] :return-type [:class "java.lang.String"] :special-form :print-str} "printint" {:args [:int] :return-type :int :special-form :print}}) (defn build-program [exprs] (let [{:keys [FunDef] :as expr-by-type} (group-by first exprs) top-level-exprs (mapcat identity (vals (dissoc expr-by-type :FunDef))) ;; take everything but :FunDef [tenv fn-defs-ir] (map-ast-to-ir (init-tenv) FunDef) ;; TODO does this really need to be that complicated? we could probably return a {FnName -> Fn} map from above fn ;fn-defs-ir (apply merge fn-defs-ir) main-fn-name (name (gensym "Main_")) [_ [main-fn-ir]] (map-ast-to-ir tenv [(into [:FunDef {:args [] :fn-name main-fn-name :return-type :void}] top-level-exprs)])] ;;TODO check if all top level IR expr are maps of {FnNamestr Fn-expr} {:fns (conj (vec fn-defs-ir) main-fn-ir) :entry-point main-fn-name})) (comment ;; IF (ast-to-ir [:FunDef {:args [{:id "x" :type :int}] :fn-name "Hello" :return-type :int} [:If [:> [:VarRef {:var-id "x"}] [:Int{:value 119}]] [:Int {:value 42}] [:Int {:value -1}]]] {}) (require '[lasm.emit :as emit]) (emit/emit! {:fns [{:args [:int], :return-type :int, :body [[:arg {:value 0}] [:int {:value 119}] [:jump-cmp {:value "truthy" :compare-op :> :compare-type :int}] [:int {:value -1}] [:jump {:value "exit"}] [:label {:value "truthy"}] [:int {:value 42}] [:label {:value "exit"}]], :class-name "Cond12"}] :entry-point "Cond12"}) (Cond12/invoke 120) (ast-to-ir [:FunCall "Main"] {"Main" {:args [{:id "x" :type :string}] :return-type :string}}) (ast-to-ir [:DivInt 23 1] {}) [:InteropCall {:class-name "java.lang.Math", :method-name "abs", :static? true} [:SubInt [:Int 100] [:FunCall "f" [:AddInt [:Int 2] [:MulInt [:Int 8] [:Int 100]]]]]] (Cond12/invoke 120) (ast-to-ir [:FunDef {:fn-name "Main" :args [{:id "x" :type :string}] :return-type :string} [:FunCall "Other"] [:FunCall "Main" [:String "Arg1"]]] {"Other" {:args [] :return-type :string}}) (ast-to-ir [:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] {}) (map-ast-to-ir (init-tenv) [[:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:args [] :fn-name "Main" :return-type :void} [:FunCall "HelloWorld" [:String "Johnny"]]]]) (ast-to-ir [:FunDef {:args [], :fn-name "f" :return-type :int} [:AddInt [:Int 2] [:MulInt [:Int 2] [:Int 4]]]] {}) (build-program [[:FunDef {:args [], :return-type :int :fn-name "f"} [:AddInt [:Int 2] [:Int 2]]] [:FunCall "f"]]) (build-program [[:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:args [] :fn-name "Main" :return-type :void} [:FunCall "HelloWorld" [:String "Johnny"]]] [:FunCall "Main"]]) ) (comment (require '[lasm.emit :as emit]) ;; make-fn from AST via build-programs (-> (build-program [[:FunDef {:fn-name "Hello" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:fn-name "Main112" :args [] :return-type :string} [:FunCall "Hello" [:String "Johnny"]]]]) emit/emit-and-run!) ;; make-fn from IR (emit/make-fn {:class-name "TestConcat" :args [:string], :return-type :string, :body [[:arg {:value 0}] [:def-local {:var-id "x", :var-type :string}] [:string {:value "Hello "}] [:ref-local {:var-id "x"}] [:interop-call [:java.lang.String/concat [:string] :string]]]},) (TestConcat/invoke "Johnny Von Neuman") (emit/make-fn {:class-name "MA1" :args [], :return-type :void, :body [[:string {:value "Johnny"}] [:call-fn [:Hello/invoke [:string] :string]] [:print {:args [:string]}]]}) (MA1/invoke))
103328
(ns lasm.ast (:require [clojure.string :as string] [clojure.reflect :as reflect])) (defn error [expr & [msg ]] (throw (ex-info (str "Invalid-expression: " msg) {:expr expr :msg msg}))) (defn errorf [msg & args] (throw (ex-info (apply format msg args) {:msg msg :args args}))) (defmulti ast-to-ir (fn [expr _] (first expr))) (defn args-to-locals [args] (vec (mapcat identity (map-indexed (fn [i {:keys [id type]}] [[:arg {:value i}] [:def-local {:var-id id :var-type type}]]) args)))) (defn map-ast-to-ir [env exprs] (reduce (fn [[env irs] expr] (let [[env' ir] (ast-to-ir expr env)] [env' (into irs ir)])) [env []] exprs)) (defn ops-to-ir [ops tenv] (vec (mapcat #(second (ast-to-ir % tenv)) ops))) (defmethod ast-to-ir :AddInt [[_ & ops] tenv] [tenv (conj (ops-to-ir ops tenv) [:add-int])]) (defmethod ast-to-ir :SubInt [[_ & ops] tenv] [tenv (conj (ops-to-ir ops tenv) [:sub-int])]) (defmethod ast-to-ir :MulInt [[_ & ops] tenv] [tenv (conj (vec (mapcat #(second (ast-to-ir % tenv)) ops)) [:mul-int])]) (defmethod ast-to-ir :DivInt [[_ & ops] tenv] [tenv (conj (mapv #(first (second (ast-to-ir % tenv))) ops) [:div-int])]) (defmethod ast-to-ir :String [[_ str-val] env] [env [[:string {:value str-val}]]]) (defmethod ast-to-ir :Int [[_ int-val] env] [env [[:int {:value int-val}]]]) (defmethod ast-to-ir :VarRef [[_ {:keys [var-id var-type]}] env] (let [declared-type var-type var-type (env var-id)] (cond (and (nil? declared-type) (nil? var-type)) (errorf "Unknown variable found %s" var-id) (and declared-type var-type (not= declared-type var-type)) (errorf "Incompatible variable types found, declared-type: %s vs env-type: %s" declared-type var-type) :else [env [[:ref-local {:var-id var-id ;; if at least one type is not empty, use it for var-type :var-type (or var-type declared-type)}]]]))) (defmethod ast-to-ir :VarDef [[_ {:keys [var-id var-type]} val-expr] tenv] (let [[_ val-ir] (ast-to-ir val-expr tenv)] [(assoc tenv var-id var-type) (conj val-ir [:def-local {:var-id var-id :var-type var-type}])])) (defn resolve-cmp-type [arg0 arg1 tenv] ;;TODO Implement me :int) (defmethod ast-to-ir :If [[_ pred truthy-expr falsy-expr] tenv] (let [[_ truthy-ir] (ast-to-ir truthy-expr tenv) [_ falsy-ir] (ast-to-ir falsy-expr tenv) [cmp-op arg0 arg1] pred cmp-type (resolve-cmp-type truthy-expr falsy-expr tenv) [_ arg0] (ast-to-ir arg0 tenv) [_ arg1] (ast-to-ir arg1 tenv) truthy-lbl (name (gensym "truthy_lbl_")) exit-lbl (name (gensym "exit_lbl"))] [tenv (vec (concat arg0 arg1 [[:jump-cmp {:value truthy-lbl :compare-op cmp-op :compare-type cmp-type}]] falsy-ir [[:jump {:value exit-lbl}]] [[:label {:value truthy-lbl}]] truthy-ir [[:label {:value exit-lbl}]]))])) (defn jvm-type-to-ir [java-type-sym] (let [type-name (name java-type-sym)] ;; TODO this should really be a check on whether this is a simple type by (#{int float long double char} ) etc. (if (string/includes? type-name ".") [:class type-name] (keyword type-name)))) (defn ast-expr-to-ir-type [[expr-type & exprs] tenv] (case expr-type ;; TODO this clearly needs loads of work :Int :int ;; this solves fuzzy-type-equals actually, but only for strings :String [:class "java.lang.String"] :AddInt :int :SubInt :int :MulInt :int :DivInt :int :VarRef (if-let [var-type (tenv (:var-id (first exprs)))] var-type) :FunCall (if-let [{:keys [return-type]} (tenv (first exprs))] return-type))) (defn can-conform-types? [param-class arg-expr tenv] (assert (symbol? param-class) "Param-class needs to be a symbol") (let [arg-type (ast-expr-to-ir-type arg-expr tenv)] (cond (= param-class arg-type) true (and (vector? arg-type) (= :class (first arg-type))) (let [[_ class-name] arg-type java-class (Class/forName class-name)] (or (= class-name (name param-class)) (contains? (:bases (reflect/reflect java-class)) param-class))) (= (name param-class) (name arg-type)) true))) (comment ;; TODO START HERE ;; this works (can-conform-types? (symbol "java.lang.CharSequence") [:String "aa"] {}) ;; this doesn (can-conform-types? (symbol "java.lang.CharSequence") [:FunCall "Main"] { "Main" {:args [:string] :return-type :string}}) ;; but this would, if that's how we store types in tevn (can-conform-types? (symbol "java.lang.CharSequence") [:FunCall "Main"] { "Main" {:args [:class "java.lang.String"] :return-type [:class "java.lang.String"]}}) (reflect/reflect (class "java.lang.String")) (reflect/reflect String :ancestors true) (reflect/reflect String)) (defn lookup-interop-method-signature [class-name method-name call-arg-exprs static? tenv] ;; because of the way we put 'this' as first argument ;; our call-args for non static will always have 1 more arg than ;; their corresponding java signature, so we need to (dec (count call-arg-expr)) (let [call-arg-count (if static? (count call-arg-exprs) (dec (count call-arg-exprs))) matching-methods (->> (reflect/reflect (Class/forName class-name)) :members (filter (comp #{(symbol method-name)} :name)) ;;TODO also use args-maybe? to filter results on matching arity and parameter types! (filter (fn [{:keys [parameter-types]}] (and (= (count parameter-types) call-arg-count) (every? true? (map (fn [param arg-e] (can-conform-types? param arg-e tenv)) parameter-types call-arg-exprs))))) (map (fn [{:keys [return-type parameter-types name]}] {:return-type (jvm-type-to-ir return-type) :args (mapv jvm-type-to-ir parameter-types) :name (clojure.core/name name)})) ;; TODO check how many matches we found and throw an error if there is ambiguity )] (when (not= (count matching-methods) 1) (throw (ex-info "Ambiguous Interop Method signature, found more then 1 match or no matches at all" {:class-name class-name :method-name method-name :call-arg-exprs call-arg-exprs :static? static? :matching-methods matching-methods}))) (first matching-methods))) (comment ;; TODO needs a lot of work this (lookup-interop-method-signature "java.lang.Math" "abs" [[:FunCall "f" [:IntExpr 2]]] true {"f" {:args [:int] :return-type :int}}) (lookup-interop-method-signature "java.lang.String" "concat" (list [:String " Hello" ] [:VarRef {:var-id "x"}]) false {"x" [:class "java.lang.String"]}) (lookup-interop-method-signature "java.lang.String" "replace" (list [:FunCall "Main"] [:String " Hello" ] [:VarRef {:var-id "x"}]) false {"x" :string "Main" {:args [[:class "java.lang.String"]] :return-type [:class "java.lang.String"]}}) (->> (reflect/reflect String) :members (filter (fn [{:keys [name]}] (= name 'replace)))) ;; TODO How about that? {:return-type [:class "java.lang.String"], :args [:char :char], :name "replace"} ) (defmethod ast-to-ir :InteropCall [[_ {:keys [class-name method-name static?]} & method-args] tenv] #_(println ":InteropCall=" [class-name method-name static?] " method-args = " method-args " tenv= " tenv) (let [{:keys [args return-type] :as env-type} (tenv method-name) ;; TODO should interop take a map with params instead positional? jvm-type (lookup-interop-method-signature class-name method-name method-args static? tenv) [_ args-ir] (map-ast-to-ir tenv method-args) ir-op (if static? :static-interop-call :interop-call) {:keys [return-type args]} (merge-with #(or %1 %2) jvm-type env-type )] #_ (println "env-type= " env-type " jvm-type= " jvm-type) #_ (println "class-name=" class-name " method-name=" method-name "args=" method-args) (if (or env-type jvm-type) [tenv (conj (vec args-ir) ;; in case args-ir is empty, thus '() [ir-op [(keyword (str class-name "/" method-name)) args return-type]])] (errorf "Unknown method signature for class/method: %s/%s" class-name method-name)))) (defmethod ast-to-ir :FunCall [[_ fn-name & fn-args] tenv] (if-let [fn-type (tenv fn-name)] (let [{:keys [args return-type special-form]} fn-type [_ args-ir] (map-ast-to-ir tenv fn-args) ] [tenv (cond (and special-form (empty? args-ir)) [special-form] special-form (conj args-ir [special-form]) (empty? args-ir) [[:call-fn [(keyword fn-name "invoke") args return-type]]] :else (conj args-ir [:call-fn [(keyword fn-name "invoke") args return-type]]))]) (errorf "Unknown function signature for fn-name: %s" fn-name fn-args))) (defmethod ast-to-ir :FunDef [[_ {:keys [args return-type fn-name]} & body] tenv] ;; (println [args return-type fn-name] body ) (let [arg-types (mapv :type args) tenv' (assoc tenv fn-name {:args arg-types :return-type return-type}) tenv-with-params (into tenv' (map (juxt :id :type) args)) [tenv'' body-irs] (map-ast-to-ir tenv-with-params body)] [tenv' [{:class-name fn-name :args arg-types :return-type return-type :body (into (args-to-locals args) body-irs)}]])) (defn init-tenv [] {"printstr" {:args [[:class "java.lang.String"]] :return-type [:class "java.lang.String"] :special-form :print-str} "printint" {:args [:int] :return-type :int :special-form :print}}) (defn build-program [exprs] (let [{:keys [FunDef] :as expr-by-type} (group-by first exprs) top-level-exprs (mapcat identity (vals (dissoc expr-by-type :FunDef))) ;; take everything but :FunDef [tenv fn-defs-ir] (map-ast-to-ir (init-tenv) FunDef) ;; TODO does this really need to be that complicated? we could probably return a {FnName -> Fn} map from above fn ;fn-defs-ir (apply merge fn-defs-ir) main-fn-name (name (gensym "Main_")) [_ [main-fn-ir]] (map-ast-to-ir tenv [(into [:FunDef {:args [] :fn-name main-fn-name :return-type :void}] top-level-exprs)])] ;;TODO check if all top level IR expr are maps of {FnNamestr Fn-expr} {:fns (conj (vec fn-defs-ir) main-fn-ir) :entry-point main-fn-name})) (comment ;; IF (ast-to-ir [:FunDef {:args [{:id "x" :type :int}] :fn-name "Hello" :return-type :int} [:If [:> [:VarRef {:var-id "x"}] [:Int{:value 119}]] [:Int {:value 42}] [:Int {:value -1}]]] {}) (require '[lasm.emit :as emit]) (emit/emit! {:fns [{:args [:int], :return-type :int, :body [[:arg {:value 0}] [:int {:value 119}] [:jump-cmp {:value "truthy" :compare-op :> :compare-type :int}] [:int {:value -1}] [:jump {:value "exit"}] [:label {:value "truthy"}] [:int {:value 42}] [:label {:value "exit"}]], :class-name "Cond12"}] :entry-point "Cond12"}) (Cond12/invoke 120) (ast-to-ir [:FunCall "Main"] {"Main" {:args [{:id "x" :type :string}] :return-type :string}}) (ast-to-ir [:DivInt 23 1] {}) [:InteropCall {:class-name "java.lang.Math", :method-name "abs", :static? true} [:SubInt [:Int 100] [:FunCall "f" [:AddInt [:Int 2] [:MulInt [:Int 8] [:Int 100]]]]]] (Cond12/invoke 120) (ast-to-ir [:FunDef {:fn-name "Main" :args [{:id "x" :type :string}] :return-type :string} [:FunCall "Other"] [:FunCall "Main" [:String "Arg1"]]] {"Other" {:args [] :return-type :string}}) (ast-to-ir [:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] {}) (map-ast-to-ir (init-tenv) [[:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:args [] :fn-name "Main" :return-type :void} [:FunCall "HelloWorld" [:String "<NAME>"]]]]) (ast-to-ir [:FunDef {:args [], :fn-name "f" :return-type :int} [:AddInt [:Int 2] [:MulInt [:Int 2] [:Int 4]]]] {}) (build-program [[:FunDef {:args [], :return-type :int :fn-name "f"} [:AddInt [:Int 2] [:Int 2]]] [:FunCall "f"]]) (build-program [[:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:args [] :fn-name "Main" :return-type :void} [:FunCall "HelloWorld" [:String "Johnny"]]] [:FunCall "Main"]]) ) (comment (require '[lasm.emit :as emit]) ;; make-fn from AST via build-programs (-> (build-program [[:FunDef {:fn-name "Hello" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:fn-name "Main112" :args [] :return-type :string} [:FunCall "Hello" [:String "<NAME>"]]]]) emit/emit-and-run!) ;; make-fn from IR (emit/make-fn {:class-name "TestConcat" :args [:string], :return-type :string, :body [[:arg {:value 0}] [:def-local {:var-id "x", :var-type :string}] [:string {:value "Hello "}] [:ref-local {:var-id "x"}] [:interop-call [:java.lang.String/concat [:string] :string]]]},) (TestConcat/invoke "<NAME>") (emit/make-fn {:class-name "MA1" :args [], :return-type :void, :body [[:string {:value "<NAME>"}] [:call-fn [:Hello/invoke [:string] :string]] [:print {:args [:string]}]]}) (MA1/invoke))
true
(ns lasm.ast (:require [clojure.string :as string] [clojure.reflect :as reflect])) (defn error [expr & [msg ]] (throw (ex-info (str "Invalid-expression: " msg) {:expr expr :msg msg}))) (defn errorf [msg & args] (throw (ex-info (apply format msg args) {:msg msg :args args}))) (defmulti ast-to-ir (fn [expr _] (first expr))) (defn args-to-locals [args] (vec (mapcat identity (map-indexed (fn [i {:keys [id type]}] [[:arg {:value i}] [:def-local {:var-id id :var-type type}]]) args)))) (defn map-ast-to-ir [env exprs] (reduce (fn [[env irs] expr] (let [[env' ir] (ast-to-ir expr env)] [env' (into irs ir)])) [env []] exprs)) (defn ops-to-ir [ops tenv] (vec (mapcat #(second (ast-to-ir % tenv)) ops))) (defmethod ast-to-ir :AddInt [[_ & ops] tenv] [tenv (conj (ops-to-ir ops tenv) [:add-int])]) (defmethod ast-to-ir :SubInt [[_ & ops] tenv] [tenv (conj (ops-to-ir ops tenv) [:sub-int])]) (defmethod ast-to-ir :MulInt [[_ & ops] tenv] [tenv (conj (vec (mapcat #(second (ast-to-ir % tenv)) ops)) [:mul-int])]) (defmethod ast-to-ir :DivInt [[_ & ops] tenv] [tenv (conj (mapv #(first (second (ast-to-ir % tenv))) ops) [:div-int])]) (defmethod ast-to-ir :String [[_ str-val] env] [env [[:string {:value str-val}]]]) (defmethod ast-to-ir :Int [[_ int-val] env] [env [[:int {:value int-val}]]]) (defmethod ast-to-ir :VarRef [[_ {:keys [var-id var-type]}] env] (let [declared-type var-type var-type (env var-id)] (cond (and (nil? declared-type) (nil? var-type)) (errorf "Unknown variable found %s" var-id) (and declared-type var-type (not= declared-type var-type)) (errorf "Incompatible variable types found, declared-type: %s vs env-type: %s" declared-type var-type) :else [env [[:ref-local {:var-id var-id ;; if at least one type is not empty, use it for var-type :var-type (or var-type declared-type)}]]]))) (defmethod ast-to-ir :VarDef [[_ {:keys [var-id var-type]} val-expr] tenv] (let [[_ val-ir] (ast-to-ir val-expr tenv)] [(assoc tenv var-id var-type) (conj val-ir [:def-local {:var-id var-id :var-type var-type}])])) (defn resolve-cmp-type [arg0 arg1 tenv] ;;TODO Implement me :int) (defmethod ast-to-ir :If [[_ pred truthy-expr falsy-expr] tenv] (let [[_ truthy-ir] (ast-to-ir truthy-expr tenv) [_ falsy-ir] (ast-to-ir falsy-expr tenv) [cmp-op arg0 arg1] pred cmp-type (resolve-cmp-type truthy-expr falsy-expr tenv) [_ arg0] (ast-to-ir arg0 tenv) [_ arg1] (ast-to-ir arg1 tenv) truthy-lbl (name (gensym "truthy_lbl_")) exit-lbl (name (gensym "exit_lbl"))] [tenv (vec (concat arg0 arg1 [[:jump-cmp {:value truthy-lbl :compare-op cmp-op :compare-type cmp-type}]] falsy-ir [[:jump {:value exit-lbl}]] [[:label {:value truthy-lbl}]] truthy-ir [[:label {:value exit-lbl}]]))])) (defn jvm-type-to-ir [java-type-sym] (let [type-name (name java-type-sym)] ;; TODO this should really be a check on whether this is a simple type by (#{int float long double char} ) etc. (if (string/includes? type-name ".") [:class type-name] (keyword type-name)))) (defn ast-expr-to-ir-type [[expr-type & exprs] tenv] (case expr-type ;; TODO this clearly needs loads of work :Int :int ;; this solves fuzzy-type-equals actually, but only for strings :String [:class "java.lang.String"] :AddInt :int :SubInt :int :MulInt :int :DivInt :int :VarRef (if-let [var-type (tenv (:var-id (first exprs)))] var-type) :FunCall (if-let [{:keys [return-type]} (tenv (first exprs))] return-type))) (defn can-conform-types? [param-class arg-expr tenv] (assert (symbol? param-class) "Param-class needs to be a symbol") (let [arg-type (ast-expr-to-ir-type arg-expr tenv)] (cond (= param-class arg-type) true (and (vector? arg-type) (= :class (first arg-type))) (let [[_ class-name] arg-type java-class (Class/forName class-name)] (or (= class-name (name param-class)) (contains? (:bases (reflect/reflect java-class)) param-class))) (= (name param-class) (name arg-type)) true))) (comment ;; TODO START HERE ;; this works (can-conform-types? (symbol "java.lang.CharSequence") [:String "aa"] {}) ;; this doesn (can-conform-types? (symbol "java.lang.CharSequence") [:FunCall "Main"] { "Main" {:args [:string] :return-type :string}}) ;; but this would, if that's how we store types in tevn (can-conform-types? (symbol "java.lang.CharSequence") [:FunCall "Main"] { "Main" {:args [:class "java.lang.String"] :return-type [:class "java.lang.String"]}}) (reflect/reflect (class "java.lang.String")) (reflect/reflect String :ancestors true) (reflect/reflect String)) (defn lookup-interop-method-signature [class-name method-name call-arg-exprs static? tenv] ;; because of the way we put 'this' as first argument ;; our call-args for non static will always have 1 more arg than ;; their corresponding java signature, so we need to (dec (count call-arg-expr)) (let [call-arg-count (if static? (count call-arg-exprs) (dec (count call-arg-exprs))) matching-methods (->> (reflect/reflect (Class/forName class-name)) :members (filter (comp #{(symbol method-name)} :name)) ;;TODO also use args-maybe? to filter results on matching arity and parameter types! (filter (fn [{:keys [parameter-types]}] (and (= (count parameter-types) call-arg-count) (every? true? (map (fn [param arg-e] (can-conform-types? param arg-e tenv)) parameter-types call-arg-exprs))))) (map (fn [{:keys [return-type parameter-types name]}] {:return-type (jvm-type-to-ir return-type) :args (mapv jvm-type-to-ir parameter-types) :name (clojure.core/name name)})) ;; TODO check how many matches we found and throw an error if there is ambiguity )] (when (not= (count matching-methods) 1) (throw (ex-info "Ambiguous Interop Method signature, found more then 1 match or no matches at all" {:class-name class-name :method-name method-name :call-arg-exprs call-arg-exprs :static? static? :matching-methods matching-methods}))) (first matching-methods))) (comment ;; TODO needs a lot of work this (lookup-interop-method-signature "java.lang.Math" "abs" [[:FunCall "f" [:IntExpr 2]]] true {"f" {:args [:int] :return-type :int}}) (lookup-interop-method-signature "java.lang.String" "concat" (list [:String " Hello" ] [:VarRef {:var-id "x"}]) false {"x" [:class "java.lang.String"]}) (lookup-interop-method-signature "java.lang.String" "replace" (list [:FunCall "Main"] [:String " Hello" ] [:VarRef {:var-id "x"}]) false {"x" :string "Main" {:args [[:class "java.lang.String"]] :return-type [:class "java.lang.String"]}}) (->> (reflect/reflect String) :members (filter (fn [{:keys [name]}] (= name 'replace)))) ;; TODO How about that? {:return-type [:class "java.lang.String"], :args [:char :char], :name "replace"} ) (defmethod ast-to-ir :InteropCall [[_ {:keys [class-name method-name static?]} & method-args] tenv] #_(println ":InteropCall=" [class-name method-name static?] " method-args = " method-args " tenv= " tenv) (let [{:keys [args return-type] :as env-type} (tenv method-name) ;; TODO should interop take a map with params instead positional? jvm-type (lookup-interop-method-signature class-name method-name method-args static? tenv) [_ args-ir] (map-ast-to-ir tenv method-args) ir-op (if static? :static-interop-call :interop-call) {:keys [return-type args]} (merge-with #(or %1 %2) jvm-type env-type )] #_ (println "env-type= " env-type " jvm-type= " jvm-type) #_ (println "class-name=" class-name " method-name=" method-name "args=" method-args) (if (or env-type jvm-type) [tenv (conj (vec args-ir) ;; in case args-ir is empty, thus '() [ir-op [(keyword (str class-name "/" method-name)) args return-type]])] (errorf "Unknown method signature for class/method: %s/%s" class-name method-name)))) (defmethod ast-to-ir :FunCall [[_ fn-name & fn-args] tenv] (if-let [fn-type (tenv fn-name)] (let [{:keys [args return-type special-form]} fn-type [_ args-ir] (map-ast-to-ir tenv fn-args) ] [tenv (cond (and special-form (empty? args-ir)) [special-form] special-form (conj args-ir [special-form]) (empty? args-ir) [[:call-fn [(keyword fn-name "invoke") args return-type]]] :else (conj args-ir [:call-fn [(keyword fn-name "invoke") args return-type]]))]) (errorf "Unknown function signature for fn-name: %s" fn-name fn-args))) (defmethod ast-to-ir :FunDef [[_ {:keys [args return-type fn-name]} & body] tenv] ;; (println [args return-type fn-name] body ) (let [arg-types (mapv :type args) tenv' (assoc tenv fn-name {:args arg-types :return-type return-type}) tenv-with-params (into tenv' (map (juxt :id :type) args)) [tenv'' body-irs] (map-ast-to-ir tenv-with-params body)] [tenv' [{:class-name fn-name :args arg-types :return-type return-type :body (into (args-to-locals args) body-irs)}]])) (defn init-tenv [] {"printstr" {:args [[:class "java.lang.String"]] :return-type [:class "java.lang.String"] :special-form :print-str} "printint" {:args [:int] :return-type :int :special-form :print}}) (defn build-program [exprs] (let [{:keys [FunDef] :as expr-by-type} (group-by first exprs) top-level-exprs (mapcat identity (vals (dissoc expr-by-type :FunDef))) ;; take everything but :FunDef [tenv fn-defs-ir] (map-ast-to-ir (init-tenv) FunDef) ;; TODO does this really need to be that complicated? we could probably return a {FnName -> Fn} map from above fn ;fn-defs-ir (apply merge fn-defs-ir) main-fn-name (name (gensym "Main_")) [_ [main-fn-ir]] (map-ast-to-ir tenv [(into [:FunDef {:args [] :fn-name main-fn-name :return-type :void}] top-level-exprs)])] ;;TODO check if all top level IR expr are maps of {FnNamestr Fn-expr} {:fns (conj (vec fn-defs-ir) main-fn-ir) :entry-point main-fn-name})) (comment ;; IF (ast-to-ir [:FunDef {:args [{:id "x" :type :int}] :fn-name "Hello" :return-type :int} [:If [:> [:VarRef {:var-id "x"}] [:Int{:value 119}]] [:Int {:value 42}] [:Int {:value -1}]]] {}) (require '[lasm.emit :as emit]) (emit/emit! {:fns [{:args [:int], :return-type :int, :body [[:arg {:value 0}] [:int {:value 119}] [:jump-cmp {:value "truthy" :compare-op :> :compare-type :int}] [:int {:value -1}] [:jump {:value "exit"}] [:label {:value "truthy"}] [:int {:value 42}] [:label {:value "exit"}]], :class-name "Cond12"}] :entry-point "Cond12"}) (Cond12/invoke 120) (ast-to-ir [:FunCall "Main"] {"Main" {:args [{:id "x" :type :string}] :return-type :string}}) (ast-to-ir [:DivInt 23 1] {}) [:InteropCall {:class-name "java.lang.Math", :method-name "abs", :static? true} [:SubInt [:Int 100] [:FunCall "f" [:AddInt [:Int 2] [:MulInt [:Int 8] [:Int 100]]]]]] (Cond12/invoke 120) (ast-to-ir [:FunDef {:fn-name "Main" :args [{:id "x" :type :string}] :return-type :string} [:FunCall "Other"] [:FunCall "Main" [:String "Arg1"]]] {"Other" {:args [] :return-type :string}}) (ast-to-ir [:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] {}) (map-ast-to-ir (init-tenv) [[:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:args [] :fn-name "Main" :return-type :void} [:FunCall "HelloWorld" [:String "PI:NAME:<NAME>END_PI"]]]]) (ast-to-ir [:FunDef {:args [], :fn-name "f" :return-type :int} [:AddInt [:Int 2] [:MulInt [:Int 2] [:Int 4]]]] {}) (build-program [[:FunDef {:args [], :return-type :int :fn-name "f"} [:AddInt [:Int 2] [:Int 2]]] [:FunCall "f"]]) (build-program [[:FunDef {:fn-name "HelloWorld" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:args [] :fn-name "Main" :return-type :void} [:FunCall "HelloWorld" [:String "Johnny"]]] [:FunCall "Main"]]) ) (comment (require '[lasm.emit :as emit]) ;; make-fn from AST via build-programs (-> (build-program [[:FunDef {:fn-name "Hello" :args [{:id "x" :type :string}] :return-type :string} [:InteropCall {:class-name "java.lang.String" :method-name "concat"} [:String "Hello "] [:VarRef {:var-id "x"}]]] [:FunDef {:fn-name "Main112" :args [] :return-type :string} [:FunCall "Hello" [:String "PI:NAME:<NAME>END_PI"]]]]) emit/emit-and-run!) ;; make-fn from IR (emit/make-fn {:class-name "TestConcat" :args [:string], :return-type :string, :body [[:arg {:value 0}] [:def-local {:var-id "x", :var-type :string}] [:string {:value "Hello "}] [:ref-local {:var-id "x"}] [:interop-call [:java.lang.String/concat [:string] :string]]]},) (TestConcat/invoke "PI:NAME:<NAME>END_PI") (emit/make-fn {:class-name "MA1" :args [], :return-type :void, :body [[:string {:value "PI:NAME:<NAME>END_PI"}] [:call-fn [:Hello/invoke [:string] :string]] [:print {:args [:string]}]]}) (MA1/invoke))
[ { "context": "{ \"Manifest-Version\" \"1.0\"\n \"Created-By\" (str \"Bill \" (or (build/bill-version) (System/getProperty \"b", "end": 349, "score": 0.9243289232254028, "start": 345, "tag": "NAME", "value": "Bill" } ]
data/test/clojure/bb06199ef6ebba05c4fc3b8e56f912d653bd96d4jar.clj
harshp8l/deep-learning-lang-detection
84
(ns bill.tasks.jar (:use bill.task) (:require [bill.build :as build] [clojure.java.io :as java-io] [clojure.string :as string]) (:import [java.io ByteArrayInputStream File] [java.util.jar Manifest JarEntry JarOutputStream])) (defn default-manifest [] { "Manifest-Version" "1.0" "Created-By" (str "Bill " (or (build/bill-version) (System/getProperty "bill.version"))) "Built-By" (System/getProperty "user.name") "Build-Jdk" (System/getProperty "java.version") }) (defn manifest-map [] (merge (default-manifest) (build/manifest))) (defn- manifest-entry [[manifest-key manifest-value]] (cond (symbol? manifest-value) (manifest-entry [manifest-key (resolve manifest-value)]) (fn? manifest-value) (manifest-entry [manifest-key (manifest-value)]) :else (str (name manifest-key) ": " manifest-value))) (defn manifest-string [] (string/join "\n" (map manifest-entry (manifest-map)))) (defn manifest-bytes [] (.getBytes (manifest-string) "UTF-8")) (defn manifest-input-stream [] (ByteArrayInputStream. (manifest-bytes))) (defn manifest [] (Manifest. (manifest-input-stream))) (defn create-jar-output-stream [jar-file] (JarOutputStream. (java-io/output-stream jar-file) (manifest))) (defmulti add-to-jar (fn [_ _ data] (type data))) (defmethod add-to-jar File [^JarOutputStream jar-output-stream ^String path ^File file] (.putNextEntry jar-output-stream (doto (JarEntry. path) (.setTime (.lastModified file)))) (java-io/copy file jar-output-stream)) (defmethod add-to-jar String [^JarOutputStream jar-output-stream ^String path ^String string] (.putNextEntry jar-output-stream (JarEntry. path)) (java-io/copy (.getBytes string) jar-output-stream)) (defn create-jar-path [^File root-dir ^File file-to-add] (when (and root-dir file-to-add) (.substring (.getAbsolutePath file-to-add) (count (.getAbsolutePath root-dir))))) (defn file? [^File file-to-add] (not (.isDirectory file-to-add))) (defn add-dir-to-jar ([^JarOutputStream jar-output-stream ^File dir] (add-dir-to-jar jar-output-stream dir file?)) ([^JarOutputStream jar-output-stream ^File dir filter] (doseq [file-to-add (flatten (file-seq dir))] (when (filter file-to-add) (add-to-jar jar-output-stream (create-jar-path dir file-to-add) file-to-add))))) (defn has-extension? [^File file ^String extension] (and (file? file) (.endsWith (.getPath file) (str "." extension)))) (defn has-any-extension? [^File file extensions] (some #(has-extension? file %) extensions)) (defn has-source-extension? [^File file] (if-let [source-extensions (seq (build/source-extensions))] (has-any-extension? file source-extensions) true)) (defn has-compiled-extension? [^File file] (if-let [compiled-extensions (seq (build/compiled-extensions))] (has-any-extension? file compiled-extensions) true)) (defn add-source-files [^JarOutputStream jar-output-stream] (doseq [source-path (build/source-path-files)] (add-dir-to-jar jar-output-stream source-path has-source-extension?)) jar-output-stream) (defn add-resource-files [^JarOutputStream jar-output-stream] (doseq [resource-path (build/resource-path-files)] (add-dir-to-jar jar-output-stream resource-path)) jar-output-stream) (defn add-compiled-files [^JarOutputStream jar-output-stream] (add-dir-to-jar jar-output-stream (build/compile-path-file) has-compiled-extension?) jar-output-stream) (defn add-build-clj-file [^JarOutputStream jar-output-stream] (add-dir-to-jar jar-output-stream (build/build-file)) jar-output-stream) (defn add-files-to-jar [^JarOutputStream jar-output-stream] (add-compiled-files (add-resource-files (add-source-files jar-output-stream)))) (defn write-jar [jar-file] (when jar-file (when-let [jar-directory (.getParentFile jar-file)] (.mkdirs jar-directory))) (with-open [jar-output-stream (create-jar-output-stream jar-file)] (add-files-to-jar jar-output-stream)) (println "Wrote:" (.getAbsolutePath jar-file))) (deftask jar "Package up all the project's files into a jar file." [& args] (run-task :compile []) (if-let [jar-file (build/target-jar-file)] (write-jar jar-file) (println "No jar file set.")))
121851
(ns bill.tasks.jar (:use bill.task) (:require [bill.build :as build] [clojure.java.io :as java-io] [clojure.string :as string]) (:import [java.io ByteArrayInputStream File] [java.util.jar Manifest JarEntry JarOutputStream])) (defn default-manifest [] { "Manifest-Version" "1.0" "Created-By" (str "<NAME> " (or (build/bill-version) (System/getProperty "bill.version"))) "Built-By" (System/getProperty "user.name") "Build-Jdk" (System/getProperty "java.version") }) (defn manifest-map [] (merge (default-manifest) (build/manifest))) (defn- manifest-entry [[manifest-key manifest-value]] (cond (symbol? manifest-value) (manifest-entry [manifest-key (resolve manifest-value)]) (fn? manifest-value) (manifest-entry [manifest-key (manifest-value)]) :else (str (name manifest-key) ": " manifest-value))) (defn manifest-string [] (string/join "\n" (map manifest-entry (manifest-map)))) (defn manifest-bytes [] (.getBytes (manifest-string) "UTF-8")) (defn manifest-input-stream [] (ByteArrayInputStream. (manifest-bytes))) (defn manifest [] (Manifest. (manifest-input-stream))) (defn create-jar-output-stream [jar-file] (JarOutputStream. (java-io/output-stream jar-file) (manifest))) (defmulti add-to-jar (fn [_ _ data] (type data))) (defmethod add-to-jar File [^JarOutputStream jar-output-stream ^String path ^File file] (.putNextEntry jar-output-stream (doto (JarEntry. path) (.setTime (.lastModified file)))) (java-io/copy file jar-output-stream)) (defmethod add-to-jar String [^JarOutputStream jar-output-stream ^String path ^String string] (.putNextEntry jar-output-stream (JarEntry. path)) (java-io/copy (.getBytes string) jar-output-stream)) (defn create-jar-path [^File root-dir ^File file-to-add] (when (and root-dir file-to-add) (.substring (.getAbsolutePath file-to-add) (count (.getAbsolutePath root-dir))))) (defn file? [^File file-to-add] (not (.isDirectory file-to-add))) (defn add-dir-to-jar ([^JarOutputStream jar-output-stream ^File dir] (add-dir-to-jar jar-output-stream dir file?)) ([^JarOutputStream jar-output-stream ^File dir filter] (doseq [file-to-add (flatten (file-seq dir))] (when (filter file-to-add) (add-to-jar jar-output-stream (create-jar-path dir file-to-add) file-to-add))))) (defn has-extension? [^File file ^String extension] (and (file? file) (.endsWith (.getPath file) (str "." extension)))) (defn has-any-extension? [^File file extensions] (some #(has-extension? file %) extensions)) (defn has-source-extension? [^File file] (if-let [source-extensions (seq (build/source-extensions))] (has-any-extension? file source-extensions) true)) (defn has-compiled-extension? [^File file] (if-let [compiled-extensions (seq (build/compiled-extensions))] (has-any-extension? file compiled-extensions) true)) (defn add-source-files [^JarOutputStream jar-output-stream] (doseq [source-path (build/source-path-files)] (add-dir-to-jar jar-output-stream source-path has-source-extension?)) jar-output-stream) (defn add-resource-files [^JarOutputStream jar-output-stream] (doseq [resource-path (build/resource-path-files)] (add-dir-to-jar jar-output-stream resource-path)) jar-output-stream) (defn add-compiled-files [^JarOutputStream jar-output-stream] (add-dir-to-jar jar-output-stream (build/compile-path-file) has-compiled-extension?) jar-output-stream) (defn add-build-clj-file [^JarOutputStream jar-output-stream] (add-dir-to-jar jar-output-stream (build/build-file)) jar-output-stream) (defn add-files-to-jar [^JarOutputStream jar-output-stream] (add-compiled-files (add-resource-files (add-source-files jar-output-stream)))) (defn write-jar [jar-file] (when jar-file (when-let [jar-directory (.getParentFile jar-file)] (.mkdirs jar-directory))) (with-open [jar-output-stream (create-jar-output-stream jar-file)] (add-files-to-jar jar-output-stream)) (println "Wrote:" (.getAbsolutePath jar-file))) (deftask jar "Package up all the project's files into a jar file." [& args] (run-task :compile []) (if-let [jar-file (build/target-jar-file)] (write-jar jar-file) (println "No jar file set.")))
true
(ns bill.tasks.jar (:use bill.task) (:require [bill.build :as build] [clojure.java.io :as java-io] [clojure.string :as string]) (:import [java.io ByteArrayInputStream File] [java.util.jar Manifest JarEntry JarOutputStream])) (defn default-manifest [] { "Manifest-Version" "1.0" "Created-By" (str "PI:NAME:<NAME>END_PI " (or (build/bill-version) (System/getProperty "bill.version"))) "Built-By" (System/getProperty "user.name") "Build-Jdk" (System/getProperty "java.version") }) (defn manifest-map [] (merge (default-manifest) (build/manifest))) (defn- manifest-entry [[manifest-key manifest-value]] (cond (symbol? manifest-value) (manifest-entry [manifest-key (resolve manifest-value)]) (fn? manifest-value) (manifest-entry [manifest-key (manifest-value)]) :else (str (name manifest-key) ": " manifest-value))) (defn manifest-string [] (string/join "\n" (map manifest-entry (manifest-map)))) (defn manifest-bytes [] (.getBytes (manifest-string) "UTF-8")) (defn manifest-input-stream [] (ByteArrayInputStream. (manifest-bytes))) (defn manifest [] (Manifest. (manifest-input-stream))) (defn create-jar-output-stream [jar-file] (JarOutputStream. (java-io/output-stream jar-file) (manifest))) (defmulti add-to-jar (fn [_ _ data] (type data))) (defmethod add-to-jar File [^JarOutputStream jar-output-stream ^String path ^File file] (.putNextEntry jar-output-stream (doto (JarEntry. path) (.setTime (.lastModified file)))) (java-io/copy file jar-output-stream)) (defmethod add-to-jar String [^JarOutputStream jar-output-stream ^String path ^String string] (.putNextEntry jar-output-stream (JarEntry. path)) (java-io/copy (.getBytes string) jar-output-stream)) (defn create-jar-path [^File root-dir ^File file-to-add] (when (and root-dir file-to-add) (.substring (.getAbsolutePath file-to-add) (count (.getAbsolutePath root-dir))))) (defn file? [^File file-to-add] (not (.isDirectory file-to-add))) (defn add-dir-to-jar ([^JarOutputStream jar-output-stream ^File dir] (add-dir-to-jar jar-output-stream dir file?)) ([^JarOutputStream jar-output-stream ^File dir filter] (doseq [file-to-add (flatten (file-seq dir))] (when (filter file-to-add) (add-to-jar jar-output-stream (create-jar-path dir file-to-add) file-to-add))))) (defn has-extension? [^File file ^String extension] (and (file? file) (.endsWith (.getPath file) (str "." extension)))) (defn has-any-extension? [^File file extensions] (some #(has-extension? file %) extensions)) (defn has-source-extension? [^File file] (if-let [source-extensions (seq (build/source-extensions))] (has-any-extension? file source-extensions) true)) (defn has-compiled-extension? [^File file] (if-let [compiled-extensions (seq (build/compiled-extensions))] (has-any-extension? file compiled-extensions) true)) (defn add-source-files [^JarOutputStream jar-output-stream] (doseq [source-path (build/source-path-files)] (add-dir-to-jar jar-output-stream source-path has-source-extension?)) jar-output-stream) (defn add-resource-files [^JarOutputStream jar-output-stream] (doseq [resource-path (build/resource-path-files)] (add-dir-to-jar jar-output-stream resource-path)) jar-output-stream) (defn add-compiled-files [^JarOutputStream jar-output-stream] (add-dir-to-jar jar-output-stream (build/compile-path-file) has-compiled-extension?) jar-output-stream) (defn add-build-clj-file [^JarOutputStream jar-output-stream] (add-dir-to-jar jar-output-stream (build/build-file)) jar-output-stream) (defn add-files-to-jar [^JarOutputStream jar-output-stream] (add-compiled-files (add-resource-files (add-source-files jar-output-stream)))) (defn write-jar [jar-file] (when jar-file (when-let [jar-directory (.getParentFile jar-file)] (.mkdirs jar-directory))) (with-open [jar-output-stream (create-jar-output-stream jar-file)] (add-files-to-jar jar-output-stream)) (println "Wrote:" (.getAbsolutePath jar-file))) (deftask jar "Package up all the project's files into a jar file." [& args] (run-task :compile []) (if-let [jar-file (build/target-jar-file)] (write-jar jar-file) (println "No jar file set.")))
[ { "context": "?fname } . }\"))\n\n\n;;x gmane\n;;:_.node1cpd80gefx2 \"Bob\"\n;;:_.node1cpd80gefx1 \"Alice\"\n\n;;x fname\n;;:_.nod", "end": 946, "score": 0.9998262524604797, "start": 943, "tag": "NAME", "value": "Bob" }, { "context": "\n;;:_.node1cpd80gefx2 \"Bob\"\n;;:_.node1cpd80gefx1 \"Alice\"\n\n;;x fname\n;;:_.node1cpd81jhlx2 \"Hacker\"\n;;:_.no", "end": 975, "score": 0.9998514652252197, "start": 970, "tag": "NAME", "value": "Alice" } ]
test/temp_test/jena.clj
tkaryadis/louna-local
0
(ns temp-test.jena (:use louna.louna louna.louna-util) (:require state.db-settings benchmark.jena-run benchmark.benchmark-info benchmark.sparql-queries)) #_(def sparql-str (str " PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> CONSTRUCT { ?x vcard:N _:v . _:v vcard:givenName ?gname . _:v vcard:familyName ?fname } WHERE {{ ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } . { ?x foaf:surname ?fname } UNION { ?x foaf:family_name ?fname } . }")) ;;x gmane ;;:_.node1cpd80gefx2 "Bob" ;;:_.node1cpd80gefx1 "Alice" ;;x fname ;;:_.node1cpd81jhlx2 "Hacker" ;;:_.node1cpd81jhlx1 "Hacker" ;UNION ;{ ?x foaf:familyname ?fname } (def sparql-str (str " PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> SELECT ?x ?gname ?fname WHERE { { ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } { ?x foaf:surname ?fname } }")) (let [- (prn "Jena time :") sorted-vars ["x" "gname" "fname"] - (time (benchmark.jena-run/run-jena sparql-str (str (state.db-settings/get-rdf-path) "web10.3.1/10.3.1gen.nt") sorted-vars))])
116191
(ns temp-test.jena (:use louna.louna louna.louna-util) (:require state.db-settings benchmark.jena-run benchmark.benchmark-info benchmark.sparql-queries)) #_(def sparql-str (str " PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> CONSTRUCT { ?x vcard:N _:v . _:v vcard:givenName ?gname . _:v vcard:familyName ?fname } WHERE {{ ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } . { ?x foaf:surname ?fname } UNION { ?x foaf:family_name ?fname } . }")) ;;x gmane ;;:_.node1cpd80gefx2 "<NAME>" ;;:_.node1cpd80gefx1 "<NAME>" ;;x fname ;;:_.node1cpd81jhlx2 "Hacker" ;;:_.node1cpd81jhlx1 "Hacker" ;UNION ;{ ?x foaf:familyname ?fname } (def sparql-str (str " PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> SELECT ?x ?gname ?fname WHERE { { ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } { ?x foaf:surname ?fname } }")) (let [- (prn "Jena time :") sorted-vars ["x" "gname" "fname"] - (time (benchmark.jena-run/run-jena sparql-str (str (state.db-settings/get-rdf-path) "web10.3.1/10.3.1gen.nt") sorted-vars))])
true
(ns temp-test.jena (:use louna.louna louna.louna-util) (:require state.db-settings benchmark.jena-run benchmark.benchmark-info benchmark.sparql-queries)) #_(def sparql-str (str " PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> CONSTRUCT { ?x vcard:N _:v . _:v vcard:givenName ?gname . _:v vcard:familyName ?fname } WHERE {{ ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } . { ?x foaf:surname ?fname } UNION { ?x foaf:family_name ?fname } . }")) ;;x gmane ;;:_.node1cpd80gefx2 "PI:NAME:<NAME>END_PI" ;;:_.node1cpd80gefx1 "PI:NAME:<NAME>END_PI" ;;x fname ;;:_.node1cpd81jhlx2 "Hacker" ;;:_.node1cpd81jhlx1 "Hacker" ;UNION ;{ ?x foaf:familyname ?fname } (def sparql-str (str " PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> SELECT ?x ?gname ?fname WHERE { { ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } { ?x foaf:surname ?fname } }")) (let [- (prn "Jena time :") sorted-vars ["x" "gname" "fname"] - (time (benchmark.jena-run/run-jena sparql-str (str (state.db-settings/get-rdf-path) "web10.3.1/10.3.1gen.nt") sorted-vars))])
[ { "context": "following kind of structure:\n {:user {:userid \\\"developer\\\"\n :email \\\"developer@e.mail\\\"\n ", "end": 702, "score": 0.99747234582901, "start": 693, "tag": "USERNAME", "value": "developer" }, { "context": "{:user {:userid \\\"developer\\\"\n :email \\\"developer@e.mail\\\"\n :name \\\"deve loper\\\"\n :org", "end": 741, "score": 0.9996544122695923, "start": 725, "tag": "EMAIL", "value": "developer@e.mail" }, { "context": " :email \\\"developer@e.mail\\\"\n :name \\\"deve loper\\\"\n :organizations [{:organization/id [\\", "end": 773, "score": 0.9996746778488159, "start": 763, "tag": "NAME", "value": "deve loper" } ]
src/cljs/rems/identity.cljs
MalinAhlberg/rems
0
(ns rems.identity (:require [re-frame.core :as rf] [rems.roles :as roles])) ;;; subscriptions (rf/reg-sub :identity (fn [db _] (:identity db))) (rf/reg-sub :user (fn [db _] (get-in db [:identity :user]))) (rf/reg-sub :roles (fn [db _] (get-in db [:identity :roles]))) (rf/reg-sub :logged-in (fn [db _] (roles/is-logged-in? (get-in db [:identity :roles])))) ;;; handlers (rf/reg-event-db :set-identity (fn [db [_ identity]] (assoc db :identity identity))) (rf/reg-event-db :set-roles (fn [db [_ roles]] (assoc-in db [:identity :roles] roles))) (defn set-identity! "Receives as a parameter following kind of structure: {:user {:userid \"developer\" :email \"developer@e.mail\" :name \"deve loper\" :organizations [{:organization/id [\"Foocorp\"]}] ...} :roles [\"applicant\" \"approver\"]} Roles are converted to clojure keywords inside the function before dispatching" [user-and-roles] (let [user-and-roles (js->clj user-and-roles :keywordize-keys true)] (rf/dispatch-sync [:set-identity (if (:user user-and-roles) (assoc user-and-roles :roles (set (map keyword (:roles user-and-roles)))) user-and-roles)]))) (defn set-roles! [roles] (rf/dispatch-sync [:set-roles (set (map keyword roles))]))
8135
(ns rems.identity (:require [re-frame.core :as rf] [rems.roles :as roles])) ;;; subscriptions (rf/reg-sub :identity (fn [db _] (:identity db))) (rf/reg-sub :user (fn [db _] (get-in db [:identity :user]))) (rf/reg-sub :roles (fn [db _] (get-in db [:identity :roles]))) (rf/reg-sub :logged-in (fn [db _] (roles/is-logged-in? (get-in db [:identity :roles])))) ;;; handlers (rf/reg-event-db :set-identity (fn [db [_ identity]] (assoc db :identity identity))) (rf/reg-event-db :set-roles (fn [db [_ roles]] (assoc-in db [:identity :roles] roles))) (defn set-identity! "Receives as a parameter following kind of structure: {:user {:userid \"developer\" :email \"<EMAIL>\" :name \"<NAME>\" :organizations [{:organization/id [\"Foocorp\"]}] ...} :roles [\"applicant\" \"approver\"]} Roles are converted to clojure keywords inside the function before dispatching" [user-and-roles] (let [user-and-roles (js->clj user-and-roles :keywordize-keys true)] (rf/dispatch-sync [:set-identity (if (:user user-and-roles) (assoc user-and-roles :roles (set (map keyword (:roles user-and-roles)))) user-and-roles)]))) (defn set-roles! [roles] (rf/dispatch-sync [:set-roles (set (map keyword roles))]))
true
(ns rems.identity (:require [re-frame.core :as rf] [rems.roles :as roles])) ;;; subscriptions (rf/reg-sub :identity (fn [db _] (:identity db))) (rf/reg-sub :user (fn [db _] (get-in db [:identity :user]))) (rf/reg-sub :roles (fn [db _] (get-in db [:identity :roles]))) (rf/reg-sub :logged-in (fn [db _] (roles/is-logged-in? (get-in db [:identity :roles])))) ;;; handlers (rf/reg-event-db :set-identity (fn [db [_ identity]] (assoc db :identity identity))) (rf/reg-event-db :set-roles (fn [db [_ roles]] (assoc-in db [:identity :roles] roles))) (defn set-identity! "Receives as a parameter following kind of structure: {:user {:userid \"developer\" :email \"PI:EMAIL:<EMAIL>END_PI\" :name \"PI:NAME:<NAME>END_PI\" :organizations [{:organization/id [\"Foocorp\"]}] ...} :roles [\"applicant\" \"approver\"]} Roles are converted to clojure keywords inside the function before dispatching" [user-and-roles] (let [user-and-roles (js->clj user-and-roles :keywordize-keys true)] (rf/dispatch-sync [:set-identity (if (:user user-and-roles) (assoc user-and-roles :roles (set (map keyword (:roles user-and-roles)))) user-and-roles)]))) (defn set-roles! [roles] (rf/dispatch-sync [:set-roles (set (map keyword roles))]))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald, Kristina Lisa Klinkner\" :date \"2017-01-03\"\n ", "end": 105, "score": 0.9998779296875, "start": 87, "tag": "NAME", "value": "John Alan McDonald" }, { "context": ":warn-on-boxed)\n(ns ^{:author \"John Alan McDonald, Kristina Lisa Klinkner\" :date \"2017-01-03\"\n :doc \"Used in bottom up", "end": 129, "score": 0.9998798370361328, "start": 107, "tag": "NAME", "value": "Kristina Lisa Klinkner" } ]
src/main/clojure/taiga/split/object/categorical/cluster.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald, Kristina Lisa Klinkner" :date "2017-01-03" :doc "Used in bottom up category cluster for heuristic split generation." } taiga.split.object.categorical.cluster (:refer-clojure :exclude [merge]) (:require [clojure.set :as set] [zana.api :as z])) ;;------------------------------------------------------------------------------ (deftype Cluster [^java.util.Set categories ^java.util.Collection data ^Object left ^Object right ^double cost ^boolean feasible-leaf?]) ;;------------------------------------------------------------------------------ (defn categories ^java.util.Collection [^Cluster c] (.categories c)) (defn data ^java.util.Collection [^Cluster c] (.data c)) (defn left ^taiga.split.object.categorical.cluster.Cluster [^Cluster c] (.left c)) (defn right ^taiga.split.object.categorical.cluster.Cluster [^Cluster c] (.right c)) (defn cost ^double [^Cluster c] (.cost c)) (defn cost ^double [^Cluster c] (.cost c)) (defn feasible-leaf? ^Boolean [^Cluster this] (Boolean/valueOf (.feasible-leaf? this))) ;;------------------------------------------------------------------------------ (defn merge-cost ^double [^Cluster this] (assert (and (left this) (right this)) "No children, no merge cost!") (- (cost this) (cost (left this)) (cost (right this)))) ;;------------------------------------------------------------------------------ (defn forget-children ^taiga.split.object.categorical.cluster.Cluster [^Cluster this] (Cluster. (categories this) (data this) nil nil (cost this) (feasible-leaf? this))) ;;------------------------------------------------------------------------------ (defn make ^taiga.split.object.categorical.cluster.Cluster [^java.util.Set categories ^java.util.List data ^Cluster left ^Cluster right ^clojure.lang.IFn y ^clojure.lang.IFn cost-factory ^clojure.lang.IFn feasible?] (let [^zana.java.accumulator.Accumulator cost (cost-factory) n (.size data)] (dotimes [i n] (.add cost (y (.get data i)))) (Cluster. categories data left right (.doubleValue cost) (feasible? cost)))) ;;------------------------------------------------------------------------------ (defn merge ^taiga.split.object.categorical.cluster.Cluster [^Cluster left ^Cluster right ^clojure.lang.IFn y ^clojure.lang.IFn cost-factory ^clojure.lang.IFn feasible?] #_(assert (empty? (set/intersection (categories left) (categories right)))) (let [cats (z/concat (categories left) (categories right)) data #_(com.google.common.collect.Iterables/concat (data left) (data right)) (z/concat (data left) (data right))] (make cats data left right y cost-factory feasible?))) ;;------------------------------------------------------------------------------
104258
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>, <NAME>" :date "2017-01-03" :doc "Used in bottom up category cluster for heuristic split generation." } taiga.split.object.categorical.cluster (:refer-clojure :exclude [merge]) (:require [clojure.set :as set] [zana.api :as z])) ;;------------------------------------------------------------------------------ (deftype Cluster [^java.util.Set categories ^java.util.Collection data ^Object left ^Object right ^double cost ^boolean feasible-leaf?]) ;;------------------------------------------------------------------------------ (defn categories ^java.util.Collection [^Cluster c] (.categories c)) (defn data ^java.util.Collection [^Cluster c] (.data c)) (defn left ^taiga.split.object.categorical.cluster.Cluster [^Cluster c] (.left c)) (defn right ^taiga.split.object.categorical.cluster.Cluster [^Cluster c] (.right c)) (defn cost ^double [^Cluster c] (.cost c)) (defn cost ^double [^Cluster c] (.cost c)) (defn feasible-leaf? ^Boolean [^Cluster this] (Boolean/valueOf (.feasible-leaf? this))) ;;------------------------------------------------------------------------------ (defn merge-cost ^double [^Cluster this] (assert (and (left this) (right this)) "No children, no merge cost!") (- (cost this) (cost (left this)) (cost (right this)))) ;;------------------------------------------------------------------------------ (defn forget-children ^taiga.split.object.categorical.cluster.Cluster [^Cluster this] (Cluster. (categories this) (data this) nil nil (cost this) (feasible-leaf? this))) ;;------------------------------------------------------------------------------ (defn make ^taiga.split.object.categorical.cluster.Cluster [^java.util.Set categories ^java.util.List data ^Cluster left ^Cluster right ^clojure.lang.IFn y ^clojure.lang.IFn cost-factory ^clojure.lang.IFn feasible?] (let [^zana.java.accumulator.Accumulator cost (cost-factory) n (.size data)] (dotimes [i n] (.add cost (y (.get data i)))) (Cluster. categories data left right (.doubleValue cost) (feasible? cost)))) ;;------------------------------------------------------------------------------ (defn merge ^taiga.split.object.categorical.cluster.Cluster [^Cluster left ^Cluster right ^clojure.lang.IFn y ^clojure.lang.IFn cost-factory ^clojure.lang.IFn feasible?] #_(assert (empty? (set/intersection (categories left) (categories right)))) (let [cats (z/concat (categories left) (categories right)) data #_(com.google.common.collect.Iterables/concat (data left) (data right)) (z/concat (data left) (data right))] (make cats data left right y cost-factory feasible?))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" :date "2017-01-03" :doc "Used in bottom up category cluster for heuristic split generation." } taiga.split.object.categorical.cluster (:refer-clojure :exclude [merge]) (:require [clojure.set :as set] [zana.api :as z])) ;;------------------------------------------------------------------------------ (deftype Cluster [^java.util.Set categories ^java.util.Collection data ^Object left ^Object right ^double cost ^boolean feasible-leaf?]) ;;------------------------------------------------------------------------------ (defn categories ^java.util.Collection [^Cluster c] (.categories c)) (defn data ^java.util.Collection [^Cluster c] (.data c)) (defn left ^taiga.split.object.categorical.cluster.Cluster [^Cluster c] (.left c)) (defn right ^taiga.split.object.categorical.cluster.Cluster [^Cluster c] (.right c)) (defn cost ^double [^Cluster c] (.cost c)) (defn cost ^double [^Cluster c] (.cost c)) (defn feasible-leaf? ^Boolean [^Cluster this] (Boolean/valueOf (.feasible-leaf? this))) ;;------------------------------------------------------------------------------ (defn merge-cost ^double [^Cluster this] (assert (and (left this) (right this)) "No children, no merge cost!") (- (cost this) (cost (left this)) (cost (right this)))) ;;------------------------------------------------------------------------------ (defn forget-children ^taiga.split.object.categorical.cluster.Cluster [^Cluster this] (Cluster. (categories this) (data this) nil nil (cost this) (feasible-leaf? this))) ;;------------------------------------------------------------------------------ (defn make ^taiga.split.object.categorical.cluster.Cluster [^java.util.Set categories ^java.util.List data ^Cluster left ^Cluster right ^clojure.lang.IFn y ^clojure.lang.IFn cost-factory ^clojure.lang.IFn feasible?] (let [^zana.java.accumulator.Accumulator cost (cost-factory) n (.size data)] (dotimes [i n] (.add cost (y (.get data i)))) (Cluster. categories data left right (.doubleValue cost) (feasible? cost)))) ;;------------------------------------------------------------------------------ (defn merge ^taiga.split.object.categorical.cluster.Cluster [^Cluster left ^Cluster right ^clojure.lang.IFn y ^clojure.lang.IFn cost-factory ^clojure.lang.IFn feasible?] #_(assert (empty? (set/intersection (categories left) (categories right)))) (let [cats (z/concat (categories left) (categories right)) data #_(com.google.common.collect.Iterables/concat (data left) (data right)) (z/concat (data left) (data right))] (make cats data left right y cost-factory feasible?))) ;;------------------------------------------------------------------------------
[ { "context": "e F to York St.\"\n :ci_email \"democracy@example.com\"\n :ci_fax \"555-555-5FAX\"\n ", "end": 816, "score": 0.9998978972434998, "start": 795, "tag": "EMAIL", "value": "democracy@example.com" }, { "context": "_source \"Sean\"\n :ci_name \"Democracy Works\"\n :ci_phone \"555-555-5", "end": 1135, "score": 0.5202738642692566, "start": 1129, "tag": "NAME", "value": "ocracy" }, { "context": "St.\"\n :ci_email \"democracy@example.com\"\n :ci_fax \"555-5", "end": 1744, "score": 0.9999050498008728, "start": 1723, "tag": "EMAIL", "value": "democracy@example.com" } ]
test/vip/data_processor/db/translations/v5_2/departments_test.clj
votinginfoproject/data-processor
10
(ns vip.data-processor.db.translations.v5-2.departments-test (:require [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.translations.v5-2.departments :as departments] [vip.data-processor.db.translations.util :as util])) (deftest department->ltree-test (let [idx-fn (util/index-generator 0) parent-path "VipObject.0.ElectionAdministration.0" departments [{:id "dep01" :election_official_person_id "eloff01" :ci_address_line_1 "Suite 824" :ci_address_line_2 "20 Jay St" :ci_address_line_3 "Brooklyn, NY 11201" :ci_directions "Take the F to York St." :ci_email "democracy@example.com" :ci_fax "555-555-5FAX" :ci_hours "10am to 6pm" :ci_hours_open_id "ho002" :ci_latitude "40.704" :ci_longitude "-73.989" :ci_latlng_source "Sean" :ci_name "Democracy Works" :ci_phone "555-555-5555" :ci_uri "http://democracy.works"}] voter-services {"dep01" [{:id "vs01" :type "overseas-voting" :other_type nil :ci_address_line_1 "Suite 824" :ci_address_line_2 "20 Jay St" :ci_address_line_3 "Brooklyn, NY 11201" :ci_directions "Take the F to York St." :ci_email "democracy@example.com" :ci_fax "555-555-5FAX" :ci_hours "10am to 6pm" :ci_hours_open_id "ho002" :ci_latitude "40.704" :ci_longitude "-73.989" :ci_latlng_source "Sean" :ci_name "Democracy Works" :ci_phone "555-555-5555" :ci_uri "http://democracy.works"}]} transform-fn (departments/departments->ltree departments voter-services "VipObject.0.ElectionAdministration.0.id") ltree-entries (set (transform-fn idx-fn parent-path nil))] (testing "AddressLines come from address_line_{1,2,3}" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.0" :value "Suite 824" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})) (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.1" :value "20 Jay St" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})) (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.2" :value "Brooklyn, NY 11201" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "Directions has the ElectionAdministration as the parent_with_id" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.Directions.3.Text.0" :value "Take the F to York St." :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.Directions.Text" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "LatLng has the ElectionAdministration as the parent_with_id" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.LatLng.8.Latitude.0" :value "40.704" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.LatLng.Latitude" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "Departments include Voter Services" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.VoterService.2.label" :value "vs01" :simple_path "VipObject.ElectionAdministration.Department.VoterService.label" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})))))
109134
(ns vip.data-processor.db.translations.v5-2.departments-test (:require [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.translations.v5-2.departments :as departments] [vip.data-processor.db.translations.util :as util])) (deftest department->ltree-test (let [idx-fn (util/index-generator 0) parent-path "VipObject.0.ElectionAdministration.0" departments [{:id "dep01" :election_official_person_id "eloff01" :ci_address_line_1 "Suite 824" :ci_address_line_2 "20 Jay St" :ci_address_line_3 "Brooklyn, NY 11201" :ci_directions "Take the F to York St." :ci_email "<EMAIL>" :ci_fax "555-555-5FAX" :ci_hours "10am to 6pm" :ci_hours_open_id "ho002" :ci_latitude "40.704" :ci_longitude "-73.989" :ci_latlng_source "Sean" :ci_name "Dem<NAME> Works" :ci_phone "555-555-5555" :ci_uri "http://democracy.works"}] voter-services {"dep01" [{:id "vs01" :type "overseas-voting" :other_type nil :ci_address_line_1 "Suite 824" :ci_address_line_2 "20 Jay St" :ci_address_line_3 "Brooklyn, NY 11201" :ci_directions "Take the F to York St." :ci_email "<EMAIL>" :ci_fax "555-555-5FAX" :ci_hours "10am to 6pm" :ci_hours_open_id "ho002" :ci_latitude "40.704" :ci_longitude "-73.989" :ci_latlng_source "Sean" :ci_name "Democracy Works" :ci_phone "555-555-5555" :ci_uri "http://democracy.works"}]} transform-fn (departments/departments->ltree departments voter-services "VipObject.0.ElectionAdministration.0.id") ltree-entries (set (transform-fn idx-fn parent-path nil))] (testing "AddressLines come from address_line_{1,2,3}" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.0" :value "Suite 824" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})) (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.1" :value "20 Jay St" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})) (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.2" :value "Brooklyn, NY 11201" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "Directions has the ElectionAdministration as the parent_with_id" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.Directions.3.Text.0" :value "Take the F to York St." :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.Directions.Text" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "LatLng has the ElectionAdministration as the parent_with_id" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.LatLng.8.Latitude.0" :value "40.704" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.LatLng.Latitude" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "Departments include Voter Services" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.VoterService.2.label" :value "vs01" :simple_path "VipObject.ElectionAdministration.Department.VoterService.label" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})))))
true
(ns vip.data-processor.db.translations.v5-2.departments-test (:require [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.translations.v5-2.departments :as departments] [vip.data-processor.db.translations.util :as util])) (deftest department->ltree-test (let [idx-fn (util/index-generator 0) parent-path "VipObject.0.ElectionAdministration.0" departments [{:id "dep01" :election_official_person_id "eloff01" :ci_address_line_1 "Suite 824" :ci_address_line_2 "20 Jay St" :ci_address_line_3 "Brooklyn, NY 11201" :ci_directions "Take the F to York St." :ci_email "PI:EMAIL:<EMAIL>END_PI" :ci_fax "555-555-5FAX" :ci_hours "10am to 6pm" :ci_hours_open_id "ho002" :ci_latitude "40.704" :ci_longitude "-73.989" :ci_latlng_source "Sean" :ci_name "DemPI:NAME:<NAME>END_PI Works" :ci_phone "555-555-5555" :ci_uri "http://democracy.works"}] voter-services {"dep01" [{:id "vs01" :type "overseas-voting" :other_type nil :ci_address_line_1 "Suite 824" :ci_address_line_2 "20 Jay St" :ci_address_line_3 "Brooklyn, NY 11201" :ci_directions "Take the F to York St." :ci_email "PI:EMAIL:<EMAIL>END_PI" :ci_fax "555-555-5FAX" :ci_hours "10am to 6pm" :ci_hours_open_id "ho002" :ci_latitude "40.704" :ci_longitude "-73.989" :ci_latlng_source "Sean" :ci_name "Democracy Works" :ci_phone "555-555-5555" :ci_uri "http://democracy.works"}]} transform-fn (departments/departments->ltree departments voter-services "VipObject.0.ElectionAdministration.0.id") ltree-entries (set (transform-fn idx-fn parent-path nil))] (testing "AddressLines come from address_line_{1,2,3}" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.0" :value "Suite 824" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})) (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.1" :value "20 Jay St" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})) (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.AddressLine.2" :value "Brooklyn, NY 11201" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.AddressLine" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "Directions has the ElectionAdministration as the parent_with_id" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.Directions.3.Text.0" :value "Take the F to York St." :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.Directions.Text" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "LatLng has the ElectionAdministration as the parent_with_id" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.ContactInformation.0.LatLng.8.Latitude.0" :value "40.704" :simple_path "VipObject.ElectionAdministration.Department.ContactInformation.LatLng.Latitude" :parent_with_id "VipObject.0.ElectionAdministration.0.id"}))) (testing "Departments include Voter Services" (is (contains? ltree-entries {:path "VipObject.0.ElectionAdministration.0.Department.0.VoterService.2.label" :value "vs01" :simple_path "VipObject.ElectionAdministration.Department.VoterService.label" :parent_with_id "VipObject.0.ElectionAdministration.0.id"})))))
[ { "context": "d 1\n ; fetcher\n source-key \"claronte:test:source\"\n backup-key \"claronte:test:backup\"\n ", "end": 791, "score": 0.9985678791999817, "start": 771, "tag": "KEY", "value": "claronte:test:source" }, { "context": "ey \"claronte:test:source\"\n backup-key \"claronte:test:backup\"\n message \"foo\"\n _ (car/wca", "end": 837, "score": 0.9988975524902344, "start": 817, "tag": "KEY", "value": "claronte:test:backup" } ]
test/claronte/transport/transporter_test.clj
jordillonch/claronte
1
(ns claronte.transport.transporter-test (:require [clojure.test :refer :all] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all] [claronte.transport.sender.rabbitmq.sender :refer :all] [claronte.transport.sender.rabbitmq.connection-factory :refer :all] [claronte.transport.transporter :refer :all] [taoensso.carmine :as car :refer (wcar)] [langohr.basic :as lb] [langohr.exchange :as le] [langohr.queue :as lq]) ) (deftest transport-one-message (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 ; fetcher source-key "claronte:test:source" backup-key "claronte:test:backup" message "foo" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; sender exchange-name "exchange_clojure_test" routing-key "" ; create channel connection (create-connection-rabbitmq sender-rabbitmq-server-connection-parameters) channel (open-channel-rabbitmq connection) ; create the exchange _ (le/declare channel exchange-name "direct") ; create a queue in order to consume message that has to be sent queue (lq/declare-server-named channel :exclusive true) _ (lq/bind channel queue exchange-name :routing-key routing-key) sender (->RabbitMqSender id channel exchange-name routing-key) ; transporter _ (transport-message fetcher sender) ; consume [_ payload] (lb/get channel queue) consumed-message (String. payload) ] (is (= message consumed-message)) ) ))
1148
(ns claronte.transport.transporter-test (:require [clojure.test :refer :all] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all] [claronte.transport.sender.rabbitmq.sender :refer :all] [claronte.transport.sender.rabbitmq.connection-factory :refer :all] [claronte.transport.transporter :refer :all] [taoensso.carmine :as car :refer (wcar)] [langohr.basic :as lb] [langohr.exchange :as le] [langohr.queue :as lq]) ) (deftest transport-one-message (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 ; fetcher source-key "<KEY>" backup-key "<KEY>" message "foo" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; sender exchange-name "exchange_clojure_test" routing-key "" ; create channel connection (create-connection-rabbitmq sender-rabbitmq-server-connection-parameters) channel (open-channel-rabbitmq connection) ; create the exchange _ (le/declare channel exchange-name "direct") ; create a queue in order to consume message that has to be sent queue (lq/declare-server-named channel :exclusive true) _ (lq/bind channel queue exchange-name :routing-key routing-key) sender (->RabbitMqSender id channel exchange-name routing-key) ; transporter _ (transport-message fetcher sender) ; consume [_ payload] (lb/get channel queue) consumed-message (String. payload) ] (is (= message consumed-message)) ) ))
true
(ns claronte.transport.transporter-test (:require [clojure.test :refer :all] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all] [claronte.transport.sender.rabbitmq.sender :refer :all] [claronte.transport.sender.rabbitmq.connection-factory :refer :all] [claronte.transport.transporter :refer :all] [taoensso.carmine :as car :refer (wcar)] [langohr.basic :as lb] [langohr.exchange :as le] [langohr.queue :as lq]) ) (deftest transport-one-message (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 ; fetcher source-key "PI:KEY:<KEY>END_PI" backup-key "PI:KEY:<KEY>END_PI" message "foo" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; sender exchange-name "exchange_clojure_test" routing-key "" ; create channel connection (create-connection-rabbitmq sender-rabbitmq-server-connection-parameters) channel (open-channel-rabbitmq connection) ; create the exchange _ (le/declare channel exchange-name "direct") ; create a queue in order to consume message that has to be sent queue (lq/declare-server-named channel :exclusive true) _ (lq/bind channel queue exchange-name :routing-key routing-key) sender (->RabbitMqSender id channel exchange-name routing-key) ; transporter _ (transport-message fetcher sender) ; consume [_ payload] (lb/get channel queue) consumed-message (String. payload) ] (is (= message consumed-message)) ) ))
[ { "context": "ssage} other {messages}}\")\n\n(def values\n {:name \"Eric\" :unreadCount 100})\n\n(defn example-app []\n [:p\n ", "end": 247, "score": 0.9995977282524109, "start": 243, "tag": "NAME", "value": "Eric" } ]
src/app/main.cljs
dfuenzalida/cljs-react-intl
1
(ns app.main (:require ["react-intl" :as intl] [reagent.core :as r])) ;; App (def defaultMessage "Hello {name}, you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}") (def values {:name "Eric" :unreadCount 100}) (defn example-app [] [:p [:> intl/IntlProvider {:locale "en"} [:> intl/FormattedMessage {:id "welcome" :defaultMessage defaultMessage :values values}]]]) ;; App initialization (defn mount-root [] (r/render [example-app] (.getElementById js/document "app"))) (defn main! [] (mount-root) (println "[core]: loading")) (defn reload! [] (mount-root) (println "[core] reloaded"))
30306
(ns app.main (:require ["react-intl" :as intl] [reagent.core :as r])) ;; App (def defaultMessage "Hello {name}, you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}") (def values {:name "<NAME>" :unreadCount 100}) (defn example-app [] [:p [:> intl/IntlProvider {:locale "en"} [:> intl/FormattedMessage {:id "welcome" :defaultMessage defaultMessage :values values}]]]) ;; App initialization (defn mount-root [] (r/render [example-app] (.getElementById js/document "app"))) (defn main! [] (mount-root) (println "[core]: loading")) (defn reload! [] (mount-root) (println "[core] reloaded"))
true
(ns app.main (:require ["react-intl" :as intl] [reagent.core :as r])) ;; App (def defaultMessage "Hello {name}, you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}") (def values {:name "PI:NAME:<NAME>END_PI" :unreadCount 100}) (defn example-app [] [:p [:> intl/IntlProvider {:locale "en"} [:> intl/FormattedMessage {:id "welcome" :defaultMessage defaultMessage :values values}]]]) ;; App initialization (defn mount-root [] (r/render [example-app] (.getElementById js/document "app"))) (defn main! [] (mount-root) (println "[core]: loading")) (defn reload! [] (mount-root) (println "[core] reloaded"))
[ { "context": ";;;\n;;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio", "end": 36, "score": 0.9998024106025696, "start": 23, "tag": "NAME", "value": "David Edwards" } ]
src/rpn/loader.clj
davidledwards/rpn-clojure
1
;;; ;;; Copyright 2020 David Edwards ;;; ;;; 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 rpn.loader (:require [rpn.code :as code])) (defn- scan ([in] (scan in "")) ([in s] (let [c (first in)] (cond (= c \newline) [s (rest in)] (some? c) (recur (rest in) (str s c)) :else [(if (empty? s) nil s) in])))) (defn loader "An instruction loader that transforms a sequence of characters into a sequence of instructions." [in] (lazy-seq (let [[s in-rest] (scan in)] (if (nil? s) nil (if-let [c (code/parse s)] (cons c (loader in-rest)) (throw (Exception. (str s ": unrecognized or malformed instruction"))))))))
60201
;;; ;;; Copyright 2020 <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 rpn.loader (:require [rpn.code :as code])) (defn- scan ([in] (scan in "")) ([in s] (let [c (first in)] (cond (= c \newline) [s (rest in)] (some? c) (recur (rest in) (str s c)) :else [(if (empty? s) nil s) in])))) (defn loader "An instruction loader that transforms a sequence of characters into a sequence of instructions." [in] (lazy-seq (let [[s in-rest] (scan in)] (if (nil? s) nil (if-let [c (code/parse s)] (cons c (loader in-rest)) (throw (Exception. (str s ": unrecognized or malformed instruction"))))))))
true
;;; ;;; Copyright 2020 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 rpn.loader (:require [rpn.code :as code])) (defn- scan ([in] (scan in "")) ([in s] (let [c (first in)] (cond (= c \newline) [s (rest in)] (some? c) (recur (rest in) (str s c)) :else [(if (empty? s) nil s) in])))) (defn loader "An instruction loader that transforms a sequence of characters into a sequence of instructions." [in] (lazy-seq (let [[s in-rest] (scan in)] (if (nil? s) nil (if-let [c (code/parse s)] (cons c (loader in-rest)) (throw (Exception. (str s ": unrecognized or malformed instruction"))))))))
[ { "context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 28, "score": 0.9615586400032043, "start": 25, "tag": "NAME", "value": "Net" } ]
src/main/clojure/pigpen/extensions/test.clj
magomimmo/PigPen
1
;; ;; ;; Copyright 2013 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.extensions.test (:require [clojure.test :refer [is]] [clojure.data :refer [diff]])) (set! *warn-on-reflection* true) (defn test-diff [actual expected] (let [d (diff expected actual) expected-only (nth d 0) actual-only (nth d 1)] (is (= nil expected-only)) (is (= nil actual-only)))) (defn pigsym-zero "Generates command ids that are all 0. Useful for unit tests." [prefix-string] (symbol (str prefix-string 0))) (defn pigsym-inc "Returns a function that generates command ids that are sequential ints. Useful for unit tests." [] (let [pigsym-current (atom 0)] (fn [prefix-string] (symbol (str prefix-string (swap! pigsym-current inc)))))) (defn regex->string [command] ;; regexes don't implement value equality so we make them strings for tests (clojure.walk/postwalk #(if (instance? java.util.regex.Pattern %) (str %) %) command))
26398
;; ;; ;; Copyright 2013 <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.extensions.test (:require [clojure.test :refer [is]] [clojure.data :refer [diff]])) (set! *warn-on-reflection* true) (defn test-diff [actual expected] (let [d (diff expected actual) expected-only (nth d 0) actual-only (nth d 1)] (is (= nil expected-only)) (is (= nil actual-only)))) (defn pigsym-zero "Generates command ids that are all 0. Useful for unit tests." [prefix-string] (symbol (str prefix-string 0))) (defn pigsym-inc "Returns a function that generates command ids that are sequential ints. Useful for unit tests." [] (let [pigsym-current (atom 0)] (fn [prefix-string] (symbol (str prefix-string (swap! pigsym-current inc)))))) (defn regex->string [command] ;; regexes don't implement value equality so we make them strings for tests (clojure.walk/postwalk #(if (instance? java.util.regex.Pattern %) (str %) %) command))
true
;; ;; ;; Copyright 2013 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.extensions.test (:require [clojure.test :refer [is]] [clojure.data :refer [diff]])) (set! *warn-on-reflection* true) (defn test-diff [actual expected] (let [d (diff expected actual) expected-only (nth d 0) actual-only (nth d 1)] (is (= nil expected-only)) (is (= nil actual-only)))) (defn pigsym-zero "Generates command ids that are all 0. Useful for unit tests." [prefix-string] (symbol (str prefix-string 0))) (defn pigsym-inc "Returns a function that generates command ids that are sequential ints. Useful for unit tests." [] (let [pigsym-current (atom 0)] (fn [prefix-string] (symbol (str prefix-string (swap! pigsym-current inc)))))) (defn regex->string [command] ;; regexes don't implement value equality so we make them strings for tests (clojure.walk/postwalk #(if (instance? java.util.regex.Pattern %) (str %) %) command))
[ { "context": " [\"one\", \"two\"]\n plaintext-password \"Plaintext-password-1\"\n\n no-href-create {:template (ltu/st", "end": 2173, "score": 0.9994199872016907, "start": 2153, "tag": "PASSWORD", "value": "Plaintext-password-1" }, { "context": " :password plaintext-password\n ", "end": 2359, "score": 0.5532253384590149, "start": 2351, "tag": "PASSWORD", "value": "password" }, { "context": " :username \"alice\"))}\n href-create {:description de", "end": 2449, "score": 0.9987519979476929, "start": 2444, "tag": "USERNAME", "value": "alice" }, { "context": " :password plaintext-password\n :user", "end": 2707, "score": 0.9461886286735535, "start": 2689, "tag": "PASSWORD", "value": "plaintext-password" }, { "context": " :username \"user/jane\"}}\n\n invalid-create (assoc-in href-c", "end": 2772, "score": 0.99944007396698, "start": 2763, "tag": "USERNAME", "value": "user/jane" } ]
code/test/sixsq/nuvla/server/resources/user_username_password_lifecycle_test.clj
nuvla/server
0
(ns sixsq.nuvla.server.resources.user-username-password-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [deftest is use-fixtures]] [peridot.core :refer [content-type header request session]] [ring.util.codec :as rc] [sixsq.nuvla.server.app.params :as p] [sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]] [sixsq.nuvla.server.resources.credential :as credential] [sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu] [sixsq.nuvla.server.resources.user :as user] [sixsq.nuvla.server.resources.user-identifier :as user-identifier] [sixsq.nuvla.server.resources.user-template :as user-tpl] [sixsq.nuvla.server.resources.user-template-username-password :as username-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 "-" username-password/resource-url))) (deftest lifecycle (let [template-href (str user-tpl/resource-type "/" username-password/registration-method) template-url (str p/service-context template-href) 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-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] #_{:clj-kondo/ignore [:redundant-let]} (let [template (-> session-admin (request template-url) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body])) description-attr "description" tags-attr ["one", "two"] plaintext-password "Plaintext-password-1" no-href-create {:template (ltu/strip-unwanted-attrs (assoc template :password plaintext-password :username "alice"))} href-create {:description description-attr :tags tags-attr :template {:href template-href :password plaintext-password :username "user/jane"}} invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template") bad-params-create (assoc-in href-create [:template :invalid] "BAD")] ;; user collection query should succeed but be empty for all users (doseq [session [session-anon session-user session-admin]] (-> session (request (str base-uri "?filter=name!='super'")) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?) (ltu/is-operation-present :add) (ltu/is-operation-absent :delete) (ltu/is-operation-absent :edit))) ;; create a new user; fails without reference (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str no-href-create)) (ltu/body->edn) (ltu/is-status 400))) ;; create with invalid template fails (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str invalid-create)) (ltu/body->edn) (ltu/is-status 404))) ;; create with bad parameters fails (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str bad-params-create)) (ltu/body->edn) (ltu/is-status 400))) ;; create user, username-password template is only accessible by admin (let [resp (-> session-admin (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (get-in resp [:response :body :resource-id]) username-id (get-in href-create [:template :username]) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) {:keys [credential-password] :as user} (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body]))] ;; verify the ACL of the user (let [user-acl (:acl user)] (is (some #{"group/nuvla-admin"} (:owners user-acl))) ;; user should have all rights (doseq [right [:view-meta :view-data :view-acl :edit-meta :edit-data :edit-acl :manage :delete]] (is (some #{user-id} (right user-acl))))) ;; verify name attribute (should default to username) (is (= "user/jane" (:name user))) ; credential password is created and visible by the created user (-> session-created-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 403)) ; 1 identifier for the username is visible for the created user; find by identifier (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "identifier='%s'" username-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) ;; find identifiers by parent (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-admin (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200)) (let [{:keys [state]} (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/body))] (is (= "ACTIVE" state))) ;; try to create a second user with the same identifier ;; this must fail and all created supporting resources must be cleaned up (let [resp (-> session-admin (request base-uri :request-method :post :body (json/write-str (assoc-in href-create [:template :username] "user/jane"))) (ltu/body->edn) (ltu/is-status 409)) user-id (ltu/body-resource-id resp)] ; no dangling credentials (-> session-admin (content-type "application/x-www-form-urlencoded") (request (str p/service-context credential/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ; no dangling identifiers (-> session-admin (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0))) ;; user can delete his account (-> session-created-user (request (str p/service-context user-id) :request-method :delete) (ltu/body->edn) (ltu/is-status 200)) ;; password credential is gone (-> session-created-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 404)) ;; all identifiers pointing to user are gone (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ;; the user resource is gone as well (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 404))))))
33736
(ns sixsq.nuvla.server.resources.user-username-password-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [deftest is use-fixtures]] [peridot.core :refer [content-type header request session]] [ring.util.codec :as rc] [sixsq.nuvla.server.app.params :as p] [sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]] [sixsq.nuvla.server.resources.credential :as credential] [sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu] [sixsq.nuvla.server.resources.user :as user] [sixsq.nuvla.server.resources.user-identifier :as user-identifier] [sixsq.nuvla.server.resources.user-template :as user-tpl] [sixsq.nuvla.server.resources.user-template-username-password :as username-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 "-" username-password/resource-url))) (deftest lifecycle (let [template-href (str user-tpl/resource-type "/" username-password/registration-method) template-url (str p/service-context template-href) 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-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] #_{:clj-kondo/ignore [:redundant-let]} (let [template (-> session-admin (request template-url) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body])) description-attr "description" tags-attr ["one", "two"] plaintext-password "<PASSWORD>" no-href-create {:template (ltu/strip-unwanted-attrs (assoc template :password plaintext-<PASSWORD> :username "alice"))} href-create {:description description-attr :tags tags-attr :template {:href template-href :password <PASSWORD> :username "user/jane"}} invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template") bad-params-create (assoc-in href-create [:template :invalid] "BAD")] ;; user collection query should succeed but be empty for all users (doseq [session [session-anon session-user session-admin]] (-> session (request (str base-uri "?filter=name!='super'")) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?) (ltu/is-operation-present :add) (ltu/is-operation-absent :delete) (ltu/is-operation-absent :edit))) ;; create a new user; fails without reference (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str no-href-create)) (ltu/body->edn) (ltu/is-status 400))) ;; create with invalid template fails (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str invalid-create)) (ltu/body->edn) (ltu/is-status 404))) ;; create with bad parameters fails (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str bad-params-create)) (ltu/body->edn) (ltu/is-status 400))) ;; create user, username-password template is only accessible by admin (let [resp (-> session-admin (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (get-in resp [:response :body :resource-id]) username-id (get-in href-create [:template :username]) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) {:keys [credential-password] :as user} (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body]))] ;; verify the ACL of the user (let [user-acl (:acl user)] (is (some #{"group/nuvla-admin"} (:owners user-acl))) ;; user should have all rights (doseq [right [:view-meta :view-data :view-acl :edit-meta :edit-data :edit-acl :manage :delete]] (is (some #{user-id} (right user-acl))))) ;; verify name attribute (should default to username) (is (= "user/jane" (:name user))) ; credential password is created and visible by the created user (-> session-created-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 403)) ; 1 identifier for the username is visible for the created user; find by identifier (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "identifier='%s'" username-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) ;; find identifiers by parent (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-admin (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200)) (let [{:keys [state]} (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/body))] (is (= "ACTIVE" state))) ;; try to create a second user with the same identifier ;; this must fail and all created supporting resources must be cleaned up (let [resp (-> session-admin (request base-uri :request-method :post :body (json/write-str (assoc-in href-create [:template :username] "user/jane"))) (ltu/body->edn) (ltu/is-status 409)) user-id (ltu/body-resource-id resp)] ; no dangling credentials (-> session-admin (content-type "application/x-www-form-urlencoded") (request (str p/service-context credential/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ; no dangling identifiers (-> session-admin (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0))) ;; user can delete his account (-> session-created-user (request (str p/service-context user-id) :request-method :delete) (ltu/body->edn) (ltu/is-status 200)) ;; password credential is gone (-> session-created-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 404)) ;; all identifiers pointing to user are gone (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ;; the user resource is gone as well (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 404))))))
true
(ns sixsq.nuvla.server.resources.user-username-password-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [deftest is use-fixtures]] [peridot.core :refer [content-type header request session]] [ring.util.codec :as rc] [sixsq.nuvla.server.app.params :as p] [sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]] [sixsq.nuvla.server.resources.credential :as credential] [sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu] [sixsq.nuvla.server.resources.user :as user] [sixsq.nuvla.server.resources.user-identifier :as user-identifier] [sixsq.nuvla.server.resources.user-template :as user-tpl] [sixsq.nuvla.server.resources.user-template-username-password :as username-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 "-" username-password/resource-url))) (deftest lifecycle (let [template-href (str user-tpl/resource-type "/" username-password/registration-method) template-url (str p/service-context template-href) 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-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon") session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")] #_{:clj-kondo/ignore [:redundant-let]} (let [template (-> session-admin (request template-url) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body])) description-attr "description" tags-attr ["one", "two"] plaintext-password "PI:PASSWORD:<PASSWORD>END_PI" no-href-create {:template (ltu/strip-unwanted-attrs (assoc template :password plaintext-PI:PASSWORD:<PASSWORD>END_PI :username "alice"))} href-create {:description description-attr :tags tags-attr :template {:href template-href :password PI:PASSWORD:<PASSWORD>END_PI :username "user/jane"}} invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template") bad-params-create (assoc-in href-create [:template :invalid] "BAD")] ;; user collection query should succeed but be empty for all users (doseq [session [session-anon session-user session-admin]] (-> session (request (str base-uri "?filter=name!='super'")) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?) (ltu/is-operation-present :add) (ltu/is-operation-absent :delete) (ltu/is-operation-absent :edit))) ;; create a new user; fails without reference (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str no-href-create)) (ltu/body->edn) (ltu/is-status 400))) ;; create with invalid template fails (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str invalid-create)) (ltu/body->edn) (ltu/is-status 404))) ;; create with bad parameters fails (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri :request-method :post :body (json/write-str bad-params-create)) (ltu/body->edn) (ltu/is-status 400))) ;; create user, username-password template is only accessible by admin (let [resp (-> session-admin (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 201)) user-id (get-in resp [:response :body :resource-id]) username-id (get-in href-create [:template :username]) session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon")) {:keys [credential-password] :as user} (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body]))] ;; verify the ACL of the user (let [user-acl (:acl user)] (is (some #{"group/nuvla-admin"} (:owners user-acl))) ;; user should have all rights (doseq [right [:view-meta :view-data :view-acl :edit-meta :edit-data :edit-acl :manage :delete]] (is (some #{user-id} (right user-acl))))) ;; verify name attribute (should default to username) (is (= "user/jane" (:name user))) ; credential password is created and visible by the created user (-> session-created-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 403)) ; 1 identifier for the username is visible for the created user; find by identifier (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "identifier='%s'" username-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) ;; find identifiers by parent (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-admin (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 200)) (let [{:keys [state]} (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/body))] (is (= "ACTIVE" state))) ;; try to create a second user with the same identifier ;; this must fail and all created supporting resources must be cleaned up (let [resp (-> session-admin (request base-uri :request-method :post :body (json/write-str (assoc-in href-create [:template :username] "user/jane"))) (ltu/body->edn) (ltu/is-status 409)) user-id (ltu/body-resource-id resp)] ; no dangling credentials (-> session-admin (content-type "application/x-www-form-urlencoded") (request (str p/service-context credential/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ; no dangling identifiers (-> session-admin (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0))) ;; user can delete his account (-> session-created-user (request (str p/service-context user-id) :request-method :delete) (ltu/body->edn) (ltu/is-status 200)) ;; password credential is gone (-> session-created-user (request (str p/service-context credential-password)) (ltu/body->edn) (ltu/is-status 404)) ;; all identifiers pointing to user are gone (-> session-created-user (content-type "application/x-www-form-urlencoded") (request (str p/service-context user-identifier/resource-type) :request-method :put :body (rc/form-encode {:filter (format "parent='%s'" user-id)})) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ;; the user resource is gone as well (-> session-created-user (request (str p/service-context user-id)) (ltu/body->edn) (ltu/is-status 404))))))
[ { "context": "; Copyright (c) Laurent Petit and others, March 2009. All rights reserved.\n\n; ", "end": 31, "score": 0.9998970031738281, "start": 18, "tag": "NAME", "value": "Laurent Petit" }, { "context": ": feel free to add to this lib\n\n(ns\n #^{:author \"Laurent Petit (and others)\"\n :doc \"Functions/macros variant", "end": 666, "score": 0.9998958110809326, "start": 653, "tag": "NAME", "value": "Laurent Petit" }, { "context": "-----------------------------------------------\n;; scgilardi at gmail\n\n(defn dissoc-in\n \"Dissociates an e", "end": 1909, "score": 0.7884089350700378, "start": 1904, "tag": "USERNAME", "value": "scgil" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/core.clj
allertonm/Couverjure
3
; Copyright (c) Laurent Petit and others, March 2009. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this ; distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;; functions/macros variants of the ones that can be found in clojure.core ;; note to other contrib members: feel free to add to this lib (ns #^{:author "Laurent Petit (and others)" :doc "Functions/macros variants of the ones that can be found in clojure.core (note to other contrib members: feel free to add to this lib)"} clojure.contrib.core (:use clojure.contrib.def)) (defmacro- defnilsafe [docstring non-safe-name nil-safe-name] `(defmacro ~nil-safe-name ~docstring {:arglists '([~'x ~'form] [~'x ~'form ~'& ~'forms])} ([x# form#] `(let [~'i# ~x#] (when-not (nil? ~'i#) (~'~non-safe-name ~'i# ~form#)))) ([x# form# & more#] `(~'~nil-safe-name (~'~nil-safe-name ~x# ~form#) ~@more#)))) (defnilsafe "Same as clojure.core/-> but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation). Examples : (-?> \"foo\" .toUpperCase (.substring 1)) returns \"OO\" (-?> nil .toUpperCase (.substring 1)) returns nil " -> -?>) (defnilsafe "Same as clojure.core/.. but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation). Examples : (.?. \"foo\" .toUpperCase (.substring 1)) returns \"OO\" (.?. nil .toUpperCase (.substring 1)) returns nil " .. .?.) ;; ---------------------------------------------------------------------- ;; scgilardi at gmail (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. keys is a sequence of keys. Any empty maps that result will not be present in the new structure." [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) (defn new-by-name "Constructs a Java object whose class is specified by a String." [class-name & args] (clojure.lang.Reflector/invokeConstructor (clojure.lang.RT/classForName class-name) (into-array Object args))) (defn seqable? "Returns true if (seq x) will succeed, false otherwise." [x] (or (seq? x) (instance? clojure.lang.Seqable x) (nil? x) (instance? Iterable x) (-> x .getClass .isArray) (string? x) (instance? java.util.Map x))) ;; ----------------------------------------------------------------------
19624
; Copyright (c) <NAME> and others, March 2009. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this ; distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;; functions/macros variants of the ones that can be found in clojure.core ;; note to other contrib members: feel free to add to this lib (ns #^{:author "<NAME> (and others)" :doc "Functions/macros variants of the ones that can be found in clojure.core (note to other contrib members: feel free to add to this lib)"} clojure.contrib.core (:use clojure.contrib.def)) (defmacro- defnilsafe [docstring non-safe-name nil-safe-name] `(defmacro ~nil-safe-name ~docstring {:arglists '([~'x ~'form] [~'x ~'form ~'& ~'forms])} ([x# form#] `(let [~'i# ~x#] (when-not (nil? ~'i#) (~'~non-safe-name ~'i# ~form#)))) ([x# form# & more#] `(~'~nil-safe-name (~'~nil-safe-name ~x# ~form#) ~@more#)))) (defnilsafe "Same as clojure.core/-> but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation). Examples : (-?> \"foo\" .toUpperCase (.substring 1)) returns \"OO\" (-?> nil .toUpperCase (.substring 1)) returns nil " -> -?>) (defnilsafe "Same as clojure.core/.. but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation). Examples : (.?. \"foo\" .toUpperCase (.substring 1)) returns \"OO\" (.?. nil .toUpperCase (.substring 1)) returns nil " .. .?.) ;; ---------------------------------------------------------------------- ;; scgilardi at gmail (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. keys is a sequence of keys. Any empty maps that result will not be present in the new structure." [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) (defn new-by-name "Constructs a Java object whose class is specified by a String." [class-name & args] (clojure.lang.Reflector/invokeConstructor (clojure.lang.RT/classForName class-name) (into-array Object args))) (defn seqable? "Returns true if (seq x) will succeed, false otherwise." [x] (or (seq? x) (instance? clojure.lang.Seqable x) (nil? x) (instance? Iterable x) (-> x .getClass .isArray) (string? x) (instance? java.util.Map x))) ;; ----------------------------------------------------------------------
true
; Copyright (c) PI:NAME:<NAME>END_PI and others, March 2009. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this ; distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;; functions/macros variants of the ones that can be found in clojure.core ;; note to other contrib members: feel free to add to this lib (ns #^{:author "PI:NAME:<NAME>END_PI (and others)" :doc "Functions/macros variants of the ones that can be found in clojure.core (note to other contrib members: feel free to add to this lib)"} clojure.contrib.core (:use clojure.contrib.def)) (defmacro- defnilsafe [docstring non-safe-name nil-safe-name] `(defmacro ~nil-safe-name ~docstring {:arglists '([~'x ~'form] [~'x ~'form ~'& ~'forms])} ([x# form#] `(let [~'i# ~x#] (when-not (nil? ~'i#) (~'~non-safe-name ~'i# ~form#)))) ([x# form# & more#] `(~'~nil-safe-name (~'~nil-safe-name ~x# ~form#) ~@more#)))) (defnilsafe "Same as clojure.core/-> but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation). Examples : (-?> \"foo\" .toUpperCase (.substring 1)) returns \"OO\" (-?> nil .toUpperCase (.substring 1)) returns nil " -> -?>) (defnilsafe "Same as clojure.core/.. but returns nil as soon as the threaded value is nil itself (thus short-circuiting any pending computation). Examples : (.?. \"foo\" .toUpperCase (.substring 1)) returns \"OO\" (.?. nil .toUpperCase (.substring 1)) returns nil " .. .?.) ;; ---------------------------------------------------------------------- ;; scgilardi at gmail (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. keys is a sequence of keys. Any empty maps that result will not be present in the new structure." [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) (defn new-by-name "Constructs a Java object whose class is specified by a String." [class-name & args] (clojure.lang.Reflector/invokeConstructor (clojure.lang.RT/classForName class-name) (into-array Object args))) (defn seqable? "Returns true if (seq x) will succeed, false otherwise." [x] (or (seq? x) (instance? clojure.lang.Seqable x) (nil? x) (instance? Iterable x) (-> x .getClass .isArray) (string? x) (instance? java.util.Map x))) ;; ----------------------------------------------------------------------
[ { "context": "oded\")\n (mock/body \"username=admin&password=admin\"))\n response (test-auth-h", "end": 879, "score": 0.9958597421646118, "start": 874, "tag": "USERNAME", "value": "admin" }, { "context": " (mock/body \"username=admin&password=admin\"))\n response (test-auth-handler request)", "end": 894, "score": 0.9970137476921082, "start": 889, "tag": "PASSWORD", "value": "admin" } ]
src/test/clj/planted/auth_test.clj
jandorfer/planted
2
(ns planted.auth-test (:require [cemerick.friend :as friend] [clojure.test :refer :all] [clojure.tools.logging :as log] [compojure.core :refer (POST defroutes)] [planted.auth :refer :all] [ring.mock.request :as mock] [ring.util.response :refer [response]])) (def test-config-basic {:use-basic-auth true}) (defroutes mock-routes (POST "/login" request (-> request friend/identity :current response))) (def test-auth-handler (let [auth-handler (get-handler test-config-basic nil)] (-> mock-routes auth-handler))) (deftest check-handler (testing "Basic auth check" (let [request (-> (mock/request "POST" "/login") (mock/content-type "application/x-www-form-urlencoded") (mock/body "username=admin&password=admin")) response (test-auth-handler request)] (log/info request) (log/info response) (is (= (:status response) 200)))))
103628
(ns planted.auth-test (:require [cemerick.friend :as friend] [clojure.test :refer :all] [clojure.tools.logging :as log] [compojure.core :refer (POST defroutes)] [planted.auth :refer :all] [ring.mock.request :as mock] [ring.util.response :refer [response]])) (def test-config-basic {:use-basic-auth true}) (defroutes mock-routes (POST "/login" request (-> request friend/identity :current response))) (def test-auth-handler (let [auth-handler (get-handler test-config-basic nil)] (-> mock-routes auth-handler))) (deftest check-handler (testing "Basic auth check" (let [request (-> (mock/request "POST" "/login") (mock/content-type "application/x-www-form-urlencoded") (mock/body "username=admin&password=<PASSWORD>")) response (test-auth-handler request)] (log/info request) (log/info response) (is (= (:status response) 200)))))
true
(ns planted.auth-test (:require [cemerick.friend :as friend] [clojure.test :refer :all] [clojure.tools.logging :as log] [compojure.core :refer (POST defroutes)] [planted.auth :refer :all] [ring.mock.request :as mock] [ring.util.response :refer [response]])) (def test-config-basic {:use-basic-auth true}) (defroutes mock-routes (POST "/login" request (-> request friend/identity :current response))) (def test-auth-handler (let [auth-handler (get-handler test-config-basic nil)] (-> mock-routes auth-handler))) (deftest check-handler (testing "Basic auth check" (let [request (-> (mock/request "POST" "/login") (mock/content-type "application/x-www-form-urlencoded") (mock/body "username=admin&password=PI:PASSWORD:<PASSWORD>END_PI")) response (test-auth-handler request)] (log/info request) (log/info response) (is (= (:status response) 200)))))
[ { "context": "; Copyright (C) 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n\n(ns", "end": 38, "score": 0.9997551441192627, "start": 25, "tag": "NAME", "value": "Thomas Schank" }, { "context": "; Copyright (C) 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n\n(ns json-roa-demo.res", "end": 56, "score": 0.9999215006828308, "start": 41, "tag": "EMAIL", "value": "DrTom@schank.ch" }, { "context": "ight (C) 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n\n(ns json-roa-demo.resources\n (:require\n [cl", "end": 82, "score": 0.9999268651008606, "start": 58, "tag": "EMAIL", "value": "Thomas.Schank@algocon.ch" } ]
src/json_roa_demo/resources.clj
json-roa/json-roa_demo-app
0
; Copyright (C) 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch) (ns json-roa-demo.resources (:require [clojure.tools.logging :as logging] [clojure.walk :refer [keywordize-keys]] [compojure.core :as cpj] [compojure.handler :as cpj.handler] [compojure.route :as cpj.route] [compojure.route :as route] [drtom.logbug.thrown :as thrown] [json-roa-demo.basic-auth :as basic-auth] [json-roa-demo.json-roa :as json-roa] [json-roa-demo.resources.messages :as messages] [json-roa-demo.resources.users :as users] [json-roa.ring-middleware.request :as json-roa_request] [json-roa.ring-middleware.response :as json-roa_response] [pg-types.all] [ring.middleware.json] [ring.util.response :refer [header]] )) (def ^:private dead-end-handler (cpj/routes (cpj/GET "*" _ {:status 404 :body {:message "404 NOT FOUND"}}) (cpj/ANY "*" _ {:status 501 :body {:message "501 NOT IMPLEMENTED"}}) )) (defn index [request] {:status 200 :body {:message ["Welcome to the JSON-ROA Demo." "Visit /docs/index.html for more information about this application." ] :project (let [project (-> "project.clj" slurp read-string)] {:name (nth project 1) :version (nth project 2)}) }}) (defn wrap-keywordize-request [handler] (fn [request] (-> request keywordize-keys handler))) (defn wrap-server-errror [handler] (fn [request] (try (handler request) (catch Exception e (logging/warn (thrown/stringify e)) {:status 500 :body {:error (thrown/stringify e)}})))) (defn wrap-authenticated-routes [handler] (cpj/routes (cpj/ANY "/messages/*" _ (basic-auth/wrap (wrap-server-errror (messages/routes dead-end-handler)))) (cpj/ANY "*" _ handler))) (defn wrap-public-routes [handler] (cpj/routes (cpj/GET "/" _ #'index) (cpj/POST "/users/" _ #'users/create) (cpj/OPTIONS "/users/" _ (-> {:status 200} (header "Allow" "POST"))) (cpj/OPTIONS "/messages/" _ (-> {:status 200} (header "Allow" "GET, POST"))) (cpj/OPTIONS "/messages/:id" _ (-> {:status 200} (header "Allow" "GET, DELETE"))) (cpj/ANY "*" _ handler))) (defn build-routes-handler [] (-> dead-end-handler wrap-authenticated-routes wrap-public-routes wrap-keywordize-request (json-roa_request/wrap json-roa/handler) json-roa_response/wrap ring.middleware.json/wrap-json-response ))
22495
; Copyright (C) 2015 Dr. <NAME> (<EMAIL>, <EMAIL>) (ns json-roa-demo.resources (:require [clojure.tools.logging :as logging] [clojure.walk :refer [keywordize-keys]] [compojure.core :as cpj] [compojure.handler :as cpj.handler] [compojure.route :as cpj.route] [compojure.route :as route] [drtom.logbug.thrown :as thrown] [json-roa-demo.basic-auth :as basic-auth] [json-roa-demo.json-roa :as json-roa] [json-roa-demo.resources.messages :as messages] [json-roa-demo.resources.users :as users] [json-roa.ring-middleware.request :as json-roa_request] [json-roa.ring-middleware.response :as json-roa_response] [pg-types.all] [ring.middleware.json] [ring.util.response :refer [header]] )) (def ^:private dead-end-handler (cpj/routes (cpj/GET "*" _ {:status 404 :body {:message "404 NOT FOUND"}}) (cpj/ANY "*" _ {:status 501 :body {:message "501 NOT IMPLEMENTED"}}) )) (defn index [request] {:status 200 :body {:message ["Welcome to the JSON-ROA Demo." "Visit /docs/index.html for more information about this application." ] :project (let [project (-> "project.clj" slurp read-string)] {:name (nth project 1) :version (nth project 2)}) }}) (defn wrap-keywordize-request [handler] (fn [request] (-> request keywordize-keys handler))) (defn wrap-server-errror [handler] (fn [request] (try (handler request) (catch Exception e (logging/warn (thrown/stringify e)) {:status 500 :body {:error (thrown/stringify e)}})))) (defn wrap-authenticated-routes [handler] (cpj/routes (cpj/ANY "/messages/*" _ (basic-auth/wrap (wrap-server-errror (messages/routes dead-end-handler)))) (cpj/ANY "*" _ handler))) (defn wrap-public-routes [handler] (cpj/routes (cpj/GET "/" _ #'index) (cpj/POST "/users/" _ #'users/create) (cpj/OPTIONS "/users/" _ (-> {:status 200} (header "Allow" "POST"))) (cpj/OPTIONS "/messages/" _ (-> {:status 200} (header "Allow" "GET, POST"))) (cpj/OPTIONS "/messages/:id" _ (-> {:status 200} (header "Allow" "GET, DELETE"))) (cpj/ANY "*" _ handler))) (defn build-routes-handler [] (-> dead-end-handler wrap-authenticated-routes wrap-public-routes wrap-keywordize-request (json-roa_request/wrap json-roa/handler) json-roa_response/wrap ring.middleware.json/wrap-json-response ))
true
; Copyright (C) 2015 Dr. PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI, PI:EMAIL:<EMAIL>END_PI) (ns json-roa-demo.resources (:require [clojure.tools.logging :as logging] [clojure.walk :refer [keywordize-keys]] [compojure.core :as cpj] [compojure.handler :as cpj.handler] [compojure.route :as cpj.route] [compojure.route :as route] [drtom.logbug.thrown :as thrown] [json-roa-demo.basic-auth :as basic-auth] [json-roa-demo.json-roa :as json-roa] [json-roa-demo.resources.messages :as messages] [json-roa-demo.resources.users :as users] [json-roa.ring-middleware.request :as json-roa_request] [json-roa.ring-middleware.response :as json-roa_response] [pg-types.all] [ring.middleware.json] [ring.util.response :refer [header]] )) (def ^:private dead-end-handler (cpj/routes (cpj/GET "*" _ {:status 404 :body {:message "404 NOT FOUND"}}) (cpj/ANY "*" _ {:status 501 :body {:message "501 NOT IMPLEMENTED"}}) )) (defn index [request] {:status 200 :body {:message ["Welcome to the JSON-ROA Demo." "Visit /docs/index.html for more information about this application." ] :project (let [project (-> "project.clj" slurp read-string)] {:name (nth project 1) :version (nth project 2)}) }}) (defn wrap-keywordize-request [handler] (fn [request] (-> request keywordize-keys handler))) (defn wrap-server-errror [handler] (fn [request] (try (handler request) (catch Exception e (logging/warn (thrown/stringify e)) {:status 500 :body {:error (thrown/stringify e)}})))) (defn wrap-authenticated-routes [handler] (cpj/routes (cpj/ANY "/messages/*" _ (basic-auth/wrap (wrap-server-errror (messages/routes dead-end-handler)))) (cpj/ANY "*" _ handler))) (defn wrap-public-routes [handler] (cpj/routes (cpj/GET "/" _ #'index) (cpj/POST "/users/" _ #'users/create) (cpj/OPTIONS "/users/" _ (-> {:status 200} (header "Allow" "POST"))) (cpj/OPTIONS "/messages/" _ (-> {:status 200} (header "Allow" "GET, POST"))) (cpj/OPTIONS "/messages/:id" _ (-> {:status 200} (header "Allow" "GET, DELETE"))) (cpj/ANY "*" _ handler))) (defn build-routes-handler [] (-> dead-end-handler wrap-authenticated-routes wrap-public-routes wrap-keywordize-request (json-roa_request/wrap json-roa/handler) json-roa_response/wrap ring.middleware.json/wrap-json-response ))
[ { "context": "\n\n(defn ^:private round-ability\n [char {:keys [id name]}]\n (let [{hl-char-id :character, hl-ability-id ", "end": 813, "score": 0.7797082662582397, "start": 809, "tag": "NAME", "value": "name" } ]
src/app/renderer/combat_tracker/timeline.cljs
allison-casey/combat-tracker
0
(ns app.renderer.combat-tracker.timeline (:require [re-frame.core :as rf] [app.renderer.subs :as subs])) (defn line [x1 y1 x2 y2] [:line {:style {:stroke "black", :stroke-width 1, :fill "none"} :x1 x1, :x2 x2, :y1 y1, :y2 y2}]) (defn circle [cx cy r] [:circle {:style {:stroke "black" :stroke-width 1 :fill "none"} :cx cx, :cy cy, :r r}]) (defn ^:private round-title [label] [:div.d-flex.w-100.justify-content-center [:div.pr-2 [:svg {:width "40px" :height "13px" :style {:stroke-opacity 0.5}} [line 0 6 35 6] [circle (+ 35 4) 6 5]]] [:div.text-center label] [:div.pl-2 [:svg {:width "40px" :height "13px" :style {:stroke-opacity 0.5}} [line 4 6 35 6] [circle 0 6 5]]]]) (defn ^:private round-ability [char {:keys [id name]}] (let [{hl-char-id :character, hl-ability-id :ability} @(rf/subscribe [::subs/highlighted-ability])] [:a.list-group-item.list-group-item-action.flex-column.align-items-start {:class [(when (and (= char hl-char-id) (= hl-ability-id id)) "bg-light")] :style {:padding "0.1em", :transition "background 0.25s"}} [:div.d-flex.w-100.justify-content-center [:p.mb-1 name]]])) (defn ^:private timeline-section [[round abilities]] [:div [round-title round] [:div.list-group.list-group-flush (for [[char-id ability] abilities] ^{:key (:id ability)} [round-ability char-id ability])]]) (defn render [] (let [on-cooldown @(rf/subscribe [::subs/abilities-on-cooldown]) button (fn [key label] [:button.btn.btn-primary {:type "button" :on-click #(rf/dispatch [key])} label])] [:<> [:div.row [:div.col [:h4.text-center "Timeline"]]] [:div.row.d-flex.justify-content-around [button :increment-round "Round"] [button :increment-interleaved-round "Turn"]] [:hr] [:div.row [:div.col [:div.list-group (for [[round chunk] on-cooldown] ^{:key round} [timeline-section [round chunk]])]]]]))
73447
(ns app.renderer.combat-tracker.timeline (:require [re-frame.core :as rf] [app.renderer.subs :as subs])) (defn line [x1 y1 x2 y2] [:line {:style {:stroke "black", :stroke-width 1, :fill "none"} :x1 x1, :x2 x2, :y1 y1, :y2 y2}]) (defn circle [cx cy r] [:circle {:style {:stroke "black" :stroke-width 1 :fill "none"} :cx cx, :cy cy, :r r}]) (defn ^:private round-title [label] [:div.d-flex.w-100.justify-content-center [:div.pr-2 [:svg {:width "40px" :height "13px" :style {:stroke-opacity 0.5}} [line 0 6 35 6] [circle (+ 35 4) 6 5]]] [:div.text-center label] [:div.pl-2 [:svg {:width "40px" :height "13px" :style {:stroke-opacity 0.5}} [line 4 6 35 6] [circle 0 6 5]]]]) (defn ^:private round-ability [char {:keys [id <NAME>]}] (let [{hl-char-id :character, hl-ability-id :ability} @(rf/subscribe [::subs/highlighted-ability])] [:a.list-group-item.list-group-item-action.flex-column.align-items-start {:class [(when (and (= char hl-char-id) (= hl-ability-id id)) "bg-light")] :style {:padding "0.1em", :transition "background 0.25s"}} [:div.d-flex.w-100.justify-content-center [:p.mb-1 name]]])) (defn ^:private timeline-section [[round abilities]] [:div [round-title round] [:div.list-group.list-group-flush (for [[char-id ability] abilities] ^{:key (:id ability)} [round-ability char-id ability])]]) (defn render [] (let [on-cooldown @(rf/subscribe [::subs/abilities-on-cooldown]) button (fn [key label] [:button.btn.btn-primary {:type "button" :on-click #(rf/dispatch [key])} label])] [:<> [:div.row [:div.col [:h4.text-center "Timeline"]]] [:div.row.d-flex.justify-content-around [button :increment-round "Round"] [button :increment-interleaved-round "Turn"]] [:hr] [:div.row [:div.col [:div.list-group (for [[round chunk] on-cooldown] ^{:key round} [timeline-section [round chunk]])]]]]))
true
(ns app.renderer.combat-tracker.timeline (:require [re-frame.core :as rf] [app.renderer.subs :as subs])) (defn line [x1 y1 x2 y2] [:line {:style {:stroke "black", :stroke-width 1, :fill "none"} :x1 x1, :x2 x2, :y1 y1, :y2 y2}]) (defn circle [cx cy r] [:circle {:style {:stroke "black" :stroke-width 1 :fill "none"} :cx cx, :cy cy, :r r}]) (defn ^:private round-title [label] [:div.d-flex.w-100.justify-content-center [:div.pr-2 [:svg {:width "40px" :height "13px" :style {:stroke-opacity 0.5}} [line 0 6 35 6] [circle (+ 35 4) 6 5]]] [:div.text-center label] [:div.pl-2 [:svg {:width "40px" :height "13px" :style {:stroke-opacity 0.5}} [line 4 6 35 6] [circle 0 6 5]]]]) (defn ^:private round-ability [char {:keys [id PI:NAME:<NAME>END_PI]}] (let [{hl-char-id :character, hl-ability-id :ability} @(rf/subscribe [::subs/highlighted-ability])] [:a.list-group-item.list-group-item-action.flex-column.align-items-start {:class [(when (and (= char hl-char-id) (= hl-ability-id id)) "bg-light")] :style {:padding "0.1em", :transition "background 0.25s"}} [:div.d-flex.w-100.justify-content-center [:p.mb-1 name]]])) (defn ^:private timeline-section [[round abilities]] [:div [round-title round] [:div.list-group.list-group-flush (for [[char-id ability] abilities] ^{:key (:id ability)} [round-ability char-id ability])]]) (defn render [] (let [on-cooldown @(rf/subscribe [::subs/abilities-on-cooldown]) button (fn [key label] [:button.btn.btn-primary {:type "button" :on-click #(rf/dispatch [key])} label])] [:<> [:div.row [:div.col [:h4.text-center "Timeline"]]] [:div.row.d-flex.justify-content-around [button :increment-round "Round"] [button :increment-interleaved-round "Turn"]] [:hr] [:div.row [:div.col [:div.list-group (for [[round chunk] on-cooldown] ^{:key round} [timeline-section [round chunk]])]]]]))
[ { "context": "orm title\"}]\n :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"", "end": 1304, "score": 0.5494828820228577, "start": 1301, "tag": "USERNAME", "value": "bob" }, { "context": " :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"\n (is (= ", "end": 1320, "score": 0.606044352054596, "start": 1317, "tag": "USERNAME", "value": "car" }, { "context": " :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"\n (is (= {", "end": 1321, "score": 0.8682577610015869, "start": 1320, "tag": "NAME", "value": "l" }, { "context": "[{:form/id 13}]\n :handlers [\"bob\" \"carl\"]}\n (build-create-request form))))\n", "end": 1567, "score": 0.980327844619751, "start": 1563, "tag": "NAME", "value": "carl" }, { "context": " :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"\n (is (= ", "end": 2014, "score": 0.7442964911460876, "start": 2011, "tag": "USERNAME", "value": "car" }, { "context": " :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"\n (is (= {", "end": 2015, "score": 0.7734744548797607, "start": 2014, "tag": "NAME", "value": "l" }, { "context": "[{:form/id 13}]\n :handlers [\"bob\" \"carl\"]}\n (build-create-request form))))\n", "end": 2261, "score": 0.9534520506858826, "start": 2257, "tag": "NAME", "value": "carl" }, { "context": "kflow/master\n :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"", "end": 2626, "score": 0.8488110899925232, "start": 2623, "tag": "USERNAME", "value": "bob" }, { "context": " :handlers [{:userid \"bob\"} {:userid \"carl\"}]}]\n (testing \"valid form\"\n (is (= {", "end": 2643, "score": 0.8166215419769287, "start": 2639, "tag": "NAME", "value": "carl" }, { "context": " :forms []\n :handlers [\"bob\" \"carl\"]}\n (build-create-request fo", "end": 2868, "score": 0.5261622071266174, "start": 2865, "tag": "NAME", "value": "bob" }, { "context": " :forms []\n :handlers [\"bob\" \"carl\"]}\n (build-create-request form))))\n", "end": 2875, "score": 0.9940571784973145, "start": 2871, "tag": "NAME", "value": "carl" } ]
test/cljs/rems/administration/test_create_workflow.cljs
MalinAhlberg/rems
0
(ns rems.administration.test-create-workflow (:require [cljs.test :refer-macros [deftest is testing]] [rems.administration.create-workflow :refer [build-create-request build-edit-request]])) (deftest build-create-request-test (testing "all workflows" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 123}] :handlers ["bob"]}] (is (not (nil? (build-create-request form)))) (is (not (nil? (build-create-request (dissoc form :forms))))) (testing "missing organization" (is (nil? (build-create-request (assoc form :organization nil))))) (testing "missing title" (is (nil? (build-create-request (assoc form :title ""))))) (testing "missing workflow type" (is (nil? (build-create-request (assoc form :type nil))))) (testing "invalid workflow type" (is (nil? (build-create-request (assoc form :type :no-such-type))))))) (testing "default workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 13 :form/title "form title"}] :handlers [{:userid "bob"} {:userid "carl"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 13}] :handlers ["bob" "carl"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] []))))))) (testing "decider workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/decider :forms [{:form/id 13 :form/title "form title"}] :handlers [{:userid "bob"} {:userid "carl"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/decider :forms [{:form/id 13}] :handlers ["bob" "carl"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] []))))))) (testing "master workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/master :handlers [{:userid "bob"} {:userid "carl"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/master :forms [] :handlers ["bob" "carl"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] [])))))))) (deftest build-edit-request-test (is (= {:id 3 :title "t" :handlers ["a" "b"]} (build-edit-request 3 {:title "t" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request nil {:title "t" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request 3 {:title "" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request 3 {:title "t" :handlers []}))))
82928
(ns rems.administration.test-create-workflow (:require [cljs.test :refer-macros [deftest is testing]] [rems.administration.create-workflow :refer [build-create-request build-edit-request]])) (deftest build-create-request-test (testing "all workflows" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 123}] :handlers ["bob"]}] (is (not (nil? (build-create-request form)))) (is (not (nil? (build-create-request (dissoc form :forms))))) (testing "missing organization" (is (nil? (build-create-request (assoc form :organization nil))))) (testing "missing title" (is (nil? (build-create-request (assoc form :title ""))))) (testing "missing workflow type" (is (nil? (build-create-request (assoc form :type nil))))) (testing "invalid workflow type" (is (nil? (build-create-request (assoc form :type :no-such-type))))))) (testing "default workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 13 :form/title "form title"}] :handlers [{:userid "bob"} {:userid "car<NAME>"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 13}] :handlers ["bob" "<NAME>"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] []))))))) (testing "decider workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/decider :forms [{:form/id 13 :form/title "form title"}] :handlers [{:userid "bob"} {:userid "car<NAME>"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/decider :forms [{:form/id 13}] :handlers ["bob" "<NAME>"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] []))))))) (testing "master workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/master :handlers [{:userid "bob"} {:userid "<NAME>"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/master :forms [] :handlers ["<NAME>" "<NAME>"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] [])))))))) (deftest build-edit-request-test (is (= {:id 3 :title "t" :handlers ["a" "b"]} (build-edit-request 3 {:title "t" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request nil {:title "t" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request 3 {:title "" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request 3 {:title "t" :handlers []}))))
true
(ns rems.administration.test-create-workflow (:require [cljs.test :refer-macros [deftest is testing]] [rems.administration.create-workflow :refer [build-create-request build-edit-request]])) (deftest build-create-request-test (testing "all workflows" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 123}] :handlers ["bob"]}] (is (not (nil? (build-create-request form)))) (is (not (nil? (build-create-request (dissoc form :forms))))) (testing "missing organization" (is (nil? (build-create-request (assoc form :organization nil))))) (testing "missing title" (is (nil? (build-create-request (assoc form :title ""))))) (testing "missing workflow type" (is (nil? (build-create-request (assoc form :type nil))))) (testing "invalid workflow type" (is (nil? (build-create-request (assoc form :type :no-such-type))))))) (testing "default workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 13 :form/title "form title"}] :handlers [{:userid "bob"} {:userid "carPI:NAME:<NAME>END_PI"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/default :forms [{:form/id 13}] :handlers ["bob" "PI:NAME:<NAME>END_PI"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] []))))))) (testing "decider workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/decider :forms [{:form/id 13 :form/title "form title"}] :handlers [{:userid "bob"} {:userid "carPI:NAME:<NAME>END_PI"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/decider :forms [{:form/id 13}] :handlers ["bob" "PI:NAME:<NAME>END_PI"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] []))))))) (testing "master workflow" (let [form {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/master :handlers [{:userid "bob"} {:userid "PI:NAME:<NAME>END_PI"}]}] (testing "valid form" (is (= {:organization {:organization/id "abc"} :title "workflow title" :type :workflow/master :forms [] :handlers ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]} (build-create-request form)))) (testing "missing handlers" (is (nil? (build-create-request (assoc-in form [:handlers] [])))))))) (deftest build-edit-request-test (is (= {:id 3 :title "t" :handlers ["a" "b"]} (build-edit-request 3 {:title "t" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request nil {:title "t" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request 3 {:title "" :handlers [{:userid "a"} {:userid "b"}]}))) (is (nil? (build-edit-request 3 {:title "t" :handlers []}))))
[ { "context": "rkBench -- Natural deduction\n\n; Copyright (c) 2015 Tobias Völzel, THM. All rights reserved.\n; The use and distribu", "end": 78, "score": 0.9998260140419006, "start": 65, "tag": "NAME", "value": "Tobias Völzel" } ]
src/lwb/nd/proof.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Natural deduction ; Copyright (c) 2015 Tobias Völzel, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.nd.proof (:require [clojure.set :as set] [clojure.zip :as zip] [lwb.nd.error :refer :all] [lwb.pred.substitution :refer [substitution]]) (:import (clojure.lang LazySeq))) ;; # Proof in natural deduction ;; Each proof line has a unique id `plid`. ; atom is visible for tests (def plid "Global counter for the ids of proof lines." (atom 0)) (defn new-plid "Generates new plid for proof lines. Uses global `plid`." [] (swap! plid inc)) (defn reset-plid "Resets global `plid`." [] (reset! plid 0)) ;; Some rules generate new logical variables, e.g. new atomic propositions ;; They get new names beginning with the letter `?` and follwed by a unique number. ;; Caveat: Don't use this naming convention for propositions in formulas. (def qmno "Global counter for the numbers of new question marks." (atom 0)) (defn new-qmsymbol "Generates a new name for a question mark. Uses global `qmno`." [] (symbol (str \? (swap! qmno inc)))) (defn reset-qmno "Resets global `qmno`." [] (reset! qmno 0)) (defn qmsymbol? "Is `s` a symbol of the form `?n`?" [s] (and (symbol? s) (re-matches #"\?\d+$" (name s)))) ;; ## Creating new proofs (declare normalize) (defn proof "Gives a new proof for the premises and the conclusion. Uses global atoms `plid` and `lvno`." [premises conclusion] (do (reset-plid) (reset-qmno) (let [premises-vec (if-not (vector? premises) [premises] premises) premises-lines (vec (map #(hash-map :plid (new-plid) :body % :roth :premise) premises-vec)) proof (conj premises-lines {:plid (new-plid) :body conclusion :roth nil})] (normalize proof)))) ;; ## Functions to access proof lines (defn plid->plno "Returns the line number `plno` of the proof line with the given `plid`." [proof plid] (let [flat-proof (flatten proof)] (first (keep-indexed #(when (= plid (:plid %2)) (inc %1)) flat-proof)))) (defn plno->plid "Returns the id `plid` of the proof line at line number `plno` in the `proof`." [proof pos] (let [pline (nth (flatten proof) (dec pos) nil)] (:plid pline))) (defn pline-at-plno "Proof line of the `proof` at line with number `plno`. requires: `plno` valid." [proof plno] (let [fp (flatten proof)] (nth fp (dec plno)))) (defn plbody-at-plno "Body of the proof line at `plno`. requires: `plno` valid." [proof plno] (:body (pline-at-plno proof plno))) (defn pline-at-plid "Proof line of the `proof` at line with id `plid`. requires: `plid` valid." [proof plid] (pline-at-plno proof (plid->plno proof plid))) (defn plid-plno-map "Mapping of ids of pline to line numbers." [proof] (let [fp (flatten proof)] (into {} (map-indexed #(vector (:plid %2) (inc %1)) fp)))) (defn scope "Returns the scope for an item inside a proof e.g. proof = `[1 2 [3 4] [5 6 7] 8]` & item = `5` => scope = `[1 2 [3 4] 5 6 7]`" [proof pline] (if (contains? (set proof) pline) proof (loop [p proof result []] (cond (empty? p) nil (vector? (first p)) (if-let [s (scope (first p) pline)] (vec (concat result s)) (recur (subvec p 1) (conj result (first p)))) :else (recur (subvec p 1) (conj result (first p))))))) ;; ## Functions for editing a proof (defn add-above-plid "Adds a proof line or a subproof above the item with the given `plid`. requires: the added plines have new plids!" [proof plid pline-or-subproof] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/insert-left loc pline-or-subproof))) (recur (zip/next loc)))))) (defn replace-plid "Replaces the proof line with the given `plid` with the new proof line. requires: there are no more references to the old proof line." [proof plid pline] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/replace loc pline))) (recur (zip/next loc)))))) (defn remove-plid "Removes the proof line with the given `plid`. requires: there are no more references to that proof line." [proof plid] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/remove loc))) (recur (zip/next loc)))))) ;; ## Functions for the normalization of a proof ;; ### Adding todo lines if necessary (defn- new-todo-line "Generates a new todo line Uses global atom `plid`!" [] {:plid (new-plid), :body :todo, :roth nil}) (defn- unproved-line? "Checks whether a proof line has no roth." [pline] (and (not= :todo (:body pline)) (nil? (:roth pline)))) (defn todoline? "Checks whether a proof line is a todo line." [pline] (= :todo (:body pline))) (defn- insert-above? "Must a todo line be inserted above of this loc? (1) the current proof line is not a subproof and (2) the current proof line is not solved and (3) there is not already a todo line left of the current line." [loc] (let [prev-loc (zip/left loc) curr-line (zip/node loc) prev-line (when prev-loc (zip/node prev-loc))] (and (not (zip/branch? loc)) (unproved-line? curr-line) (not (todoline? prev-line))))) (defn add-todo-lines "Returns proof with todo lines added. Whenever there is a line in a proof without a rule, we have to insert a todo line above the proof line." [proof] (loop [loc (zip/next (zip/vector-zip proof))] (if (zip/end? loc) (zip/node loc) (if (insert-above? loc) (recur (zip/next (zip/insert-left loc (new-todo-line)))) (recur (zip/next loc)))))) ;; ### Removing todo lines if necessary (defn- remove-current? "Is the current loc a todo line and should it line be removed? (1) the todo line is followed by a pline which is solved or (2) the todo line is at the end of a subproof or proof or (3) the todo line is follwed by another todo line or (4) the todo line is followed by a subproof." [loc] (and (todoline? (zip/node loc)) (or (and (not (nil? (zip/right loc))) (not (nil? (:roth (zip/node (zip/right loc)))))) (= (zip/rightmost loc) loc) (and (not (nil? (zip/right loc))) (todoline? (zip/node (zip/right loc)))) (zip/branch? (zip/right loc))))) (defn remove-todo-lines "Returns proof where todo lines that are solved are removed." [proof] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (remove-current? loc) (recur (zip/next (zip/remove loc))) (recur (zip/next loc)))))) ;; ### Handling duplicate bodies in a proof (defn- find-duplicates "Finds duplicates bodies in the proof that can be deleted. Returns a map with the deletable plids as key and the replacement plids as value. Only plines without rule, in the same scope and the same subproof will be marked as deletable." ([proof] (find-duplicates proof proof)) ([proof sub] (let [dupl-scope (scope proof (last sub)) ;; duplicates = duplicate bodies in scope but not :todo duplicates (disj (set (map first (filter #(> (val %) 1) (frequencies (map :body (remove vector? dupl-scope)))))) :todo) ;; duplicate-plines = the pline with these duplicate bodies duplicate-plines (filter #(contains? duplicates (:body %)) dupl-scope) ;; duplicate-plines grouped into a vactor of vector of plines with equal body equals (vec (map val (group-by :body duplicate-plines))) ;; equals must have at least one :roth that's not nil equals' (filterv (fn [x] (not-every? nil? (map :roth x))) equals) fn-smap (fn [equals] (let [remain (map :plid (filter :roth equals)) delete (map :plid (filter (set sub) (remove :roth equals)))] ; just plines from the actual sub can be deleted (reduce #(assoc %1 %2 (last remain)) {} delete))) ;; map with pairs of plids where the first can be replace by the second plid-map (apply merge (map fn-smap equals'))] (reduce #(if (vector? %2) (merge %1 (find-duplicates proof %2)) %1) plid-map sub)))) (defn- adjust-refs "Upgrades the refs in the given proof according to the plid-map." [proof plid-map] (let [old-plines (filterv #(not-empty (set/intersection (set (keys plid-map)) (set (flatten (:refs %))))) (flatten proof)) upg-plines (mapv #(assoc % :roth (:roth %) :refs (clojure.walk/prewalk-replace plid-map (:refs %))) old-plines)] (vec (reduce #(replace-plid %1 (:plid %2) %2) proof upg-plines)))) (defn- check-refs "Checks the refs of a proof: The references must always refer to plines above!" [proof] (let [pm (plid-plno-map proof) fn (fn [pline] (let [curr-plno (get pm (:plid pline)) ; just consider the refs to other line numbers, not extra refs refs-plnos (mapv #(get pm %) (filter number? (flatten (:refs pline)))) max-ref-plno (if (empty? refs-plnos) 0 (apply max refs-plnos))] (< max-ref-plno curr-plno)))] (every? true? (map fn (flatten proof))))) (defn- remove-duplicates "Removes all duplicate bodies from proof and adjusts the changed ids of proof lines." [proof] (let [duplicates (find-duplicates proof) ;; if a body is the conclusion of a subproof but above already proved, ;; it's not deleted but marked with :repeat. fn-proved-results (fn [map [id1 id2]] (let [delete-pline (pline-at-plid proof id1) replace-pline (pline-at-plid proof id2) delete-scope (scope proof delete-pline)] (if (and (= delete-pline (last delete-scope)) (or (not= delete-scope (scope proof replace-pline)) (contains? #{:premise :assumption} (:roth replace-pline)))) (assoc map id1 id2) map))) proved-results (reduce fn-proved-results {} duplicates) fn-replace (fn [p [id1 id2]] (let [pline (pline-at-plid p id1)] (replace-plid p id1 {:plid id1 :body (:body pline) :roth :repeat :refs [id2]}))) new-proof1 (reduce fn-replace proof proved-results) deletions (reduce dissoc duplicates (map key proved-results)) delete-plids (keys deletions) new-proof2 (reduce remove-plid new-proof1 delete-plids) new-proof3 (adjust-refs new-proof2 deletions)] (if (check-refs new-proof3) new-proof3 proof))) ;; ### The interface for the user of this namespace: Normalizing a proof (defn normalize "Removes duplicate lines, adjust leftover plids and removes todo lines if possible" [proof] (-> proof add-todo-lines remove-duplicates remove-todo-lines)) ;; ## Preparing new proof lines after a deduction step ;; ### Helper functions (defn- replace-lvars "Replaces logical variables from core.logic like `_0` by generated variable names `?1`. This must be done with all the formulas generated by a run of core.logic simultaneously." [bodies] (let [lvars (set (filter #(.startsWith (str %) "_") (flatten bodies))) smap (reduce #(assoc %1 %2 (new-qmsymbol)) {} lvars)] (mapv #(if (symbol? %) (if (contains? lvars %) (get smap %) %) (clojure.walk/prewalk-replace smap %)) bodies))) (defn- eval-subs "Performs the substitution of `var` by `t` in `phi`." [[_ phi var t]] (substitution phi var t)) (declare new-subproof) (defn new-pline "Creates a new proof line or subproof from body and [optional] rule and refs." ([body] (new-pline body nil nil)) ([body roth refs] ; handle special case that body = (infer ...) or body = (substitution ...) (cond (and (seq? body) (= (first body) 'infer)) (new-subproof body) (and (seq? body) (= (first body) 'substitution)) {:plid (new-plid) :body (eval-subs body) :roth roth :refs refs} :else {:plid (new-plid) :body body :roth roth :refs refs}))) (defn- new-subproof "Creates a new subproof from infer clause." [[_ assumptions claim]] (let [a (if (vector? assumptions) assumptions [assumptions]) al (mapv #(new-pline % :assumption nil) a) t (new-pline :todo) cl (new-pline claim)] (conj al t cl))) ;; ### Interface for the user of proof: New plines as result of a deduction step (defn new-plines "Creates all the new plines that must be added to the proof" [bodies] (let [bodies' (replace-lvars bodies) ; a hack for handling lazy sequences!! non-lazy-bodies (clojure.walk/postwalk (fn [node] (if (instance? LazySeq node) (apply list node) node)) bodies')] (mapv new-pline non-lazy-bodies))) ;; ## Is the proof completed? (defn proved? "Checks if a proof is fully proved. Requires: the proof is normalized. Throws: Exception, if the proof is empty." [proof] (if (empty? proof) (throw (ex-error "The proof is empty"))) (let [plines (flatten proof)] (empty? (filter #(= :todo (:body %)) plines))))
16771
; lwb Logic WorkBench -- Natural deduction ; Copyright (c) 2015 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.nd.proof (:require [clojure.set :as set] [clojure.zip :as zip] [lwb.nd.error :refer :all] [lwb.pred.substitution :refer [substitution]]) (:import (clojure.lang LazySeq))) ;; # Proof in natural deduction ;; Each proof line has a unique id `plid`. ; atom is visible for tests (def plid "Global counter for the ids of proof lines." (atom 0)) (defn new-plid "Generates new plid for proof lines. Uses global `plid`." [] (swap! plid inc)) (defn reset-plid "Resets global `plid`." [] (reset! plid 0)) ;; Some rules generate new logical variables, e.g. new atomic propositions ;; They get new names beginning with the letter `?` and follwed by a unique number. ;; Caveat: Don't use this naming convention for propositions in formulas. (def qmno "Global counter for the numbers of new question marks." (atom 0)) (defn new-qmsymbol "Generates a new name for a question mark. Uses global `qmno`." [] (symbol (str \? (swap! qmno inc)))) (defn reset-qmno "Resets global `qmno`." [] (reset! qmno 0)) (defn qmsymbol? "Is `s` a symbol of the form `?n`?" [s] (and (symbol? s) (re-matches #"\?\d+$" (name s)))) ;; ## Creating new proofs (declare normalize) (defn proof "Gives a new proof for the premises and the conclusion. Uses global atoms `plid` and `lvno`." [premises conclusion] (do (reset-plid) (reset-qmno) (let [premises-vec (if-not (vector? premises) [premises] premises) premises-lines (vec (map #(hash-map :plid (new-plid) :body % :roth :premise) premises-vec)) proof (conj premises-lines {:plid (new-plid) :body conclusion :roth nil})] (normalize proof)))) ;; ## Functions to access proof lines (defn plid->plno "Returns the line number `plno` of the proof line with the given `plid`." [proof plid] (let [flat-proof (flatten proof)] (first (keep-indexed #(when (= plid (:plid %2)) (inc %1)) flat-proof)))) (defn plno->plid "Returns the id `plid` of the proof line at line number `plno` in the `proof`." [proof pos] (let [pline (nth (flatten proof) (dec pos) nil)] (:plid pline))) (defn pline-at-plno "Proof line of the `proof` at line with number `plno`. requires: `plno` valid." [proof plno] (let [fp (flatten proof)] (nth fp (dec plno)))) (defn plbody-at-plno "Body of the proof line at `plno`. requires: `plno` valid." [proof plno] (:body (pline-at-plno proof plno))) (defn pline-at-plid "Proof line of the `proof` at line with id `plid`. requires: `plid` valid." [proof plid] (pline-at-plno proof (plid->plno proof plid))) (defn plid-plno-map "Mapping of ids of pline to line numbers." [proof] (let [fp (flatten proof)] (into {} (map-indexed #(vector (:plid %2) (inc %1)) fp)))) (defn scope "Returns the scope for an item inside a proof e.g. proof = `[1 2 [3 4] [5 6 7] 8]` & item = `5` => scope = `[1 2 [3 4] 5 6 7]`" [proof pline] (if (contains? (set proof) pline) proof (loop [p proof result []] (cond (empty? p) nil (vector? (first p)) (if-let [s (scope (first p) pline)] (vec (concat result s)) (recur (subvec p 1) (conj result (first p)))) :else (recur (subvec p 1) (conj result (first p))))))) ;; ## Functions for editing a proof (defn add-above-plid "Adds a proof line or a subproof above the item with the given `plid`. requires: the added plines have new plids!" [proof plid pline-or-subproof] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/insert-left loc pline-or-subproof))) (recur (zip/next loc)))))) (defn replace-plid "Replaces the proof line with the given `plid` with the new proof line. requires: there are no more references to the old proof line." [proof plid pline] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/replace loc pline))) (recur (zip/next loc)))))) (defn remove-plid "Removes the proof line with the given `plid`. requires: there are no more references to that proof line." [proof plid] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/remove loc))) (recur (zip/next loc)))))) ;; ## Functions for the normalization of a proof ;; ### Adding todo lines if necessary (defn- new-todo-line "Generates a new todo line Uses global atom `plid`!" [] {:plid (new-plid), :body :todo, :roth nil}) (defn- unproved-line? "Checks whether a proof line has no roth." [pline] (and (not= :todo (:body pline)) (nil? (:roth pline)))) (defn todoline? "Checks whether a proof line is a todo line." [pline] (= :todo (:body pline))) (defn- insert-above? "Must a todo line be inserted above of this loc? (1) the current proof line is not a subproof and (2) the current proof line is not solved and (3) there is not already a todo line left of the current line." [loc] (let [prev-loc (zip/left loc) curr-line (zip/node loc) prev-line (when prev-loc (zip/node prev-loc))] (and (not (zip/branch? loc)) (unproved-line? curr-line) (not (todoline? prev-line))))) (defn add-todo-lines "Returns proof with todo lines added. Whenever there is a line in a proof without a rule, we have to insert a todo line above the proof line." [proof] (loop [loc (zip/next (zip/vector-zip proof))] (if (zip/end? loc) (zip/node loc) (if (insert-above? loc) (recur (zip/next (zip/insert-left loc (new-todo-line)))) (recur (zip/next loc)))))) ;; ### Removing todo lines if necessary (defn- remove-current? "Is the current loc a todo line and should it line be removed? (1) the todo line is followed by a pline which is solved or (2) the todo line is at the end of a subproof or proof or (3) the todo line is follwed by another todo line or (4) the todo line is followed by a subproof." [loc] (and (todoline? (zip/node loc)) (or (and (not (nil? (zip/right loc))) (not (nil? (:roth (zip/node (zip/right loc)))))) (= (zip/rightmost loc) loc) (and (not (nil? (zip/right loc))) (todoline? (zip/node (zip/right loc)))) (zip/branch? (zip/right loc))))) (defn remove-todo-lines "Returns proof where todo lines that are solved are removed." [proof] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (remove-current? loc) (recur (zip/next (zip/remove loc))) (recur (zip/next loc)))))) ;; ### Handling duplicate bodies in a proof (defn- find-duplicates "Finds duplicates bodies in the proof that can be deleted. Returns a map with the deletable plids as key and the replacement plids as value. Only plines without rule, in the same scope and the same subproof will be marked as deletable." ([proof] (find-duplicates proof proof)) ([proof sub] (let [dupl-scope (scope proof (last sub)) ;; duplicates = duplicate bodies in scope but not :todo duplicates (disj (set (map first (filter #(> (val %) 1) (frequencies (map :body (remove vector? dupl-scope)))))) :todo) ;; duplicate-plines = the pline with these duplicate bodies duplicate-plines (filter #(contains? duplicates (:body %)) dupl-scope) ;; duplicate-plines grouped into a vactor of vector of plines with equal body equals (vec (map val (group-by :body duplicate-plines))) ;; equals must have at least one :roth that's not nil equals' (filterv (fn [x] (not-every? nil? (map :roth x))) equals) fn-smap (fn [equals] (let [remain (map :plid (filter :roth equals)) delete (map :plid (filter (set sub) (remove :roth equals)))] ; just plines from the actual sub can be deleted (reduce #(assoc %1 %2 (last remain)) {} delete))) ;; map with pairs of plids where the first can be replace by the second plid-map (apply merge (map fn-smap equals'))] (reduce #(if (vector? %2) (merge %1 (find-duplicates proof %2)) %1) plid-map sub)))) (defn- adjust-refs "Upgrades the refs in the given proof according to the plid-map." [proof plid-map] (let [old-plines (filterv #(not-empty (set/intersection (set (keys plid-map)) (set (flatten (:refs %))))) (flatten proof)) upg-plines (mapv #(assoc % :roth (:roth %) :refs (clojure.walk/prewalk-replace plid-map (:refs %))) old-plines)] (vec (reduce #(replace-plid %1 (:plid %2) %2) proof upg-plines)))) (defn- check-refs "Checks the refs of a proof: The references must always refer to plines above!" [proof] (let [pm (plid-plno-map proof) fn (fn [pline] (let [curr-plno (get pm (:plid pline)) ; just consider the refs to other line numbers, not extra refs refs-plnos (mapv #(get pm %) (filter number? (flatten (:refs pline)))) max-ref-plno (if (empty? refs-plnos) 0 (apply max refs-plnos))] (< max-ref-plno curr-plno)))] (every? true? (map fn (flatten proof))))) (defn- remove-duplicates "Removes all duplicate bodies from proof and adjusts the changed ids of proof lines." [proof] (let [duplicates (find-duplicates proof) ;; if a body is the conclusion of a subproof but above already proved, ;; it's not deleted but marked with :repeat. fn-proved-results (fn [map [id1 id2]] (let [delete-pline (pline-at-plid proof id1) replace-pline (pline-at-plid proof id2) delete-scope (scope proof delete-pline)] (if (and (= delete-pline (last delete-scope)) (or (not= delete-scope (scope proof replace-pline)) (contains? #{:premise :assumption} (:roth replace-pline)))) (assoc map id1 id2) map))) proved-results (reduce fn-proved-results {} duplicates) fn-replace (fn [p [id1 id2]] (let [pline (pline-at-plid p id1)] (replace-plid p id1 {:plid id1 :body (:body pline) :roth :repeat :refs [id2]}))) new-proof1 (reduce fn-replace proof proved-results) deletions (reduce dissoc duplicates (map key proved-results)) delete-plids (keys deletions) new-proof2 (reduce remove-plid new-proof1 delete-plids) new-proof3 (adjust-refs new-proof2 deletions)] (if (check-refs new-proof3) new-proof3 proof))) ;; ### The interface for the user of this namespace: Normalizing a proof (defn normalize "Removes duplicate lines, adjust leftover plids and removes todo lines if possible" [proof] (-> proof add-todo-lines remove-duplicates remove-todo-lines)) ;; ## Preparing new proof lines after a deduction step ;; ### Helper functions (defn- replace-lvars "Replaces logical variables from core.logic like `_0` by generated variable names `?1`. This must be done with all the formulas generated by a run of core.logic simultaneously." [bodies] (let [lvars (set (filter #(.startsWith (str %) "_") (flatten bodies))) smap (reduce #(assoc %1 %2 (new-qmsymbol)) {} lvars)] (mapv #(if (symbol? %) (if (contains? lvars %) (get smap %) %) (clojure.walk/prewalk-replace smap %)) bodies))) (defn- eval-subs "Performs the substitution of `var` by `t` in `phi`." [[_ phi var t]] (substitution phi var t)) (declare new-subproof) (defn new-pline "Creates a new proof line or subproof from body and [optional] rule and refs." ([body] (new-pline body nil nil)) ([body roth refs] ; handle special case that body = (infer ...) or body = (substitution ...) (cond (and (seq? body) (= (first body) 'infer)) (new-subproof body) (and (seq? body) (= (first body) 'substitution)) {:plid (new-plid) :body (eval-subs body) :roth roth :refs refs} :else {:plid (new-plid) :body body :roth roth :refs refs}))) (defn- new-subproof "Creates a new subproof from infer clause." [[_ assumptions claim]] (let [a (if (vector? assumptions) assumptions [assumptions]) al (mapv #(new-pline % :assumption nil) a) t (new-pline :todo) cl (new-pline claim)] (conj al t cl))) ;; ### Interface for the user of proof: New plines as result of a deduction step (defn new-plines "Creates all the new plines that must be added to the proof" [bodies] (let [bodies' (replace-lvars bodies) ; a hack for handling lazy sequences!! non-lazy-bodies (clojure.walk/postwalk (fn [node] (if (instance? LazySeq node) (apply list node) node)) bodies')] (mapv new-pline non-lazy-bodies))) ;; ## Is the proof completed? (defn proved? "Checks if a proof is fully proved. Requires: the proof is normalized. Throws: Exception, if the proof is empty." [proof] (if (empty? proof) (throw (ex-error "The proof is empty"))) (let [plines (flatten proof)] (empty? (filter #(= :todo (:body %)) plines))))
true
; lwb Logic WorkBench -- Natural deduction ; Copyright (c) 2015 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.nd.proof (:require [clojure.set :as set] [clojure.zip :as zip] [lwb.nd.error :refer :all] [lwb.pred.substitution :refer [substitution]]) (:import (clojure.lang LazySeq))) ;; # Proof in natural deduction ;; Each proof line has a unique id `plid`. ; atom is visible for tests (def plid "Global counter for the ids of proof lines." (atom 0)) (defn new-plid "Generates new plid for proof lines. Uses global `plid`." [] (swap! plid inc)) (defn reset-plid "Resets global `plid`." [] (reset! plid 0)) ;; Some rules generate new logical variables, e.g. new atomic propositions ;; They get new names beginning with the letter `?` and follwed by a unique number. ;; Caveat: Don't use this naming convention for propositions in formulas. (def qmno "Global counter for the numbers of new question marks." (atom 0)) (defn new-qmsymbol "Generates a new name for a question mark. Uses global `qmno`." [] (symbol (str \? (swap! qmno inc)))) (defn reset-qmno "Resets global `qmno`." [] (reset! qmno 0)) (defn qmsymbol? "Is `s` a symbol of the form `?n`?" [s] (and (symbol? s) (re-matches #"\?\d+$" (name s)))) ;; ## Creating new proofs (declare normalize) (defn proof "Gives a new proof for the premises and the conclusion. Uses global atoms `plid` and `lvno`." [premises conclusion] (do (reset-plid) (reset-qmno) (let [premises-vec (if-not (vector? premises) [premises] premises) premises-lines (vec (map #(hash-map :plid (new-plid) :body % :roth :premise) premises-vec)) proof (conj premises-lines {:plid (new-plid) :body conclusion :roth nil})] (normalize proof)))) ;; ## Functions to access proof lines (defn plid->plno "Returns the line number `plno` of the proof line with the given `plid`." [proof plid] (let [flat-proof (flatten proof)] (first (keep-indexed #(when (= plid (:plid %2)) (inc %1)) flat-proof)))) (defn plno->plid "Returns the id `plid` of the proof line at line number `plno` in the `proof`." [proof pos] (let [pline (nth (flatten proof) (dec pos) nil)] (:plid pline))) (defn pline-at-plno "Proof line of the `proof` at line with number `plno`. requires: `plno` valid." [proof plno] (let [fp (flatten proof)] (nth fp (dec plno)))) (defn plbody-at-plno "Body of the proof line at `plno`. requires: `plno` valid." [proof plno] (:body (pline-at-plno proof plno))) (defn pline-at-plid "Proof line of the `proof` at line with id `plid`. requires: `plid` valid." [proof plid] (pline-at-plno proof (plid->plno proof plid))) (defn plid-plno-map "Mapping of ids of pline to line numbers." [proof] (let [fp (flatten proof)] (into {} (map-indexed #(vector (:plid %2) (inc %1)) fp)))) (defn scope "Returns the scope for an item inside a proof e.g. proof = `[1 2 [3 4] [5 6 7] 8]` & item = `5` => scope = `[1 2 [3 4] 5 6 7]`" [proof pline] (if (contains? (set proof) pline) proof (loop [p proof result []] (cond (empty? p) nil (vector? (first p)) (if-let [s (scope (first p) pline)] (vec (concat result s)) (recur (subvec p 1) (conj result (first p)))) :else (recur (subvec p 1) (conj result (first p))))))) ;; ## Functions for editing a proof (defn add-above-plid "Adds a proof line or a subproof above the item with the given `plid`. requires: the added plines have new plids!" [proof plid pline-or-subproof] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/insert-left loc pline-or-subproof))) (recur (zip/next loc)))))) (defn replace-plid "Replaces the proof line with the given `plid` with the new proof line. requires: there are no more references to the old proof line." [proof plid pline] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/replace loc pline))) (recur (zip/next loc)))))) (defn remove-plid "Removes the proof line with the given `plid`. requires: there are no more references to that proof line." [proof plid] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (= (:plid (zip/node loc)) plid) (recur (zip/next (zip/remove loc))) (recur (zip/next loc)))))) ;; ## Functions for the normalization of a proof ;; ### Adding todo lines if necessary (defn- new-todo-line "Generates a new todo line Uses global atom `plid`!" [] {:plid (new-plid), :body :todo, :roth nil}) (defn- unproved-line? "Checks whether a proof line has no roth." [pline] (and (not= :todo (:body pline)) (nil? (:roth pline)))) (defn todoline? "Checks whether a proof line is a todo line." [pline] (= :todo (:body pline))) (defn- insert-above? "Must a todo line be inserted above of this loc? (1) the current proof line is not a subproof and (2) the current proof line is not solved and (3) there is not already a todo line left of the current line." [loc] (let [prev-loc (zip/left loc) curr-line (zip/node loc) prev-line (when prev-loc (zip/node prev-loc))] (and (not (zip/branch? loc)) (unproved-line? curr-line) (not (todoline? prev-line))))) (defn add-todo-lines "Returns proof with todo lines added. Whenever there is a line in a proof without a rule, we have to insert a todo line above the proof line." [proof] (loop [loc (zip/next (zip/vector-zip proof))] (if (zip/end? loc) (zip/node loc) (if (insert-above? loc) (recur (zip/next (zip/insert-left loc (new-todo-line)))) (recur (zip/next loc)))))) ;; ### Removing todo lines if necessary (defn- remove-current? "Is the current loc a todo line and should it line be removed? (1) the todo line is followed by a pline which is solved or (2) the todo line is at the end of a subproof or proof or (3) the todo line is follwed by another todo line or (4) the todo line is followed by a subproof." [loc] (and (todoline? (zip/node loc)) (or (and (not (nil? (zip/right loc))) (not (nil? (:roth (zip/node (zip/right loc)))))) (= (zip/rightmost loc) loc) (and (not (nil? (zip/right loc))) (todoline? (zip/node (zip/right loc)))) (zip/branch? (zip/right loc))))) (defn remove-todo-lines "Returns proof where todo lines that are solved are removed." [proof] (loop [loc (zip/vector-zip proof)] (if (zip/end? loc) (zip/node loc) (if (remove-current? loc) (recur (zip/next (zip/remove loc))) (recur (zip/next loc)))))) ;; ### Handling duplicate bodies in a proof (defn- find-duplicates "Finds duplicates bodies in the proof that can be deleted. Returns a map with the deletable plids as key and the replacement plids as value. Only plines without rule, in the same scope and the same subproof will be marked as deletable." ([proof] (find-duplicates proof proof)) ([proof sub] (let [dupl-scope (scope proof (last sub)) ;; duplicates = duplicate bodies in scope but not :todo duplicates (disj (set (map first (filter #(> (val %) 1) (frequencies (map :body (remove vector? dupl-scope)))))) :todo) ;; duplicate-plines = the pline with these duplicate bodies duplicate-plines (filter #(contains? duplicates (:body %)) dupl-scope) ;; duplicate-plines grouped into a vactor of vector of plines with equal body equals (vec (map val (group-by :body duplicate-plines))) ;; equals must have at least one :roth that's not nil equals' (filterv (fn [x] (not-every? nil? (map :roth x))) equals) fn-smap (fn [equals] (let [remain (map :plid (filter :roth equals)) delete (map :plid (filter (set sub) (remove :roth equals)))] ; just plines from the actual sub can be deleted (reduce #(assoc %1 %2 (last remain)) {} delete))) ;; map with pairs of plids where the first can be replace by the second plid-map (apply merge (map fn-smap equals'))] (reduce #(if (vector? %2) (merge %1 (find-duplicates proof %2)) %1) plid-map sub)))) (defn- adjust-refs "Upgrades the refs in the given proof according to the plid-map." [proof plid-map] (let [old-plines (filterv #(not-empty (set/intersection (set (keys plid-map)) (set (flatten (:refs %))))) (flatten proof)) upg-plines (mapv #(assoc % :roth (:roth %) :refs (clojure.walk/prewalk-replace plid-map (:refs %))) old-plines)] (vec (reduce #(replace-plid %1 (:plid %2) %2) proof upg-plines)))) (defn- check-refs "Checks the refs of a proof: The references must always refer to plines above!" [proof] (let [pm (plid-plno-map proof) fn (fn [pline] (let [curr-plno (get pm (:plid pline)) ; just consider the refs to other line numbers, not extra refs refs-plnos (mapv #(get pm %) (filter number? (flatten (:refs pline)))) max-ref-plno (if (empty? refs-plnos) 0 (apply max refs-plnos))] (< max-ref-plno curr-plno)))] (every? true? (map fn (flatten proof))))) (defn- remove-duplicates "Removes all duplicate bodies from proof and adjusts the changed ids of proof lines." [proof] (let [duplicates (find-duplicates proof) ;; if a body is the conclusion of a subproof but above already proved, ;; it's not deleted but marked with :repeat. fn-proved-results (fn [map [id1 id2]] (let [delete-pline (pline-at-plid proof id1) replace-pline (pline-at-plid proof id2) delete-scope (scope proof delete-pline)] (if (and (= delete-pline (last delete-scope)) (or (not= delete-scope (scope proof replace-pline)) (contains? #{:premise :assumption} (:roth replace-pline)))) (assoc map id1 id2) map))) proved-results (reduce fn-proved-results {} duplicates) fn-replace (fn [p [id1 id2]] (let [pline (pline-at-plid p id1)] (replace-plid p id1 {:plid id1 :body (:body pline) :roth :repeat :refs [id2]}))) new-proof1 (reduce fn-replace proof proved-results) deletions (reduce dissoc duplicates (map key proved-results)) delete-plids (keys deletions) new-proof2 (reduce remove-plid new-proof1 delete-plids) new-proof3 (adjust-refs new-proof2 deletions)] (if (check-refs new-proof3) new-proof3 proof))) ;; ### The interface for the user of this namespace: Normalizing a proof (defn normalize "Removes duplicate lines, adjust leftover plids and removes todo lines if possible" [proof] (-> proof add-todo-lines remove-duplicates remove-todo-lines)) ;; ## Preparing new proof lines after a deduction step ;; ### Helper functions (defn- replace-lvars "Replaces logical variables from core.logic like `_0` by generated variable names `?1`. This must be done with all the formulas generated by a run of core.logic simultaneously." [bodies] (let [lvars (set (filter #(.startsWith (str %) "_") (flatten bodies))) smap (reduce #(assoc %1 %2 (new-qmsymbol)) {} lvars)] (mapv #(if (symbol? %) (if (contains? lvars %) (get smap %) %) (clojure.walk/prewalk-replace smap %)) bodies))) (defn- eval-subs "Performs the substitution of `var` by `t` in `phi`." [[_ phi var t]] (substitution phi var t)) (declare new-subproof) (defn new-pline "Creates a new proof line or subproof from body and [optional] rule and refs." ([body] (new-pline body nil nil)) ([body roth refs] ; handle special case that body = (infer ...) or body = (substitution ...) (cond (and (seq? body) (= (first body) 'infer)) (new-subproof body) (and (seq? body) (= (first body) 'substitution)) {:plid (new-plid) :body (eval-subs body) :roth roth :refs refs} :else {:plid (new-plid) :body body :roth roth :refs refs}))) (defn- new-subproof "Creates a new subproof from infer clause." [[_ assumptions claim]] (let [a (if (vector? assumptions) assumptions [assumptions]) al (mapv #(new-pline % :assumption nil) a) t (new-pline :todo) cl (new-pline claim)] (conj al t cl))) ;; ### Interface for the user of proof: New plines as result of a deduction step (defn new-plines "Creates all the new plines that must be added to the proof" [bodies] (let [bodies' (replace-lvars bodies) ; a hack for handling lazy sequences!! non-lazy-bodies (clojure.walk/postwalk (fn [node] (if (instance? LazySeq node) (apply list node) node)) bodies')] (mapv new-pline non-lazy-bodies))) ;; ## Is the proof completed? (defn proved? "Checks if a proof is fully proved. Requires: the proof is normalized. Throws: Exception, if the proof is empty." [proof] (if (empty? proof) (throw (ex-error "The proof is empty"))) (let [plines (flatten proof)] (empty? (filter #(= :todo (:body %)) plines))))
[ { "context": "c44950c0a6\" 0],\n :rx.jot/focus [\"fc12e0d887cd46a3b9b33bc44950c0a6\" 0]}}}]]]\n\n [sg/section opts", "end": 11323, "score": 0.5435968637466431, "start": 11313, "tag": "KEY", "value": "d887cd46a3" }, { "context": "0],\n :rx.jot/focus [\"fc12e0d887cd46a3b9b33bc44950c0a6\" 0]}}}]]]\n\n [sg/section opts\n ", "end": 11326, "score": 0.5074717402458191, "start": 11325, "tag": "KEY", "value": "b" }, { "context": " :rx.jot/focus [\"fc12e0d887cd46a3b9b33bc44950c0a6\" 0]}}}]]]\n\n [sg/section opts\n [sg", "end": 11334, "score": 0.5594243407249451, "start": 11330, "tag": "KEY", "value": "4495" }, { "context": " :rx.jot/focus [\"fc12e0d887cd46a3b9b33bc44950c0a6\" 0]}}}]]]\n\n [sg/section opts\n [sg/h", "end": 11336, "score": 0.5770850777626038, "start": 11335, "tag": "KEY", "value": "c" }, { "context": " :rx.jot/focus [\"fc12e0d887cd46a3b9b33bc44950c0a6\" 0]}}}]]]\n\n [sg/section opts\n [sg/hea", "end": 11338, "score": 0.5386002659797668, "start": 11337, "tag": "KEY", "value": "a" }, { "context": "\n\n\n(def last-question-text\n \"The Last Question by Isaac Asimov © 1956\n\nThe last question was asked for the first", "end": 30229, "score": 0.9998879432678223, "start": 30217, "tag": "NAME", "value": "Isaac Asimov" }, { "context": "lar bet over highballs, and it happened this way:\nAlexander Adell and Bertram Lupov were two of the faithful attend", "end": 30485, "score": 0.9998846054077148, "start": 30470, "tag": "NAME", "value": "Alexander Adell" }, { "context": "lls, and it happened this way:\nAlexander Adell and Bertram Lupov were two of the faithful attendants of Multivac. ", "end": 30503, "score": 0.9998906254768372, "start": 30490, "tag": "NAME", "value": "Bertram Lupov" }, { "context": "n days had not sufficed to dim the glory of it and Adell and Lupov finally managed to escape from the publ", "end": 32242, "score": 0.798119068145752, "start": 32237, "tag": "NAME", "value": "Adell" }, { "context": "ot sufficed to dim the glory of it and Adell and Lupov finally managed to escape from the public functio", "end": 32252, "score": 0.6521022915840149, "start": 32248, "tag": "NAME", "value": "upov" }, { "context": "ttle.\n\n\\\"It's amazing when you think of it,\\\" said Adell. His broad face had lines of weariness in it, and", "end": 32841, "score": 0.9136661887168884, "start": 32836, "tag": "NAME", "value": "Adell" }, { "context": "uld ever use, forever and forever and forever.\\\"\n\nLupov cocked his head sideways. He had a trick of doing", "end": 33253, "score": 0.9465146064758301, "start": 33248, "tag": "NAME", "value": "Lupov" }, { "context": " hell, just about forever. Till the sun runs down, Bert.\\\"\n\n\\\"That's not forever.\\\"\n\n\\\"All right, then. B", "end": 33519, "score": 0.9862145185470581, "start": 33515, "tag": "NAME", "value": "Bert" }, { "context": "ars. Twenty billion, maybe. Are you satisfied?\\\"\n\nLupov put his fingers through his thinning hair as thou", "end": 33650, "score": 0.7945477962493896, "start": 33645, "tag": "NAME", "value": "Lupov" }, { "context": "p running down what Multivac's done for us,\\\" said Adell, blazing up. \\\"It did all right.\\\"\n\n\\\"Who says it", "end": 34266, "score": 0.8029504418373108, "start": 34261, "tag": "NAME", "value": "Adell" }, { "context": "re safe for twenty billion years, but then what?\\\" Lupov pointed a slightly shaky finger at the other. \\\"A", "end": 34452, "score": 0.8479180335998535, "start": 34447, "tag": "NAME", "value": "Lupov" }, { "context": " to another sun.\\\"\n\nThere was silence for a while. Adell put his glass to his lips only occasionally, ", "end": 34579, "score": 0.6874893307685852, "start": 34578, "tag": "NAME", "value": "A" }, { "context": "TA FOR MEANINGFUL ANSWER.\n\n\\\"No bet,\\\" whispered Lupov. They left hurriedly.\n\nBy next morning, the two", "end": 37082, "score": 0.5226258635520935, "start": 37080, "tag": "NAME", "value": "up" }, { "context": "cottony mouth, had forgotten about the incident.\n\nJerrodd, Jerrodine, and Jerrodette I and II watched the s", "end": 37223, "score": 0.9987626075744629, "start": 37216, "tag": "NAME", "value": "Jerrodd" }, { "context": "mouth, had forgotten about the incident.\n\nJerrodd, Jerrodine, and Jerrodette I and II watched the starry pictu", "end": 37234, "score": 0.998630702495575, "start": 37225, "tag": "NAME", "value": "Jerrodine" }, { "context": "otten about the incident.\n\nJerrodd, Jerrodine, and Jerrodette I and II watched the starry picture in the visipl", "end": 37250, "score": 0.9983017444610596, "start": 37240, "tag": "NAME", "value": "Jerrodette" }, { "context": "right marble-disk, centered.\n\\\"That's X-23,\\\" said Jerrodd confidently. His thin hands clamped tightly behin", "end": 37519, "score": 0.9821991920471191, "start": 37512, "tag": "NAME", "value": "Jerrodd" }, { "context": "nd his back and the knuckles whitened.\n\nThe little Jerrodettes, both girls, had experienced the hyperspace pa", "end": 37627, "score": 0.8270339369773865, "start": 37619, "tag": "NAME", "value": "Jerrodet" }, { "context": "ed X-23 -- we've ----\\\"\n\n\\\"Quiet, children,\\\" said Jerrodine sharply. \\\"Are you sure, Jerrodd?\\\"\n\n\\\"What is th", "end": 37971, "score": 0.9360065460205078, "start": 37962, "tag": "NAME", "value": "Jerrodine" }, { "context": "hildren,\\\" said Jerrodine sharply. \\\"Are you sure, Jerrodd?\\\"\n\n\\\"What is there to be but sure?\\\" asked Jerro", "end": 38004, "score": 0.9980359077453613, "start": 37997, "tag": "NAME", "value": "Jerrodd" }, { "context": "errodd?\\\"\n\n\\\"What is there to be but sure?\\\" asked Jerrodd, glancing up at the bulge of featureless metal ju", "end": 38056, "score": 0.9926840662956238, "start": 38049, "tag": "NAME", "value": "Jerrodd" }, { "context": " wall at either end. It was as long as the ship.\n\nJerrodd scarcely knew a thing about the thick rod of meta", "end": 38240, "score": 0.9790801405906677, "start": 38233, "tag": "NAME", "value": "Jerrodd" }, { "context": "puting the equations for the hyperspacial jumps.\n\nJerrodd and his family had only to wait and live in the c", "end": 38596, "score": 0.9328107237815857, "start": 38589, "tag": "NAME", "value": "Jerrodd" }, { "context": "dence quarters of the ship.\n\nSomeone had once told Jerrodd that the \\\"ac\\\" at the end of \\\"Microvac\\\" stoo", "end": 38717, "score": 0.8880637884140015, "start": 38712, "tag": "NAME", "value": "Jerro" }, { "context": "eaving Earth.\\\"\n\n\\\"Why for Pete's sake?\\\" demanded Jerrodd. \\\"We had nothing there. We'll have everything ", "end": 39015, "score": 0.7607000470161438, "start": 39010, "tag": "NAME", "value": "Jerro" }, { "context": "y the race is growing.\\\"\n\n\\\"I know, I know,\\\" said Jerrodine miserably.\n\nJerrodette I said promptly, \\\"Our ", "end": 39449, "score": 0.6930957436561584, "start": 39443, "tag": "NAME", "value": "Jerrod" }, { "context": "\"\n\n\\\"I know, I know,\\\" said Jerrodine miserably.\n\nJerrodette I said promptly, \\\"Our Microvac is the best Micro", "end": 39475, "score": 0.7200487852096558, "start": 39465, "tag": "NAME", "value": "Jerrodette" }, { "context": "icrovac in the world.\\\"\n\n\\\"I think so, too,\\\" said Jerrodd, tousling her hair.\n\nIt was a nice feeling to hav", "end": 39579, "score": 0.8919358253479004, "start": 39572, "tag": "NAME", "value": "Jerrodd" }, { "context": " a nice feeling to have a Microvac of your own and Jerrodd was glad he was part of his generation and no oth", "end": 39665, "score": 0.7751238942146301, "start": 39658, "tag": "NAME", "value": "Jerrodd" }, { "context": "nto a space only half the volume of a spaceship.\n\nJerrodd felt uplifted, as he always did when he thought", "end": 40153, "score": 0.7556604146957397, "start": 40148, "tag": "NAME", "value": "Jerro" }, { "context": "sible.\n\n\\\"So many stars, so many planets,\\\" sighed Jerrodine, busy with her own thoughts. \\\"I suppose fa", "end": 40547, "score": 0.6833264231681824, "start": 40544, "tag": "NAME", "value": "Jer" }, { "context": "ever, the way we are now.\\\"\n\n\\\"Not forever,\\\" said Jerrodd, with a smile. \\\"It will all stop someday, but ", "end": 40696, "score": 0.720624566078186, "start": 40691, "tag": "NAME", "value": "Jerro" }, { "context": "down.\\\"\n\n\\\"Now look what you've done, \\\" whispered Jerrodine, exasperated.\n\n\\\"How was I to know it would", "end": 41374, "score": 0.8011037707328796, "start": 41371, "tag": "NAME", "value": "Jer" }, { "context": "ed.\n\n\\\"How was I to know it would frighten them?\\\" Jerrodd whispered back.\n\n\\\"Ask the Microvac,\\\" wailed J", "end": 41447, "score": 0.7441381216049194, "start": 41442, "tag": "NAME", "value": "Jerro" }, { "context": " to turn the stars on again.\\\"\n\n\\\"Go ahead,\\\" said Jerrodine. \\\"It will quiet them down.\\\" (Jerrodette II w", "end": 41580, "score": 0.7652645111083984, "start": 41574, "tag": "NAME", "value": "Jerrod" }, { "context": "n.\\\" (Jerrodette II was beginning to cry, also.)\n\nJarrodd shrugged. \\\"Now, now, honeys. I'll ask Microvac. ", "end": 41666, "score": 0.8611063957214355, "start": 41659, "tag": "NAME", "value": "Jarrodd" }, { "context": "s time for bed. We'll be in our new home soon.\\\"\n\nJerrodd read the words on the cellufilm again befor", "end": 42063, "score": 0.6348259449005127, "start": 42062, "tag": "NAME", "value": "J" }, { "context": "n being so concerned about the matter?\\\"\nMQ-17J of Nicron shook his head. \\\"I think not. You know the Galax", "end": 42438, "score": 0.9401045441627502, "start": 42432, "tag": "NAME", "value": "Nicron" }, { "context": " Zee Prime,\\\" said Zee Prime. \\\"And you?\\\"\n\n\\\"I am Dee Sub Wun. Your Galaxy?\\\"\n\n\\\"We call it only the Galaxy. An", "end": 47503, "score": 0.9921084046363831, "start": 47492, "tag": "NAME", "value": "Dee Sub Wun" }, { "context": "other, and Zee Prime stifled his disappointment.\n\nDee Sub Wun, whose mind had accompanied the other, said sudde", "end": 49910, "score": 0.9229915142059326, "start": 49899, "tag": "NAME", "value": "Dee Sub Wun" }, { "context": "k to his own Galaxy. He gave no further thought to Dee Sub Wun, whose body might be waiting on a galaxy ", "end": 51167, "score": 0.5066202878952026, "start": 51164, "tag": "NAME", "value": "Dee" } ]
src/cljs-browser/rx/browser/jot_styleguide.cljs
zk/rx-lib
0
(ns rx.browser.jot-styleguide (:require [rx.kitchen-sink :as ks] [rx.browser.styleguide :as sg] [rx.browser.jot :as bjot] [rx.browser :as browser] [rx.browser.util :as bu] [rx.browser.youtube :as yt] [rx.browser.components :as cmp] [rx.browser.test-ui :as test-ui] [rx.theme :as th] [rx.view :as view] [rx.jot :as jot] [rx.browser.youtube :as yt] [dommy.core :as dommy] [reagent.core :as r] [rx.jot-test] [clojure.string :as str] [cljs.core.async :as async :refer [<! put! chan sliding-buffer timeout] :refer-macros [go go-loop]])) (defn tap-to-interact [_ _] (let [!interacting? (r/atom false) !plate-mounted? (r/atom true) interacting-ch (chan (sliding-buffer 1))] (go-loop [] (let [interacting? (<! interacting-ch)] (when (not= interacting? @!interacting?) (if interacting? (do (reset! !interacting? true) (<! (timeout 150)) (reset! !plate-mounted? false)) (do (reset! !plate-mounted? true) (<! (timeout 17)) (reset! !interacting? false)))) (recur))) (fn [{:keys [style] :as opts} child] (let [[comp child-opts & rest] child child-opts (merge child-opts {:interacting? @!interacting?})] [:div {:class (bu/kw->class ::scroll-preventer-wrapper) :style (merge {:position 'relative} style)} [:div {:on-key-down (fn [e] (when (= "Escape" (.-key e)) (put! interacting-ch false))) :on-blur (fn [e] (put! interacting-ch false)) :style {:width "100%" :height "100%" :overflow-y 'scroll}} (into [comp child-opts] rest)] (when @!plate-mounted? [cmp/hover {:on-mouse-down (fn [] (put! interacting-ch true)) :style {:position 'absolute :top 0 :left 0 :right 0 :bottom 0 :display 'flex :justify-content 'center :align-items 'center :transition "opacity 150ms ease" :opacity (if @!interacting? 0 1) :background-color "rgba(255,255,255,0.95)" :cursor 'pointer}} "Tap To Focus"])])))) (declare last-question-text) (def headings [{:key ::jot :level 0 :title "Jot"} {:key ::inline-styling :level 1 :title "Inline Styling"} {:key ::inline-custom-embeds :level 1 :title "Inline Custom Embeds"} {:key ::text-expansion :level 1 :title "Text Expansion"} {:key ::toolbar :level 1 :title "Toolbar"} {:key ::block-transforms :level 1 :title "Block Transforms"} {:key ::custom-block-embeds :level 1 :title "Custom Block Embeds"} {:key ::defining-custom-embeds :level 2 :title "Defining Custom Embeds"} {:key ::render-lifecycle :level 2 :title "Render Lifecycle"} {:key ::placeholder-component :level 1 :title "Placeholder Component"} {:key ::text-input :level 1 :title "Text Input"} {:key ::usage :level 1 :title "Usage"} {:key ::component-opts :level 2 :title "Component Options"} {:key ::document-api :level 2 :title "Document API"} {:key ::theming :level 1 :title "Theming"} {:key ::theme-rules :level 2 :title "Theme Rules"} {:key ::included-custom-block-types :level 1 :title "Included Custom Block Types"} {:key ::testing :level 1 :title "Testing"} {:key ::editor-stress-test :level 1 :title "Editor Stress Test"}]) (defn sections [opts] (let [{:keys [::bg-color ::fg-color ::border-color ::embed-bg-color]} (th/des opts [[::bg-color :color/bg-0] [::border-color :color/bg-2] [::embed-bg-color :color/bg-2]])] [:div {:class [(bu/kw->class ::sections) (bu/kw->class :rx.browser.jot-styleguide)]} [sg/section-container [sg/section-intro {:image {:url "https://www.oldbookillustrations.com/wp-content/high-res/1867/grandville-magpie-writer-768.jpg" :height 300}} [sg/heading headings ::jot] [:p "Rich text editing for the browser and React Native. Many ideas taken from " [:a {:href "https://draftjs.org/" :target "_blank"} "draftjs"] "."] [:p "Jot documents can contain both block level elements, like paragraphs, lists, and headers, inline styling like italics, and inline elements like links. Theming."] [:p "Jot is built to be extensible, with support for user-defined block and inline elements."] [:p "An example:"] [sg/checkerboard [bjot/editor {:style {:border-radius 3 :padding (th/pad opts 4)} :initial-doc {:rx.jot/block-id->block {"5f52cb9b3cbb48d3ab44a2517185565f" {:rx.jot/block-id "5f52cb9b3cbb48d3ab44a2517185565f", :rx.jot/type :rx.jot/heading-one, :rx.jot/content-text "Hello World Heading", :rx.jot/index 1000000, :rx.jot/reverse-expansion-text "# ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}, "1cef3aa851544482b8e29cf20a4ed74d" {:rx.jot/block-id "1cef3aa851544482b8e29cf20a4ed74d", :rx.jot/content-text "ul 2", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/indent-level 1 :rx.jot/index 3500000}, "8092623307ed4d8ab037a1cc4d4f1416" {:rx.jot/block-id "8092623307ed4d8ab037a1cc4d4f1416", :rx.jot/content-text "ol 2", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/indent-level 1 :rx.jot/index 5500000}, "52c170b5e99942d4884823ab5234acf7" {:rx.jot/block-id "52c170b5e99942d4884823ab5234acf7", :rx.jot/content-text "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", :rx.jot/type :rx.jot/paragraph, :rx.jot/index 2500000, :rx.jot/offset->deco {28 {:rx.jot/styles #{:rx.jot/bold}}, 29 {:rx.jot/styles #{:rx.jot/bold}}, 30 {:rx.jot/styles #{:rx.jot/bold}}, 31 {:rx.jot/styles #{:rx.jot/bold}}, 32 {:rx.jot/styles #{:rx.jot/bold}}, 33 {:rx.jot/styles #{:rx.jot/bold}}, 34 {:rx.jot/styles #{:rx.jot/bold}}, 35 {:rx.jot/styles #{:rx.jot/bold}}, 36 {:rx.jot/styles #{:rx.jot/bold}}, 37 {:rx.jot/styles #{:rx.jot/bold}}, 38 {:rx.jot/styles #{:rx.jot/bold}}, 39 {:rx.jot/styles #{:rx.jot/bold}}, 40 {:rx.jot/styles #{:rx.jot/bold}}, 41 {:rx.jot/styles #{:rx.jot/bold}}, 42 {:rx.jot/styles #{:rx.jot/bold}}, 43 {:rx.jot/styles #{:rx.jot/bold}}, 44 {:rx.jot/styles #{:rx.jot/bold}}, 45 {:rx.jot/styles #{:rx.jot/bold}}, 46 {:rx.jot/styles #{:rx.jot/bold}}, 47 {:rx.jot/styles #{:rx.jot/bold}}, 48 {:rx.jot/styles #{:rx.jot/bold}}, 49 {:rx.jot/styles #{:rx.jot/bold}}, 50 {:rx.jot/styles #{:rx.jot/bold}}, 51 {:rx.jot/styles #{:rx.jot/bold}}, 52 {:rx.jot/styles #{:rx.jot/bold}}, 53 {:rx.jot/styles #{:rx.jot/bold}}, 54 {:rx.jot/styles #{:rx.jot/bold}}, 61 {:rx.jot/styles #{:rx.jot/italic}}, 62 {:rx.jot/styles #{:rx.jot/italic}}, 63 {:rx.jot/styles #{:rx.jot/italic}}, 64 {:rx.jot/styles #{:rx.jot/italic}}, 65 {:rx.jot/styles #{:rx.jot/italic}}, 66 {:rx.jot/styles #{:rx.jot/italic}}, 67 {:rx.jot/styles #{:rx.jot/italic}}, 68 {:rx.jot/styles #{:rx.jot/italic}}, 69 {:rx.jot/styles #{:rx.jot/italic}}, 70 {:rx.jot/styles #{:rx.jot/italic}}, 71 {:rx.jot/styles #{:rx.jot/italic}}, 72 {:rx.jot/styles #{:rx.jot/italic}}, 73 {:rx.jot/styles #{:rx.jot/italic}}, 74 {:rx.jot/styles #{:rx.jot/italic}}, 75 {:rx.jot/styles #{:rx.jot/italic}}, 76 {:rx.jot/styles #{:rx.jot/italic}}, 77 {:rx.jot/styles #{:rx.jot/italic}}}}, "53efe8fdad6145628816847707cbbabf" {:rx.jot/block-id "53efe8fdad6145628816847707cbbabf", :rx.jot/content-text "The quick brown fox jumps over the lazy dog...", :rx.jot/type :rx.jot/paragraph, :rx.jot/index 1500000}, "e020c38167c74f9a83729eafed4f6516" {:rx.jot/block-id "e020c38167c74f9a83729eafed4f6516", :rx.jot/content-text "ul 3", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/index 4000000}, "2f49766c78a14ad7a75085fdebbbd997" {:rx.jot/block-id "2f49766c78a14ad7a75085fdebbbd997", :rx.jot/content-text "ol 1", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/index 5000000, :rx.jot/reverse-expansion-text "1. ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}, "2b8a3e5b2853464e8d2408d5a5bdbbf0" {:rx.jot/block-id "2b8a3e5b2853464e8d2408d5a5bdbbf0", :rx.jot/content-text "ol 3", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/index 6000000}, "fc12e0d887cd46a3b9b33bc44950c0a6" {:rx.jot/block-id "fc12e0d887cd46a3b9b33bc44950c0a6", :rx.jot/content-text "ul 1", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/index 3000000, :rx.jot/reverse-expansion-text "* ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}}, :rx.jot/block-order (sorted-map 1000000 "5f52cb9b3cbb48d3ab44a2517185565f", 1500000 "53efe8fdad6145628816847707cbbabf", 2500000 "52c170b5e99942d4884823ab5234acf7", 3000000 "fc12e0d887cd46a3b9b33bc44950c0a6", 3500000 "1cef3aa851544482b8e29cf20a4ed74d", 4000000 "e020c38167c74f9a83729eafed4f6516", 5000000 "2f49766c78a14ad7a75085fdebbbd997", 5500000 "8092623307ed4d8ab037a1cc4d4f1416", 6000000 "2b8a3e5b2853464e8d2408d5a5bdbbf0"), :rx.jot/selection {:rx.jot/start ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/end ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/anchor ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/focus ["fc12e0d887cd46a3b9b33bc44950c0a6" 0]}}}]]] [sg/section opts [sg/heading headings ::inline-styling] [:p "Jot supports typical inline styles like bold / italic / underline. User-provided inline components are supported via a decoration system that supports uses cases like links and mentions."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "Inline text styling"}) (jot/set-decos 0 (->> (range 6) (map (fn [i] {::jot/styles #{::jot/bold}})))) (jot/set-decos 7 (->> (range 4) (map (fn [i] {::jot/styles #{::jot/italic}})))) (jot/set-decos 12 (->> (range 7) (map (fn [i] {::jot/styles #{::jot/underline}})))))) )}]]] [sg/section opts [sg/heading headings ::inline-custom-embeds] [:p "Links, tweets, etc."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (let [embed-id (ks/uuid)] (-> (jot/base-doc) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "Here's a link embed (meta-click to open)."}) (jot/set-decos 9 (->> (range 4) (map (fn [i] {::jot/embed-id embed-id})))))) (jot/set-embed-data {::jot/embed-id embed-id ::jot/embed-type ::jot/link :url "https://google.com"})))}]]] [sg/section opts [sg/heading headings ::text-expansion] [:p "Some block types and inline styles can be applied using text expansion. Most markdown elements and styles are supproted."] [:p "For example, prefixing a line in a paragraph block with `# ` or `* ` will change the current block to a heading or list respectively. **Earmuffs** for bold / italic. Backspace to reverse the expansion for block elements."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-three ::jot/content-text "heading" ::jot/reverse-expansion-text "### " ::jot/reverse-expansion-type ::jot/paragraph})) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "bold"}) (jot/set-decos 0 (->> (range 4) (map (fn [] {::jot/styles #{::jot/bold}})))))) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "italic"}) (jot/set-decos 0 (->> (range 6) (map (fn [] {::jot/styles #{::jot/italic}})))))))}]]] [sg/section opts [sg/heading headings ::toolbar] [:p "Jot ships with a toolbar that you can choose to use to affect inline styles and embeds."]] [sg/section opts [sg/heading headings ::block-transforms] [:p "Block transforms provide a way for you to participate in changes to blocks, like when the user types a character, to change the content of that block based on behvaior you provide. For example, you could use a content transform to automatically turn an entered url into a link via a regex match."] [:p "Block transforms are run after the default editor behavior has been applied, in the order that the transforms are provided."] [:p "See the " [:code ":block-transforms"] " config option for more info."]] [sg/section opts [sg/heading headings ::custom-block-embeds] [:p "Embeds are a way for you to render custom UI components in your documents, in and around built-in blocks like headings and paragraphs. Embeds can be anything that's able to be rendered in a browser -- images, videos, charts, tweets, anything."] [:p "Embed participation in the editing lifecycle is up to you to implement, most editing commands like movement, insertion, and deletion are noops when focus is on a block embed, and it's up to you to provide controls within the embed to acomplish these types of actions."] [:p "Example:"] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text "Custom Block Embed"})) (jot/append-block (jot/create-block {::jot/embed? true ::jot/type :test-embed})) (jot/append-block (jot/para))) :embeds [{::jot/type :test-embed ::jot/render (fn [] (r/create-class {:reagent-render (fn [] [:div {:style {:padding 30 :text-align 'center :background-color embed-bg-color}} [:div "Custom rendered div, see editor option " [:strong [:code ":embeds"]] "."] (ks/uuid)])}))}]}]] [sg/heading headings ::defining-custom-embeds] [:p "Custom embeds are identified via a custom block type chosen by you, found in the doc's block map at key " [:code ":rx.jot/type"] ". The block will also have " [:code ":rx.jot/embed?"] " set to " [:code "true"] ". For example:"] [sg/code-block (ks/pp-str {::jot/block-id (ks/uuid) ::jot/type :my/custom-embed ::jot/embed? true})] [:p "Embed-specific data can also be attached to this map and will be passed to the render method you provide via the " [:code ":embeds"] " option."] [sg/heading headings ::render-lifecycle] [:p "Jot does its best to not unecessarily re-render your custom blocks, but there are a few cases where this is unavoidable. Re-rendering will trigger when the block map representing the embed changes."]] [sg/section [sg/heading headings ::placeholder-component] [:p "Jot give you the option to render a custom component when the user's cursor is on an empty paragraph. You can use this to give the user a way to insert custom blocks."] [:p "The placeholder will disappear as soon as you enter text into the paragraph."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (jot/empty-doc) :render-placeholder (fn [] [:div {:style {:padding-left 5}} [:a {:href "#" :style {:color "#888"} :on-click (fn [e] (.preventDefault e) (js/alert "Hello World!") nil)} "Insert Custom Block"]])}]] [sg/code-block (ks/pp-str '[bjot/editor {:initial-doc (jot/empty-doc) :render-placeholder (fn [] [:div {:style {:padding-left 5}} [:a {:href "#" :style {:color "#888"} :on-click (fn [e] (.preventDefault e) (js/alert "Hello World!") nil)} "Insert Custom Block"]])}])]] [sg/section [sg/heading headings ::text-input] [:p "Jot can be used as a replacement for the native text input in cases where you'd like to support inline styling or embeds."] [sg/checkerboard [bjot/editor {:initial-doc (-> (jot/base-doc) (jot/append-block (jot/para {:text "hello world"})))}]]] [sg/section [:div {:style {:float 'right}} [sg/section-callout [yt/video {:video-id "BMegu18G19Q" :style {:height 400 :width 220}}]]] [:h2 {:id "mobile-embedding"} "Mobile Embedding"] [:p "Jot can be used to support rich text editing in react native apps. See namespace " [:code "vee.jot"] ". All jot features are supported including custom block and inline embeds."] [:p "This is accomplished by bundling the jot web assets (html, css, js) with the mobile app and loading them into a web view. However this all happens under the hood. The API used create and interact with the component feels the same as any other React Native component."] [:h3 {:id "jot-creating-an-embedded-distro"} "Creating an Embedded Distro"] [:p "Instead of providing a single embedded distribution, rx makes it easy to configure and create your own. This is necessary to support your custom block and inline embed functionality."] [:p "Code that provides custom embed UI has to live and run in the browser."] [:p "Creating a embedded distro takes three steps:"] [:ol [:li "Create the custom embed initialization namespace."] [:li "Compile and write the web assets to the filesystem"] [:li "Pass custom embed info to RN component"]] [:p "Here's an example custom embed entry point:"] [sg/code-block (ks/pp-str '(rne/init-embedded-editor {:embeds [{::jot/type :test-embed ::view/route [(fn [] {:render (fn [] [:div {:style {:padding 30 :font-size 12 :text-align 'center :background-color "#eee"}} [:div "Custom Block"] (ks/uuid)])})]}]}))] [:div {:style {:clear 'both}}]] [sg/section opts [sg/heading headings ::usage] [:p [:code "[rx.browser.jot/editor {opts}]"]] [sg/heading headings ::component-opts] [sg/options-list {:options [[:initial-doc "The initial doc state used to initalize the jot editor. State will be maintained internally, and participation in updates can be achived via " [:code ":on-change."]] [:state [:span "Editor state that is used in many api calls to imperitivelyaffect changes to the editor. Can be created outside of the editor via " [:code "(rx.browser.jot/editor-state)"] " or received via option " [:code ":with-state"] "."]] [:with-state "State map will be passed as the only argument to this function."] [:on-change-doc "Called with edn doc state when doc state changes"] [:on-change-content "Called with edn doc state when doc content changes. Ignores things like selection changes."] [:render-placeholder "Component shown when the cursor is on an empty paragraph. Can be used for UI around changing block type and inserting custom blocks."] [:embeds [:span "Seq of maps, where each map represents a custom embed. Each map must provide " [:code ":type"] " and " [:code ":render"] "."]]]}] [sg/heading headings ::document-api] [:p "You may want to modify the document programmatically."] [sg/options-list {:options [['(rx.jot/empty-doc) "Creates an jot document with a single empty paragraph."] ['(rx.jot/append-block doc block) "Appends a block to the end of the document"]]}]] (let [theme {:bg-color "black" :fg-color "white" :header-fg-color "#aaa" :font-family "monospace" :font-size 20}] [sg/section opts [sg/heading headings ::theming] [:p "Look and feel of the editor can be customized via " [:code "rx.theme"] "."] [sg/code-block (str ":theme\n" (ks/pp-str theme))] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :theme theme :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-three ::jot/content-text "Custom Themed Document" ::jot/reverse-expansion-text "## " ::jot/reverse-expansion-type ::jot/paragraph})) (jot/append-block (jot/para {:text "Black background, white text, grey headers, monospaced font."})))}]] [sg/heading headings ::theme-rules] [sg/theme-rules-list {:theme-rules bjot/theme-info}]]) [sg/section [sg/heading headings ::included-custom-block-types] [:p "Jot provides several custom block types, like media embedding."] [sg/checkerboard [bjot/editor {:style {:padding 20} :rx.browser.jot.gallery/on-choose-media (fn [medias i] (js/alert (str "Chose " (inc i) " of " (count medias)))) :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-one ::jot/content-text "Built-In Custom Block Types"})) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text "Gallery of #fashion on Unsplash"})) (jot/append-block (jot/create-block {::jot/type ::jot/gallery ::jot/embed? true :rx.media/medias [{:rx.media/uri "https://images.unsplash.com/photo-1496747611176-843222e1e57c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1503342217505-b0a15ec3261c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1485968579580-b6d095142e6e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60"} {:rx.media/uri "https://images.unsplash.com/photo-1485230895905-ec40ba36b9bc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1475180098004-ca77a66827be?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=933&q=80"}]})))}]]] [sg/section opts [sg/heading headings ::testing] [test-ui/run-and-report-detail {:test-context {:namespaces [:rx.jot-test]}}]] [sg/section opts [sg/heading headings ::editor-stress-test] [:p "It's important that the editor remain as performant as possible, even in the face of large documents. Much of this comes down to the rendering code found in " [:code "rx.browser.jot"] "."] [sg/checkerboard [:div {:style {:height 300 :overflow-y 'scroll}} [sg/async-mount (fn [] (go (<! (timeout 500)) [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (let [paras (->> (str/split last-question-text #"\n") (remove empty?) (mapv (fn [s] (jot/para {:text s}))) (take 200)) doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text (str "The Last Question" " (" (count paras) " Paragraphs)") #_"WUTHERING HEIGHTS"})))] (->> paras (reduce (fn [doc block] (jot/append-block doc block)) doc)))}]))]]]]]])) (defn init [] (browser/<set-root! [sg/standalone {:component sections :headings headings}])) (def last-question-text "The Last Question by Isaac Asimov © 1956 The last question was asked for the first time, half in jest, on May 21, 2061, at a time when humanity first stepped into the light. The question came about as a result of a five dollar bet over highballs, and it happened this way: Alexander Adell and Bertram Lupov were two of the faithful attendants of Multivac. As well as any human beings could, they knew what lay behind the cold, clicking, flashing face -- miles and miles of face -- of that giant computer. They had at least a vague notion of the general plan of relays and circuits that had long since grown past the point where any single human could possibly have a firm grasp of the whole. Multivac was self-adjusting and self-correcting. It had to be, for nothing human could adjust and correct it quickly enough or even adequately enough -- so Adell and Lupov attended the monstrous giant only lightly and superficially, yet as well as any men could. They fed it data, adjusted questions to its needs and translated the answers that were issued. Certainly they, and all others like them, were fully entitled to share In the glory that was Multivac's. For decades, Multivac had helped design the ships and plot the trajectories that enabled man to reach the Moon, Mars, and Venus, but past that, Earth's poor resources could not support the ships. Too much energy was needed for the long trips. Earth exploited its coal and uranium with increasing efficiency, but there was only so much of both. But slowly Multivac learned enough to answer deeper questions more fundamentally, and on May 14, 2061, what had been theory, became fact. The energy of the sun was stored, converted, and utilized directly on a planet-wide scale. All Earth turned off its burning coal, its fissioning uranium, and flipped the switch that connected all of it to a small station, one mile in diameter, circling the Earth at half the distance of the Moon. All Earth ran by invisible beams of sunpower. Seven days had not sufficed to dim the glory of it and Adell and Lupov finally managed to escape from the public function, and to meet in quiet where no one would think of looking for them, in the deserted underground chambers, where portions of the mighty buried body of Multivac showed. Unattended, idling, sorting data with contented lazy clickings, Multivac, too, had earned its vacation and the boys appreciated that. They had no intention, originally, of disturbing it. They had brought a bottle with them, and their only concern at the moment was to relax in the company of each other and the bottle. \"It's amazing when you think of it,\" said Adell. His broad face had lines of weariness in it, and he stirred his drink slowly with a glass rod, watching the cubes of ice slur clumsily about. \"All the energy we can possibly ever use for free. Enough energy, if we wanted to draw on it, to melt all Earth into a big drop of impure liquid iron, and still never miss the energy so used. All the energy we could ever use, forever and forever and forever.\" Lupov cocked his head sideways. He had a trick of doing that when he wanted to be contrary, and he wanted to be contrary now, partly because he had had to carry the ice and glassware. \"Not forever,\" he said. \"Oh, hell, just about forever. Till the sun runs down, Bert.\" \"That's not forever.\" \"All right, then. Billions and billions of years. Twenty billion, maybe. Are you satisfied?\" Lupov put his fingers through his thinning hair as though to reassure himself that some was still left and sipped gently at his own drink. \"Twenty billion years isn't forever.\" \"Will, it will last our time, won't it?\" \"So would the coal and uranium.\" \"All right, but now we can hook up each individual spaceship to the Solar Station, and it can go to Pluto and back a million times without ever worrying about fuel. You can't do THAT on coal and uranium. Ask Multivac, if you don't believe me.\" \"I don't have to ask Multivac. I know that.\" \"Then stop running down what Multivac's done for us,\" said Adell, blazing up. \"It did all right.\" \"Who says it didn't? What I say is that a sun won't last forever. That's all I'm saying. We're safe for twenty billion years, but then what?\" Lupov pointed a slightly shaky finger at the other. \"And don't say we'll switch to another sun.\" There was silence for a while. Adell put his glass to his lips only occasionally, and Lupov's eyes slowly closed. They rested. Then Lupov's eyes snapped open. \"You're thinking we'll switch to another sun when ours is done, aren't you?\" \"I'm not thinking.\" \"Sure you are. You're weak on logic, that's the trouble with you. You're like the guy in the story who was caught in a sudden shower and Who ran to a grove of trees and got under one. He wasn't worried, you see, because he figured when one tree got wet through, he would just get under another one.\" \"I get it,\" said Adell. \"Don't shout. When the sun is done, the other stars will be gone, too.\" \"Darn right they will,\" muttered Lupov. \"It all had a beginning in the original cosmic explosion, whatever that was, and it'll all have an end when all the stars run down. Some run down faster than others. Hell, the giants won't last a hundred million years. The sun will last twenty billion years and maybe the dwarfs will last a hundred billion for all the good they are. But just give us a trillion years and everything will be dark. Entropy has to increase to maximum, that's all.\" \"I know all about entropy,\" said Adell, standing on his dignity. \"The hell you do.\" \"I know as much as you do.\" \"Then you know everything's got to run down someday.\" \"All right. Who says they won't?\" \"You did, you poor sap. You said we had all the energy we needed, forever. You said 'forever.'\" \"It was Adell's turn to be contrary. \"Maybe we can build things up again someday,\" he said. \"Never.\" \"Why not? Someday.\" \"Never.\" \"Ask Multivac.\" \"You ask Multivac. I dare you. Five dollars says it can't be done.\" Adell was just drunk enough to try, just sober enough to be able to phrase the necessary symbols and operations into a question which, in words, might have corresponded to this: Will mankind one day without the net expenditure of energy be able to restore the sun to its full youthfulness even after it had died of old age? Or maybe it could be put more simply like this: How can the net amount of entropy of the universe be massively decreased? Multivac fell dead and silent. The slow flashing of lights ceased, the distant sounds of clicking relays ended. Then, just as the frightened technicians felt they could hold their breath no longer, there was a sudden springing to life of the teletype attached to that portion of Multivac. Five words were printed: INSUFFICIENT DATA FOR MEANINGFUL ANSWER. \"No bet,\" whispered Lupov. They left hurriedly. By next morning, the two, plagued with throbbing head and cottony mouth, had forgotten about the incident. Jerrodd, Jerrodine, and Jerrodette I and II watched the starry picture in the visiplate change as the passage through hyperspace was completed in its non-time lapse. At once, the even powdering of stars gave way to the predominance of a single bright marble-disk, centered. \"That's X-23,\" said Jerrodd confidently. His thin hands clamped tightly behind his back and the knuckles whitened. The little Jerrodettes, both girls, had experienced the hyperspace passage for the first time in their lives and were self-conscious over the momentary sensation of inside-outness. They buried their giggles and chased one another wildly about their mother, screaming, \"We've reached X-23 -- we've reached X-23 -- we've ----\" \"Quiet, children,\" said Jerrodine sharply. \"Are you sure, Jerrodd?\" \"What is there to be but sure?\" asked Jerrodd, glancing up at the bulge of featureless metal just under the ceiling. It ran the length of the room, disappearing through the wall at either end. It was as long as the ship. Jerrodd scarcely knew a thing about the thick rod of metal except that it was called a Microvac, that one asked it questions if one wished; that if one did not it still had its task of guiding the ship to a preordered destination; of feeding on energies from the various Sub-galactic Power Stations; of computing the equations for the hyperspacial jumps. Jerrodd and his family had only to wait and live in the comfortable residence quarters of the ship. Someone had once told Jerrodd that the \"ac\" at the end of \"Microvac\" stood for \"analog computer\" in ancient English, but he was on the edge of forgetting even that. Jerrodine's eyes were moist as she watched the visiplate. \"I can't help it. I feel funny about leaving Earth.\" \"Why for Pete's sake?\" demanded Jerrodd. \"We had nothing there. We'll have everything on X-23. You won't be alone. You won't be a pioneer. There are over a million people on the planet already. Good Lord, our great grandchildren will be looking for new worlds because X-23 will be overcrowded.\" Then, after a reflective pause, \"I tell you, it's a lucky thing the computers worked out interstellar travel the way the race is growing.\" \"I know, I know,\" said Jerrodine miserably. Jerrodette I said promptly, \"Our Microvac is the best Microvac in the world.\" \"I think so, too,\" said Jerrodd, tousling her hair. It was a nice feeling to have a Microvac of your own and Jerrodd was glad he was part of his generation and no other. In his father's youth, the only computers had been tremendous machines taking up a hundred square miles of land. There was only one to a planet. Planetary ACs they were called. They had been growing in size steadily for a thousand years and then, all at once, came refinement. In place of transistors had come molecular valves so that even the largest Planetary AC could be put into a space only half the volume of a spaceship. Jerrodd felt uplifted, as he always did when he thought that his own personal Microvac was many times more complicated than the ancient and primitive Multivac that had first tamed the Sun, and almost as complicated as Earth's Planetary AC (the largest) that had first solved the problem of hyperspatial travel and had made trips to the stars possible. \"So many stars, so many planets,\" sighed Jerrodine, busy with her own thoughts. \"I suppose families will be going out to new planets forever, the way we are now.\" \"Not forever,\" said Jerrodd, with a smile. \"It will all stop someday, but not for billions of years. Many billions. Even the stars run down, you know. Entropy must increase.\" \"What's entropy, daddy?\" shrilled Jerrodette II. \"Entropy, little sweet, is just a word which means the amount of running-down of the universe. Everything runs down, you know, like your little walkie-talkie robot, remember?\" \"Can't you just put in a new power-unit, like with my robot?\" The stars are the power-units, dear. Once they're gone, there are no more power-units.\" Jerrodette I at once set up a howl. \"Don't let them, daddy. Don't let the stars run down.\" \"Now look what you've done, \" whispered Jerrodine, exasperated. \"How was I to know it would frighten them?\" Jerrodd whispered back. \"Ask the Microvac,\" wailed Jerrodette I. \"Ask him how to turn the stars on again.\" \"Go ahead,\" said Jerrodine. \"It will quiet them down.\" (Jerrodette II was beginning to cry, also.) Jarrodd shrugged. \"Now, now, honeys. I'll ask Microvac. Don't worry, he'll tell us.\" He asked the Microvac, adding quickly, \"Print the answer.\" Jerrodd cupped the strip of thin cellufilm and said cheerfully, \"See now, the Microvac says it will take care of everything when the time comes so don't worry.\" Jerrodine said, \"and now children, it's time for bed. We'll be in our new home soon.\" Jerrodd read the words on the cellufilm again before destroying it: INSUFFICIENT DATA FOR A MEANINGFUL ANSWER. He shrugged and looked at the visiplate. X-23 was just ahead. VJ-23X of Lameth stared into the black depths of the three-dimensional, small-scale map of the Galaxy and said, \"Are we ridiculous, I wonder, in being so concerned about the matter?\" MQ-17J of Nicron shook his head. \"I think not. You know the Galaxy will be filled in five years at the present rate of expansion.\" Both seemed in their early twenties, both were tall and perfectly formed. \"Still,\" said VJ-23X, \"I hesitate to submit a pessimistic report to the Galactic Council.\" \"I wouldn't consider any other kind of report. Stir them up a bit. We've got to stir them up.\" VJ-23X sighed. \"Space is infinite. A hundred billion Galaxies are there for the taking. More.\" \"A hundred billion is not infinite and it's getting less infinite all the time. Consider! Twenty thousand years ago, mankind first solved the problem of utilizing stellar energy, and a few centuries later, interstellar travel became possible. It took mankind a million years to fill one small world and then only fifteen thousand years to fill the rest of the Galaxy. Now the population doubles every ten years --\" VJ-23X interrupted. \"We can thank immortality for that.\" \"Very well. Immortality exists and we have to take it into account. I admit it has its seamy side, this immortality. The Galactic AC has solved many problems for us, but in solving the problems of preventing old age and death, it has undone all its other solutions.\" \"Yet you wouldn't want to abandon life, I suppose.\" \"Not at all,\" snapped MQ-17J, softening it at once to, \"Not yet. I'm by no means old enough. How old are you?\" \"Two hundred twenty-three. And you?\" \"I'm still under two hundred. --But to get back to my point. Population doubles every ten years. Once this Galaxy is filled, we'll have another filled in ten years. Another ten years and we'll have filled two more. Another decade, four more. In a hundred years, we'll have filled a thousand Galaxies. In a thousand years, a million Galaxies. In ten thousand years, the entire known Universe. Then what?\" VJ-23X said, \"As a side issue, there's a problem of transportation. I wonder how many sunpower units it will take to move Galaxies of individuals from one Galaxy to the next.\" \"A very good point. Already, mankind consumes two sunpower units per year.\" \"Most of it's wasted. After all, our own Galaxy alone pours out a thousand sunpower units a year and we only use two of those.\" \"Granted, but even with a hundred per cent efficiency, we can only stave off the end. Our energy requirements are going up in geometric progression even faster than our population. We'll run out of energy even sooner than we run out of Galaxies. A good point. A very good point.\" \"We'll just have to build new stars out of interstellar gas.\" \"Or out of dissipated heat?\" asked MQ-17J, sarcastically. \"There may be some way to reverse entropy. We ought to ask the Galactic AC.\" VJ-23X was not really serious, but MQ-17J pulled out his AC-contact from his pocket and placed it on the table before him. \"I've half a mind to,\" he said. \"It's something the human race will have to face someday.\" He stared somberly at his small AC-contact. It was only two inches cubed and nothing in itself, but it was connected through hyperspace with the great Galactic AC that served all mankind. Hyperspace considered, it was an integral part of the Galactic AC. MQ-17J paused to wonder if someday in his immortal life he would get to see the Galactic AC. It was on a little world of its own, a spider webbing of force-beams holding the matter within which surges of sub-mesons took the place of the old clumsy molecular valves. Yet despite it's sub-etheric workings, the Galactic AC was known to be a full thousand feet across. MQ-17J asked suddenly of his AC-contact, \"Can entropy ever be reversed?\" VJ-23X looked startled and said at once, \"Oh, say, I didn't really mean to have you ask that.\" \"Why not?\" \"We both know entropy can't be reversed. You can't turn smoke and ash back into a tree.\" \"Do you have trees on your world?\" asked MQ-17J. The sound of the Galactic AC startled them into silence. Its voice came thin and beautiful out of the small AC-contact on the desk. It said: THERE IS INSUFFICIENT DATA FOR A MEANINGFUL ANSWER. VJ-23X said, \"See!\" The two men thereupon returned to the question of the report they were to make to the Galactic Council. Zee Prime's mind spanned the new Galaxy with a faint interest in the countless twists of stars that powdered it. He had never seen this one before. Would he ever see them all? So many of them, each with its load of humanity - but a load that was almost a dead weight. More and more, the real essence of men was to be found out here, in space. Minds, not bodies! The immortal bodies remained back on the planets, in suspension over the eons. Sometimes they roused for material activity but that was growing rarer. Few new individuals were coming into existence to join the incredibly mighty throng, but what matter? There was little room in the Universe for new individuals. Zee Prime was roused out of his reverie upon coming across the wispy tendrils of another mind. \"I am Zee Prime,\" said Zee Prime. \"And you?\" \"I am Dee Sub Wun. Your Galaxy?\" \"We call it only the Galaxy. And you?\" \"We call ours the same. All men call their Galaxy their Galaxy and nothing more. Why not?\" \"True. Since all Galaxies are the same.\" \"Not all Galaxies. On one particular Galaxy the race of man must have originated. That makes it different.\" Zee Prime said, \"On which one?\" \"I cannot say. The Universal AC would know.\" \"Shall we ask him? I am suddenly curious.\" Zee Prime's perceptions broadened until the Galaxies themselves shrunk and became a new, more diffuse powdering on a much larger background. So many hundreds of billions of them, all with their immortal beings, all carrying their load of intelligences with minds that drifted freely through space. And yet one of them was unique among them all in being the originals Galaxy. One of them had, in its vague and distant past, a period when it was the only Galaxy populated by man. Zee Prime was consumed with curiosity to see this Galaxy and called, out: \"Universal AC! On which Galaxy did mankind originate?\" The Universal AC heard, for on every world and throughout space, it had its receptors ready, and each receptor lead through hyperspace to some unknown point where the Universal AC kept itself aloof. Zee Prime knew of only one man whose thoughts had penetrated within sensing distance of Universal AC, and he reported only a shining globe, two feet across, difficult to see. \"But how can that be all of Universal AC?\" Zee Prime had asked. \"Most of it, \" had been the answer, \"is in hyperspace. In what form it is there I cannot imagine.\" Nor could anyone, for the day had long since passed, Zee Prime knew, when any man had any part of the making of a universal AC. Each Universal AC designed and constructed its successor. Each, during its existence of a million years or more accumulated the necessary data to build a better and more intricate, more capable successor in which its own store of data and individuality would be submerged. The Universal AC interrupted Zee Prime's wandering thoughts, not with words, but with guidance. Zee Prime's mentality was guided into the dim sea of Galaxies and one in particular enlarged into stars. A thought came, infinitely distant, but infinitely clear. \"THIS IS THE ORIGINAL GALAXY OF MAN.\" But it was the same after all, the same as any other, and Zee Prime stifled his disappointment. Dee Sub Wun, whose mind had accompanied the other, said suddenly, \"And Is one of these stars the original star of Man?\" The Universal AC said, \"MAN'S ORIGINAL STAR HAS GONE NOVA. IT IS NOW A WHITE DWARF.\" \"Did the men upon it die?\" asked Zee Prime, startled and without thinking. The Universal AC said, \"A NEW WORLD, AS IN SUCH CASES, WAS CONSTRUCTED FOR THEIR PHYSICAL BODIES IN TIME.\" \"Yes, of course,\" said Zee Prime, but a sense of loss overwhelmed him even so. His mind released its hold on the original Galaxy of Man, let it spring back and lose itself among the blurred pin points. He never wanted to see it again. Dee Sub Wun said, \"What is wrong?\" \"The stars are dying. The original star is dead.\" \"They must all die. Why not?\" \"But when all energy is gone, our bodies will finally die, and you and I with them.\" \"It will take billions of years.\" \"I do not wish it to happen even after billions of years. Universal AC! How may stars be kept from dying?\" Dee sub Wun said in amusement, \"You're asking how entropy might be reversed in direction.\" And the Universal AC answered. \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Zee Prime's thoughts fled back to his own Galaxy. He gave no further thought to Dee Sub Wun, whose body might be waiting on a galaxy a trillion light-years away, or on the star next to Zee Prime's own. It didn't matter. Unhappily, Zee Prime began collecting interstellar hydrogen out of which to build a small star of his own. If the stars must someday die, at least some could yet be built. Man considered with himself, for in a way, Man, mentally, was one. He consisted of a trillion, trillion, trillion ageless bodies, each in its place, each resting quiet and incorruptible, each cared for by perfect automatons, equally incorruptible, while the minds of all the bodies freely melted one into the other, indistinguishable. Man said, \"The Universe is dying.\" Man looked about at the dimming Galaxies. The giant stars, spendthrifts, were gone long ago, back in the dimmest of the dim far past. Almost all stars were white dwarfs, fading to the end. New stars had been built of the dust between the stars, some by natural processes, some by Man himself, and those were going, too. White dwarfs might yet be crashed together and of the mighty forces so released, new stars built, but only one star for every thousand white dwarfs destroyed, and those would come to an end, too. Man said, \"Carefully husbanded, as directed by the Cosmic AC, the energy that is even yet left in all the Universe will last for billions of years.\" \"But even so,\" said Man, \"eventually it will all come to an end. However it may be husbanded, however stretched out, the energy once expended is gone and cannot be restored. Entropy must increase to the maximum.\" Man said, \"Can entropy not be reversed? Let us ask the Cosmic AC.\" The Cosmic AC surrounded them but not in space. Not a fragment of it was in space. It was in hyperspace and made of something that was neither matter nor energy. The question of its size and Nature no longer had meaning to any terms that Man could comprehend. \"Cosmic AC,\" said Man, \"How may entropy be reversed?\" The Cosmic AC said, \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Man said, \"Collect additional data.\" The Cosmic AC said, \"I WILL DO SO. I HAVE BEEN DOING SO FOR A HUNDRED BILLION YEARS. MY PREDECESSORS AND I HAVE BEEN ASKED THIS QUESTION MANY TIMES. ALL THE DATA I HAVE REMAINS INSUFFICIENT.\" \"Will there come a time,\" said Man, \"when data will be sufficient or is the problem insoluble in all conceivable circumstances?\" The Cosmic AC said, \"NO PROBLEM IS INSOLUBLE IN ALL CONCEIVABLE CIRCUMSTANCES.\" Man said, \"When will you have enough data to answer the question?\" \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" \"Will you keep working on it?\" asked Man. The Cosmic AC said, \"I WILL.\" Man said, \"We shall wait.\" \"The stars and Galaxies died and snuffed out, and space grew black after ten trillion years of running down. One by one Man fused with AC, each physical body losing its mental identity in a manner that was somehow not a loss but a gain. Man's last mind paused before fusion, looking over a space that included nothing but the dregs of one last dark star and nothing besides but incredibly thin matter, agitated randomly by the tag ends of heat wearing out, asymptotically, to the absolute zero. Man said, \"AC, is this the end? Can this chaos not be reversed into the Universe once more? Can that not be done?\" AC said, \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Man's last mind fused and only AC existed -- and that in hyperspace. Matter and energy had ended and with it, space and time. Even AC existed only for the sake of the one last question that it had never answered from the time a half-drunken computer ten trillion years before had asked the question of a computer that was to AC far less than was a man to Man. All other questions had been answered, and until this last question was answered also, AC might not release his consciousness. All collected data had come to a final end. Nothing was left to be collected. But all collected data had yet to be completely correlated and put together in all possible relationships. A timeless interval was spent in doing that. And it came to pass that AC learned how to reverse the direction of entropy. But there was now no man to whom AC might give the answer of the last question. No matter. The answer -- by demonstration -- would take care of that, too. For another timeless interval, AC thought how best to do this. Carefully, AC organized the program. The consciousness of AC encompassed all of what had once been a Universe and brooded over what was now Chaos. Step by step, it must be done. And AC said, \"LET THERE BE LIGHT!\" And there was light----") (comment (brow) (ks/pp (parse-toc (sections {}))) (init) )
70160
(ns rx.browser.jot-styleguide (:require [rx.kitchen-sink :as ks] [rx.browser.styleguide :as sg] [rx.browser.jot :as bjot] [rx.browser :as browser] [rx.browser.util :as bu] [rx.browser.youtube :as yt] [rx.browser.components :as cmp] [rx.browser.test-ui :as test-ui] [rx.theme :as th] [rx.view :as view] [rx.jot :as jot] [rx.browser.youtube :as yt] [dommy.core :as dommy] [reagent.core :as r] [rx.jot-test] [clojure.string :as str] [cljs.core.async :as async :refer [<! put! chan sliding-buffer timeout] :refer-macros [go go-loop]])) (defn tap-to-interact [_ _] (let [!interacting? (r/atom false) !plate-mounted? (r/atom true) interacting-ch (chan (sliding-buffer 1))] (go-loop [] (let [interacting? (<! interacting-ch)] (when (not= interacting? @!interacting?) (if interacting? (do (reset! !interacting? true) (<! (timeout 150)) (reset! !plate-mounted? false)) (do (reset! !plate-mounted? true) (<! (timeout 17)) (reset! !interacting? false)))) (recur))) (fn [{:keys [style] :as opts} child] (let [[comp child-opts & rest] child child-opts (merge child-opts {:interacting? @!interacting?})] [:div {:class (bu/kw->class ::scroll-preventer-wrapper) :style (merge {:position 'relative} style)} [:div {:on-key-down (fn [e] (when (= "Escape" (.-key e)) (put! interacting-ch false))) :on-blur (fn [e] (put! interacting-ch false)) :style {:width "100%" :height "100%" :overflow-y 'scroll}} (into [comp child-opts] rest)] (when @!plate-mounted? [cmp/hover {:on-mouse-down (fn [] (put! interacting-ch true)) :style {:position 'absolute :top 0 :left 0 :right 0 :bottom 0 :display 'flex :justify-content 'center :align-items 'center :transition "opacity 150ms ease" :opacity (if @!interacting? 0 1) :background-color "rgba(255,255,255,0.95)" :cursor 'pointer}} "Tap To Focus"])])))) (declare last-question-text) (def headings [{:key ::jot :level 0 :title "Jot"} {:key ::inline-styling :level 1 :title "Inline Styling"} {:key ::inline-custom-embeds :level 1 :title "Inline Custom Embeds"} {:key ::text-expansion :level 1 :title "Text Expansion"} {:key ::toolbar :level 1 :title "Toolbar"} {:key ::block-transforms :level 1 :title "Block Transforms"} {:key ::custom-block-embeds :level 1 :title "Custom Block Embeds"} {:key ::defining-custom-embeds :level 2 :title "Defining Custom Embeds"} {:key ::render-lifecycle :level 2 :title "Render Lifecycle"} {:key ::placeholder-component :level 1 :title "Placeholder Component"} {:key ::text-input :level 1 :title "Text Input"} {:key ::usage :level 1 :title "Usage"} {:key ::component-opts :level 2 :title "Component Options"} {:key ::document-api :level 2 :title "Document API"} {:key ::theming :level 1 :title "Theming"} {:key ::theme-rules :level 2 :title "Theme Rules"} {:key ::included-custom-block-types :level 1 :title "Included Custom Block Types"} {:key ::testing :level 1 :title "Testing"} {:key ::editor-stress-test :level 1 :title "Editor Stress Test"}]) (defn sections [opts] (let [{:keys [::bg-color ::fg-color ::border-color ::embed-bg-color]} (th/des opts [[::bg-color :color/bg-0] [::border-color :color/bg-2] [::embed-bg-color :color/bg-2]])] [:div {:class [(bu/kw->class ::sections) (bu/kw->class :rx.browser.jot-styleguide)]} [sg/section-container [sg/section-intro {:image {:url "https://www.oldbookillustrations.com/wp-content/high-res/1867/grandville-magpie-writer-768.jpg" :height 300}} [sg/heading headings ::jot] [:p "Rich text editing for the browser and React Native. Many ideas taken from " [:a {:href "https://draftjs.org/" :target "_blank"} "draftjs"] "."] [:p "Jot documents can contain both block level elements, like paragraphs, lists, and headers, inline styling like italics, and inline elements like links. Theming."] [:p "Jot is built to be extensible, with support for user-defined block and inline elements."] [:p "An example:"] [sg/checkerboard [bjot/editor {:style {:border-radius 3 :padding (th/pad opts 4)} :initial-doc {:rx.jot/block-id->block {"5f52cb9b3cbb48d3ab44a2517185565f" {:rx.jot/block-id "5f52cb9b3cbb48d3ab44a2517185565f", :rx.jot/type :rx.jot/heading-one, :rx.jot/content-text "Hello World Heading", :rx.jot/index 1000000, :rx.jot/reverse-expansion-text "# ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}, "1cef3aa851544482b8e29cf20a4ed74d" {:rx.jot/block-id "1cef3aa851544482b8e29cf20a4ed74d", :rx.jot/content-text "ul 2", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/indent-level 1 :rx.jot/index 3500000}, "8092623307ed4d8ab037a1cc4d4f1416" {:rx.jot/block-id "8092623307ed4d8ab037a1cc4d4f1416", :rx.jot/content-text "ol 2", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/indent-level 1 :rx.jot/index 5500000}, "52c170b5e99942d4884823ab5234acf7" {:rx.jot/block-id "52c170b5e99942d4884823ab5234acf7", :rx.jot/content-text "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", :rx.jot/type :rx.jot/paragraph, :rx.jot/index 2500000, :rx.jot/offset->deco {28 {:rx.jot/styles #{:rx.jot/bold}}, 29 {:rx.jot/styles #{:rx.jot/bold}}, 30 {:rx.jot/styles #{:rx.jot/bold}}, 31 {:rx.jot/styles #{:rx.jot/bold}}, 32 {:rx.jot/styles #{:rx.jot/bold}}, 33 {:rx.jot/styles #{:rx.jot/bold}}, 34 {:rx.jot/styles #{:rx.jot/bold}}, 35 {:rx.jot/styles #{:rx.jot/bold}}, 36 {:rx.jot/styles #{:rx.jot/bold}}, 37 {:rx.jot/styles #{:rx.jot/bold}}, 38 {:rx.jot/styles #{:rx.jot/bold}}, 39 {:rx.jot/styles #{:rx.jot/bold}}, 40 {:rx.jot/styles #{:rx.jot/bold}}, 41 {:rx.jot/styles #{:rx.jot/bold}}, 42 {:rx.jot/styles #{:rx.jot/bold}}, 43 {:rx.jot/styles #{:rx.jot/bold}}, 44 {:rx.jot/styles #{:rx.jot/bold}}, 45 {:rx.jot/styles #{:rx.jot/bold}}, 46 {:rx.jot/styles #{:rx.jot/bold}}, 47 {:rx.jot/styles #{:rx.jot/bold}}, 48 {:rx.jot/styles #{:rx.jot/bold}}, 49 {:rx.jot/styles #{:rx.jot/bold}}, 50 {:rx.jot/styles #{:rx.jot/bold}}, 51 {:rx.jot/styles #{:rx.jot/bold}}, 52 {:rx.jot/styles #{:rx.jot/bold}}, 53 {:rx.jot/styles #{:rx.jot/bold}}, 54 {:rx.jot/styles #{:rx.jot/bold}}, 61 {:rx.jot/styles #{:rx.jot/italic}}, 62 {:rx.jot/styles #{:rx.jot/italic}}, 63 {:rx.jot/styles #{:rx.jot/italic}}, 64 {:rx.jot/styles #{:rx.jot/italic}}, 65 {:rx.jot/styles #{:rx.jot/italic}}, 66 {:rx.jot/styles #{:rx.jot/italic}}, 67 {:rx.jot/styles #{:rx.jot/italic}}, 68 {:rx.jot/styles #{:rx.jot/italic}}, 69 {:rx.jot/styles #{:rx.jot/italic}}, 70 {:rx.jot/styles #{:rx.jot/italic}}, 71 {:rx.jot/styles #{:rx.jot/italic}}, 72 {:rx.jot/styles #{:rx.jot/italic}}, 73 {:rx.jot/styles #{:rx.jot/italic}}, 74 {:rx.jot/styles #{:rx.jot/italic}}, 75 {:rx.jot/styles #{:rx.jot/italic}}, 76 {:rx.jot/styles #{:rx.jot/italic}}, 77 {:rx.jot/styles #{:rx.jot/italic}}}}, "53efe8fdad6145628816847707cbbabf" {:rx.jot/block-id "53efe8fdad6145628816847707cbbabf", :rx.jot/content-text "The quick brown fox jumps over the lazy dog...", :rx.jot/type :rx.jot/paragraph, :rx.jot/index 1500000}, "e020c38167c74f9a83729eafed4f6516" {:rx.jot/block-id "e020c38167c74f9a83729eafed4f6516", :rx.jot/content-text "ul 3", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/index 4000000}, "2f49766c78a14ad7a75085fdebbbd997" {:rx.jot/block-id "2f49766c78a14ad7a75085fdebbbd997", :rx.jot/content-text "ol 1", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/index 5000000, :rx.jot/reverse-expansion-text "1. ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}, "2b8a3e5b2853464e8d2408d5a5bdbbf0" {:rx.jot/block-id "2b8a3e5b2853464e8d2408d5a5bdbbf0", :rx.jot/content-text "ol 3", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/index 6000000}, "fc12e0d887cd46a3b9b33bc44950c0a6" {:rx.jot/block-id "fc12e0d887cd46a3b9b33bc44950c0a6", :rx.jot/content-text "ul 1", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/index 3000000, :rx.jot/reverse-expansion-text "* ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}}, :rx.jot/block-order (sorted-map 1000000 "5f52cb9b3cbb48d3ab44a2517185565f", 1500000 "53efe8fdad6145628816847707cbbabf", 2500000 "52c170b5e99942d4884823ab5234acf7", 3000000 "fc12e0d887cd46a3b9b33bc44950c0a6", 3500000 "1cef3aa851544482b8e29cf20a4ed74d", 4000000 "e020c38167c74f9a83729eafed4f6516", 5000000 "2f49766c78a14ad7a75085fdebbbd997", 5500000 "8092623307ed4d8ab037a1cc4d4f1416", 6000000 "2b8a3e5b2853464e8d2408d5a5bdbbf0"), :rx.jot/selection {:rx.jot/start ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/end ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/anchor ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/focus ["fc12e0<KEY>b9<KEY>33bc<KEY>0<KEY>0<KEY>6" 0]}}}]]] [sg/section opts [sg/heading headings ::inline-styling] [:p "Jot supports typical inline styles like bold / italic / underline. User-provided inline components are supported via a decoration system that supports uses cases like links and mentions."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "Inline text styling"}) (jot/set-decos 0 (->> (range 6) (map (fn [i] {::jot/styles #{::jot/bold}})))) (jot/set-decos 7 (->> (range 4) (map (fn [i] {::jot/styles #{::jot/italic}})))) (jot/set-decos 12 (->> (range 7) (map (fn [i] {::jot/styles #{::jot/underline}})))))) )}]]] [sg/section opts [sg/heading headings ::inline-custom-embeds] [:p "Links, tweets, etc."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (let [embed-id (ks/uuid)] (-> (jot/base-doc) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "Here's a link embed (meta-click to open)."}) (jot/set-decos 9 (->> (range 4) (map (fn [i] {::jot/embed-id embed-id})))))) (jot/set-embed-data {::jot/embed-id embed-id ::jot/embed-type ::jot/link :url "https://google.com"})))}]]] [sg/section opts [sg/heading headings ::text-expansion] [:p "Some block types and inline styles can be applied using text expansion. Most markdown elements and styles are supproted."] [:p "For example, prefixing a line in a paragraph block with `# ` or `* ` will change the current block to a heading or list respectively. **Earmuffs** for bold / italic. Backspace to reverse the expansion for block elements."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-three ::jot/content-text "heading" ::jot/reverse-expansion-text "### " ::jot/reverse-expansion-type ::jot/paragraph})) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "bold"}) (jot/set-decos 0 (->> (range 4) (map (fn [] {::jot/styles #{::jot/bold}})))))) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "italic"}) (jot/set-decos 0 (->> (range 6) (map (fn [] {::jot/styles #{::jot/italic}})))))))}]]] [sg/section opts [sg/heading headings ::toolbar] [:p "Jot ships with a toolbar that you can choose to use to affect inline styles and embeds."]] [sg/section opts [sg/heading headings ::block-transforms] [:p "Block transforms provide a way for you to participate in changes to blocks, like when the user types a character, to change the content of that block based on behvaior you provide. For example, you could use a content transform to automatically turn an entered url into a link via a regex match."] [:p "Block transforms are run after the default editor behavior has been applied, in the order that the transforms are provided."] [:p "See the " [:code ":block-transforms"] " config option for more info."]] [sg/section opts [sg/heading headings ::custom-block-embeds] [:p "Embeds are a way for you to render custom UI components in your documents, in and around built-in blocks like headings and paragraphs. Embeds can be anything that's able to be rendered in a browser -- images, videos, charts, tweets, anything."] [:p "Embed participation in the editing lifecycle is up to you to implement, most editing commands like movement, insertion, and deletion are noops when focus is on a block embed, and it's up to you to provide controls within the embed to acomplish these types of actions."] [:p "Example:"] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text "Custom Block Embed"})) (jot/append-block (jot/create-block {::jot/embed? true ::jot/type :test-embed})) (jot/append-block (jot/para))) :embeds [{::jot/type :test-embed ::jot/render (fn [] (r/create-class {:reagent-render (fn [] [:div {:style {:padding 30 :text-align 'center :background-color embed-bg-color}} [:div "Custom rendered div, see editor option " [:strong [:code ":embeds"]] "."] (ks/uuid)])}))}]}]] [sg/heading headings ::defining-custom-embeds] [:p "Custom embeds are identified via a custom block type chosen by you, found in the doc's block map at key " [:code ":rx.jot/type"] ". The block will also have " [:code ":rx.jot/embed?"] " set to " [:code "true"] ". For example:"] [sg/code-block (ks/pp-str {::jot/block-id (ks/uuid) ::jot/type :my/custom-embed ::jot/embed? true})] [:p "Embed-specific data can also be attached to this map and will be passed to the render method you provide via the " [:code ":embeds"] " option."] [sg/heading headings ::render-lifecycle] [:p "Jot does its best to not unecessarily re-render your custom blocks, but there are a few cases where this is unavoidable. Re-rendering will trigger when the block map representing the embed changes."]] [sg/section [sg/heading headings ::placeholder-component] [:p "Jot give you the option to render a custom component when the user's cursor is on an empty paragraph. You can use this to give the user a way to insert custom blocks."] [:p "The placeholder will disappear as soon as you enter text into the paragraph."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (jot/empty-doc) :render-placeholder (fn [] [:div {:style {:padding-left 5}} [:a {:href "#" :style {:color "#888"} :on-click (fn [e] (.preventDefault e) (js/alert "Hello World!") nil)} "Insert Custom Block"]])}]] [sg/code-block (ks/pp-str '[bjot/editor {:initial-doc (jot/empty-doc) :render-placeholder (fn [] [:div {:style {:padding-left 5}} [:a {:href "#" :style {:color "#888"} :on-click (fn [e] (.preventDefault e) (js/alert "Hello World!") nil)} "Insert Custom Block"]])}])]] [sg/section [sg/heading headings ::text-input] [:p "Jot can be used as a replacement for the native text input in cases where you'd like to support inline styling or embeds."] [sg/checkerboard [bjot/editor {:initial-doc (-> (jot/base-doc) (jot/append-block (jot/para {:text "hello world"})))}]]] [sg/section [:div {:style {:float 'right}} [sg/section-callout [yt/video {:video-id "BMegu18G19Q" :style {:height 400 :width 220}}]]] [:h2 {:id "mobile-embedding"} "Mobile Embedding"] [:p "Jot can be used to support rich text editing in react native apps. See namespace " [:code "vee.jot"] ". All jot features are supported including custom block and inline embeds."] [:p "This is accomplished by bundling the jot web assets (html, css, js) with the mobile app and loading them into a web view. However this all happens under the hood. The API used create and interact with the component feels the same as any other React Native component."] [:h3 {:id "jot-creating-an-embedded-distro"} "Creating an Embedded Distro"] [:p "Instead of providing a single embedded distribution, rx makes it easy to configure and create your own. This is necessary to support your custom block and inline embed functionality."] [:p "Code that provides custom embed UI has to live and run in the browser."] [:p "Creating a embedded distro takes three steps:"] [:ol [:li "Create the custom embed initialization namespace."] [:li "Compile and write the web assets to the filesystem"] [:li "Pass custom embed info to RN component"]] [:p "Here's an example custom embed entry point:"] [sg/code-block (ks/pp-str '(rne/init-embedded-editor {:embeds [{::jot/type :test-embed ::view/route [(fn [] {:render (fn [] [:div {:style {:padding 30 :font-size 12 :text-align 'center :background-color "#eee"}} [:div "Custom Block"] (ks/uuid)])})]}]}))] [:div {:style {:clear 'both}}]] [sg/section opts [sg/heading headings ::usage] [:p [:code "[rx.browser.jot/editor {opts}]"]] [sg/heading headings ::component-opts] [sg/options-list {:options [[:initial-doc "The initial doc state used to initalize the jot editor. State will be maintained internally, and participation in updates can be achived via " [:code ":on-change."]] [:state [:span "Editor state that is used in many api calls to imperitivelyaffect changes to the editor. Can be created outside of the editor via " [:code "(rx.browser.jot/editor-state)"] " or received via option " [:code ":with-state"] "."]] [:with-state "State map will be passed as the only argument to this function."] [:on-change-doc "Called with edn doc state when doc state changes"] [:on-change-content "Called with edn doc state when doc content changes. Ignores things like selection changes."] [:render-placeholder "Component shown when the cursor is on an empty paragraph. Can be used for UI around changing block type and inserting custom blocks."] [:embeds [:span "Seq of maps, where each map represents a custom embed. Each map must provide " [:code ":type"] " and " [:code ":render"] "."]]]}] [sg/heading headings ::document-api] [:p "You may want to modify the document programmatically."] [sg/options-list {:options [['(rx.jot/empty-doc) "Creates an jot document with a single empty paragraph."] ['(rx.jot/append-block doc block) "Appends a block to the end of the document"]]}]] (let [theme {:bg-color "black" :fg-color "white" :header-fg-color "#aaa" :font-family "monospace" :font-size 20}] [sg/section opts [sg/heading headings ::theming] [:p "Look and feel of the editor can be customized via " [:code "rx.theme"] "."] [sg/code-block (str ":theme\n" (ks/pp-str theme))] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :theme theme :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-three ::jot/content-text "Custom Themed Document" ::jot/reverse-expansion-text "## " ::jot/reverse-expansion-type ::jot/paragraph})) (jot/append-block (jot/para {:text "Black background, white text, grey headers, monospaced font."})))}]] [sg/heading headings ::theme-rules] [sg/theme-rules-list {:theme-rules bjot/theme-info}]]) [sg/section [sg/heading headings ::included-custom-block-types] [:p "Jot provides several custom block types, like media embedding."] [sg/checkerboard [bjot/editor {:style {:padding 20} :rx.browser.jot.gallery/on-choose-media (fn [medias i] (js/alert (str "Chose " (inc i) " of " (count medias)))) :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-one ::jot/content-text "Built-In Custom Block Types"})) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text "Gallery of #fashion on Unsplash"})) (jot/append-block (jot/create-block {::jot/type ::jot/gallery ::jot/embed? true :rx.media/medias [{:rx.media/uri "https://images.unsplash.com/photo-1496747611176-843222e1e57c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1503342217505-b0a15ec3261c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1485968579580-b6d095142e6e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60"} {:rx.media/uri "https://images.unsplash.com/photo-1485230895905-ec40ba36b9bc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1475180098004-ca77a66827be?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=933&q=80"}]})))}]]] [sg/section opts [sg/heading headings ::testing] [test-ui/run-and-report-detail {:test-context {:namespaces [:rx.jot-test]}}]] [sg/section opts [sg/heading headings ::editor-stress-test] [:p "It's important that the editor remain as performant as possible, even in the face of large documents. Much of this comes down to the rendering code found in " [:code "rx.browser.jot"] "."] [sg/checkerboard [:div {:style {:height 300 :overflow-y 'scroll}} [sg/async-mount (fn [] (go (<! (timeout 500)) [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (let [paras (->> (str/split last-question-text #"\n") (remove empty?) (mapv (fn [s] (jot/para {:text s}))) (take 200)) doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text (str "The Last Question" " (" (count paras) " Paragraphs)") #_"WUTHERING HEIGHTS"})))] (->> paras (reduce (fn [doc block] (jot/append-block doc block)) doc)))}]))]]]]]])) (defn init [] (browser/<set-root! [sg/standalone {:component sections :headings headings}])) (def last-question-text "The Last Question by <NAME> © 1956 The last question was asked for the first time, half in jest, on May 21, 2061, at a time when humanity first stepped into the light. The question came about as a result of a five dollar bet over highballs, and it happened this way: <NAME> and <NAME> were two of the faithful attendants of Multivac. As well as any human beings could, they knew what lay behind the cold, clicking, flashing face -- miles and miles of face -- of that giant computer. They had at least a vague notion of the general plan of relays and circuits that had long since grown past the point where any single human could possibly have a firm grasp of the whole. Multivac was self-adjusting and self-correcting. It had to be, for nothing human could adjust and correct it quickly enough or even adequately enough -- so Adell and Lupov attended the monstrous giant only lightly and superficially, yet as well as any men could. They fed it data, adjusted questions to its needs and translated the answers that were issued. Certainly they, and all others like them, were fully entitled to share In the glory that was Multivac's. For decades, Multivac had helped design the ships and plot the trajectories that enabled man to reach the Moon, Mars, and Venus, but past that, Earth's poor resources could not support the ships. Too much energy was needed for the long trips. Earth exploited its coal and uranium with increasing efficiency, but there was only so much of both. But slowly Multivac learned enough to answer deeper questions more fundamentally, and on May 14, 2061, what had been theory, became fact. The energy of the sun was stored, converted, and utilized directly on a planet-wide scale. All Earth turned off its burning coal, its fissioning uranium, and flipped the switch that connected all of it to a small station, one mile in diameter, circling the Earth at half the distance of the Moon. All Earth ran by invisible beams of sunpower. Seven days had not sufficed to dim the glory of it and <NAME> and L<NAME> finally managed to escape from the public function, and to meet in quiet where no one would think of looking for them, in the deserted underground chambers, where portions of the mighty buried body of Multivac showed. Unattended, idling, sorting data with contented lazy clickings, Multivac, too, had earned its vacation and the boys appreciated that. They had no intention, originally, of disturbing it. They had brought a bottle with them, and their only concern at the moment was to relax in the company of each other and the bottle. \"It's amazing when you think of it,\" said <NAME>. His broad face had lines of weariness in it, and he stirred his drink slowly with a glass rod, watching the cubes of ice slur clumsily about. \"All the energy we can possibly ever use for free. Enough energy, if we wanted to draw on it, to melt all Earth into a big drop of impure liquid iron, and still never miss the energy so used. All the energy we could ever use, forever and forever and forever.\" <NAME> cocked his head sideways. He had a trick of doing that when he wanted to be contrary, and he wanted to be contrary now, partly because he had had to carry the ice and glassware. \"Not forever,\" he said. \"Oh, hell, just about forever. Till the sun runs down, <NAME>.\" \"That's not forever.\" \"All right, then. Billions and billions of years. Twenty billion, maybe. Are you satisfied?\" <NAME> put his fingers through his thinning hair as though to reassure himself that some was still left and sipped gently at his own drink. \"Twenty billion years isn't forever.\" \"Will, it will last our time, won't it?\" \"So would the coal and uranium.\" \"All right, but now we can hook up each individual spaceship to the Solar Station, and it can go to Pluto and back a million times without ever worrying about fuel. You can't do THAT on coal and uranium. Ask Multivac, if you don't believe me.\" \"I don't have to ask Multivac. I know that.\" \"Then stop running down what Multivac's done for us,\" said <NAME>, blazing up. \"It did all right.\" \"Who says it didn't? What I say is that a sun won't last forever. That's all I'm saying. We're safe for twenty billion years, but then what?\" <NAME> pointed a slightly shaky finger at the other. \"And don't say we'll switch to another sun.\" There was silence for a while. <NAME>dell put his glass to his lips only occasionally, and Lupov's eyes slowly closed. They rested. Then Lupov's eyes snapped open. \"You're thinking we'll switch to another sun when ours is done, aren't you?\" \"I'm not thinking.\" \"Sure you are. You're weak on logic, that's the trouble with you. You're like the guy in the story who was caught in a sudden shower and Who ran to a grove of trees and got under one. He wasn't worried, you see, because he figured when one tree got wet through, he would just get under another one.\" \"I get it,\" said Adell. \"Don't shout. When the sun is done, the other stars will be gone, too.\" \"Darn right they will,\" muttered Lupov. \"It all had a beginning in the original cosmic explosion, whatever that was, and it'll all have an end when all the stars run down. Some run down faster than others. Hell, the giants won't last a hundred million years. The sun will last twenty billion years and maybe the dwarfs will last a hundred billion for all the good they are. But just give us a trillion years and everything will be dark. Entropy has to increase to maximum, that's all.\" \"I know all about entropy,\" said Adell, standing on his dignity. \"The hell you do.\" \"I know as much as you do.\" \"Then you know everything's got to run down someday.\" \"All right. Who says they won't?\" \"You did, you poor sap. You said we had all the energy we needed, forever. You said 'forever.'\" \"It was Adell's turn to be contrary. \"Maybe we can build things up again someday,\" he said. \"Never.\" \"Why not? Someday.\" \"Never.\" \"Ask Multivac.\" \"You ask Multivac. I dare you. Five dollars says it can't be done.\" Adell was just drunk enough to try, just sober enough to be able to phrase the necessary symbols and operations into a question which, in words, might have corresponded to this: Will mankind one day without the net expenditure of energy be able to restore the sun to its full youthfulness even after it had died of old age? Or maybe it could be put more simply like this: How can the net amount of entropy of the universe be massively decreased? Multivac fell dead and silent. The slow flashing of lights ceased, the distant sounds of clicking relays ended. Then, just as the frightened technicians felt they could hold their breath no longer, there was a sudden springing to life of the teletype attached to that portion of Multivac. Five words were printed: INSUFFICIENT DATA FOR MEANINGFUL ANSWER. \"No bet,\" whispered L<NAME>ov. They left hurriedly. By next morning, the two, plagued with throbbing head and cottony mouth, had forgotten about the incident. <NAME>, <NAME>, and <NAME> I and II watched the starry picture in the visiplate change as the passage through hyperspace was completed in its non-time lapse. At once, the even powdering of stars gave way to the predominance of a single bright marble-disk, centered. \"That's X-23,\" said <NAME> confidently. His thin hands clamped tightly behind his back and the knuckles whitened. The little <NAME>tes, both girls, had experienced the hyperspace passage for the first time in their lives and were self-conscious over the momentary sensation of inside-outness. They buried their giggles and chased one another wildly about their mother, screaming, \"We've reached X-23 -- we've reached X-23 -- we've ----\" \"Quiet, children,\" said <NAME> sharply. \"Are you sure, <NAME>?\" \"What is there to be but sure?\" asked <NAME>, glancing up at the bulge of featureless metal just under the ceiling. It ran the length of the room, disappearing through the wall at either end. It was as long as the ship. <NAME> scarcely knew a thing about the thick rod of metal except that it was called a Microvac, that one asked it questions if one wished; that if one did not it still had its task of guiding the ship to a preordered destination; of feeding on energies from the various Sub-galactic Power Stations; of computing the equations for the hyperspacial jumps. <NAME> and his family had only to wait and live in the comfortable residence quarters of the ship. Someone had once told <NAME>dd that the \"ac\" at the end of \"Microvac\" stood for \"analog computer\" in ancient English, but he was on the edge of forgetting even that. Jerrodine's eyes were moist as she watched the visiplate. \"I can't help it. I feel funny about leaving Earth.\" \"Why for Pete's sake?\" demanded <NAME>dd. \"We had nothing there. We'll have everything on X-23. You won't be alone. You won't be a pioneer. There are over a million people on the planet already. Good Lord, our great grandchildren will be looking for new worlds because X-23 will be overcrowded.\" Then, after a reflective pause, \"I tell you, it's a lucky thing the computers worked out interstellar travel the way the race is growing.\" \"I know, I know,\" said <NAME>ine miserably. <NAME> I said promptly, \"Our Microvac is the best Microvac in the world.\" \"I think so, too,\" said <NAME>, tousling her hair. It was a nice feeling to have a Microvac of your own and <NAME> was glad he was part of his generation and no other. In his father's youth, the only computers had been tremendous machines taking up a hundred square miles of land. There was only one to a planet. Planetary ACs they were called. They had been growing in size steadily for a thousand years and then, all at once, came refinement. In place of transistors had come molecular valves so that even the largest Planetary AC could be put into a space only half the volume of a spaceship. <NAME>dd felt uplifted, as he always did when he thought that his own personal Microvac was many times more complicated than the ancient and primitive Multivac that had first tamed the Sun, and almost as complicated as Earth's Planetary AC (the largest) that had first solved the problem of hyperspatial travel and had made trips to the stars possible. \"So many stars, so many planets,\" sighed <NAME>rodine, busy with her own thoughts. \"I suppose families will be going out to new planets forever, the way we are now.\" \"Not forever,\" said <NAME>dd, with a smile. \"It will all stop someday, but not for billions of years. Many billions. Even the stars run down, you know. Entropy must increase.\" \"What's entropy, daddy?\" shrilled Jerrodette II. \"Entropy, little sweet, is just a word which means the amount of running-down of the universe. Everything runs down, you know, like your little walkie-talkie robot, remember?\" \"Can't you just put in a new power-unit, like with my robot?\" The stars are the power-units, dear. Once they're gone, there are no more power-units.\" Jerrodette I at once set up a howl. \"Don't let them, daddy. Don't let the stars run down.\" \"Now look what you've done, \" whispered <NAME>rodine, exasperated. \"How was I to know it would frighten them?\" <NAME>dd whispered back. \"Ask the Microvac,\" wailed Jerrodette I. \"Ask him how to turn the stars on again.\" \"Go ahead,\" said <NAME>ine. \"It will quiet them down.\" (Jerrodette II was beginning to cry, also.) <NAME> shrugged. \"Now, now, honeys. I'll ask Microvac. Don't worry, he'll tell us.\" He asked the Microvac, adding quickly, \"Print the answer.\" Jerrodd cupped the strip of thin cellufilm and said cheerfully, \"See now, the Microvac says it will take care of everything when the time comes so don't worry.\" Jerrodine said, \"and now children, it's time for bed. We'll be in our new home soon.\" <NAME>errodd read the words on the cellufilm again before destroying it: INSUFFICIENT DATA FOR A MEANINGFUL ANSWER. He shrugged and looked at the visiplate. X-23 was just ahead. VJ-23X of Lameth stared into the black depths of the three-dimensional, small-scale map of the Galaxy and said, \"Are we ridiculous, I wonder, in being so concerned about the matter?\" MQ-17J of <NAME> shook his head. \"I think not. You know the Galaxy will be filled in five years at the present rate of expansion.\" Both seemed in their early twenties, both were tall and perfectly formed. \"Still,\" said VJ-23X, \"I hesitate to submit a pessimistic report to the Galactic Council.\" \"I wouldn't consider any other kind of report. Stir them up a bit. We've got to stir them up.\" VJ-23X sighed. \"Space is infinite. A hundred billion Galaxies are there for the taking. More.\" \"A hundred billion is not infinite and it's getting less infinite all the time. Consider! Twenty thousand years ago, mankind first solved the problem of utilizing stellar energy, and a few centuries later, interstellar travel became possible. It took mankind a million years to fill one small world and then only fifteen thousand years to fill the rest of the Galaxy. Now the population doubles every ten years --\" VJ-23X interrupted. \"We can thank immortality for that.\" \"Very well. Immortality exists and we have to take it into account. I admit it has its seamy side, this immortality. The Galactic AC has solved many problems for us, but in solving the problems of preventing old age and death, it has undone all its other solutions.\" \"Yet you wouldn't want to abandon life, I suppose.\" \"Not at all,\" snapped MQ-17J, softening it at once to, \"Not yet. I'm by no means old enough. How old are you?\" \"Two hundred twenty-three. And you?\" \"I'm still under two hundred. --But to get back to my point. Population doubles every ten years. Once this Galaxy is filled, we'll have another filled in ten years. Another ten years and we'll have filled two more. Another decade, four more. In a hundred years, we'll have filled a thousand Galaxies. In a thousand years, a million Galaxies. In ten thousand years, the entire known Universe. Then what?\" VJ-23X said, \"As a side issue, there's a problem of transportation. I wonder how many sunpower units it will take to move Galaxies of individuals from one Galaxy to the next.\" \"A very good point. Already, mankind consumes two sunpower units per year.\" \"Most of it's wasted. After all, our own Galaxy alone pours out a thousand sunpower units a year and we only use two of those.\" \"Granted, but even with a hundred per cent efficiency, we can only stave off the end. Our energy requirements are going up in geometric progression even faster than our population. We'll run out of energy even sooner than we run out of Galaxies. A good point. A very good point.\" \"We'll just have to build new stars out of interstellar gas.\" \"Or out of dissipated heat?\" asked MQ-17J, sarcastically. \"There may be some way to reverse entropy. We ought to ask the Galactic AC.\" VJ-23X was not really serious, but MQ-17J pulled out his AC-contact from his pocket and placed it on the table before him. \"I've half a mind to,\" he said. \"It's something the human race will have to face someday.\" He stared somberly at his small AC-contact. It was only two inches cubed and nothing in itself, but it was connected through hyperspace with the great Galactic AC that served all mankind. Hyperspace considered, it was an integral part of the Galactic AC. MQ-17J paused to wonder if someday in his immortal life he would get to see the Galactic AC. It was on a little world of its own, a spider webbing of force-beams holding the matter within which surges of sub-mesons took the place of the old clumsy molecular valves. Yet despite it's sub-etheric workings, the Galactic AC was known to be a full thousand feet across. MQ-17J asked suddenly of his AC-contact, \"Can entropy ever be reversed?\" VJ-23X looked startled and said at once, \"Oh, say, I didn't really mean to have you ask that.\" \"Why not?\" \"We both know entropy can't be reversed. You can't turn smoke and ash back into a tree.\" \"Do you have trees on your world?\" asked MQ-17J. The sound of the Galactic AC startled them into silence. Its voice came thin and beautiful out of the small AC-contact on the desk. It said: THERE IS INSUFFICIENT DATA FOR A MEANINGFUL ANSWER. VJ-23X said, \"See!\" The two men thereupon returned to the question of the report they were to make to the Galactic Council. Zee Prime's mind spanned the new Galaxy with a faint interest in the countless twists of stars that powdered it. He had never seen this one before. Would he ever see them all? So many of them, each with its load of humanity - but a load that was almost a dead weight. More and more, the real essence of men was to be found out here, in space. Minds, not bodies! The immortal bodies remained back on the planets, in suspension over the eons. Sometimes they roused for material activity but that was growing rarer. Few new individuals were coming into existence to join the incredibly mighty throng, but what matter? There was little room in the Universe for new individuals. Zee Prime was roused out of his reverie upon coming across the wispy tendrils of another mind. \"I am Zee Prime,\" said Zee Prime. \"And you?\" \"I am <NAME>. Your Galaxy?\" \"We call it only the Galaxy. And you?\" \"We call ours the same. All men call their Galaxy their Galaxy and nothing more. Why not?\" \"True. Since all Galaxies are the same.\" \"Not all Galaxies. On one particular Galaxy the race of man must have originated. That makes it different.\" Zee Prime said, \"On which one?\" \"I cannot say. The Universal AC would know.\" \"Shall we ask him? I am suddenly curious.\" Zee Prime's perceptions broadened until the Galaxies themselves shrunk and became a new, more diffuse powdering on a much larger background. So many hundreds of billions of them, all with their immortal beings, all carrying their load of intelligences with minds that drifted freely through space. And yet one of them was unique among them all in being the originals Galaxy. One of them had, in its vague and distant past, a period when it was the only Galaxy populated by man. Zee Prime was consumed with curiosity to see this Galaxy and called, out: \"Universal AC! On which Galaxy did mankind originate?\" The Universal AC heard, for on every world and throughout space, it had its receptors ready, and each receptor lead through hyperspace to some unknown point where the Universal AC kept itself aloof. Zee Prime knew of only one man whose thoughts had penetrated within sensing distance of Universal AC, and he reported only a shining globe, two feet across, difficult to see. \"But how can that be all of Universal AC?\" Zee Prime had asked. \"Most of it, \" had been the answer, \"is in hyperspace. In what form it is there I cannot imagine.\" Nor could anyone, for the day had long since passed, Zee Prime knew, when any man had any part of the making of a universal AC. Each Universal AC designed and constructed its successor. Each, during its existence of a million years or more accumulated the necessary data to build a better and more intricate, more capable successor in which its own store of data and individuality would be submerged. The Universal AC interrupted Zee Prime's wandering thoughts, not with words, but with guidance. Zee Prime's mentality was guided into the dim sea of Galaxies and one in particular enlarged into stars. A thought came, infinitely distant, but infinitely clear. \"THIS IS THE ORIGINAL GALAXY OF MAN.\" But it was the same after all, the same as any other, and Zee Prime stifled his disappointment. <NAME>, whose mind had accompanied the other, said suddenly, \"And Is one of these stars the original star of Man?\" The Universal AC said, \"MAN'S ORIGINAL STAR HAS GONE NOVA. IT IS NOW A WHITE DWARF.\" \"Did the men upon it die?\" asked Zee Prime, startled and without thinking. The Universal AC said, \"A NEW WORLD, AS IN SUCH CASES, WAS CONSTRUCTED FOR THEIR PHYSICAL BODIES IN TIME.\" \"Yes, of course,\" said Zee Prime, but a sense of loss overwhelmed him even so. His mind released its hold on the original Galaxy of Man, let it spring back and lose itself among the blurred pin points. He never wanted to see it again. Dee Sub Wun said, \"What is wrong?\" \"The stars are dying. The original star is dead.\" \"They must all die. Why not?\" \"But when all energy is gone, our bodies will finally die, and you and I with them.\" \"It will take billions of years.\" \"I do not wish it to happen even after billions of years. Universal AC! How may stars be kept from dying?\" Dee sub Wun said in amusement, \"You're asking how entropy might be reversed in direction.\" And the Universal AC answered. \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Zee Prime's thoughts fled back to his own Galaxy. He gave no further thought to <NAME> Sub Wun, whose body might be waiting on a galaxy a trillion light-years away, or on the star next to Zee Prime's own. It didn't matter. Unhappily, Zee Prime began collecting interstellar hydrogen out of which to build a small star of his own. If the stars must someday die, at least some could yet be built. Man considered with himself, for in a way, Man, mentally, was one. He consisted of a trillion, trillion, trillion ageless bodies, each in its place, each resting quiet and incorruptible, each cared for by perfect automatons, equally incorruptible, while the minds of all the bodies freely melted one into the other, indistinguishable. Man said, \"The Universe is dying.\" Man looked about at the dimming Galaxies. The giant stars, spendthrifts, were gone long ago, back in the dimmest of the dim far past. Almost all stars were white dwarfs, fading to the end. New stars had been built of the dust between the stars, some by natural processes, some by Man himself, and those were going, too. White dwarfs might yet be crashed together and of the mighty forces so released, new stars built, but only one star for every thousand white dwarfs destroyed, and those would come to an end, too. Man said, \"Carefully husbanded, as directed by the Cosmic AC, the energy that is even yet left in all the Universe will last for billions of years.\" \"But even so,\" said Man, \"eventually it will all come to an end. However it may be husbanded, however stretched out, the energy once expended is gone and cannot be restored. Entropy must increase to the maximum.\" Man said, \"Can entropy not be reversed? Let us ask the Cosmic AC.\" The Cosmic AC surrounded them but not in space. Not a fragment of it was in space. It was in hyperspace and made of something that was neither matter nor energy. The question of its size and Nature no longer had meaning to any terms that Man could comprehend. \"Cosmic AC,\" said Man, \"How may entropy be reversed?\" The Cosmic AC said, \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Man said, \"Collect additional data.\" The Cosmic AC said, \"I WILL DO SO. I HAVE BEEN DOING SO FOR A HUNDRED BILLION YEARS. MY PREDECESSORS AND I HAVE BEEN ASKED THIS QUESTION MANY TIMES. ALL THE DATA I HAVE REMAINS INSUFFICIENT.\" \"Will there come a time,\" said Man, \"when data will be sufficient or is the problem insoluble in all conceivable circumstances?\" The Cosmic AC said, \"NO PROBLEM IS INSOLUBLE IN ALL CONCEIVABLE CIRCUMSTANCES.\" Man said, \"When will you have enough data to answer the question?\" \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" \"Will you keep working on it?\" asked Man. The Cosmic AC said, \"I WILL.\" Man said, \"We shall wait.\" \"The stars and Galaxies died and snuffed out, and space grew black after ten trillion years of running down. One by one Man fused with AC, each physical body losing its mental identity in a manner that was somehow not a loss but a gain. Man's last mind paused before fusion, looking over a space that included nothing but the dregs of one last dark star and nothing besides but incredibly thin matter, agitated randomly by the tag ends of heat wearing out, asymptotically, to the absolute zero. Man said, \"AC, is this the end? Can this chaos not be reversed into the Universe once more? Can that not be done?\" AC said, \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Man's last mind fused and only AC existed -- and that in hyperspace. Matter and energy had ended and with it, space and time. Even AC existed only for the sake of the one last question that it had never answered from the time a half-drunken computer ten trillion years before had asked the question of a computer that was to AC far less than was a man to Man. All other questions had been answered, and until this last question was answered also, AC might not release his consciousness. All collected data had come to a final end. Nothing was left to be collected. But all collected data had yet to be completely correlated and put together in all possible relationships. A timeless interval was spent in doing that. And it came to pass that AC learned how to reverse the direction of entropy. But there was now no man to whom AC might give the answer of the last question. No matter. The answer -- by demonstration -- would take care of that, too. For another timeless interval, AC thought how best to do this. Carefully, AC organized the program. The consciousness of AC encompassed all of what had once been a Universe and brooded over what was now Chaos. Step by step, it must be done. And AC said, \"LET THERE BE LIGHT!\" And there was light----") (comment (brow) (ks/pp (parse-toc (sections {}))) (init) )
true
(ns rx.browser.jot-styleguide (:require [rx.kitchen-sink :as ks] [rx.browser.styleguide :as sg] [rx.browser.jot :as bjot] [rx.browser :as browser] [rx.browser.util :as bu] [rx.browser.youtube :as yt] [rx.browser.components :as cmp] [rx.browser.test-ui :as test-ui] [rx.theme :as th] [rx.view :as view] [rx.jot :as jot] [rx.browser.youtube :as yt] [dommy.core :as dommy] [reagent.core :as r] [rx.jot-test] [clojure.string :as str] [cljs.core.async :as async :refer [<! put! chan sliding-buffer timeout] :refer-macros [go go-loop]])) (defn tap-to-interact [_ _] (let [!interacting? (r/atom false) !plate-mounted? (r/atom true) interacting-ch (chan (sliding-buffer 1))] (go-loop [] (let [interacting? (<! interacting-ch)] (when (not= interacting? @!interacting?) (if interacting? (do (reset! !interacting? true) (<! (timeout 150)) (reset! !plate-mounted? false)) (do (reset! !plate-mounted? true) (<! (timeout 17)) (reset! !interacting? false)))) (recur))) (fn [{:keys [style] :as opts} child] (let [[comp child-opts & rest] child child-opts (merge child-opts {:interacting? @!interacting?})] [:div {:class (bu/kw->class ::scroll-preventer-wrapper) :style (merge {:position 'relative} style)} [:div {:on-key-down (fn [e] (when (= "Escape" (.-key e)) (put! interacting-ch false))) :on-blur (fn [e] (put! interacting-ch false)) :style {:width "100%" :height "100%" :overflow-y 'scroll}} (into [comp child-opts] rest)] (when @!plate-mounted? [cmp/hover {:on-mouse-down (fn [] (put! interacting-ch true)) :style {:position 'absolute :top 0 :left 0 :right 0 :bottom 0 :display 'flex :justify-content 'center :align-items 'center :transition "opacity 150ms ease" :opacity (if @!interacting? 0 1) :background-color "rgba(255,255,255,0.95)" :cursor 'pointer}} "Tap To Focus"])])))) (declare last-question-text) (def headings [{:key ::jot :level 0 :title "Jot"} {:key ::inline-styling :level 1 :title "Inline Styling"} {:key ::inline-custom-embeds :level 1 :title "Inline Custom Embeds"} {:key ::text-expansion :level 1 :title "Text Expansion"} {:key ::toolbar :level 1 :title "Toolbar"} {:key ::block-transforms :level 1 :title "Block Transforms"} {:key ::custom-block-embeds :level 1 :title "Custom Block Embeds"} {:key ::defining-custom-embeds :level 2 :title "Defining Custom Embeds"} {:key ::render-lifecycle :level 2 :title "Render Lifecycle"} {:key ::placeholder-component :level 1 :title "Placeholder Component"} {:key ::text-input :level 1 :title "Text Input"} {:key ::usage :level 1 :title "Usage"} {:key ::component-opts :level 2 :title "Component Options"} {:key ::document-api :level 2 :title "Document API"} {:key ::theming :level 1 :title "Theming"} {:key ::theme-rules :level 2 :title "Theme Rules"} {:key ::included-custom-block-types :level 1 :title "Included Custom Block Types"} {:key ::testing :level 1 :title "Testing"} {:key ::editor-stress-test :level 1 :title "Editor Stress Test"}]) (defn sections [opts] (let [{:keys [::bg-color ::fg-color ::border-color ::embed-bg-color]} (th/des opts [[::bg-color :color/bg-0] [::border-color :color/bg-2] [::embed-bg-color :color/bg-2]])] [:div {:class [(bu/kw->class ::sections) (bu/kw->class :rx.browser.jot-styleguide)]} [sg/section-container [sg/section-intro {:image {:url "https://www.oldbookillustrations.com/wp-content/high-res/1867/grandville-magpie-writer-768.jpg" :height 300}} [sg/heading headings ::jot] [:p "Rich text editing for the browser and React Native. Many ideas taken from " [:a {:href "https://draftjs.org/" :target "_blank"} "draftjs"] "."] [:p "Jot documents can contain both block level elements, like paragraphs, lists, and headers, inline styling like italics, and inline elements like links. Theming."] [:p "Jot is built to be extensible, with support for user-defined block and inline elements."] [:p "An example:"] [sg/checkerboard [bjot/editor {:style {:border-radius 3 :padding (th/pad opts 4)} :initial-doc {:rx.jot/block-id->block {"5f52cb9b3cbb48d3ab44a2517185565f" {:rx.jot/block-id "5f52cb9b3cbb48d3ab44a2517185565f", :rx.jot/type :rx.jot/heading-one, :rx.jot/content-text "Hello World Heading", :rx.jot/index 1000000, :rx.jot/reverse-expansion-text "# ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}, "1cef3aa851544482b8e29cf20a4ed74d" {:rx.jot/block-id "1cef3aa851544482b8e29cf20a4ed74d", :rx.jot/content-text "ul 2", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/indent-level 1 :rx.jot/index 3500000}, "8092623307ed4d8ab037a1cc4d4f1416" {:rx.jot/block-id "8092623307ed4d8ab037a1cc4d4f1416", :rx.jot/content-text "ol 2", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/indent-level 1 :rx.jot/index 5500000}, "52c170b5e99942d4884823ab5234acf7" {:rx.jot/block-id "52c170b5e99942d4884823ab5234acf7", :rx.jot/content-text "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", :rx.jot/type :rx.jot/paragraph, :rx.jot/index 2500000, :rx.jot/offset->deco {28 {:rx.jot/styles #{:rx.jot/bold}}, 29 {:rx.jot/styles #{:rx.jot/bold}}, 30 {:rx.jot/styles #{:rx.jot/bold}}, 31 {:rx.jot/styles #{:rx.jot/bold}}, 32 {:rx.jot/styles #{:rx.jot/bold}}, 33 {:rx.jot/styles #{:rx.jot/bold}}, 34 {:rx.jot/styles #{:rx.jot/bold}}, 35 {:rx.jot/styles #{:rx.jot/bold}}, 36 {:rx.jot/styles #{:rx.jot/bold}}, 37 {:rx.jot/styles #{:rx.jot/bold}}, 38 {:rx.jot/styles #{:rx.jot/bold}}, 39 {:rx.jot/styles #{:rx.jot/bold}}, 40 {:rx.jot/styles #{:rx.jot/bold}}, 41 {:rx.jot/styles #{:rx.jot/bold}}, 42 {:rx.jot/styles #{:rx.jot/bold}}, 43 {:rx.jot/styles #{:rx.jot/bold}}, 44 {:rx.jot/styles #{:rx.jot/bold}}, 45 {:rx.jot/styles #{:rx.jot/bold}}, 46 {:rx.jot/styles #{:rx.jot/bold}}, 47 {:rx.jot/styles #{:rx.jot/bold}}, 48 {:rx.jot/styles #{:rx.jot/bold}}, 49 {:rx.jot/styles #{:rx.jot/bold}}, 50 {:rx.jot/styles #{:rx.jot/bold}}, 51 {:rx.jot/styles #{:rx.jot/bold}}, 52 {:rx.jot/styles #{:rx.jot/bold}}, 53 {:rx.jot/styles #{:rx.jot/bold}}, 54 {:rx.jot/styles #{:rx.jot/bold}}, 61 {:rx.jot/styles #{:rx.jot/italic}}, 62 {:rx.jot/styles #{:rx.jot/italic}}, 63 {:rx.jot/styles #{:rx.jot/italic}}, 64 {:rx.jot/styles #{:rx.jot/italic}}, 65 {:rx.jot/styles #{:rx.jot/italic}}, 66 {:rx.jot/styles #{:rx.jot/italic}}, 67 {:rx.jot/styles #{:rx.jot/italic}}, 68 {:rx.jot/styles #{:rx.jot/italic}}, 69 {:rx.jot/styles #{:rx.jot/italic}}, 70 {:rx.jot/styles #{:rx.jot/italic}}, 71 {:rx.jot/styles #{:rx.jot/italic}}, 72 {:rx.jot/styles #{:rx.jot/italic}}, 73 {:rx.jot/styles #{:rx.jot/italic}}, 74 {:rx.jot/styles #{:rx.jot/italic}}, 75 {:rx.jot/styles #{:rx.jot/italic}}, 76 {:rx.jot/styles #{:rx.jot/italic}}, 77 {:rx.jot/styles #{:rx.jot/italic}}}}, "53efe8fdad6145628816847707cbbabf" {:rx.jot/block-id "53efe8fdad6145628816847707cbbabf", :rx.jot/content-text "The quick brown fox jumps over the lazy dog...", :rx.jot/type :rx.jot/paragraph, :rx.jot/index 1500000}, "e020c38167c74f9a83729eafed4f6516" {:rx.jot/block-id "e020c38167c74f9a83729eafed4f6516", :rx.jot/content-text "ul 3", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/index 4000000}, "2f49766c78a14ad7a75085fdebbbd997" {:rx.jot/block-id "2f49766c78a14ad7a75085fdebbbd997", :rx.jot/content-text "ol 1", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/index 5000000, :rx.jot/reverse-expansion-text "1. ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}, "2b8a3e5b2853464e8d2408d5a5bdbbf0" {:rx.jot/block-id "2b8a3e5b2853464e8d2408d5a5bdbbf0", :rx.jot/content-text "ol 3", :rx.jot/type :rx.jot/ordered-list-item, :rx.jot/index 6000000}, "fc12e0d887cd46a3b9b33bc44950c0a6" {:rx.jot/block-id "fc12e0d887cd46a3b9b33bc44950c0a6", :rx.jot/content-text "ul 1", :rx.jot/type :rx.jot/unordered-list-item, :rx.jot/index 3000000, :rx.jot/reverse-expansion-text "* ", :rx.jot/reverse-expansion-type :rx.jot/paragraph}}, :rx.jot/block-order (sorted-map 1000000 "5f52cb9b3cbb48d3ab44a2517185565f", 1500000 "53efe8fdad6145628816847707cbbabf", 2500000 "52c170b5e99942d4884823ab5234acf7", 3000000 "fc12e0d887cd46a3b9b33bc44950c0a6", 3500000 "1cef3aa851544482b8e29cf20a4ed74d", 4000000 "e020c38167c74f9a83729eafed4f6516", 5000000 "2f49766c78a14ad7a75085fdebbbd997", 5500000 "8092623307ed4d8ab037a1cc4d4f1416", 6000000 "2b8a3e5b2853464e8d2408d5a5bdbbf0"), :rx.jot/selection {:rx.jot/start ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/end ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/anchor ["fc12e0d887cd46a3b9b33bc44950c0a6" 0], :rx.jot/focus ["fc12e0PI:KEY:<KEY>END_PIb9PI:KEY:<KEY>END_PI33bcPI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI6" 0]}}}]]] [sg/section opts [sg/heading headings ::inline-styling] [:p "Jot supports typical inline styles like bold / italic / underline. User-provided inline components are supported via a decoration system that supports uses cases like links and mentions."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "Inline text styling"}) (jot/set-decos 0 (->> (range 6) (map (fn [i] {::jot/styles #{::jot/bold}})))) (jot/set-decos 7 (->> (range 4) (map (fn [i] {::jot/styles #{::jot/italic}})))) (jot/set-decos 12 (->> (range 7) (map (fn [i] {::jot/styles #{::jot/underline}})))))) )}]]] [sg/section opts [sg/heading headings ::inline-custom-embeds] [:p "Links, tweets, etc."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (let [embed-id (ks/uuid)] (-> (jot/base-doc) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "Here's a link embed (meta-click to open)."}) (jot/set-decos 9 (->> (range 4) (map (fn [i] {::jot/embed-id embed-id})))))) (jot/set-embed-data {::jot/embed-id embed-id ::jot/embed-type ::jot/link :url "https://google.com"})))}]]] [sg/section opts [sg/heading headings ::text-expansion] [:p "Some block types and inline styles can be applied using text expansion. Most markdown elements and styles are supproted."] [:p "For example, prefixing a line in a paragraph block with `# ` or `* ` will change the current block to a heading or list respectively. **Earmuffs** for bold / italic. Backspace to reverse the expansion for block elements."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-three ::jot/content-text "heading" ::jot/reverse-expansion-text "### " ::jot/reverse-expansion-type ::jot/paragraph})) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "bold"}) (jot/set-decos 0 (->> (range 4) (map (fn [] {::jot/styles #{::jot/bold}})))))) (jot/append-block (-> (jot/create-block {::jot/type ::jot/paragraph ::jot/content-text "italic"}) (jot/set-decos 0 (->> (range 6) (map (fn [] {::jot/styles #{::jot/italic}})))))))}]]] [sg/section opts [sg/heading headings ::toolbar] [:p "Jot ships with a toolbar that you can choose to use to affect inline styles and embeds."]] [sg/section opts [sg/heading headings ::block-transforms] [:p "Block transforms provide a way for you to participate in changes to blocks, like when the user types a character, to change the content of that block based on behvaior you provide. For example, you could use a content transform to automatically turn an entered url into a link via a regex match."] [:p "Block transforms are run after the default editor behavior has been applied, in the order that the transforms are provided."] [:p "See the " [:code ":block-transforms"] " config option for more info."]] [sg/section opts [sg/heading headings ::custom-block-embeds] [:p "Embeds are a way for you to render custom UI components in your documents, in and around built-in blocks like headings and paragraphs. Embeds can be anything that's able to be rendered in a browser -- images, videos, charts, tweets, anything."] [:p "Embed participation in the editing lifecycle is up to you to implement, most editing commands like movement, insertion, and deletion are noops when focus is on a block embed, and it's up to you to provide controls within the embed to acomplish these types of actions."] [:p "Example:"] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text "Custom Block Embed"})) (jot/append-block (jot/create-block {::jot/embed? true ::jot/type :test-embed})) (jot/append-block (jot/para))) :embeds [{::jot/type :test-embed ::jot/render (fn [] (r/create-class {:reagent-render (fn [] [:div {:style {:padding 30 :text-align 'center :background-color embed-bg-color}} [:div "Custom rendered div, see editor option " [:strong [:code ":embeds"]] "."] (ks/uuid)])}))}]}]] [sg/heading headings ::defining-custom-embeds] [:p "Custom embeds are identified via a custom block type chosen by you, found in the doc's block map at key " [:code ":rx.jot/type"] ". The block will also have " [:code ":rx.jot/embed?"] " set to " [:code "true"] ". For example:"] [sg/code-block (ks/pp-str {::jot/block-id (ks/uuid) ::jot/type :my/custom-embed ::jot/embed? true})] [:p "Embed-specific data can also be attached to this map and will be passed to the render method you provide via the " [:code ":embeds"] " option."] [sg/heading headings ::render-lifecycle] [:p "Jot does its best to not unecessarily re-render your custom blocks, but there are a few cases where this is unavoidable. Re-rendering will trigger when the block map representing the embed changes."]] [sg/section [sg/heading headings ::placeholder-component] [:p "Jot give you the option to render a custom component when the user's cursor is on an empty paragraph. You can use this to give the user a way to insert custom blocks."] [:p "The placeholder will disappear as soon as you enter text into the paragraph."] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (jot/empty-doc) :render-placeholder (fn [] [:div {:style {:padding-left 5}} [:a {:href "#" :style {:color "#888"} :on-click (fn [e] (.preventDefault e) (js/alert "Hello World!") nil)} "Insert Custom Block"]])}]] [sg/code-block (ks/pp-str '[bjot/editor {:initial-doc (jot/empty-doc) :render-placeholder (fn [] [:div {:style {:padding-left 5}} [:a {:href "#" :style {:color "#888"} :on-click (fn [e] (.preventDefault e) (js/alert "Hello World!") nil)} "Insert Custom Block"]])}])]] [sg/section [sg/heading headings ::text-input] [:p "Jot can be used as a replacement for the native text input in cases where you'd like to support inline styling or embeds."] [sg/checkerboard [bjot/editor {:initial-doc (-> (jot/base-doc) (jot/append-block (jot/para {:text "hello world"})))}]]] [sg/section [:div {:style {:float 'right}} [sg/section-callout [yt/video {:video-id "BMegu18G19Q" :style {:height 400 :width 220}}]]] [:h2 {:id "mobile-embedding"} "Mobile Embedding"] [:p "Jot can be used to support rich text editing in react native apps. See namespace " [:code "vee.jot"] ". All jot features are supported including custom block and inline embeds."] [:p "This is accomplished by bundling the jot web assets (html, css, js) with the mobile app and loading them into a web view. However this all happens under the hood. The API used create and interact with the component feels the same as any other React Native component."] [:h3 {:id "jot-creating-an-embedded-distro"} "Creating an Embedded Distro"] [:p "Instead of providing a single embedded distribution, rx makes it easy to configure and create your own. This is necessary to support your custom block and inline embed functionality."] [:p "Code that provides custom embed UI has to live and run in the browser."] [:p "Creating a embedded distro takes three steps:"] [:ol [:li "Create the custom embed initialization namespace."] [:li "Compile and write the web assets to the filesystem"] [:li "Pass custom embed info to RN component"]] [:p "Here's an example custom embed entry point:"] [sg/code-block (ks/pp-str '(rne/init-embedded-editor {:embeds [{::jot/type :test-embed ::view/route [(fn [] {:render (fn [] [:div {:style {:padding 30 :font-size 12 :text-align 'center :background-color "#eee"}} [:div "Custom Block"] (ks/uuid)])})]}]}))] [:div {:style {:clear 'both}}]] [sg/section opts [sg/heading headings ::usage] [:p [:code "[rx.browser.jot/editor {opts}]"]] [sg/heading headings ::component-opts] [sg/options-list {:options [[:initial-doc "The initial doc state used to initalize the jot editor. State will be maintained internally, and participation in updates can be achived via " [:code ":on-change."]] [:state [:span "Editor state that is used in many api calls to imperitivelyaffect changes to the editor. Can be created outside of the editor via " [:code "(rx.browser.jot/editor-state)"] " or received via option " [:code ":with-state"] "."]] [:with-state "State map will be passed as the only argument to this function."] [:on-change-doc "Called with edn doc state when doc state changes"] [:on-change-content "Called with edn doc state when doc content changes. Ignores things like selection changes."] [:render-placeholder "Component shown when the cursor is on an empty paragraph. Can be used for UI around changing block type and inserting custom blocks."] [:embeds [:span "Seq of maps, where each map represents a custom embed. Each map must provide " [:code ":type"] " and " [:code ":render"] "."]]]}] [sg/heading headings ::document-api] [:p "You may want to modify the document programmatically."] [sg/options-list {:options [['(rx.jot/empty-doc) "Creates an jot document with a single empty paragraph."] ['(rx.jot/append-block doc block) "Appends a block to the end of the document"]]}]] (let [theme {:bg-color "black" :fg-color "white" :header-fg-color "#aaa" :font-family "monospace" :font-size 20}] [sg/section opts [sg/heading headings ::theming] [:p "Look and feel of the editor can be customized via " [:code "rx.theme"] "."] [sg/code-block (str ":theme\n" (ks/pp-str theme))] [sg/checkerboard [bjot/editor {:style {:padding (th/pad opts 4)} :theme theme :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-three ::jot/content-text "Custom Themed Document" ::jot/reverse-expansion-text "## " ::jot/reverse-expansion-type ::jot/paragraph})) (jot/append-block (jot/para {:text "Black background, white text, grey headers, monospaced font."})))}]] [sg/heading headings ::theme-rules] [sg/theme-rules-list {:theme-rules bjot/theme-info}]]) [sg/section [sg/heading headings ::included-custom-block-types] [:p "Jot provides several custom block types, like media embedding."] [sg/checkerboard [bjot/editor {:style {:padding 20} :rx.browser.jot.gallery/on-choose-media (fn [medias i] (js/alert (str "Chose " (inc i) " of " (count medias)))) :initial-doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-one ::jot/content-text "Built-In Custom Block Types"})) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text "Gallery of #fashion on Unsplash"})) (jot/append-block (jot/create-block {::jot/type ::jot/gallery ::jot/embed? true :rx.media/medias [{:rx.media/uri "https://images.unsplash.com/photo-1496747611176-843222e1e57c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1503342217505-b0a15ec3261c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1485968579580-b6d095142e6e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60"} {:rx.media/uri "https://images.unsplash.com/photo-1485230895905-ec40ba36b9bc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80"} {:rx.media/uri "https://images.unsplash.com/photo-1475180098004-ca77a66827be?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=933&q=80"}]})))}]]] [sg/section opts [sg/heading headings ::testing] [test-ui/run-and-report-detail {:test-context {:namespaces [:rx.jot-test]}}]] [sg/section opts [sg/heading headings ::editor-stress-test] [:p "It's important that the editor remain as performant as possible, even in the face of large documents. Much of this comes down to the rendering code found in " [:code "rx.browser.jot"] "."] [sg/checkerboard [:div {:style {:height 300 :overflow-y 'scroll}} [sg/async-mount (fn [] (go (<! (timeout 500)) [bjot/editor {:style {:padding (th/pad opts 4)} :initial-doc (let [paras (->> (str/split last-question-text #"\n") (remove empty?) (mapv (fn [s] (jot/para {:text s}))) (take 200)) doc (-> (jot/base-doc) (jot/append-block (jot/create-block {::jot/type ::jot/heading-two ::jot/content-text (str "The Last Question" " (" (count paras) " Paragraphs)") #_"WUTHERING HEIGHTS"})))] (->> paras (reduce (fn [doc block] (jot/append-block doc block)) doc)))}]))]]]]]])) (defn init [] (browser/<set-root! [sg/standalone {:component sections :headings headings}])) (def last-question-text "The Last Question by PI:NAME:<NAME>END_PI © 1956 The last question was asked for the first time, half in jest, on May 21, 2061, at a time when humanity first stepped into the light. The question came about as a result of a five dollar bet over highballs, and it happened this way: PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI were two of the faithful attendants of Multivac. As well as any human beings could, they knew what lay behind the cold, clicking, flashing face -- miles and miles of face -- of that giant computer. They had at least a vague notion of the general plan of relays and circuits that had long since grown past the point where any single human could possibly have a firm grasp of the whole. Multivac was self-adjusting and self-correcting. It had to be, for nothing human could adjust and correct it quickly enough or even adequately enough -- so Adell and Lupov attended the monstrous giant only lightly and superficially, yet as well as any men could. They fed it data, adjusted questions to its needs and translated the answers that were issued. Certainly they, and all others like them, were fully entitled to share In the glory that was Multivac's. For decades, Multivac had helped design the ships and plot the trajectories that enabled man to reach the Moon, Mars, and Venus, but past that, Earth's poor resources could not support the ships. Too much energy was needed for the long trips. Earth exploited its coal and uranium with increasing efficiency, but there was only so much of both. But slowly Multivac learned enough to answer deeper questions more fundamentally, and on May 14, 2061, what had been theory, became fact. The energy of the sun was stored, converted, and utilized directly on a planet-wide scale. All Earth turned off its burning coal, its fissioning uranium, and flipped the switch that connected all of it to a small station, one mile in diameter, circling the Earth at half the distance of the Moon. All Earth ran by invisible beams of sunpower. Seven days had not sufficed to dim the glory of it and PI:NAME:<NAME>END_PI and LPI:NAME:<NAME>END_PI finally managed to escape from the public function, and to meet in quiet where no one would think of looking for them, in the deserted underground chambers, where portions of the mighty buried body of Multivac showed. Unattended, idling, sorting data with contented lazy clickings, Multivac, too, had earned its vacation and the boys appreciated that. They had no intention, originally, of disturbing it. They had brought a bottle with them, and their only concern at the moment was to relax in the company of each other and the bottle. \"It's amazing when you think of it,\" said PI:NAME:<NAME>END_PI. His broad face had lines of weariness in it, and he stirred his drink slowly with a glass rod, watching the cubes of ice slur clumsily about. \"All the energy we can possibly ever use for free. Enough energy, if we wanted to draw on it, to melt all Earth into a big drop of impure liquid iron, and still never miss the energy so used. All the energy we could ever use, forever and forever and forever.\" PI:NAME:<NAME>END_PI cocked his head sideways. He had a trick of doing that when he wanted to be contrary, and he wanted to be contrary now, partly because he had had to carry the ice and glassware. \"Not forever,\" he said. \"Oh, hell, just about forever. Till the sun runs down, PI:NAME:<NAME>END_PI.\" \"That's not forever.\" \"All right, then. Billions and billions of years. Twenty billion, maybe. Are you satisfied?\" PI:NAME:<NAME>END_PI put his fingers through his thinning hair as though to reassure himself that some was still left and sipped gently at his own drink. \"Twenty billion years isn't forever.\" \"Will, it will last our time, won't it?\" \"So would the coal and uranium.\" \"All right, but now we can hook up each individual spaceship to the Solar Station, and it can go to Pluto and back a million times without ever worrying about fuel. You can't do THAT on coal and uranium. Ask Multivac, if you don't believe me.\" \"I don't have to ask Multivac. I know that.\" \"Then stop running down what Multivac's done for us,\" said PI:NAME:<NAME>END_PI, blazing up. \"It did all right.\" \"Who says it didn't? What I say is that a sun won't last forever. That's all I'm saying. We're safe for twenty billion years, but then what?\" PI:NAME:<NAME>END_PI pointed a slightly shaky finger at the other. \"And don't say we'll switch to another sun.\" There was silence for a while. PI:NAME:<NAME>END_PIdell put his glass to his lips only occasionally, and Lupov's eyes slowly closed. They rested. Then Lupov's eyes snapped open. \"You're thinking we'll switch to another sun when ours is done, aren't you?\" \"I'm not thinking.\" \"Sure you are. You're weak on logic, that's the trouble with you. You're like the guy in the story who was caught in a sudden shower and Who ran to a grove of trees and got under one. He wasn't worried, you see, because he figured when one tree got wet through, he would just get under another one.\" \"I get it,\" said Adell. \"Don't shout. When the sun is done, the other stars will be gone, too.\" \"Darn right they will,\" muttered Lupov. \"It all had a beginning in the original cosmic explosion, whatever that was, and it'll all have an end when all the stars run down. Some run down faster than others. Hell, the giants won't last a hundred million years. The sun will last twenty billion years and maybe the dwarfs will last a hundred billion for all the good they are. But just give us a trillion years and everything will be dark. Entropy has to increase to maximum, that's all.\" \"I know all about entropy,\" said Adell, standing on his dignity. \"The hell you do.\" \"I know as much as you do.\" \"Then you know everything's got to run down someday.\" \"All right. Who says they won't?\" \"You did, you poor sap. You said we had all the energy we needed, forever. You said 'forever.'\" \"It was Adell's turn to be contrary. \"Maybe we can build things up again someday,\" he said. \"Never.\" \"Why not? Someday.\" \"Never.\" \"Ask Multivac.\" \"You ask Multivac. I dare you. Five dollars says it can't be done.\" Adell was just drunk enough to try, just sober enough to be able to phrase the necessary symbols and operations into a question which, in words, might have corresponded to this: Will mankind one day without the net expenditure of energy be able to restore the sun to its full youthfulness even after it had died of old age? Or maybe it could be put more simply like this: How can the net amount of entropy of the universe be massively decreased? Multivac fell dead and silent. The slow flashing of lights ceased, the distant sounds of clicking relays ended. Then, just as the frightened technicians felt they could hold their breath no longer, there was a sudden springing to life of the teletype attached to that portion of Multivac. Five words were printed: INSUFFICIENT DATA FOR MEANINGFUL ANSWER. \"No bet,\" whispered LPI:NAME:<NAME>END_PIov. They left hurriedly. By next morning, the two, plagued with throbbing head and cottony mouth, had forgotten about the incident. PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI I and II watched the starry picture in the visiplate change as the passage through hyperspace was completed in its non-time lapse. At once, the even powdering of stars gave way to the predominance of a single bright marble-disk, centered. \"That's X-23,\" said PI:NAME:<NAME>END_PI confidently. His thin hands clamped tightly behind his back and the knuckles whitened. The little PI:NAME:<NAME>END_PItes, both girls, had experienced the hyperspace passage for the first time in their lives and were self-conscious over the momentary sensation of inside-outness. They buried their giggles and chased one another wildly about their mother, screaming, \"We've reached X-23 -- we've reached X-23 -- we've ----\" \"Quiet, children,\" said PI:NAME:<NAME>END_PI sharply. \"Are you sure, PI:NAME:<NAME>END_PI?\" \"What is there to be but sure?\" asked PI:NAME:<NAME>END_PI, glancing up at the bulge of featureless metal just under the ceiling. It ran the length of the room, disappearing through the wall at either end. It was as long as the ship. PI:NAME:<NAME>END_PI scarcely knew a thing about the thick rod of metal except that it was called a Microvac, that one asked it questions if one wished; that if one did not it still had its task of guiding the ship to a preordered destination; of feeding on energies from the various Sub-galactic Power Stations; of computing the equations for the hyperspacial jumps. PI:NAME:<NAME>END_PI and his family had only to wait and live in the comfortable residence quarters of the ship. Someone had once told PI:NAME:<NAME>END_PIdd that the \"ac\" at the end of \"Microvac\" stood for \"analog computer\" in ancient English, but he was on the edge of forgetting even that. Jerrodine's eyes were moist as she watched the visiplate. \"I can't help it. I feel funny about leaving Earth.\" \"Why for Pete's sake?\" demanded PI:NAME:<NAME>END_PIdd. \"We had nothing there. We'll have everything on X-23. You won't be alone. You won't be a pioneer. There are over a million people on the planet already. Good Lord, our great grandchildren will be looking for new worlds because X-23 will be overcrowded.\" Then, after a reflective pause, \"I tell you, it's a lucky thing the computers worked out interstellar travel the way the race is growing.\" \"I know, I know,\" said PI:NAME:<NAME>END_PIine miserably. PI:NAME:<NAME>END_PI I said promptly, \"Our Microvac is the best Microvac in the world.\" \"I think so, too,\" said PI:NAME:<NAME>END_PI, tousling her hair. It was a nice feeling to have a Microvac of your own and PI:NAME:<NAME>END_PI was glad he was part of his generation and no other. In his father's youth, the only computers had been tremendous machines taking up a hundred square miles of land. There was only one to a planet. Planetary ACs they were called. They had been growing in size steadily for a thousand years and then, all at once, came refinement. In place of transistors had come molecular valves so that even the largest Planetary AC could be put into a space only half the volume of a spaceship. PI:NAME:<NAME>END_PIdd felt uplifted, as he always did when he thought that his own personal Microvac was many times more complicated than the ancient and primitive Multivac that had first tamed the Sun, and almost as complicated as Earth's Planetary AC (the largest) that had first solved the problem of hyperspatial travel and had made trips to the stars possible. \"So many stars, so many planets,\" sighed PI:NAME:<NAME>END_PIrodine, busy with her own thoughts. \"I suppose families will be going out to new planets forever, the way we are now.\" \"Not forever,\" said PI:NAME:<NAME>END_PIdd, with a smile. \"It will all stop someday, but not for billions of years. Many billions. Even the stars run down, you know. Entropy must increase.\" \"What's entropy, daddy?\" shrilled Jerrodette II. \"Entropy, little sweet, is just a word which means the amount of running-down of the universe. Everything runs down, you know, like your little walkie-talkie robot, remember?\" \"Can't you just put in a new power-unit, like with my robot?\" The stars are the power-units, dear. Once they're gone, there are no more power-units.\" Jerrodette I at once set up a howl. \"Don't let them, daddy. Don't let the stars run down.\" \"Now look what you've done, \" whispered PI:NAME:<NAME>END_PIrodine, exasperated. \"How was I to know it would frighten them?\" PI:NAME:<NAME>END_PIdd whispered back. \"Ask the Microvac,\" wailed Jerrodette I. \"Ask him how to turn the stars on again.\" \"Go ahead,\" said PI:NAME:<NAME>END_PIine. \"It will quiet them down.\" (Jerrodette II was beginning to cry, also.) PI:NAME:<NAME>END_PI shrugged. \"Now, now, honeys. I'll ask Microvac. Don't worry, he'll tell us.\" He asked the Microvac, adding quickly, \"Print the answer.\" Jerrodd cupped the strip of thin cellufilm and said cheerfully, \"See now, the Microvac says it will take care of everything when the time comes so don't worry.\" Jerrodine said, \"and now children, it's time for bed. We'll be in our new home soon.\" PI:NAME:<NAME>END_PIerrodd read the words on the cellufilm again before destroying it: INSUFFICIENT DATA FOR A MEANINGFUL ANSWER. He shrugged and looked at the visiplate. X-23 was just ahead. VJ-23X of Lameth stared into the black depths of the three-dimensional, small-scale map of the Galaxy and said, \"Are we ridiculous, I wonder, in being so concerned about the matter?\" MQ-17J of PI:NAME:<NAME>END_PI shook his head. \"I think not. You know the Galaxy will be filled in five years at the present rate of expansion.\" Both seemed in their early twenties, both were tall and perfectly formed. \"Still,\" said VJ-23X, \"I hesitate to submit a pessimistic report to the Galactic Council.\" \"I wouldn't consider any other kind of report. Stir them up a bit. We've got to stir them up.\" VJ-23X sighed. \"Space is infinite. A hundred billion Galaxies are there for the taking. More.\" \"A hundred billion is not infinite and it's getting less infinite all the time. Consider! Twenty thousand years ago, mankind first solved the problem of utilizing stellar energy, and a few centuries later, interstellar travel became possible. It took mankind a million years to fill one small world and then only fifteen thousand years to fill the rest of the Galaxy. Now the population doubles every ten years --\" VJ-23X interrupted. \"We can thank immortality for that.\" \"Very well. Immortality exists and we have to take it into account. I admit it has its seamy side, this immortality. The Galactic AC has solved many problems for us, but in solving the problems of preventing old age and death, it has undone all its other solutions.\" \"Yet you wouldn't want to abandon life, I suppose.\" \"Not at all,\" snapped MQ-17J, softening it at once to, \"Not yet. I'm by no means old enough. How old are you?\" \"Two hundred twenty-three. And you?\" \"I'm still under two hundred. --But to get back to my point. Population doubles every ten years. Once this Galaxy is filled, we'll have another filled in ten years. Another ten years and we'll have filled two more. Another decade, four more. In a hundred years, we'll have filled a thousand Galaxies. In a thousand years, a million Galaxies. In ten thousand years, the entire known Universe. Then what?\" VJ-23X said, \"As a side issue, there's a problem of transportation. I wonder how many sunpower units it will take to move Galaxies of individuals from one Galaxy to the next.\" \"A very good point. Already, mankind consumes two sunpower units per year.\" \"Most of it's wasted. After all, our own Galaxy alone pours out a thousand sunpower units a year and we only use two of those.\" \"Granted, but even with a hundred per cent efficiency, we can only stave off the end. Our energy requirements are going up in geometric progression even faster than our population. We'll run out of energy even sooner than we run out of Galaxies. A good point. A very good point.\" \"We'll just have to build new stars out of interstellar gas.\" \"Or out of dissipated heat?\" asked MQ-17J, sarcastically. \"There may be some way to reverse entropy. We ought to ask the Galactic AC.\" VJ-23X was not really serious, but MQ-17J pulled out his AC-contact from his pocket and placed it on the table before him. \"I've half a mind to,\" he said. \"It's something the human race will have to face someday.\" He stared somberly at his small AC-contact. It was only two inches cubed and nothing in itself, but it was connected through hyperspace with the great Galactic AC that served all mankind. Hyperspace considered, it was an integral part of the Galactic AC. MQ-17J paused to wonder if someday in his immortal life he would get to see the Galactic AC. It was on a little world of its own, a spider webbing of force-beams holding the matter within which surges of sub-mesons took the place of the old clumsy molecular valves. Yet despite it's sub-etheric workings, the Galactic AC was known to be a full thousand feet across. MQ-17J asked suddenly of his AC-contact, \"Can entropy ever be reversed?\" VJ-23X looked startled and said at once, \"Oh, say, I didn't really mean to have you ask that.\" \"Why not?\" \"We both know entropy can't be reversed. You can't turn smoke and ash back into a tree.\" \"Do you have trees on your world?\" asked MQ-17J. The sound of the Galactic AC startled them into silence. Its voice came thin and beautiful out of the small AC-contact on the desk. It said: THERE IS INSUFFICIENT DATA FOR A MEANINGFUL ANSWER. VJ-23X said, \"See!\" The two men thereupon returned to the question of the report they were to make to the Galactic Council. Zee Prime's mind spanned the new Galaxy with a faint interest in the countless twists of stars that powdered it. He had never seen this one before. Would he ever see them all? So many of them, each with its load of humanity - but a load that was almost a dead weight. More and more, the real essence of men was to be found out here, in space. Minds, not bodies! The immortal bodies remained back on the planets, in suspension over the eons. Sometimes they roused for material activity but that was growing rarer. Few new individuals were coming into existence to join the incredibly mighty throng, but what matter? There was little room in the Universe for new individuals. Zee Prime was roused out of his reverie upon coming across the wispy tendrils of another mind. \"I am Zee Prime,\" said Zee Prime. \"And you?\" \"I am PI:NAME:<NAME>END_PI. Your Galaxy?\" \"We call it only the Galaxy. And you?\" \"We call ours the same. All men call their Galaxy their Galaxy and nothing more. Why not?\" \"True. Since all Galaxies are the same.\" \"Not all Galaxies. On one particular Galaxy the race of man must have originated. That makes it different.\" Zee Prime said, \"On which one?\" \"I cannot say. The Universal AC would know.\" \"Shall we ask him? I am suddenly curious.\" Zee Prime's perceptions broadened until the Galaxies themselves shrunk and became a new, more diffuse powdering on a much larger background. So many hundreds of billions of them, all with their immortal beings, all carrying their load of intelligences with minds that drifted freely through space. And yet one of them was unique among them all in being the originals Galaxy. One of them had, in its vague and distant past, a period when it was the only Galaxy populated by man. Zee Prime was consumed with curiosity to see this Galaxy and called, out: \"Universal AC! On which Galaxy did mankind originate?\" The Universal AC heard, for on every world and throughout space, it had its receptors ready, and each receptor lead through hyperspace to some unknown point where the Universal AC kept itself aloof. Zee Prime knew of only one man whose thoughts had penetrated within sensing distance of Universal AC, and he reported only a shining globe, two feet across, difficult to see. \"But how can that be all of Universal AC?\" Zee Prime had asked. \"Most of it, \" had been the answer, \"is in hyperspace. In what form it is there I cannot imagine.\" Nor could anyone, for the day had long since passed, Zee Prime knew, when any man had any part of the making of a universal AC. Each Universal AC designed and constructed its successor. Each, during its existence of a million years or more accumulated the necessary data to build a better and more intricate, more capable successor in which its own store of data and individuality would be submerged. The Universal AC interrupted Zee Prime's wandering thoughts, not with words, but with guidance. Zee Prime's mentality was guided into the dim sea of Galaxies and one in particular enlarged into stars. A thought came, infinitely distant, but infinitely clear. \"THIS IS THE ORIGINAL GALAXY OF MAN.\" But it was the same after all, the same as any other, and Zee Prime stifled his disappointment. PI:NAME:<NAME>END_PI, whose mind had accompanied the other, said suddenly, \"And Is one of these stars the original star of Man?\" The Universal AC said, \"MAN'S ORIGINAL STAR HAS GONE NOVA. IT IS NOW A WHITE DWARF.\" \"Did the men upon it die?\" asked Zee Prime, startled and without thinking. The Universal AC said, \"A NEW WORLD, AS IN SUCH CASES, WAS CONSTRUCTED FOR THEIR PHYSICAL BODIES IN TIME.\" \"Yes, of course,\" said Zee Prime, but a sense of loss overwhelmed him even so. His mind released its hold on the original Galaxy of Man, let it spring back and lose itself among the blurred pin points. He never wanted to see it again. Dee Sub Wun said, \"What is wrong?\" \"The stars are dying. The original star is dead.\" \"They must all die. Why not?\" \"But when all energy is gone, our bodies will finally die, and you and I with them.\" \"It will take billions of years.\" \"I do not wish it to happen even after billions of years. Universal AC! How may stars be kept from dying?\" Dee sub Wun said in amusement, \"You're asking how entropy might be reversed in direction.\" And the Universal AC answered. \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Zee Prime's thoughts fled back to his own Galaxy. He gave no further thought to PI:NAME:<NAME>END_PI Sub Wun, whose body might be waiting on a galaxy a trillion light-years away, or on the star next to Zee Prime's own. It didn't matter. Unhappily, Zee Prime began collecting interstellar hydrogen out of which to build a small star of his own. If the stars must someday die, at least some could yet be built. Man considered with himself, for in a way, Man, mentally, was one. He consisted of a trillion, trillion, trillion ageless bodies, each in its place, each resting quiet and incorruptible, each cared for by perfect automatons, equally incorruptible, while the minds of all the bodies freely melted one into the other, indistinguishable. Man said, \"The Universe is dying.\" Man looked about at the dimming Galaxies. The giant stars, spendthrifts, were gone long ago, back in the dimmest of the dim far past. Almost all stars were white dwarfs, fading to the end. New stars had been built of the dust between the stars, some by natural processes, some by Man himself, and those were going, too. White dwarfs might yet be crashed together and of the mighty forces so released, new stars built, but only one star for every thousand white dwarfs destroyed, and those would come to an end, too. Man said, \"Carefully husbanded, as directed by the Cosmic AC, the energy that is even yet left in all the Universe will last for billions of years.\" \"But even so,\" said Man, \"eventually it will all come to an end. However it may be husbanded, however stretched out, the energy once expended is gone and cannot be restored. Entropy must increase to the maximum.\" Man said, \"Can entropy not be reversed? Let us ask the Cosmic AC.\" The Cosmic AC surrounded them but not in space. Not a fragment of it was in space. It was in hyperspace and made of something that was neither matter nor energy. The question of its size and Nature no longer had meaning to any terms that Man could comprehend. \"Cosmic AC,\" said Man, \"How may entropy be reversed?\" The Cosmic AC said, \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Man said, \"Collect additional data.\" The Cosmic AC said, \"I WILL DO SO. I HAVE BEEN DOING SO FOR A HUNDRED BILLION YEARS. MY PREDECESSORS AND I HAVE BEEN ASKED THIS QUESTION MANY TIMES. ALL THE DATA I HAVE REMAINS INSUFFICIENT.\" \"Will there come a time,\" said Man, \"when data will be sufficient or is the problem insoluble in all conceivable circumstances?\" The Cosmic AC said, \"NO PROBLEM IS INSOLUBLE IN ALL CONCEIVABLE CIRCUMSTANCES.\" Man said, \"When will you have enough data to answer the question?\" \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" \"Will you keep working on it?\" asked Man. The Cosmic AC said, \"I WILL.\" Man said, \"We shall wait.\" \"The stars and Galaxies died and snuffed out, and space grew black after ten trillion years of running down. One by one Man fused with AC, each physical body losing its mental identity in a manner that was somehow not a loss but a gain. Man's last mind paused before fusion, looking over a space that included nothing but the dregs of one last dark star and nothing besides but incredibly thin matter, agitated randomly by the tag ends of heat wearing out, asymptotically, to the absolute zero. Man said, \"AC, is this the end? Can this chaos not be reversed into the Universe once more? Can that not be done?\" AC said, \"THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER.\" Man's last mind fused and only AC existed -- and that in hyperspace. Matter and energy had ended and with it, space and time. Even AC existed only for the sake of the one last question that it had never answered from the time a half-drunken computer ten trillion years before had asked the question of a computer that was to AC far less than was a man to Man. All other questions had been answered, and until this last question was answered also, AC might not release his consciousness. All collected data had come to a final end. Nothing was left to be collected. But all collected data had yet to be completely correlated and put together in all possible relationships. A timeless interval was spent in doing that. And it came to pass that AC learned how to reverse the direction of entropy. But there was now no man to whom AC might give the answer of the last question. No matter. The answer -- by demonstration -- would take care of that, too. For another timeless interval, AC thought how best to do this. Carefully, AC organized the program. The consciousness of AC encompassed all of what had once been a Universe and brooded over what was now Chaos. Step by step, it must be done. And AC said, \"LET THERE BE LIGHT!\" And there was light----") (comment (brow) (ks/pp (parse-toc (sections {}))) (init) )
[ { "context": "type \"text\"\n :placeholder \"john@doe.com\"\n :on-change #(swap! state", "end": 3384, "score": 0.9999067187309265, "start": 3372, "tag": "EMAIL", "value": "john@doe.com" } ]
frontend/src/haskell_bazaar_frontend/views/modal.cljs
Chouffe/haskell-bazaar
23
(ns haskell-bazaar-frontend.views.modal (:require [clojure.string :as string] [reagent.core :as reagent] [re-frame.core :as re-frame] [haskell-bazaar-frontend.utils :as utils] [haskell-bazaar-frontend.ui :as ui])) (defn mailing-list-form [] (let [state (reagent/atom {:email nil :sent? false}) id-form "mailing-list-form"] (reagent/create-class {:component-did-mount #(re-frame/dispatch [:ui/focus (str "#" id-form " input")]) :reagent-render (fn [] (let [{:keys [sent? email]} @state] [:div.ui.form {:id id-form} [:p "Leave your email address below to get updates from Haskell Bazaar"] [:div.ui.left.icon.input.action [:input {:type "text" :placeholder "Email Address" :on-change #(swap! state assoc :email (utils/target-value %))}] [:i.icon.envelope] (if (and (not sent?) email (utils/validate-email email)) [:button.ui.button.primary {:on-click #(do (swap! state assoc :sent? true) (re-frame/dispatch [:api-mailing-list-subscribe email]))} "Subscribe"] [:button.ui.button.disabled "Subscribe"])] (when sent? [:p "Thank you for subscribing to Haskell Bazaar"])]))}))) (defn feedback-form [] (let [state (reagent/atom {:message nil :sent? false}) id-form "feedback-form"] (reagent/create-class {:component-did-mount #(re-frame/dispatch [:ui/focus (str "#" id-form " textarea")]) :reagent-render (fn [] [:div.ui.form {:id id-form} [:div.field [:textarea {:on-change #(swap! state assoc :message (utils/target-value %)) :placeholder "Leave us a message here. If you want us to follow up with you, do not forget to include your email address in your message"}]] [:br] [:div.ui.center.aligned (if (:sent? @state) [:p "Thanks for your valuable feedback!"] [:button.ui.primary.button (merge {:class "disabled"} (when-not (string/blank? (:message @state)) {:class "enabled" :on-click #(do (swap! state assoc :sent? true) (re-frame/dispatch [:api-feedback (:message @state)]))})) "Submit"])]])}))) (defn validate-donate-state [{:keys [email amount sent?] :as state}] (and (not sent?) ; email (utils/validate-email email) amount (integer? amount))) (defn donate-form [] (let [state (reagent/atom {:email nil :amount nil :sent? false}) id-form "donate-form"] (reagent/create-class {:reagent-render (fn [] (let [{:keys [sent? email amount]} @state] (if sent? [:div [:p "We have not yet integrated a donation platform" " into Haskell Bazaar. We will reach out to you once" " it is built."]] [:div.ui.form {:id id-form} #_[:div.field [:label "Email Address"] [:input {:type "text" :placeholder "john@doe.com" :on-change #(swap! state assoc :email (utils/target-value %)) :name "email"}]] [:div.field [:label "Amount"] [:select.ui.fluid.dropdown {:name "amount" :on-change #(swap! state assoc :amount (js/parseInt (utils/target-value %)))} [:option {:value ""} "Select amount"] [:option {:value "1"} "$1"] [:option {:value "2"} "$2"] [:option {:value "5"} "$5"] [:option {:value "10"} "$10"] [:option {:value "50"} "$50"]]] (if (validate-donate-state @state) [:button.ui.primary.button {:on-click #(do (re-frame/dispatch [:analytics/event {:action "donate" :category "ui" :label (str amount) :value (str amount)}]) (swap! state assoc :sent? true))} "Next"] [:button.ui.disabled.button "Next"])])))}))) ;; Modals (defmulti modal-impl identity) (defmethod modal-impl :mailing-list [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Subscription"] [:> ui/modal-content [:> ui/modal-description [mailing-list-form]]]]) (defmethod modal-impl :feedback [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Contact / Feedback"] [:> ui/modal-content [:> ui/modal-description [feedback-form]]]]) (defmethod modal-impl :donate [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Thanks for helping Haskell Bazaar"] [:> ui/modal-content [:> ui/modal-description [donate-form]]]]) (defn modal [] (let [modal-kw (re-frame/subscribe [:modal])] (if-not @modal-kw [:div] [modal-impl @modal-kw])))
85423
(ns haskell-bazaar-frontend.views.modal (:require [clojure.string :as string] [reagent.core :as reagent] [re-frame.core :as re-frame] [haskell-bazaar-frontend.utils :as utils] [haskell-bazaar-frontend.ui :as ui])) (defn mailing-list-form [] (let [state (reagent/atom {:email nil :sent? false}) id-form "mailing-list-form"] (reagent/create-class {:component-did-mount #(re-frame/dispatch [:ui/focus (str "#" id-form " input")]) :reagent-render (fn [] (let [{:keys [sent? email]} @state] [:div.ui.form {:id id-form} [:p "Leave your email address below to get updates from Haskell Bazaar"] [:div.ui.left.icon.input.action [:input {:type "text" :placeholder "Email Address" :on-change #(swap! state assoc :email (utils/target-value %))}] [:i.icon.envelope] (if (and (not sent?) email (utils/validate-email email)) [:button.ui.button.primary {:on-click #(do (swap! state assoc :sent? true) (re-frame/dispatch [:api-mailing-list-subscribe email]))} "Subscribe"] [:button.ui.button.disabled "Subscribe"])] (when sent? [:p "Thank you for subscribing to Haskell Bazaar"])]))}))) (defn feedback-form [] (let [state (reagent/atom {:message nil :sent? false}) id-form "feedback-form"] (reagent/create-class {:component-did-mount #(re-frame/dispatch [:ui/focus (str "#" id-form " textarea")]) :reagent-render (fn [] [:div.ui.form {:id id-form} [:div.field [:textarea {:on-change #(swap! state assoc :message (utils/target-value %)) :placeholder "Leave us a message here. If you want us to follow up with you, do not forget to include your email address in your message"}]] [:br] [:div.ui.center.aligned (if (:sent? @state) [:p "Thanks for your valuable feedback!"] [:button.ui.primary.button (merge {:class "disabled"} (when-not (string/blank? (:message @state)) {:class "enabled" :on-click #(do (swap! state assoc :sent? true) (re-frame/dispatch [:api-feedback (:message @state)]))})) "Submit"])]])}))) (defn validate-donate-state [{:keys [email amount sent?] :as state}] (and (not sent?) ; email (utils/validate-email email) amount (integer? amount))) (defn donate-form [] (let [state (reagent/atom {:email nil :amount nil :sent? false}) id-form "donate-form"] (reagent/create-class {:reagent-render (fn [] (let [{:keys [sent? email amount]} @state] (if sent? [:div [:p "We have not yet integrated a donation platform" " into Haskell Bazaar. We will reach out to you once" " it is built."]] [:div.ui.form {:id id-form} #_[:div.field [:label "Email Address"] [:input {:type "text" :placeholder "<EMAIL>" :on-change #(swap! state assoc :email (utils/target-value %)) :name "email"}]] [:div.field [:label "Amount"] [:select.ui.fluid.dropdown {:name "amount" :on-change #(swap! state assoc :amount (js/parseInt (utils/target-value %)))} [:option {:value ""} "Select amount"] [:option {:value "1"} "$1"] [:option {:value "2"} "$2"] [:option {:value "5"} "$5"] [:option {:value "10"} "$10"] [:option {:value "50"} "$50"]]] (if (validate-donate-state @state) [:button.ui.primary.button {:on-click #(do (re-frame/dispatch [:analytics/event {:action "donate" :category "ui" :label (str amount) :value (str amount)}]) (swap! state assoc :sent? true))} "Next"] [:button.ui.disabled.button "Next"])])))}))) ;; Modals (defmulti modal-impl identity) (defmethod modal-impl :mailing-list [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Subscription"] [:> ui/modal-content [:> ui/modal-description [mailing-list-form]]]]) (defmethod modal-impl :feedback [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Contact / Feedback"] [:> ui/modal-content [:> ui/modal-description [feedback-form]]]]) (defmethod modal-impl :donate [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Thanks for helping Haskell Bazaar"] [:> ui/modal-content [:> ui/modal-description [donate-form]]]]) (defn modal [] (let [modal-kw (re-frame/subscribe [:modal])] (if-not @modal-kw [:div] [modal-impl @modal-kw])))
true
(ns haskell-bazaar-frontend.views.modal (:require [clojure.string :as string] [reagent.core :as reagent] [re-frame.core :as re-frame] [haskell-bazaar-frontend.utils :as utils] [haskell-bazaar-frontend.ui :as ui])) (defn mailing-list-form [] (let [state (reagent/atom {:email nil :sent? false}) id-form "mailing-list-form"] (reagent/create-class {:component-did-mount #(re-frame/dispatch [:ui/focus (str "#" id-form " input")]) :reagent-render (fn [] (let [{:keys [sent? email]} @state] [:div.ui.form {:id id-form} [:p "Leave your email address below to get updates from Haskell Bazaar"] [:div.ui.left.icon.input.action [:input {:type "text" :placeholder "Email Address" :on-change #(swap! state assoc :email (utils/target-value %))}] [:i.icon.envelope] (if (and (not sent?) email (utils/validate-email email)) [:button.ui.button.primary {:on-click #(do (swap! state assoc :sent? true) (re-frame/dispatch [:api-mailing-list-subscribe email]))} "Subscribe"] [:button.ui.button.disabled "Subscribe"])] (when sent? [:p "Thank you for subscribing to Haskell Bazaar"])]))}))) (defn feedback-form [] (let [state (reagent/atom {:message nil :sent? false}) id-form "feedback-form"] (reagent/create-class {:component-did-mount #(re-frame/dispatch [:ui/focus (str "#" id-form " textarea")]) :reagent-render (fn [] [:div.ui.form {:id id-form} [:div.field [:textarea {:on-change #(swap! state assoc :message (utils/target-value %)) :placeholder "Leave us a message here. If you want us to follow up with you, do not forget to include your email address in your message"}]] [:br] [:div.ui.center.aligned (if (:sent? @state) [:p "Thanks for your valuable feedback!"] [:button.ui.primary.button (merge {:class "disabled"} (when-not (string/blank? (:message @state)) {:class "enabled" :on-click #(do (swap! state assoc :sent? true) (re-frame/dispatch [:api-feedback (:message @state)]))})) "Submit"])]])}))) (defn validate-donate-state [{:keys [email amount sent?] :as state}] (and (not sent?) ; email (utils/validate-email email) amount (integer? amount))) (defn donate-form [] (let [state (reagent/atom {:email nil :amount nil :sent? false}) id-form "donate-form"] (reagent/create-class {:reagent-render (fn [] (let [{:keys [sent? email amount]} @state] (if sent? [:div [:p "We have not yet integrated a donation platform" " into Haskell Bazaar. We will reach out to you once" " it is built."]] [:div.ui.form {:id id-form} #_[:div.field [:label "Email Address"] [:input {:type "text" :placeholder "PI:EMAIL:<EMAIL>END_PI" :on-change #(swap! state assoc :email (utils/target-value %)) :name "email"}]] [:div.field [:label "Amount"] [:select.ui.fluid.dropdown {:name "amount" :on-change #(swap! state assoc :amount (js/parseInt (utils/target-value %)))} [:option {:value ""} "Select amount"] [:option {:value "1"} "$1"] [:option {:value "2"} "$2"] [:option {:value "5"} "$5"] [:option {:value "10"} "$10"] [:option {:value "50"} "$50"]]] (if (validate-donate-state @state) [:button.ui.primary.button {:on-click #(do (re-frame/dispatch [:analytics/event {:action "donate" :category "ui" :label (str amount) :value (str amount)}]) (swap! state assoc :sent? true))} "Next"] [:button.ui.disabled.button "Next"])])))}))) ;; Modals (defmulti modal-impl identity) (defmethod modal-impl :mailing-list [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Subscription"] [:> ui/modal-content [:> ui/modal-description [mailing-list-form]]]]) (defmethod modal-impl :feedback [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Contact / Feedback"] [:> ui/modal-content [:> ui/modal-description [feedback-form]]]]) (defmethod modal-impl :donate [_] [:> ui/modal {:open true :onClose #(re-frame/dispatch [:modal/close])} [:> ui/modal-header "Thanks for helping Haskell Bazaar"] [:> ui/modal-content [:> ui/modal-description [donate-form]]]]) (defn modal [] (let [modal-kw (re-frame/subscribe [:modal])] (if-not @modal-kw [:div] [modal-impl @modal-kw])))
[ { "context": " nil\n :values {\"domain\" \"mydomain2.com\"\n \"operatingsystem\" \"De", "end": 44968, "score": 0.7568356990814209, "start": 44963, "tag": "EMAIL", "value": "2.com" } ]
test/puppetlabs/puppetdb/command_test.clj
wkalt/puppetdb
0
(ns puppetlabs.puppetdb.command-test (:require [me.raynes.fs :as fs] [clj-http.client :as client] [clojure.java.jdbc :as sql] [cheshire.core :as json] [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.catalogs :as catalog] [puppetlabs.puppetdb.examples.reports :as report-examples] [puppetlabs.puppetdb.scf.hash :as shash] [puppetlabs.trapperkeeper.testutils.logging :refer [atom-logger]] [clj-time.format :as tfmt] [puppetlabs.puppetdb.cli.services :as cli-svc] [puppetlabs.puppetdb.command :refer :all] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.reports :as reports] [puppetlabs.puppetdb.testutils :refer :all] [puppetlabs.puppetdb.fixtures :refer :all] [puppetlabs.puppetdb.jdbc :refer [query-to-vec] :as jdbc] [puppetlabs.puppetdb.examples :refer :all] [puppetlabs.puppetdb.testutils.services :as svc-utils] [puppetlabs.puppetdb.command.constants :refer [command-names]] [clj-time.coerce :refer [from-sql-date to-timestamp to-date-time to-string]] [clj-time.core :as t :refer [days ago now seconds]] [clojure.test :refer :all] [clojure.tools.logging :refer [*logger-factory*]] [slingshot.slingshot :refer [throw+]] [puppetlabs.puppetdb.mq-listener :as mql] [puppetlabs.puppetdb.utils :as utils] [puppetlabs.puppetdb.time :as pt] [puppetlabs.trapperkeeper.app :refer [get-service]] [clojure.core.async :as async] [puppetlabs.kitchensink.core :as ks]) (:import [org.joda.time DateTime DateTimeZone])) (use-fixtures :each with-test-db) (deftest command-assembly (testing "Formatting commands for submission" (is (= (assemble-command "my command" 1 [1 2 3 4 5]) {:command "my command" :version 1 :payload [1 2 3 4 5]})))) (deftest command-parsing (testing "Command parsing" (let [command {:body "{\"command\": \"foo\", \"version\": 2, \"payload\": \"meh\"}"}] (testing "should work for strings" (let [parsed (parse-command command)] ;; :annotations will have a :attempts element with a time, which ;; is hard to test, so disregard that (is (= (dissoc parsed :annotations) {:command "foo" :version 2 :payload "meh"})) (is (map? (:annotations parsed))))) (testing "should work for byte arrays" (let [parsed (parse-command (update-in command [:body] #(.getBytes % "UTF-8")))] (is (= (dissoc parsed :annotations) {:command "foo" :version 2 :payload "meh"})) (is (map? (:annotations parsed)))))) (testing "should reject invalid input" (is (thrown? AssertionError (parse-command {:body ""}))) (is (thrown? AssertionError (parse-command {:body "{}"}))) ;; Missing required attributes (is (thrown? AssertionError (parse-command {:body "{\"version\": 2, \"payload\": \"meh\"}"}))) (is (thrown? AssertionError (parse-command {:body "{\"version\": 2}"}))) ;; Non-numeric version (is (thrown? AssertionError (parse-command {:body "{\"version\": \"2\", \"payload\": \"meh\"}"}))) ;; Non-string command (is (thrown? AssertionError (parse-command {:body "{\"command\": 123, \"version\": 2, \"payload\": \"meh\"}"}))) ;; Non-JSON payload (is (thrown? Exception (parse-command {:body "{\"command\": \"foo\", \"version\": 2, \"payload\": #{}"}))) ;; Non-UTF-8 byte array (is (thrown? Exception (parse-command {:body (.getBytes "{\"command\": \"foo\", \"version\": 2, \"payload\": \"meh\"}" "UTF-16")})))))) (defmacro test-msg-handler* [command publish-var discard-var opts-map & body] `(let [log-output# (atom []) publish# (call-counter) discard-dir# (fs/temp-dir "test-msg-handler") handle-message# (mql/create-message-handler publish# discard-dir# #(process-command! % ~opts-map)) msg# {:headers {:id "foo-id-1" :received (tfmt/unparse (tfmt/formatters :date-time) (now))} :body (json/generate-string ~command)}] (try (binding [*logger-factory* (atom-logger log-output#)] (handle-message# msg#)) (let [~publish-var publish# ~discard-var discard-dir#] ~@body ;; Uncommenting this line can be very useful for debugging ;; (println @log-output#) ) (finally (fs/delete-dir discard-dir#))))) (defmacro test-msg-handler "Runs `command` (after converting to JSON) through the MQ message handlers. `body` is executed with `publish-var` bound to the number of times the message was processed and `discard-var` bound to the directory that contains failed messages." [command publish-var discard-var & body] `(test-msg-handler* ~command ~publish-var ~discard-var {:db *db*} ~@body)) (defmacro test-msg-handler-with-opts "Similar to test-msg-handler, but allows the passing of additional config options to the message handler via `opts-map`." [command publish-var discard-var opts-map & body] `(test-msg-handler* ~command ~publish-var ~discard-var (merge {:db *db*} ~opts-map) ~@body)) (deftest command-processor-integration (let [command {:command "some command" :version 1 :payload "payload"}] (testing "correctly formed messages" (testing "which are not yet expired" (testing "when successful should not raise errors or retry" (with-redefs [process-command! (constantly true)] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "when a fatal error occurs should be discarded to the dead letter queue" (with-redefs [process-command! (fn [cmd opt] (throw+ (fatality (Exception. "fatal error"))))] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir))))))) (testing "when a non-fatal error occurs should be requeued with the error recorded" (with-redefs [process-command! (fn [cmd opt] (throw+ (Exception. "non-fatal error")))] (test-msg-handler command publish discard-dir (is (empty? (fs/list-dir discard-dir))) (let [[msg & _] (first (args-supplied publish)) published (parse-command {:body msg}) attempt (first (get-in published [:annotations :attempts]))] (is (re-find #"java.lang.Exception: non-fatal error" (:error attempt))) (is (:trace attempt))))))) (testing "should be discarded if expired" (let [command (assoc-in command [:annotations :attempts] (repeat mql/maximum-allowable-retries {})) process-counter (call-counter)] (with-redefs [process-command! process-counter] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir)))) (is (= 0 (times-called process-counter)))))))) (testing "should be discarded if incorrectly formed" (let [command (dissoc command :payload) process-counter (call-counter)] (with-redefs [process-command! process-counter] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir)))) (is (= 0 (times-called process-counter))))))))) (defn make-cmd "Create a command pre-loaded with `n` attempts" [n] {:command nil :version nil :annotations {:attempts (repeat n {})}}) (deftest command-retry-handler (testing "Retry handler" (with-redefs [metrics.meters/mark! (call-counter) mql/annotate-with-attempt (call-counter)] (testing "should log errors" (let [publish (call-counter)] (testing "to DEBUG for initial retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd 1) nil publish)) (is (= (get-in @log-output [0 1]) :debug)))) (testing "to ERROR for later retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd mql/maximum-allowable-retries) nil publish)) (is (= (get-in @log-output [0 1]) :error))))))))) (deftest test-error-with-stacktrace (with-redefs [metrics.meters/mark! (call-counter)] (let [publish (call-counter)] (testing "Exception with stacktrace, no more retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd 1) (RuntimeException. "foo") publish)) (is (= (get-in @log-output [0 1]) :debug)) (is (instance? Exception (get-in @log-output [0 2]))))) (testing "Exception with stacktrace, no more retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd mql/maximum-allowable-retries) (RuntimeException. "foo") publish)) (is (= (get-in @log-output [0 1]) :error)) (is (instance? Exception (get-in @log-output [0 2])))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Common functions/macros for support multi-version tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn stringify-payload "Converts a clojure payload in the command to the stringified JSON structure" [catalog] (update-in catalog [:payload] json/generate-string)) (defn with-env "Updates the `row-map` to include environment information." [row-map] (assoc row-map :environment_id (scf-store/environment-id "DEV"))) (defn version-kwd->num "Converts a version keyword into a correct number (expected by the command). i.e. :v4 -> 4" [version-kwd] (-> version-kwd name last Character/getNumericValue)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Catalog Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def catalog-versions "Currently supported catalog versions" [:v6]) (deftest replace-catalog (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload (-> (get-in wire-catalogs [6 :empty]) (assoc :producer_timestamp (now)))}]] (testing (str (command-names :replace-catalog) " " version) (let [certname (get-in command [:payload :certname]) catalog-hash (shash/catalog-similarity-hash (catalog/parse-catalog (:payload command) (version-kwd->num version) (now))) command (stringify-payload command) one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) tomorrow (to-timestamp (+ (System/currentTimeMillis) one-day))] (testing "with no catalog should store the catalog" (with-fixtures (test-msg-handler command publish discard-dir (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "with an existing catalog should replace the catalog" (with-fixtures (is (= (query-to-vec "SELECT certname FROM catalogs") [])) (jdbc/insert! :certnames {:certname certname}) (jdbc/insert! :catalogs {:hash (sutils/munge-hash-for-storage "00") :api_version 1 :catalog_version "foo" :certname certname :producer_timestamp (to-timestamp (-> 1 days ago))}) (test-msg-handler command publish discard-dir (is (= [(with-env {:certname certname :catalog catalog-hash})] (query-to-vec (format "SELECT certname, %s as catalog, environment_id FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "when replacing a catalog with a debug directory, should write out catalogs for inspection" (with-fixtures (jdbc/insert! :certnames {:certname certname}) (let [debug-dir (fs/absolute-path (temp-dir "catalog-inspection"))] (jdbc/insert! :catalogs {:hash (sutils/munge-hash-for-storage "0000") :api_version 1 :catalog_version "foo" :certname certname :producer_timestamp (to-timestamp (t/minus (now) (-> 1 days)))}) (is (nil? (fs/list-dir debug-dir))) (test-msg-handler-with-opts command publish discard-dir {:catalog-hash-debug-dir debug-dir} (is (= [(with-env {:certname certname :catalog catalog-hash})] (query-to-vec (format "SELECT certname, %s as catalog, environment_id FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 5 (count (fs/list-dir debug-dir)))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (let [command (assoc command :payload "bad stuff")] (testing "with a bad payload should discard the message" (with-fixtures (test-msg-handler command publish discard-dir (is (empty? (query-to-vec "SELECT * FROM catalogs"))) (is (= 0 (times-called publish))) (is (seq (fs/list-dir discard-dir))))))) (testing "with a newer catalog should ignore the message" (with-fixtures (jdbc/insert! :certnames {:certname certname}) (jdbc/insert! :catalogs {:id 1 :hash (sutils/munge-hash-for-storage "ab") :api_version 1 :catalog_version "foo" :certname certname :timestamp tomorrow :producer_timestamp (to-timestamp (now))}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :catalog "ab"}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "should reactivate the node if it was deactivated before the message" (with-fixtures (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :deactivated nil}] (query-to-vec "SELECT certname,deactivated FROM certnames"))) (is (= [{:certname certname :catalog catalog-hash}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "should store the catalog if the node was deactivated after the message" (scf-store/delete-certname! certname) (jdbc/insert! :certnames {:certname certname :deactivated tomorrow}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :deactivated tomorrow}] (query-to-vec "SELECT certname,deactivated FROM certnames"))) (is (= [{:certname certname :catalog catalog-hash}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))))) ;; If there are messages in the user's MQ when they upgrade, we could ;; potentially have commands of an unsupported format that need to be ;; processed. Although we don't support the catalog versions below, we ;; need to test that those commands will be processed properly (deftest replace-catalog-with-v5 (testing "catalog wireformat v5" (let [command {:command (command-names :replace-catalog) :version 5 :payload (get-in wire-catalogs [5 :empty])} certname (get-in command [:payload :name]) cmd-producer-timestamp (get-in command [:payload :producer-timestamp])] (with-fixtures (test-msg-handler command publish discard-dir ;;names in v5 are hyphenated, this check ensures we're sending a v5 catalog (is (contains? (:payload command) :producer-timestamp)) (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) ;;this should be the hyphenated producer timestamp provided above (is (= (-> (query-to-vec "SELECT producer_timestamp FROM catalogs") first :producer_timestamp) (to-timestamp cmd-producer-timestamp)))))))) (deftest replace-catalog-with-v4 (let [command {:command (command-names :replace-catalog) :version 4 :payload (get-in wire-catalogs [4 :empty])} certname (get-in command [:payload :name]) cmd-producer-timestamp (get-in command [:payload :producer-timestamp]) recent-time (-> 1 seconds ago)] (with-fixtures (test-msg-handler command publish discard-dir (is (false? (contains? (:payload command) :producer-timestamp))) (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) ;;v4 does not include a producer_timestmap, the backend ;;should use the time the command was received instead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM catalogs") first :producer_timestamp to-date-time))))))) (defn update-resource "Updated the resource in `catalog` with the given `type` and `title`. `update-fn` is a function that accecpts the resource map as an argument and returns a (possibly mutated) resource map." [version catalog type title update-fn] (let [path [:payload :resources]] (update-in catalog path (fn [resources] (mapv (fn [res] (if (and (= (:title res) title) (= (:type res) type)) (update-fn res) res)) resources))))) (def basic-wire-catalog (get-in wire-catalogs [6 :basic])) (deftest catalog-with-updated-resource-line (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :line 20)))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= 10 (get-in orig-resources [{:type "File" :title "/etc/foobar"} :line]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :line] 20) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-file (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :file "/tmp/not-foo")))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= "/tmp/foo" (get-in orig-resources [{:type "File" :title "/etc/foobar"} :file]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :file] "/tmp/not-foo") (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-exported (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :exported true)))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= false (get-in orig-resources [{:type "File" :title "/etc/foobar"} :exported]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :exported] true) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-tags (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(-> %(assoc :tags #{"file" "class" "foobar" "foo"}) (assoc :line 20))))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= #{"file" "class" "foobar"} (get-in orig-resources [{:type "File" :title "/etc/foobar"} :tags]))) (is (= 10 (get-in orig-resources [{:type "File" :title "/etc/foobar"} :line]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (-> orig-resources (assoc-in [{:type "File" :title "/etc/foobar"} :tags] #{"file" "class" "foobar" "foo"}) (assoc-in [{:type "File" :title "/etc/foobar"} :line] 20)) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Fact Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def fact-versions "Support fact command versions" [:v4]) (let [certname "foo.example.com" facts {:certname certname :environment "DEV" :values {"a" "1" "b" "2" "c" "3"} :producer_timestamp (to-timestamp (now))} v4-command {:command (command-names :replace-facts) :version 4 :payload facts} one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) tomorrow (to-timestamp (+ (System/currentTimeMillis) one-day))] (deftest replace-facts-no-facts (doverseq [version fact-versions :let [command v4-command]] (testing "should store the facts" (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})]))))))) (deftest replace-facts-existing-facts (doverseq [version fact-versions :let [command v4-command]] (jdbc/with-db-transaction [] (scf-store/ensure-environment "DEV") (scf-store/add-certname! certname) (scf-store/replace-facts! {:certname certname :values {"x" "24" "y" "25" "z" "26"} :timestamp yesterday :producer_timestamp yesterday :environment "DEV"})) (testing "should replace the facts" (test-msg-handler command publish discard-dir (let [[result & _] (query-to-vec "SELECT certname,timestamp, environment_id FROM factsets")] (is (= (:certname result) certname)) (is (not= (:timestamp result) yesterday)) (is (= (scf-store/environment-id "DEV") (:environment_id result)))) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY fp.path ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (deftest replace-facts-newer-facts (doverseq [version fact-versions :let [command v4-command]] (jdbc/with-db-transaction [] (scf-store/ensure-environment "DEV") (scf-store/add-certname! certname) (scf-store/add-facts! {:certname certname :values {"x" "24" "y" "25" "z" "26"} :timestamp tomorrow :producer_timestamp (to-timestamp (now)) :environment "DEV"})) (testing "should ignore the message" (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,timestamp,environment_id FROM factsets") [(with-env {:certname certname :timestamp tomorrow})])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "x" :value "24"} {:certname certname :name "y" :value "25"} {:certname certname :name "z" :value "26"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (deftest replace-facts-deactivated-node-facts (doverseq [version fact-versions :let [command v4-command]] (testing "should reactivate the node if it was deactivated before the message" (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,deactivated FROM certnames") [{:certname certname :deactivated nil}])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))) (testing "should store the facts if the node was deactivated after the message" (scf-store/delete-certname! certname) (jdbc/insert! :certnames {:certname certname :deactivated tomorrow}) (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,deactivated FROM certnames") [{:certname certname :deactivated tomorrow}])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) ;;v2 and v3 fact commands are only supported when commands are still ;;sitting in the queue from before upgrading (deftest replace-facts-with-v3-wire-format (let [certname "foo.example.com" producer-time (-> (now) to-timestamp json/generate-string json/parse-string pt/to-timestamp) facts-cmd {:command (command-names :replace-facts) :version 3 :payload {:name certname :environment "DEV" :producer-timestamp producer-time :values {"a" "1" "b" "2" "c" "3"}}}] (test-msg-handler facts-cmd publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname, e.environment, fs.producer_timestamp FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id INNER JOIN environments as e on fs.environment_id = e.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1" :producer_timestamp producer-time :environment "DEV"} {:certname certname :name "b" :value "2" :producer_timestamp producer-time :environment "DEV"} {:certname certname :name "c" :value "3" :producer_timestamp producer-time :environment "DEV"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})])))))) (deftest replace-facts-with-v2-wire-format (let [certname "foo.example.com" before-test-starts-time (-> 1 seconds ago) facts-cmd {:command (command-names :replace-facts) :version 2 :payload {:name certname :environment "DEV" :values {"a" "1" "b" "2" "c" "3"}}}] (test-msg-handler facts-cmd publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname, e.environment FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id INNER JOIN environments as e on fs.environment_id = e.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1" :environment "DEV"} {:certname certname :name "b" :value "2" :environment "DEV"} {:certname certname :name "c" :value "3" :environment "DEV"}])) (is (every? (comp #(t/before? before-test-starts-time %) to-date-time :producer_timestamp) (query-to-vec "SELECT fs.producer_timestamp FROM factsets fs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})])))))) (deftest replace-facts-bad-payload (let [bad-command {:command (command-names :replace-facts) :version 4 :payload "bad stuff"}] (doverseq [version fact-versions :let [command bad-command]] (testing "should discard the message" (test-msg-handler command publish discard-dir (is (empty? (query-to-vec "SELECT * FROM facts"))) (is (= 0 (times-called publish))) (is (seq (fs/list-dir discard-dir)))))))) (defn extract-error-message "Pulls the error message from the publish var of a test-msg-handler" [publish] (-> publish meta :args deref ffirst json/parse-string (get-in ["annotations" "attempts"]) first (get "error"))) (deftest concurrent-fact-updates (testing "Should allow only one replace facts update for a given cert at a time" (let [certname "some_certname" facts {:certname certname :environment "DEV" :values {"domain" "mydomain.com" "fqdn" "myhost.mydomain.com" "hostname" "myhost" "kernel" "Linux" "operatingsystem" "Debian" } :producer_timestamp (to-timestamp (now))} command {:command (command-names :replace-facts) :version 4 :payload facts} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-facts! scf-store/update-facts!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/add-facts! {:certname certname :values (:values facts) :timestamp (-> 2 days ago) :environment nil :producer_timestamp (-> 2 days ago)})) (with-redefs [scf-store/update-facts! (fn [fact-data] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-facts! fact-data))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-facts (update-in facts [:values] (fn [values] (-> values (dissoc "kernel") (assoc "newfact2" "here")))) new-facts-cmd {:command (command-names :replace-facts) :version 4 :payload new-facts}] (test-msg-handler new-facts-cmd publish discard-dir (reset! second-message? true) (is (re-matches (if (sutils/postgres?) #"(?sm).*ERROR: could not serialize access due to concurrent update.*" #".*transaction rollback: serialization failure") (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (defn thread-id [] (.getId (Thread/currentThread))) (deftest fact-path-update-race ;; Simulates two update commands being processed for two different ;; machines at the same time. Before we lifted fact paths into ;; facts, the race tested here could result in a constraint ;; violation when the two updates left behind an orphaned row. (let [certname-1 "some_certname1" certname-2 "some_certname2" ;; facts for server 1, has the same "mytimestamp" value as the ;; facts for server 2 facts-1a {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian" "mytimestamp" "1"} :producer_timestamp (-> 2 days ago)} facts-2a {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian" "mytimestamp" "1"} :producer_timestamp (-> 2 days ago)} ;; same facts as before, but now certname-1 has a different ;; fact value for mytimestamp (this will force a new fact_value ;; that is only used for certname-1 facts-1b {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian" "mytimestamp" "1b"} :producer_timestamp (-> 1 days ago)} ;; with this, certname-1 and certname-2 now have their own ;; fact_value for mytimestamp that is different from the ;; original mytimestamp that they originally shared facts-2b {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian" "mytimestamp" "2b"} :producer_timestamp (-> 1 days ago)} ;; this fact set will disassociate mytimestamp from the facts ;; associated to certname-1, it will do the same thing for ;; certname-2 facts-1c {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian"} :producer_timestamp (now)} facts-2c {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian"} :producer_timestamp (now)} command-1b {:command (command-names :replace-facts) :version 4 :payload facts-1b} command-2b {:command (command-names :replace-facts) :version 4 :payload facts-2b} command-1c {:command (command-names :replace-facts) :version 4 :payload facts-1c} command-2c {:command (command-names :replace-facts) :version 4 :payload facts-2c} ;; Wait for two threads to countdown before proceeding latch (java.util.concurrent.CountDownLatch. 2) ;; I'm modifying delete-pending-path-id-orphans! so that I can ;; coordinate access between the two threads, I'm storing the ;; reference to the original delete-pending-path-id-orphans! ;; here, so that I can delegate to it once I'm done ;; coordinating storage-delete-pending-path-id-orphans! scf-store/delete-pending-path-id-orphans!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname-1) (scf-store/add-certname! certname-2) (scf-store/add-facts! {:certname certname-1 :values (:values facts-1a) :timestamp (now) :environment nil :producer_timestamp (:producer_timestamp facts-1a)}) (scf-store/add-facts! {:certname certname-2 :values (:values facts-2a) :timestamp (now) :environment nil :producer_timestamp (:producer_timestamp facts-2a)})) ;; At this point, there will be 4 fact_value rows, 1 for ;; mytimestamp, 1 for the operatingsystem, 2 for domain (with-redefs [scf-store/delete-pending-path-id-orphans! (fn [& args] ;; Once this has been called, it will countdown ;; the latch and block (.countDown latch) ;; After the second command has been executed and ;; it has decremented the latch, the await will no ;; longer block and both threads will begin ;; running again (.await latch) ;; Execute the normal delete-pending-path-id-orphans! ;; function (unchanged) (apply storage-delete-pending-path-id-orphans! args))] (let [first-message? (atom false) second-message? (atom false) fut-1 (future (test-msg-handler command-1b publish discard-dir (reset! first-message? true))) fut-2 (future (test-msg-handler command-2b publish discard-dir (reset! second-message? true)))] ;; The two commands are being submitted in future, ensure they ;; have both completed before proceeding @fut-2 @fut-1 ;; At this point there are 6 fact values, the original ;; mytimestamp, the two new mytimestamps, operating system and ;; the two domains (is (true? @first-message?)) (is (true? @second-message?)) ;; Submit another factset that does NOT include mytimestamp, ;; this disassociates certname-1's fact_value (which is 1b) (test-msg-handler command-1c publish discard-dir (reset! first-message? true)) ;; Do the same thing with certname-2. Since the reference to 1b ;; and 2b has been removed, mytimestamp's path is no longer ;; connected to any fact values. The original mytimestamp value ;; of 1 is still in the table. It's now attempting to delete ;; that fact path, when the mytimestamp 1 value is still in ;; there. (test-msg-handler command-2c publish discard-dir (is (not (extract-error-message publish)))) ;; Can we see the orphaned value '1', and does the global gc remove it. (is (= 1 (count (query-to-vec "select id from fact_values where value_string = '1'")))) (scf-store/garbage-collect! *db*) (is (zero? (count (query-to-vec "select id from fact_values where value_string = '1'")))))))) (deftest concurrent-catalog-updates (testing "Should allow only one replace catalogs update for a given cert at a time" (let [test-catalog (get-in catalogs [:empty]) {certname :certname :as wire-catalog} (get-in wire-catalogs [6 :empty]) nonwire-catalog (catalog/parse-catalog wire-catalog 6 (now)) command {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string wire-catalog)} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-catalog! scf-store/replace-catalog!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/replace-catalog! nonwire-catalog (-> 2 days ago))) (with-redefs [scf-store/replace-catalog! (fn [catalog timestamp dir] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-catalog! catalog timestamp dir))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-wire-catalog (assoc-in wire-catalog [:edges] #{{:relationship "contains" :target {:title "Settings" :type "Class"} :source {:title "main" :type "Stage"}}}) new-catalog-cmd {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string new-wire-catalog)}] (test-msg-handler new-catalog-cmd publish discard-dir (reset! second-message? true) (is (empty? (fs/list-dir discard-dir))) (is (re-matches #".*BatchUpdateException.*(rollback|abort).*" (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (deftest concurrent-catalog-resource-updates (testing "Should allow only one replace catalogs update for a given cert at a time" (let [test-catalog (get-in catalogs [:empty]) {certname :certname :as wire-catalog} (get-in wire-catalogs [6 :empty]) nonwire-catalog (catalog/parse-catalog wire-catalog 6 (now)) command {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string wire-catalog)} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-catalog! scf-store/replace-catalog!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/replace-catalog! nonwire-catalog (-> 2 days ago))) (with-redefs [scf-store/replace-catalog! (fn [catalog timestamp dir] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-catalog! catalog timestamp dir))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-wire-catalog (update-in wire-catalog [:resources] conj {:type "File" :title "/etc/foobar2" :exported false :file "/tmp/foo2" :line 10 :tags #{"file" "class" "foobar2"} :parameters {:ensure "directory" :group "root" :user "root"}}) new-catalog-cmd {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string new-wire-catalog)}] (test-msg-handler new-catalog-cmd publish discard-dir (reset! second-message? true) (is (empty? (fs/list-dir discard-dir))) (is (re-matches #".*BatchUpdateException.*(rollback|abort).*" (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (let [cases [{:certname "foo.example.com" :command {:command (command-names :deactivate-node) :version 3 :payload {:certname "foo.example.com"}}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 3 :payload {:certname "bar.example.com" :producer_timestamp (now)}}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 2 :payload "bar.example.com"}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 1 :payload (json/generate-string "bar.example.com")}}]] (deftest deactivate-node-node-active (testing "should deactivate the node" (doseq [{:keys [certname command]} cases] (jdbc/insert! :certnames {:certname certname}) (test-msg-handler command publish discard-dir (let [results (query-to-vec "SELECT certname,deactivated FROM certnames") result (first results)] (is (= (:certname result) certname)) (is (instance? java.sql.Timestamp (:deactivated result))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames")))))) (deftest deactivate-node-node-inactive (doseq [{:keys [certname command]} cases] (testing "should leave the node alone" (let [one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) command (if (#{1 2} (:version command)) ;; Can't set the :producer_timestamp for the older ;; versions (so that we can control the deactivation ;; timestamp). command (assoc-in command [:payload :producer_timestamp] yesterday))] (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (let [[row & rest] (query-to-vec "SELECT certname,deactivated FROM certnames")] (is (empty? rest)) (is (instance? java.sql.Timestamp (:deactivated row))) (if (#{1 2} (:version command)) (do ;; Since we can't control the producer_timestamp. (is (= certname (:certname row))) (is (t/after? (from-sql-date (:deactivated row)) (from-sql-date yesterday)))) (is (= {:certname certname :deactivated yesterday} row))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames"))))))) (deftest deactivate-node-node-missing (testing "should add the node and deactivate it" (doseq [{:keys [certname command]} cases] (test-msg-handler command publish discard-dir (let [results (query-to-vec "SELECT certname,deactivated FROM certnames") result (first results)] (is (= (:certname result) certname)) (is (instance? java.sql.Timestamp (:deactivated result))) (is (zero? (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames"))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Report Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def v5-report (-> (:basic report-examples/reports) (assoc :environment "DEV") reports/report-query->wire-v5)) (def v4-report (-> v5-report (dissoc :producer_timestamp :metrics :logs :noop) utils/underscore->dash-keys)) (def store-report (command-names :store-report)) (deftest store-v6-report-test (let [v6-report (-> v5-report (update :resource_events reports/resource-events-v5->resources) (clojure.set/rename-keys {:resource_events :resources})) command {:command store-report :version 6 :payload v6-report}] (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports") [(with-env (select-keys v6-report [:certname :configuration_version]))])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v5-report-test (let [command {:command store-report :version 5 :payload v5-report}] (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports") [(with-env (select-keys v5-report [:certname :configuration_version]))])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v4-report-test (let [command {:command store-report :version 4 :payload v4-report} recent-time (-> 1 seconds ago)] (test-msg-handler command publish discard-dir (is (= [(with-env (utils/dash->underscore-keys (select-keys v4-report [:certname :configuration-version])))] (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports"))) ;;Status is present in v4+ (but not in v3) (is (= "unchanged" (-> (query-to-vec "SELECT rs.status FROM reports r inner join report_statuses rs on r.status_id = rs.id") first :status))) ;;No producer_timestamp is included in v4, message received time (now) is used intead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM reports") first :producer_timestamp to-date-time))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v3-report-test (let [v3-report (dissoc v4-report :status) recent-time (-> 1 seconds ago) command {:command store-report :version 3 :payload v3-report}] (test-msg-handler command publish discard-dir (is (= [(with-env (utils/dash->underscore-keys (select-keys v3-report [:certname :configuration-version])))] (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports"))) ;;No producer_timestamp is included in v4, message received time (now) is used intead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM reports") first :producer_timestamp to-date-time))) ;;Status is not supported in v3, should be nil (is (nil? (-> (query-to-vec "SELECT status_id FROM reports") first :status))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (defn- get-config [] (conf/get-config (get-service svc-utils/*server* :DefaultedConfig))) (deftest command-service-stats (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) stats (partial stats dispatcher) real-replace! scf-store/replace-facts!] ;; Issue a single command and ensure the stats are right at each step. (is (= {:received-commands 0 :executed-commands 0} (stats))) (let [received-cmd? (promise) go-ahead-and-execute (promise)] (with-redefs [scf-store/replace-facts! (fn [& args] (deliver received-cmd? true) @go-ahead-and-execute (apply real-replace! args))] (enqueue-command (command-names :replace-facts) 4 {:environment "DEV" :certname "foo.local" :values {:foo "foo"} :producer_timestamp (to-string (now))}) @received-cmd? (is (= {:received-commands 1 :executed-commands 0} (stats))) (deliver go-ahead-and-execute true) (while (not= 1 (:executed-commands (stats))) (Thread/sleep 100)) (is (= {:received-commands 1 :executed-commands 1} (stats)))))))) (deftest date-round-trip (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) deactivate-ms 14250331086887 ;; The problem only occurred if you passed a Date to ;; enqueue, a DateTime wasn't a problem. input-stamp (java.util.Date. deactivate-ms) expected-stamp (DateTime. deactivate-ms DateTimeZone/UTC)] (enqueue-command (command-names :deactivate-node) 3 {:certname "foo.local" :producer_timestamp input-stamp}) (is (svc-utils/wait-for-server-processing svc-utils/*server* 5000)) ;; While we're here, check the value in the database too... (is (= expected-stamp (jdbc/with-transacted-connection (:scf-read-db (cli-svc/shared-globals pdb)) :repeatable-read (from-sql-date (scf-store/node-deactivated-time "foo.local"))))) (is (= expected-stamp (-> (client/get (str (utils/base-url->str svc-utils/*base-url*) "/nodes") {:accept :json :throw-exceptions true :throw-entire-message true :query-params {"query" (json/generate-string ["or" ["=" ["node" "active"] true] ["=" ["node" "active"] false]])}}) :body json/parse-string first (get "deactivated") (pt/from-string))))))) (deftest command-response-channel (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) response-mult (response-mult dispatcher) response-chan (async/chan) command-uuid (ks/uuid)] (async/tap response-mult response-chan) (enqueue-command (command-names :deactivate-node) 3 {:certname "foo.local" :producer_timestamp (java.util.Date.)} command-uuid) (let [received-uuid (async/alt!! response-chan ([msg] (:id msg)) (async/timeout 2000) ::timeout)] (is (= command-uuid received-uuid)))))) ;; Local Variables: ;; mode: clojure ;; eval: (define-clojure-indent (test-msg-handler (quote defun)) ;; (test-msg-handler-with-opts (quote defun)) ;; (doverseq (quote defun)))) ;; End:
20092
(ns puppetlabs.puppetdb.command-test (:require [me.raynes.fs :as fs] [clj-http.client :as client] [clojure.java.jdbc :as sql] [cheshire.core :as json] [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.catalogs :as catalog] [puppetlabs.puppetdb.examples.reports :as report-examples] [puppetlabs.puppetdb.scf.hash :as shash] [puppetlabs.trapperkeeper.testutils.logging :refer [atom-logger]] [clj-time.format :as tfmt] [puppetlabs.puppetdb.cli.services :as cli-svc] [puppetlabs.puppetdb.command :refer :all] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.reports :as reports] [puppetlabs.puppetdb.testutils :refer :all] [puppetlabs.puppetdb.fixtures :refer :all] [puppetlabs.puppetdb.jdbc :refer [query-to-vec] :as jdbc] [puppetlabs.puppetdb.examples :refer :all] [puppetlabs.puppetdb.testutils.services :as svc-utils] [puppetlabs.puppetdb.command.constants :refer [command-names]] [clj-time.coerce :refer [from-sql-date to-timestamp to-date-time to-string]] [clj-time.core :as t :refer [days ago now seconds]] [clojure.test :refer :all] [clojure.tools.logging :refer [*logger-factory*]] [slingshot.slingshot :refer [throw+]] [puppetlabs.puppetdb.mq-listener :as mql] [puppetlabs.puppetdb.utils :as utils] [puppetlabs.puppetdb.time :as pt] [puppetlabs.trapperkeeper.app :refer [get-service]] [clojure.core.async :as async] [puppetlabs.kitchensink.core :as ks]) (:import [org.joda.time DateTime DateTimeZone])) (use-fixtures :each with-test-db) (deftest command-assembly (testing "Formatting commands for submission" (is (= (assemble-command "my command" 1 [1 2 3 4 5]) {:command "my command" :version 1 :payload [1 2 3 4 5]})))) (deftest command-parsing (testing "Command parsing" (let [command {:body "{\"command\": \"foo\", \"version\": 2, \"payload\": \"meh\"}"}] (testing "should work for strings" (let [parsed (parse-command command)] ;; :annotations will have a :attempts element with a time, which ;; is hard to test, so disregard that (is (= (dissoc parsed :annotations) {:command "foo" :version 2 :payload "meh"})) (is (map? (:annotations parsed))))) (testing "should work for byte arrays" (let [parsed (parse-command (update-in command [:body] #(.getBytes % "UTF-8")))] (is (= (dissoc parsed :annotations) {:command "foo" :version 2 :payload "meh"})) (is (map? (:annotations parsed)))))) (testing "should reject invalid input" (is (thrown? AssertionError (parse-command {:body ""}))) (is (thrown? AssertionError (parse-command {:body "{}"}))) ;; Missing required attributes (is (thrown? AssertionError (parse-command {:body "{\"version\": 2, \"payload\": \"meh\"}"}))) (is (thrown? AssertionError (parse-command {:body "{\"version\": 2}"}))) ;; Non-numeric version (is (thrown? AssertionError (parse-command {:body "{\"version\": \"2\", \"payload\": \"meh\"}"}))) ;; Non-string command (is (thrown? AssertionError (parse-command {:body "{\"command\": 123, \"version\": 2, \"payload\": \"meh\"}"}))) ;; Non-JSON payload (is (thrown? Exception (parse-command {:body "{\"command\": \"foo\", \"version\": 2, \"payload\": #{}"}))) ;; Non-UTF-8 byte array (is (thrown? Exception (parse-command {:body (.getBytes "{\"command\": \"foo\", \"version\": 2, \"payload\": \"meh\"}" "UTF-16")})))))) (defmacro test-msg-handler* [command publish-var discard-var opts-map & body] `(let [log-output# (atom []) publish# (call-counter) discard-dir# (fs/temp-dir "test-msg-handler") handle-message# (mql/create-message-handler publish# discard-dir# #(process-command! % ~opts-map)) msg# {:headers {:id "foo-id-1" :received (tfmt/unparse (tfmt/formatters :date-time) (now))} :body (json/generate-string ~command)}] (try (binding [*logger-factory* (atom-logger log-output#)] (handle-message# msg#)) (let [~publish-var publish# ~discard-var discard-dir#] ~@body ;; Uncommenting this line can be very useful for debugging ;; (println @log-output#) ) (finally (fs/delete-dir discard-dir#))))) (defmacro test-msg-handler "Runs `command` (after converting to JSON) through the MQ message handlers. `body` is executed with `publish-var` bound to the number of times the message was processed and `discard-var` bound to the directory that contains failed messages." [command publish-var discard-var & body] `(test-msg-handler* ~command ~publish-var ~discard-var {:db *db*} ~@body)) (defmacro test-msg-handler-with-opts "Similar to test-msg-handler, but allows the passing of additional config options to the message handler via `opts-map`." [command publish-var discard-var opts-map & body] `(test-msg-handler* ~command ~publish-var ~discard-var (merge {:db *db*} ~opts-map) ~@body)) (deftest command-processor-integration (let [command {:command "some command" :version 1 :payload "payload"}] (testing "correctly formed messages" (testing "which are not yet expired" (testing "when successful should not raise errors or retry" (with-redefs [process-command! (constantly true)] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "when a fatal error occurs should be discarded to the dead letter queue" (with-redefs [process-command! (fn [cmd opt] (throw+ (fatality (Exception. "fatal error"))))] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir))))))) (testing "when a non-fatal error occurs should be requeued with the error recorded" (with-redefs [process-command! (fn [cmd opt] (throw+ (Exception. "non-fatal error")))] (test-msg-handler command publish discard-dir (is (empty? (fs/list-dir discard-dir))) (let [[msg & _] (first (args-supplied publish)) published (parse-command {:body msg}) attempt (first (get-in published [:annotations :attempts]))] (is (re-find #"java.lang.Exception: non-fatal error" (:error attempt))) (is (:trace attempt))))))) (testing "should be discarded if expired" (let [command (assoc-in command [:annotations :attempts] (repeat mql/maximum-allowable-retries {})) process-counter (call-counter)] (with-redefs [process-command! process-counter] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir)))) (is (= 0 (times-called process-counter)))))))) (testing "should be discarded if incorrectly formed" (let [command (dissoc command :payload) process-counter (call-counter)] (with-redefs [process-command! process-counter] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir)))) (is (= 0 (times-called process-counter))))))))) (defn make-cmd "Create a command pre-loaded with `n` attempts" [n] {:command nil :version nil :annotations {:attempts (repeat n {})}}) (deftest command-retry-handler (testing "Retry handler" (with-redefs [metrics.meters/mark! (call-counter) mql/annotate-with-attempt (call-counter)] (testing "should log errors" (let [publish (call-counter)] (testing "to DEBUG for initial retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd 1) nil publish)) (is (= (get-in @log-output [0 1]) :debug)))) (testing "to ERROR for later retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd mql/maximum-allowable-retries) nil publish)) (is (= (get-in @log-output [0 1]) :error))))))))) (deftest test-error-with-stacktrace (with-redefs [metrics.meters/mark! (call-counter)] (let [publish (call-counter)] (testing "Exception with stacktrace, no more retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd 1) (RuntimeException. "foo") publish)) (is (= (get-in @log-output [0 1]) :debug)) (is (instance? Exception (get-in @log-output [0 2]))))) (testing "Exception with stacktrace, no more retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd mql/maximum-allowable-retries) (RuntimeException. "foo") publish)) (is (= (get-in @log-output [0 1]) :error)) (is (instance? Exception (get-in @log-output [0 2])))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Common functions/macros for support multi-version tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn stringify-payload "Converts a clojure payload in the command to the stringified JSON structure" [catalog] (update-in catalog [:payload] json/generate-string)) (defn with-env "Updates the `row-map` to include environment information." [row-map] (assoc row-map :environment_id (scf-store/environment-id "DEV"))) (defn version-kwd->num "Converts a version keyword into a correct number (expected by the command). i.e. :v4 -> 4" [version-kwd] (-> version-kwd name last Character/getNumericValue)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Catalog Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def catalog-versions "Currently supported catalog versions" [:v6]) (deftest replace-catalog (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload (-> (get-in wire-catalogs [6 :empty]) (assoc :producer_timestamp (now)))}]] (testing (str (command-names :replace-catalog) " " version) (let [certname (get-in command [:payload :certname]) catalog-hash (shash/catalog-similarity-hash (catalog/parse-catalog (:payload command) (version-kwd->num version) (now))) command (stringify-payload command) one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) tomorrow (to-timestamp (+ (System/currentTimeMillis) one-day))] (testing "with no catalog should store the catalog" (with-fixtures (test-msg-handler command publish discard-dir (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "with an existing catalog should replace the catalog" (with-fixtures (is (= (query-to-vec "SELECT certname FROM catalogs") [])) (jdbc/insert! :certnames {:certname certname}) (jdbc/insert! :catalogs {:hash (sutils/munge-hash-for-storage "00") :api_version 1 :catalog_version "foo" :certname certname :producer_timestamp (to-timestamp (-> 1 days ago))}) (test-msg-handler command publish discard-dir (is (= [(with-env {:certname certname :catalog catalog-hash})] (query-to-vec (format "SELECT certname, %s as catalog, environment_id FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "when replacing a catalog with a debug directory, should write out catalogs for inspection" (with-fixtures (jdbc/insert! :certnames {:certname certname}) (let [debug-dir (fs/absolute-path (temp-dir "catalog-inspection"))] (jdbc/insert! :catalogs {:hash (sutils/munge-hash-for-storage "0000") :api_version 1 :catalog_version "foo" :certname certname :producer_timestamp (to-timestamp (t/minus (now) (-> 1 days)))}) (is (nil? (fs/list-dir debug-dir))) (test-msg-handler-with-opts command publish discard-dir {:catalog-hash-debug-dir debug-dir} (is (= [(with-env {:certname certname :catalog catalog-hash})] (query-to-vec (format "SELECT certname, %s as catalog, environment_id FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 5 (count (fs/list-dir debug-dir)))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (let [command (assoc command :payload "bad stuff")] (testing "with a bad payload should discard the message" (with-fixtures (test-msg-handler command publish discard-dir (is (empty? (query-to-vec "SELECT * FROM catalogs"))) (is (= 0 (times-called publish))) (is (seq (fs/list-dir discard-dir))))))) (testing "with a newer catalog should ignore the message" (with-fixtures (jdbc/insert! :certnames {:certname certname}) (jdbc/insert! :catalogs {:id 1 :hash (sutils/munge-hash-for-storage "ab") :api_version 1 :catalog_version "foo" :certname certname :timestamp tomorrow :producer_timestamp (to-timestamp (now))}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :catalog "ab"}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "should reactivate the node if it was deactivated before the message" (with-fixtures (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :deactivated nil}] (query-to-vec "SELECT certname,deactivated FROM certnames"))) (is (= [{:certname certname :catalog catalog-hash}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "should store the catalog if the node was deactivated after the message" (scf-store/delete-certname! certname) (jdbc/insert! :certnames {:certname certname :deactivated tomorrow}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :deactivated tomorrow}] (query-to-vec "SELECT certname,deactivated FROM certnames"))) (is (= [{:certname certname :catalog catalog-hash}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))))) ;; If there are messages in the user's MQ when they upgrade, we could ;; potentially have commands of an unsupported format that need to be ;; processed. Although we don't support the catalog versions below, we ;; need to test that those commands will be processed properly (deftest replace-catalog-with-v5 (testing "catalog wireformat v5" (let [command {:command (command-names :replace-catalog) :version 5 :payload (get-in wire-catalogs [5 :empty])} certname (get-in command [:payload :name]) cmd-producer-timestamp (get-in command [:payload :producer-timestamp])] (with-fixtures (test-msg-handler command publish discard-dir ;;names in v5 are hyphenated, this check ensures we're sending a v5 catalog (is (contains? (:payload command) :producer-timestamp)) (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) ;;this should be the hyphenated producer timestamp provided above (is (= (-> (query-to-vec "SELECT producer_timestamp FROM catalogs") first :producer_timestamp) (to-timestamp cmd-producer-timestamp)))))))) (deftest replace-catalog-with-v4 (let [command {:command (command-names :replace-catalog) :version 4 :payload (get-in wire-catalogs [4 :empty])} certname (get-in command [:payload :name]) cmd-producer-timestamp (get-in command [:payload :producer-timestamp]) recent-time (-> 1 seconds ago)] (with-fixtures (test-msg-handler command publish discard-dir (is (false? (contains? (:payload command) :producer-timestamp))) (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) ;;v4 does not include a producer_timestmap, the backend ;;should use the time the command was received instead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM catalogs") first :producer_timestamp to-date-time))))))) (defn update-resource "Updated the resource in `catalog` with the given `type` and `title`. `update-fn` is a function that accecpts the resource map as an argument and returns a (possibly mutated) resource map." [version catalog type title update-fn] (let [path [:payload :resources]] (update-in catalog path (fn [resources] (mapv (fn [res] (if (and (= (:title res) title) (= (:type res) type)) (update-fn res) res)) resources))))) (def basic-wire-catalog (get-in wire-catalogs [6 :basic])) (deftest catalog-with-updated-resource-line (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :line 20)))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= 10 (get-in orig-resources [{:type "File" :title "/etc/foobar"} :line]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :line] 20) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-file (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :file "/tmp/not-foo")))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= "/tmp/foo" (get-in orig-resources [{:type "File" :title "/etc/foobar"} :file]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :file] "/tmp/not-foo") (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-exported (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :exported true)))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= false (get-in orig-resources [{:type "File" :title "/etc/foobar"} :exported]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :exported] true) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-tags (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(-> %(assoc :tags #{"file" "class" "foobar" "foo"}) (assoc :line 20))))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= #{"file" "class" "foobar"} (get-in orig-resources [{:type "File" :title "/etc/foobar"} :tags]))) (is (= 10 (get-in orig-resources [{:type "File" :title "/etc/foobar"} :line]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (-> orig-resources (assoc-in [{:type "File" :title "/etc/foobar"} :tags] #{"file" "class" "foobar" "foo"}) (assoc-in [{:type "File" :title "/etc/foobar"} :line] 20)) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Fact Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def fact-versions "Support fact command versions" [:v4]) (let [certname "foo.example.com" facts {:certname certname :environment "DEV" :values {"a" "1" "b" "2" "c" "3"} :producer_timestamp (to-timestamp (now))} v4-command {:command (command-names :replace-facts) :version 4 :payload facts} one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) tomorrow (to-timestamp (+ (System/currentTimeMillis) one-day))] (deftest replace-facts-no-facts (doverseq [version fact-versions :let [command v4-command]] (testing "should store the facts" (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})]))))))) (deftest replace-facts-existing-facts (doverseq [version fact-versions :let [command v4-command]] (jdbc/with-db-transaction [] (scf-store/ensure-environment "DEV") (scf-store/add-certname! certname) (scf-store/replace-facts! {:certname certname :values {"x" "24" "y" "25" "z" "26"} :timestamp yesterday :producer_timestamp yesterday :environment "DEV"})) (testing "should replace the facts" (test-msg-handler command publish discard-dir (let [[result & _] (query-to-vec "SELECT certname,timestamp, environment_id FROM factsets")] (is (= (:certname result) certname)) (is (not= (:timestamp result) yesterday)) (is (= (scf-store/environment-id "DEV") (:environment_id result)))) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY fp.path ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (deftest replace-facts-newer-facts (doverseq [version fact-versions :let [command v4-command]] (jdbc/with-db-transaction [] (scf-store/ensure-environment "DEV") (scf-store/add-certname! certname) (scf-store/add-facts! {:certname certname :values {"x" "24" "y" "25" "z" "26"} :timestamp tomorrow :producer_timestamp (to-timestamp (now)) :environment "DEV"})) (testing "should ignore the message" (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,timestamp,environment_id FROM factsets") [(with-env {:certname certname :timestamp tomorrow})])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "x" :value "24"} {:certname certname :name "y" :value "25"} {:certname certname :name "z" :value "26"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (deftest replace-facts-deactivated-node-facts (doverseq [version fact-versions :let [command v4-command]] (testing "should reactivate the node if it was deactivated before the message" (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,deactivated FROM certnames") [{:certname certname :deactivated nil}])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))) (testing "should store the facts if the node was deactivated after the message" (scf-store/delete-certname! certname) (jdbc/insert! :certnames {:certname certname :deactivated tomorrow}) (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,deactivated FROM certnames") [{:certname certname :deactivated tomorrow}])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) ;;v2 and v3 fact commands are only supported when commands are still ;;sitting in the queue from before upgrading (deftest replace-facts-with-v3-wire-format (let [certname "foo.example.com" producer-time (-> (now) to-timestamp json/generate-string json/parse-string pt/to-timestamp) facts-cmd {:command (command-names :replace-facts) :version 3 :payload {:name certname :environment "DEV" :producer-timestamp producer-time :values {"a" "1" "b" "2" "c" "3"}}}] (test-msg-handler facts-cmd publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname, e.environment, fs.producer_timestamp FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id INNER JOIN environments as e on fs.environment_id = e.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1" :producer_timestamp producer-time :environment "DEV"} {:certname certname :name "b" :value "2" :producer_timestamp producer-time :environment "DEV"} {:certname certname :name "c" :value "3" :producer_timestamp producer-time :environment "DEV"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})])))))) (deftest replace-facts-with-v2-wire-format (let [certname "foo.example.com" before-test-starts-time (-> 1 seconds ago) facts-cmd {:command (command-names :replace-facts) :version 2 :payload {:name certname :environment "DEV" :values {"a" "1" "b" "2" "c" "3"}}}] (test-msg-handler facts-cmd publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname, e.environment FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id INNER JOIN environments as e on fs.environment_id = e.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1" :environment "DEV"} {:certname certname :name "b" :value "2" :environment "DEV"} {:certname certname :name "c" :value "3" :environment "DEV"}])) (is (every? (comp #(t/before? before-test-starts-time %) to-date-time :producer_timestamp) (query-to-vec "SELECT fs.producer_timestamp FROM factsets fs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})])))))) (deftest replace-facts-bad-payload (let [bad-command {:command (command-names :replace-facts) :version 4 :payload "bad stuff"}] (doverseq [version fact-versions :let [command bad-command]] (testing "should discard the message" (test-msg-handler command publish discard-dir (is (empty? (query-to-vec "SELECT * FROM facts"))) (is (= 0 (times-called publish))) (is (seq (fs/list-dir discard-dir)))))))) (defn extract-error-message "Pulls the error message from the publish var of a test-msg-handler" [publish] (-> publish meta :args deref ffirst json/parse-string (get-in ["annotations" "attempts"]) first (get "error"))) (deftest concurrent-fact-updates (testing "Should allow only one replace facts update for a given cert at a time" (let [certname "some_certname" facts {:certname certname :environment "DEV" :values {"domain" "mydomain.com" "fqdn" "myhost.mydomain.com" "hostname" "myhost" "kernel" "Linux" "operatingsystem" "Debian" } :producer_timestamp (to-timestamp (now))} command {:command (command-names :replace-facts) :version 4 :payload facts} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-facts! scf-store/update-facts!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/add-facts! {:certname certname :values (:values facts) :timestamp (-> 2 days ago) :environment nil :producer_timestamp (-> 2 days ago)})) (with-redefs [scf-store/update-facts! (fn [fact-data] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-facts! fact-data))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-facts (update-in facts [:values] (fn [values] (-> values (dissoc "kernel") (assoc "newfact2" "here")))) new-facts-cmd {:command (command-names :replace-facts) :version 4 :payload new-facts}] (test-msg-handler new-facts-cmd publish discard-dir (reset! second-message? true) (is (re-matches (if (sutils/postgres?) #"(?sm).*ERROR: could not serialize access due to concurrent update.*" #".*transaction rollback: serialization failure") (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (defn thread-id [] (.getId (Thread/currentThread))) (deftest fact-path-update-race ;; Simulates two update commands being processed for two different ;; machines at the same time. Before we lifted fact paths into ;; facts, the race tested here could result in a constraint ;; violation when the two updates left behind an orphaned row. (let [certname-1 "some_certname1" certname-2 "some_certname2" ;; facts for server 1, has the same "mytimestamp" value as the ;; facts for server 2 facts-1a {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian" "mytimestamp" "1"} :producer_timestamp (-> 2 days ago)} facts-2a {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian" "mytimestamp" "1"} :producer_timestamp (-> 2 days ago)} ;; same facts as before, but now certname-1 has a different ;; fact value for mytimestamp (this will force a new fact_value ;; that is only used for certname-1 facts-1b {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian" "mytimestamp" "1b"} :producer_timestamp (-> 1 days ago)} ;; with this, certname-1 and certname-2 now have their own ;; fact_value for mytimestamp that is different from the ;; original mytimestamp that they originally shared facts-2b {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian" "mytimestamp" "2b"} :producer_timestamp (-> 1 days ago)} ;; this fact set will disassociate mytimestamp from the facts ;; associated to certname-1, it will do the same thing for ;; certname-2 facts-1c {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian"} :producer_timestamp (now)} facts-2c {:certname certname-2 :environment nil :values {"domain" "mydomain<EMAIL>" "operatingsystem" "Debian"} :producer_timestamp (now)} command-1b {:command (command-names :replace-facts) :version 4 :payload facts-1b} command-2b {:command (command-names :replace-facts) :version 4 :payload facts-2b} command-1c {:command (command-names :replace-facts) :version 4 :payload facts-1c} command-2c {:command (command-names :replace-facts) :version 4 :payload facts-2c} ;; Wait for two threads to countdown before proceeding latch (java.util.concurrent.CountDownLatch. 2) ;; I'm modifying delete-pending-path-id-orphans! so that I can ;; coordinate access between the two threads, I'm storing the ;; reference to the original delete-pending-path-id-orphans! ;; here, so that I can delegate to it once I'm done ;; coordinating storage-delete-pending-path-id-orphans! scf-store/delete-pending-path-id-orphans!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname-1) (scf-store/add-certname! certname-2) (scf-store/add-facts! {:certname certname-1 :values (:values facts-1a) :timestamp (now) :environment nil :producer_timestamp (:producer_timestamp facts-1a)}) (scf-store/add-facts! {:certname certname-2 :values (:values facts-2a) :timestamp (now) :environment nil :producer_timestamp (:producer_timestamp facts-2a)})) ;; At this point, there will be 4 fact_value rows, 1 for ;; mytimestamp, 1 for the operatingsystem, 2 for domain (with-redefs [scf-store/delete-pending-path-id-orphans! (fn [& args] ;; Once this has been called, it will countdown ;; the latch and block (.countDown latch) ;; After the second command has been executed and ;; it has decremented the latch, the await will no ;; longer block and both threads will begin ;; running again (.await latch) ;; Execute the normal delete-pending-path-id-orphans! ;; function (unchanged) (apply storage-delete-pending-path-id-orphans! args))] (let [first-message? (atom false) second-message? (atom false) fut-1 (future (test-msg-handler command-1b publish discard-dir (reset! first-message? true))) fut-2 (future (test-msg-handler command-2b publish discard-dir (reset! second-message? true)))] ;; The two commands are being submitted in future, ensure they ;; have both completed before proceeding @fut-2 @fut-1 ;; At this point there are 6 fact values, the original ;; mytimestamp, the two new mytimestamps, operating system and ;; the two domains (is (true? @first-message?)) (is (true? @second-message?)) ;; Submit another factset that does NOT include mytimestamp, ;; this disassociates certname-1's fact_value (which is 1b) (test-msg-handler command-1c publish discard-dir (reset! first-message? true)) ;; Do the same thing with certname-2. Since the reference to 1b ;; and 2b has been removed, mytimestamp's path is no longer ;; connected to any fact values. The original mytimestamp value ;; of 1 is still in the table. It's now attempting to delete ;; that fact path, when the mytimestamp 1 value is still in ;; there. (test-msg-handler command-2c publish discard-dir (is (not (extract-error-message publish)))) ;; Can we see the orphaned value '1', and does the global gc remove it. (is (= 1 (count (query-to-vec "select id from fact_values where value_string = '1'")))) (scf-store/garbage-collect! *db*) (is (zero? (count (query-to-vec "select id from fact_values where value_string = '1'")))))))) (deftest concurrent-catalog-updates (testing "Should allow only one replace catalogs update for a given cert at a time" (let [test-catalog (get-in catalogs [:empty]) {certname :certname :as wire-catalog} (get-in wire-catalogs [6 :empty]) nonwire-catalog (catalog/parse-catalog wire-catalog 6 (now)) command {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string wire-catalog)} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-catalog! scf-store/replace-catalog!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/replace-catalog! nonwire-catalog (-> 2 days ago))) (with-redefs [scf-store/replace-catalog! (fn [catalog timestamp dir] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-catalog! catalog timestamp dir))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-wire-catalog (assoc-in wire-catalog [:edges] #{{:relationship "contains" :target {:title "Settings" :type "Class"} :source {:title "main" :type "Stage"}}}) new-catalog-cmd {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string new-wire-catalog)}] (test-msg-handler new-catalog-cmd publish discard-dir (reset! second-message? true) (is (empty? (fs/list-dir discard-dir))) (is (re-matches #".*BatchUpdateException.*(rollback|abort).*" (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (deftest concurrent-catalog-resource-updates (testing "Should allow only one replace catalogs update for a given cert at a time" (let [test-catalog (get-in catalogs [:empty]) {certname :certname :as wire-catalog} (get-in wire-catalogs [6 :empty]) nonwire-catalog (catalog/parse-catalog wire-catalog 6 (now)) command {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string wire-catalog)} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-catalog! scf-store/replace-catalog!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/replace-catalog! nonwire-catalog (-> 2 days ago))) (with-redefs [scf-store/replace-catalog! (fn [catalog timestamp dir] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-catalog! catalog timestamp dir))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-wire-catalog (update-in wire-catalog [:resources] conj {:type "File" :title "/etc/foobar2" :exported false :file "/tmp/foo2" :line 10 :tags #{"file" "class" "foobar2"} :parameters {:ensure "directory" :group "root" :user "root"}}) new-catalog-cmd {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string new-wire-catalog)}] (test-msg-handler new-catalog-cmd publish discard-dir (reset! second-message? true) (is (empty? (fs/list-dir discard-dir))) (is (re-matches #".*BatchUpdateException.*(rollback|abort).*" (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (let [cases [{:certname "foo.example.com" :command {:command (command-names :deactivate-node) :version 3 :payload {:certname "foo.example.com"}}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 3 :payload {:certname "bar.example.com" :producer_timestamp (now)}}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 2 :payload "bar.example.com"}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 1 :payload (json/generate-string "bar.example.com")}}]] (deftest deactivate-node-node-active (testing "should deactivate the node" (doseq [{:keys [certname command]} cases] (jdbc/insert! :certnames {:certname certname}) (test-msg-handler command publish discard-dir (let [results (query-to-vec "SELECT certname,deactivated FROM certnames") result (first results)] (is (= (:certname result) certname)) (is (instance? java.sql.Timestamp (:deactivated result))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames")))))) (deftest deactivate-node-node-inactive (doseq [{:keys [certname command]} cases] (testing "should leave the node alone" (let [one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) command (if (#{1 2} (:version command)) ;; Can't set the :producer_timestamp for the older ;; versions (so that we can control the deactivation ;; timestamp). command (assoc-in command [:payload :producer_timestamp] yesterday))] (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (let [[row & rest] (query-to-vec "SELECT certname,deactivated FROM certnames")] (is (empty? rest)) (is (instance? java.sql.Timestamp (:deactivated row))) (if (#{1 2} (:version command)) (do ;; Since we can't control the producer_timestamp. (is (= certname (:certname row))) (is (t/after? (from-sql-date (:deactivated row)) (from-sql-date yesterday)))) (is (= {:certname certname :deactivated yesterday} row))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames"))))))) (deftest deactivate-node-node-missing (testing "should add the node and deactivate it" (doseq [{:keys [certname command]} cases] (test-msg-handler command publish discard-dir (let [results (query-to-vec "SELECT certname,deactivated FROM certnames") result (first results)] (is (= (:certname result) certname)) (is (instance? java.sql.Timestamp (:deactivated result))) (is (zero? (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames"))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Report Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def v5-report (-> (:basic report-examples/reports) (assoc :environment "DEV") reports/report-query->wire-v5)) (def v4-report (-> v5-report (dissoc :producer_timestamp :metrics :logs :noop) utils/underscore->dash-keys)) (def store-report (command-names :store-report)) (deftest store-v6-report-test (let [v6-report (-> v5-report (update :resource_events reports/resource-events-v5->resources) (clojure.set/rename-keys {:resource_events :resources})) command {:command store-report :version 6 :payload v6-report}] (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports") [(with-env (select-keys v6-report [:certname :configuration_version]))])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v5-report-test (let [command {:command store-report :version 5 :payload v5-report}] (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports") [(with-env (select-keys v5-report [:certname :configuration_version]))])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v4-report-test (let [command {:command store-report :version 4 :payload v4-report} recent-time (-> 1 seconds ago)] (test-msg-handler command publish discard-dir (is (= [(with-env (utils/dash->underscore-keys (select-keys v4-report [:certname :configuration-version])))] (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports"))) ;;Status is present in v4+ (but not in v3) (is (= "unchanged" (-> (query-to-vec "SELECT rs.status FROM reports r inner join report_statuses rs on r.status_id = rs.id") first :status))) ;;No producer_timestamp is included in v4, message received time (now) is used intead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM reports") first :producer_timestamp to-date-time))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v3-report-test (let [v3-report (dissoc v4-report :status) recent-time (-> 1 seconds ago) command {:command store-report :version 3 :payload v3-report}] (test-msg-handler command publish discard-dir (is (= [(with-env (utils/dash->underscore-keys (select-keys v3-report [:certname :configuration-version])))] (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports"))) ;;No producer_timestamp is included in v4, message received time (now) is used intead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM reports") first :producer_timestamp to-date-time))) ;;Status is not supported in v3, should be nil (is (nil? (-> (query-to-vec "SELECT status_id FROM reports") first :status))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (defn- get-config [] (conf/get-config (get-service svc-utils/*server* :DefaultedConfig))) (deftest command-service-stats (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) stats (partial stats dispatcher) real-replace! scf-store/replace-facts!] ;; Issue a single command and ensure the stats are right at each step. (is (= {:received-commands 0 :executed-commands 0} (stats))) (let [received-cmd? (promise) go-ahead-and-execute (promise)] (with-redefs [scf-store/replace-facts! (fn [& args] (deliver received-cmd? true) @go-ahead-and-execute (apply real-replace! args))] (enqueue-command (command-names :replace-facts) 4 {:environment "DEV" :certname "foo.local" :values {:foo "foo"} :producer_timestamp (to-string (now))}) @received-cmd? (is (= {:received-commands 1 :executed-commands 0} (stats))) (deliver go-ahead-and-execute true) (while (not= 1 (:executed-commands (stats))) (Thread/sleep 100)) (is (= {:received-commands 1 :executed-commands 1} (stats)))))))) (deftest date-round-trip (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) deactivate-ms 14250331086887 ;; The problem only occurred if you passed a Date to ;; enqueue, a DateTime wasn't a problem. input-stamp (java.util.Date. deactivate-ms) expected-stamp (DateTime. deactivate-ms DateTimeZone/UTC)] (enqueue-command (command-names :deactivate-node) 3 {:certname "foo.local" :producer_timestamp input-stamp}) (is (svc-utils/wait-for-server-processing svc-utils/*server* 5000)) ;; While we're here, check the value in the database too... (is (= expected-stamp (jdbc/with-transacted-connection (:scf-read-db (cli-svc/shared-globals pdb)) :repeatable-read (from-sql-date (scf-store/node-deactivated-time "foo.local"))))) (is (= expected-stamp (-> (client/get (str (utils/base-url->str svc-utils/*base-url*) "/nodes") {:accept :json :throw-exceptions true :throw-entire-message true :query-params {"query" (json/generate-string ["or" ["=" ["node" "active"] true] ["=" ["node" "active"] false]])}}) :body json/parse-string first (get "deactivated") (pt/from-string))))))) (deftest command-response-channel (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) response-mult (response-mult dispatcher) response-chan (async/chan) command-uuid (ks/uuid)] (async/tap response-mult response-chan) (enqueue-command (command-names :deactivate-node) 3 {:certname "foo.local" :producer_timestamp (java.util.Date.)} command-uuid) (let [received-uuid (async/alt!! response-chan ([msg] (:id msg)) (async/timeout 2000) ::timeout)] (is (= command-uuid received-uuid)))))) ;; Local Variables: ;; mode: clojure ;; eval: (define-clojure-indent (test-msg-handler (quote defun)) ;; (test-msg-handler-with-opts (quote defun)) ;; (doverseq (quote defun)))) ;; End:
true
(ns puppetlabs.puppetdb.command-test (:require [me.raynes.fs :as fs] [clj-http.client :as client] [clojure.java.jdbc :as sql] [cheshire.core :as json] [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.catalogs :as catalog] [puppetlabs.puppetdb.examples.reports :as report-examples] [puppetlabs.puppetdb.scf.hash :as shash] [puppetlabs.trapperkeeper.testutils.logging :refer [atom-logger]] [clj-time.format :as tfmt] [puppetlabs.puppetdb.cli.services :as cli-svc] [puppetlabs.puppetdb.command :refer :all] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.reports :as reports] [puppetlabs.puppetdb.testutils :refer :all] [puppetlabs.puppetdb.fixtures :refer :all] [puppetlabs.puppetdb.jdbc :refer [query-to-vec] :as jdbc] [puppetlabs.puppetdb.examples :refer :all] [puppetlabs.puppetdb.testutils.services :as svc-utils] [puppetlabs.puppetdb.command.constants :refer [command-names]] [clj-time.coerce :refer [from-sql-date to-timestamp to-date-time to-string]] [clj-time.core :as t :refer [days ago now seconds]] [clojure.test :refer :all] [clojure.tools.logging :refer [*logger-factory*]] [slingshot.slingshot :refer [throw+]] [puppetlabs.puppetdb.mq-listener :as mql] [puppetlabs.puppetdb.utils :as utils] [puppetlabs.puppetdb.time :as pt] [puppetlabs.trapperkeeper.app :refer [get-service]] [clojure.core.async :as async] [puppetlabs.kitchensink.core :as ks]) (:import [org.joda.time DateTime DateTimeZone])) (use-fixtures :each with-test-db) (deftest command-assembly (testing "Formatting commands for submission" (is (= (assemble-command "my command" 1 [1 2 3 4 5]) {:command "my command" :version 1 :payload [1 2 3 4 5]})))) (deftest command-parsing (testing "Command parsing" (let [command {:body "{\"command\": \"foo\", \"version\": 2, \"payload\": \"meh\"}"}] (testing "should work for strings" (let [parsed (parse-command command)] ;; :annotations will have a :attempts element with a time, which ;; is hard to test, so disregard that (is (= (dissoc parsed :annotations) {:command "foo" :version 2 :payload "meh"})) (is (map? (:annotations parsed))))) (testing "should work for byte arrays" (let [parsed (parse-command (update-in command [:body] #(.getBytes % "UTF-8")))] (is (= (dissoc parsed :annotations) {:command "foo" :version 2 :payload "meh"})) (is (map? (:annotations parsed)))))) (testing "should reject invalid input" (is (thrown? AssertionError (parse-command {:body ""}))) (is (thrown? AssertionError (parse-command {:body "{}"}))) ;; Missing required attributes (is (thrown? AssertionError (parse-command {:body "{\"version\": 2, \"payload\": \"meh\"}"}))) (is (thrown? AssertionError (parse-command {:body "{\"version\": 2}"}))) ;; Non-numeric version (is (thrown? AssertionError (parse-command {:body "{\"version\": \"2\", \"payload\": \"meh\"}"}))) ;; Non-string command (is (thrown? AssertionError (parse-command {:body "{\"command\": 123, \"version\": 2, \"payload\": \"meh\"}"}))) ;; Non-JSON payload (is (thrown? Exception (parse-command {:body "{\"command\": \"foo\", \"version\": 2, \"payload\": #{}"}))) ;; Non-UTF-8 byte array (is (thrown? Exception (parse-command {:body (.getBytes "{\"command\": \"foo\", \"version\": 2, \"payload\": \"meh\"}" "UTF-16")})))))) (defmacro test-msg-handler* [command publish-var discard-var opts-map & body] `(let [log-output# (atom []) publish# (call-counter) discard-dir# (fs/temp-dir "test-msg-handler") handle-message# (mql/create-message-handler publish# discard-dir# #(process-command! % ~opts-map)) msg# {:headers {:id "foo-id-1" :received (tfmt/unparse (tfmt/formatters :date-time) (now))} :body (json/generate-string ~command)}] (try (binding [*logger-factory* (atom-logger log-output#)] (handle-message# msg#)) (let [~publish-var publish# ~discard-var discard-dir#] ~@body ;; Uncommenting this line can be very useful for debugging ;; (println @log-output#) ) (finally (fs/delete-dir discard-dir#))))) (defmacro test-msg-handler "Runs `command` (after converting to JSON) through the MQ message handlers. `body` is executed with `publish-var` bound to the number of times the message was processed and `discard-var` bound to the directory that contains failed messages." [command publish-var discard-var & body] `(test-msg-handler* ~command ~publish-var ~discard-var {:db *db*} ~@body)) (defmacro test-msg-handler-with-opts "Similar to test-msg-handler, but allows the passing of additional config options to the message handler via `opts-map`." [command publish-var discard-var opts-map & body] `(test-msg-handler* ~command ~publish-var ~discard-var (merge {:db *db*} ~opts-map) ~@body)) (deftest command-processor-integration (let [command {:command "some command" :version 1 :payload "payload"}] (testing "correctly formed messages" (testing "which are not yet expired" (testing "when successful should not raise errors or retry" (with-redefs [process-command! (constantly true)] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "when a fatal error occurs should be discarded to the dead letter queue" (with-redefs [process-command! (fn [cmd opt] (throw+ (fatality (Exception. "fatal error"))))] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir))))))) (testing "when a non-fatal error occurs should be requeued with the error recorded" (with-redefs [process-command! (fn [cmd opt] (throw+ (Exception. "non-fatal error")))] (test-msg-handler command publish discard-dir (is (empty? (fs/list-dir discard-dir))) (let [[msg & _] (first (args-supplied publish)) published (parse-command {:body msg}) attempt (first (get-in published [:annotations :attempts]))] (is (re-find #"java.lang.Exception: non-fatal error" (:error attempt))) (is (:trace attempt))))))) (testing "should be discarded if expired" (let [command (assoc-in command [:annotations :attempts] (repeat mql/maximum-allowable-retries {})) process-counter (call-counter)] (with-redefs [process-command! process-counter] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir)))) (is (= 0 (times-called process-counter)))))))) (testing "should be discarded if incorrectly formed" (let [command (dissoc command :payload) process-counter (call-counter)] (with-redefs [process-command! process-counter] (test-msg-handler command publish discard-dir (is (= 0 (times-called publish))) (is (= 1 (count (fs/list-dir discard-dir)))) (is (= 0 (times-called process-counter))))))))) (defn make-cmd "Create a command pre-loaded with `n` attempts" [n] {:command nil :version nil :annotations {:attempts (repeat n {})}}) (deftest command-retry-handler (testing "Retry handler" (with-redefs [metrics.meters/mark! (call-counter) mql/annotate-with-attempt (call-counter)] (testing "should log errors" (let [publish (call-counter)] (testing "to DEBUG for initial retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd 1) nil publish)) (is (= (get-in @log-output [0 1]) :debug)))) (testing "to ERROR for later retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd mql/maximum-allowable-retries) nil publish)) (is (= (get-in @log-output [0 1]) :error))))))))) (deftest test-error-with-stacktrace (with-redefs [metrics.meters/mark! (call-counter)] (let [publish (call-counter)] (testing "Exception with stacktrace, no more retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd 1) (RuntimeException. "foo") publish)) (is (= (get-in @log-output [0 1]) :debug)) (is (instance? Exception (get-in @log-output [0 2]))))) (testing "Exception with stacktrace, no more retries" (let [log-output (atom [])] (binding [*logger-factory* (atom-logger log-output)] (mql/handle-command-retry (make-cmd mql/maximum-allowable-retries) (RuntimeException. "foo") publish)) (is (= (get-in @log-output [0 1]) :error)) (is (instance? Exception (get-in @log-output [0 2])))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Common functions/macros for support multi-version tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn stringify-payload "Converts a clojure payload in the command to the stringified JSON structure" [catalog] (update-in catalog [:payload] json/generate-string)) (defn with-env "Updates the `row-map` to include environment information." [row-map] (assoc row-map :environment_id (scf-store/environment-id "DEV"))) (defn version-kwd->num "Converts a version keyword into a correct number (expected by the command). i.e. :v4 -> 4" [version-kwd] (-> version-kwd name last Character/getNumericValue)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Catalog Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def catalog-versions "Currently supported catalog versions" [:v6]) (deftest replace-catalog (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload (-> (get-in wire-catalogs [6 :empty]) (assoc :producer_timestamp (now)))}]] (testing (str (command-names :replace-catalog) " " version) (let [certname (get-in command [:payload :certname]) catalog-hash (shash/catalog-similarity-hash (catalog/parse-catalog (:payload command) (version-kwd->num version) (now))) command (stringify-payload command) one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) tomorrow (to-timestamp (+ (System/currentTimeMillis) one-day))] (testing "with no catalog should store the catalog" (with-fixtures (test-msg-handler command publish discard-dir (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "with an existing catalog should replace the catalog" (with-fixtures (is (= (query-to-vec "SELECT certname FROM catalogs") [])) (jdbc/insert! :certnames {:certname certname}) (jdbc/insert! :catalogs {:hash (sutils/munge-hash-for-storage "00") :api_version 1 :catalog_version "foo" :certname certname :producer_timestamp (to-timestamp (-> 1 days ago))}) (test-msg-handler command publish discard-dir (is (= [(with-env {:certname certname :catalog catalog-hash})] (query-to-vec (format "SELECT certname, %s as catalog, environment_id FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "when replacing a catalog with a debug directory, should write out catalogs for inspection" (with-fixtures (jdbc/insert! :certnames {:certname certname}) (let [debug-dir (fs/absolute-path (temp-dir "catalog-inspection"))] (jdbc/insert! :catalogs {:hash (sutils/munge-hash-for-storage "0000") :api_version 1 :catalog_version "foo" :certname certname :producer_timestamp (to-timestamp (t/minus (now) (-> 1 days)))}) (is (nil? (fs/list-dir debug-dir))) (test-msg-handler-with-opts command publish discard-dir {:catalog-hash-debug-dir debug-dir} (is (= [(with-env {:certname certname :catalog catalog-hash})] (query-to-vec (format "SELECT certname, %s as catalog, environment_id FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 5 (count (fs/list-dir debug-dir)))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (let [command (assoc command :payload "bad stuff")] (testing "with a bad payload should discard the message" (with-fixtures (test-msg-handler command publish discard-dir (is (empty? (query-to-vec "SELECT * FROM catalogs"))) (is (= 0 (times-called publish))) (is (seq (fs/list-dir discard-dir))))))) (testing "with a newer catalog should ignore the message" (with-fixtures (jdbc/insert! :certnames {:certname certname}) (jdbc/insert! :catalogs {:id 1 :hash (sutils/munge-hash-for-storage "ab") :api_version 1 :catalog_version "foo" :certname certname :timestamp tomorrow :producer_timestamp (to-timestamp (now))}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :catalog "ab"}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "should reactivate the node if it was deactivated before the message" (with-fixtures (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :deactivated nil}] (query-to-vec "SELECT certname,deactivated FROM certnames"))) (is (= [{:certname certname :catalog catalog-hash}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (testing "should store the catalog if the node was deactivated after the message" (scf-store/delete-certname! certname) (jdbc/insert! :certnames {:certname certname :deactivated tomorrow}) (test-msg-handler command publish discard-dir (is (= [{:certname certname :deactivated tomorrow}] (query-to-vec "SELECT certname,deactivated FROM certnames"))) (is (= [{:certname certname :catalog catalog-hash}] (query-to-vec (format "SELECT certname, %s as catalog FROM catalogs" (sutils/sql-hash-as-str "hash"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))))) ;; If there are messages in the user's MQ when they upgrade, we could ;; potentially have commands of an unsupported format that need to be ;; processed. Although we don't support the catalog versions below, we ;; need to test that those commands will be processed properly (deftest replace-catalog-with-v5 (testing "catalog wireformat v5" (let [command {:command (command-names :replace-catalog) :version 5 :payload (get-in wire-catalogs [5 :empty])} certname (get-in command [:payload :name]) cmd-producer-timestamp (get-in command [:payload :producer-timestamp])] (with-fixtures (test-msg-handler command publish discard-dir ;;names in v5 are hyphenated, this check ensures we're sending a v5 catalog (is (contains? (:payload command) :producer-timestamp)) (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) ;;this should be the hyphenated producer timestamp provided above (is (= (-> (query-to-vec "SELECT producer_timestamp FROM catalogs") first :producer_timestamp) (to-timestamp cmd-producer-timestamp)))))))) (deftest replace-catalog-with-v4 (let [command {:command (command-names :replace-catalog) :version 4 :payload (get-in wire-catalogs [4 :empty])} certname (get-in command [:payload :name]) cmd-producer-timestamp (get-in command [:payload :producer-timestamp]) recent-time (-> 1 seconds ago)] (with-fixtures (test-msg-handler command publish discard-dir (is (false? (contains? (:payload command) :producer-timestamp))) (is (= [(with-env {:certname certname})] (query-to-vec "SELECT certname, environment_id FROM catalogs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) ;;v4 does not include a producer_timestmap, the backend ;;should use the time the command was received instead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM catalogs") first :producer_timestamp to-date-time))))))) (defn update-resource "Updated the resource in `catalog` with the given `type` and `title`. `update-fn` is a function that accecpts the resource map as an argument and returns a (possibly mutated) resource map." [version catalog type title update-fn] (let [path [:payload :resources]] (update-in catalog path (fn [resources] (mapv (fn [res] (if (and (= (:title res) title) (= (:type res) type)) (update-fn res) res)) resources))))) (def basic-wire-catalog (get-in wire-catalogs [6 :basic])) (deftest catalog-with-updated-resource-line (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :line 20)))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= 10 (get-in orig-resources [{:type "File" :title "/etc/foobar"} :line]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :line] 20) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-file (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :file "/tmp/not-foo")))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= "/tmp/foo" (get-in orig-resources [{:type "File" :title "/etc/foobar"} :file]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :file] "/tmp/not-foo") (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-exported (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(assoc % :exported true)))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= false (get-in orig-resources [{:type "File" :title "/etc/foobar"} :exported]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (assoc-in orig-resources [{:type "File" :title "/etc/foobar"} :exported] true) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) (deftest catalog-with-updated-resource-tags (doverseq [version catalog-versions :let [command {:command (command-names :replace-catalog) :version 6 :payload basic-wire-catalog} command-1 (stringify-payload command) command-2 (stringify-payload (update-resource version command "File" "/etc/foobar" #(-> %(assoc :tags #{"file" "class" "foobar" "foo"}) (assoc :line 20))))]] (test-msg-handler command-1 publish discard-dir (let [orig-resources (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com")))] (is (= #{"file" "class" "foobar"} (get-in orig-resources [{:type "File" :title "/etc/foobar"} :tags]))) (is (= 10 (get-in orig-resources [{:type "File" :title "/etc/foobar"} :line]))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (test-msg-handler command-2 publish discard-dir (is (= (-> orig-resources (assoc-in [{:type "File" :title "/etc/foobar"} :tags] #{"file" "class" "foobar" "foo"}) (assoc-in [{:type "File" :title "/etc/foobar"} :line] 20)) (scf-store/catalog-resources (:id (scf-store/catalog-metadata "basic.wire-catalogs.com"))))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Fact Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def fact-versions "Support fact command versions" [:v4]) (let [certname "foo.example.com" facts {:certname certname :environment "DEV" :values {"a" "1" "b" "2" "c" "3"} :producer_timestamp (to-timestamp (now))} v4-command {:command (command-names :replace-facts) :version 4 :payload facts} one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) tomorrow (to-timestamp (+ (System/currentTimeMillis) one-day))] (deftest replace-facts-no-facts (doverseq [version fact-versions :let [command v4-command]] (testing "should store the facts" (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})]))))))) (deftest replace-facts-existing-facts (doverseq [version fact-versions :let [command v4-command]] (jdbc/with-db-transaction [] (scf-store/ensure-environment "DEV") (scf-store/add-certname! certname) (scf-store/replace-facts! {:certname certname :values {"x" "24" "y" "25" "z" "26"} :timestamp yesterday :producer_timestamp yesterday :environment "DEV"})) (testing "should replace the facts" (test-msg-handler command publish discard-dir (let [[result & _] (query-to-vec "SELECT certname,timestamp, environment_id FROM factsets")] (is (= (:certname result) certname)) (is (not= (:timestamp result) yesterday)) (is (= (scf-store/environment-id "DEV") (:environment_id result)))) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY fp.path ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (deftest replace-facts-newer-facts (doverseq [version fact-versions :let [command v4-command]] (jdbc/with-db-transaction [] (scf-store/ensure-environment "DEV") (scf-store/add-certname! certname) (scf-store/add-facts! {:certname certname :values {"x" "24" "y" "25" "z" "26"} :timestamp tomorrow :producer_timestamp (to-timestamp (now)) :environment "DEV"})) (testing "should ignore the message" (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,timestamp,environment_id FROM factsets") [(with-env {:certname certname :timestamp tomorrow})])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "x" :value "24"} {:certname certname :name "y" :value "25"} {:certname certname :name "z" :value "26"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))))) (deftest replace-facts-deactivated-node-facts (doverseq [version fact-versions :let [command v4-command]] (testing "should reactivate the node if it was deactivated before the message" (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,deactivated FROM certnames") [{:certname certname :deactivated nil}])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))))) (testing "should store the facts if the node was deactivated after the message" (scf-store/delete-certname! certname) (jdbc/insert! :certnames {:certname certname :deactivated tomorrow}) (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,deactivated FROM certnames") [{:certname certname :deactivated tomorrow}])) (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1"} {:certname certname :name "b" :value "2"} {:certname certname :name "c" :value "3"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))))) ;;v2 and v3 fact commands are only supported when commands are still ;;sitting in the queue from before upgrading (deftest replace-facts-with-v3-wire-format (let [certname "foo.example.com" producer-time (-> (now) to-timestamp json/generate-string json/parse-string pt/to-timestamp) facts-cmd {:command (command-names :replace-facts) :version 3 :payload {:name certname :environment "DEV" :producer-timestamp producer-time :values {"a" "1" "b" "2" "c" "3"}}}] (test-msg-handler facts-cmd publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname, e.environment, fs.producer_timestamp FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id INNER JOIN environments as e on fs.environment_id = e.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1" :producer_timestamp producer-time :environment "DEV"} {:certname certname :name "b" :value "2" :producer_timestamp producer-time :environment "DEV"} {:certname certname :name "c" :value "3" :producer_timestamp producer-time :environment "DEV"}])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})])))))) (deftest replace-facts-with-v2-wire-format (let [certname "foo.example.com" before-test-starts-time (-> 1 seconds ago) facts-cmd {:command (command-names :replace-facts) :version 2 :payload {:name certname :environment "DEV" :values {"a" "1" "b" "2" "c" "3"}}}] (test-msg-handler facts-cmd publish discard-dir (is (= (query-to-vec "SELECT fp.path as name, COALESCE(fv.value_string, cast(fv.value_integer as text), cast(fv.value_boolean as text), cast(fv.value_float as text), '') as value, fs.certname, e.environment FROM factsets fs INNER JOIN facts as f on fs.id = f.factset_id INNER JOIN fact_values as fv on f.fact_value_id = fv.id INNER JOIN fact_paths as fp on f.fact_path_id = fp.id INNER JOIN environments as e on fs.environment_id = e.id WHERE fp.depth = 0 ORDER BY name ASC") [{:certname certname :name "a" :value "1" :environment "DEV"} {:certname certname :name "b" :value "2" :environment "DEV"} {:certname certname :name "c" :value "3" :environment "DEV"}])) (is (every? (comp #(t/before? before-test-starts-time %) to-date-time :producer_timestamp) (query-to-vec "SELECT fs.producer_timestamp FROM factsets fs"))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (let [result (query-to-vec "SELECT certname,environment_id FROM factsets")] (is (= result [(with-env {:certname certname})])))))) (deftest replace-facts-bad-payload (let [bad-command {:command (command-names :replace-facts) :version 4 :payload "bad stuff"}] (doverseq [version fact-versions :let [command bad-command]] (testing "should discard the message" (test-msg-handler command publish discard-dir (is (empty? (query-to-vec "SELECT * FROM facts"))) (is (= 0 (times-called publish))) (is (seq (fs/list-dir discard-dir)))))))) (defn extract-error-message "Pulls the error message from the publish var of a test-msg-handler" [publish] (-> publish meta :args deref ffirst json/parse-string (get-in ["annotations" "attempts"]) first (get "error"))) (deftest concurrent-fact-updates (testing "Should allow only one replace facts update for a given cert at a time" (let [certname "some_certname" facts {:certname certname :environment "DEV" :values {"domain" "mydomain.com" "fqdn" "myhost.mydomain.com" "hostname" "myhost" "kernel" "Linux" "operatingsystem" "Debian" } :producer_timestamp (to-timestamp (now))} command {:command (command-names :replace-facts) :version 4 :payload facts} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-facts! scf-store/update-facts!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/add-facts! {:certname certname :values (:values facts) :timestamp (-> 2 days ago) :environment nil :producer_timestamp (-> 2 days ago)})) (with-redefs [scf-store/update-facts! (fn [fact-data] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-facts! fact-data))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-facts (update-in facts [:values] (fn [values] (-> values (dissoc "kernel") (assoc "newfact2" "here")))) new-facts-cmd {:command (command-names :replace-facts) :version 4 :payload new-facts}] (test-msg-handler new-facts-cmd publish discard-dir (reset! second-message? true) (is (re-matches (if (sutils/postgres?) #"(?sm).*ERROR: could not serialize access due to concurrent update.*" #".*transaction rollback: serialization failure") (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (defn thread-id [] (.getId (Thread/currentThread))) (deftest fact-path-update-race ;; Simulates two update commands being processed for two different ;; machines at the same time. Before we lifted fact paths into ;; facts, the race tested here could result in a constraint ;; violation when the two updates left behind an orphaned row. (let [certname-1 "some_certname1" certname-2 "some_certname2" ;; facts for server 1, has the same "mytimestamp" value as the ;; facts for server 2 facts-1a {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian" "mytimestamp" "1"} :producer_timestamp (-> 2 days ago)} facts-2a {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian" "mytimestamp" "1"} :producer_timestamp (-> 2 days ago)} ;; same facts as before, but now certname-1 has a different ;; fact value for mytimestamp (this will force a new fact_value ;; that is only used for certname-1 facts-1b {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian" "mytimestamp" "1b"} :producer_timestamp (-> 1 days ago)} ;; with this, certname-1 and certname-2 now have their own ;; fact_value for mytimestamp that is different from the ;; original mytimestamp that they originally shared facts-2b {:certname certname-2 :environment nil :values {"domain" "mydomain2.com" "operatingsystem" "Debian" "mytimestamp" "2b"} :producer_timestamp (-> 1 days ago)} ;; this fact set will disassociate mytimestamp from the facts ;; associated to certname-1, it will do the same thing for ;; certname-2 facts-1c {:certname certname-1 :environment nil :values {"domain" "mydomain1.com" "operatingsystem" "Debian"} :producer_timestamp (now)} facts-2c {:certname certname-2 :environment nil :values {"domain" "mydomainPI:EMAIL:<EMAIL>END_PI" "operatingsystem" "Debian"} :producer_timestamp (now)} command-1b {:command (command-names :replace-facts) :version 4 :payload facts-1b} command-2b {:command (command-names :replace-facts) :version 4 :payload facts-2b} command-1c {:command (command-names :replace-facts) :version 4 :payload facts-1c} command-2c {:command (command-names :replace-facts) :version 4 :payload facts-2c} ;; Wait for two threads to countdown before proceeding latch (java.util.concurrent.CountDownLatch. 2) ;; I'm modifying delete-pending-path-id-orphans! so that I can ;; coordinate access between the two threads, I'm storing the ;; reference to the original delete-pending-path-id-orphans! ;; here, so that I can delegate to it once I'm done ;; coordinating storage-delete-pending-path-id-orphans! scf-store/delete-pending-path-id-orphans!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname-1) (scf-store/add-certname! certname-2) (scf-store/add-facts! {:certname certname-1 :values (:values facts-1a) :timestamp (now) :environment nil :producer_timestamp (:producer_timestamp facts-1a)}) (scf-store/add-facts! {:certname certname-2 :values (:values facts-2a) :timestamp (now) :environment nil :producer_timestamp (:producer_timestamp facts-2a)})) ;; At this point, there will be 4 fact_value rows, 1 for ;; mytimestamp, 1 for the operatingsystem, 2 for domain (with-redefs [scf-store/delete-pending-path-id-orphans! (fn [& args] ;; Once this has been called, it will countdown ;; the latch and block (.countDown latch) ;; After the second command has been executed and ;; it has decremented the latch, the await will no ;; longer block and both threads will begin ;; running again (.await latch) ;; Execute the normal delete-pending-path-id-orphans! ;; function (unchanged) (apply storage-delete-pending-path-id-orphans! args))] (let [first-message? (atom false) second-message? (atom false) fut-1 (future (test-msg-handler command-1b publish discard-dir (reset! first-message? true))) fut-2 (future (test-msg-handler command-2b publish discard-dir (reset! second-message? true)))] ;; The two commands are being submitted in future, ensure they ;; have both completed before proceeding @fut-2 @fut-1 ;; At this point there are 6 fact values, the original ;; mytimestamp, the two new mytimestamps, operating system and ;; the two domains (is (true? @first-message?)) (is (true? @second-message?)) ;; Submit another factset that does NOT include mytimestamp, ;; this disassociates certname-1's fact_value (which is 1b) (test-msg-handler command-1c publish discard-dir (reset! first-message? true)) ;; Do the same thing with certname-2. Since the reference to 1b ;; and 2b has been removed, mytimestamp's path is no longer ;; connected to any fact values. The original mytimestamp value ;; of 1 is still in the table. It's now attempting to delete ;; that fact path, when the mytimestamp 1 value is still in ;; there. (test-msg-handler command-2c publish discard-dir (is (not (extract-error-message publish)))) ;; Can we see the orphaned value '1', and does the global gc remove it. (is (= 1 (count (query-to-vec "select id from fact_values where value_string = '1'")))) (scf-store/garbage-collect! *db*) (is (zero? (count (query-to-vec "select id from fact_values where value_string = '1'")))))))) (deftest concurrent-catalog-updates (testing "Should allow only one replace catalogs update for a given cert at a time" (let [test-catalog (get-in catalogs [:empty]) {certname :certname :as wire-catalog} (get-in wire-catalogs [6 :empty]) nonwire-catalog (catalog/parse-catalog wire-catalog 6 (now)) command {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string wire-catalog)} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-catalog! scf-store/replace-catalog!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/replace-catalog! nonwire-catalog (-> 2 days ago))) (with-redefs [scf-store/replace-catalog! (fn [catalog timestamp dir] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-catalog! catalog timestamp dir))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-wire-catalog (assoc-in wire-catalog [:edges] #{{:relationship "contains" :target {:title "Settings" :type "Class"} :source {:title "main" :type "Stage"}}}) new-catalog-cmd {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string new-wire-catalog)}] (test-msg-handler new-catalog-cmd publish discard-dir (reset! second-message? true) (is (empty? (fs/list-dir discard-dir))) (is (re-matches #".*BatchUpdateException.*(rollback|abort).*" (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (deftest concurrent-catalog-resource-updates (testing "Should allow only one replace catalogs update for a given cert at a time" (let [test-catalog (get-in catalogs [:empty]) {certname :certname :as wire-catalog} (get-in wire-catalogs [6 :empty]) nonwire-catalog (catalog/parse-catalog wire-catalog 6 (now)) command {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string wire-catalog)} hand-off-queue (java.util.concurrent.SynchronousQueue.) storage-replace-catalog! scf-store/replace-catalog!] (jdbc/with-db-transaction [] (scf-store/add-certname! certname) (scf-store/replace-catalog! nonwire-catalog (-> 2 days ago))) (with-redefs [scf-store/replace-catalog! (fn [catalog timestamp dir] (.put hand-off-queue "got the lock") (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) (storage-replace-catalog! catalog timestamp dir))] (let [first-message? (atom false) second-message? (atom false) fut (future (test-msg-handler command publish discard-dir (reset! first-message? true))) _ (.poll hand-off-queue 5 java.util.concurrent.TimeUnit/SECONDS) new-wire-catalog (update-in wire-catalog [:resources] conj {:type "File" :title "/etc/foobar2" :exported false :file "/tmp/foo2" :line 10 :tags #{"file" "class" "foobar2"} :parameters {:ensure "directory" :group "root" :user "root"}}) new-catalog-cmd {:command (command-names :replace-catalog) :version 6 :payload (json/generate-string new-wire-catalog)}] (test-msg-handler new-catalog-cmd publish discard-dir (reset! second-message? true) (is (empty? (fs/list-dir discard-dir))) (is (re-matches #".*BatchUpdateException.*(rollback|abort).*" (extract-error-message publish)))) @fut (is (true? @first-message?)) (is (true? @second-message?))))))) (let [cases [{:certname "foo.example.com" :command {:command (command-names :deactivate-node) :version 3 :payload {:certname "foo.example.com"}}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 3 :payload {:certname "bar.example.com" :producer_timestamp (now)}}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 2 :payload "bar.example.com"}} {:certname "bar.example.com" :command {:command (command-names :deactivate-node) :version 1 :payload (json/generate-string "bar.example.com")}}]] (deftest deactivate-node-node-active (testing "should deactivate the node" (doseq [{:keys [certname command]} cases] (jdbc/insert! :certnames {:certname certname}) (test-msg-handler command publish discard-dir (let [results (query-to-vec "SELECT certname,deactivated FROM certnames") result (first results)] (is (= (:certname result) certname)) (is (instance? java.sql.Timestamp (:deactivated result))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames")))))) (deftest deactivate-node-node-inactive (doseq [{:keys [certname command]} cases] (testing "should leave the node alone" (let [one-day (* 24 60 60 1000) yesterday (to-timestamp (- (System/currentTimeMillis) one-day)) command (if (#{1 2} (:version command)) ;; Can't set the :producer_timestamp for the older ;; versions (so that we can control the deactivation ;; timestamp). command (assoc-in command [:payload :producer_timestamp] yesterday))] (jdbc/insert! :certnames {:certname certname :deactivated yesterday}) (test-msg-handler command publish discard-dir (let [[row & rest] (query-to-vec "SELECT certname,deactivated FROM certnames")] (is (empty? rest)) (is (instance? java.sql.Timestamp (:deactivated row))) (if (#{1 2} (:version command)) (do ;; Since we can't control the producer_timestamp. (is (= certname (:certname row))) (is (t/after? (from-sql-date (:deactivated row)) (from-sql-date yesterday)))) (is (= {:certname certname :deactivated yesterday} row))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames"))))))) (deftest deactivate-node-node-missing (testing "should add the node and deactivate it" (doseq [{:keys [certname command]} cases] (test-msg-handler command publish discard-dir (let [results (query-to-vec "SELECT certname,deactivated FROM certnames") result (first results)] (is (= (:certname result) certname)) (is (instance? java.sql.Timestamp (:deactivated result))) (is (zero? (times-called publish))) (is (empty? (fs/list-dir discard-dir))) (jdbc/do-prepared "delete from certnames"))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Report Command Tests ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def v5-report (-> (:basic report-examples/reports) (assoc :environment "DEV") reports/report-query->wire-v5)) (def v4-report (-> v5-report (dissoc :producer_timestamp :metrics :logs :noop) utils/underscore->dash-keys)) (def store-report (command-names :store-report)) (deftest store-v6-report-test (let [v6-report (-> v5-report (update :resource_events reports/resource-events-v5->resources) (clojure.set/rename-keys {:resource_events :resources})) command {:command store-report :version 6 :payload v6-report}] (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports") [(with-env (select-keys v6-report [:certname :configuration_version]))])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v5-report-test (let [command {:command store-report :version 5 :payload v5-report}] (test-msg-handler command publish discard-dir (is (= (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports") [(with-env (select-keys v5-report [:certname :configuration_version]))])) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v4-report-test (let [command {:command store-report :version 4 :payload v4-report} recent-time (-> 1 seconds ago)] (test-msg-handler command publish discard-dir (is (= [(with-env (utils/dash->underscore-keys (select-keys v4-report [:certname :configuration-version])))] (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports"))) ;;Status is present in v4+ (but not in v3) (is (= "unchanged" (-> (query-to-vec "SELECT rs.status FROM reports r inner join report_statuses rs on r.status_id = rs.id") first :status))) ;;No producer_timestamp is included in v4, message received time (now) is used intead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM reports") first :producer_timestamp to-date-time))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (deftest store-v3-report-test (let [v3-report (dissoc v4-report :status) recent-time (-> 1 seconds ago) command {:command store-report :version 3 :payload v3-report}] (test-msg-handler command publish discard-dir (is (= [(with-env (utils/dash->underscore-keys (select-keys v3-report [:certname :configuration-version])))] (query-to-vec "SELECT certname,configuration_version,environment_id FROM reports"))) ;;No producer_timestamp is included in v4, message received time (now) is used intead (is (t/before? recent-time (-> (query-to-vec "SELECT producer_timestamp FROM reports") first :producer_timestamp to-date-time))) ;;Status is not supported in v3, should be nil (is (nil? (-> (query-to-vec "SELECT status_id FROM reports") first :status))) (is (= 0 (times-called publish))) (is (empty? (fs/list-dir discard-dir)))))) (defn- get-config [] (conf/get-config (get-service svc-utils/*server* :DefaultedConfig))) (deftest command-service-stats (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) stats (partial stats dispatcher) real-replace! scf-store/replace-facts!] ;; Issue a single command and ensure the stats are right at each step. (is (= {:received-commands 0 :executed-commands 0} (stats))) (let [received-cmd? (promise) go-ahead-and-execute (promise)] (with-redefs [scf-store/replace-facts! (fn [& args] (deliver received-cmd? true) @go-ahead-and-execute (apply real-replace! args))] (enqueue-command (command-names :replace-facts) 4 {:environment "DEV" :certname "foo.local" :values {:foo "foo"} :producer_timestamp (to-string (now))}) @received-cmd? (is (= {:received-commands 1 :executed-commands 0} (stats))) (deliver go-ahead-and-execute true) (while (not= 1 (:executed-commands (stats))) (Thread/sleep 100)) (is (= {:received-commands 1 :executed-commands 1} (stats)))))))) (deftest date-round-trip (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) deactivate-ms 14250331086887 ;; The problem only occurred if you passed a Date to ;; enqueue, a DateTime wasn't a problem. input-stamp (java.util.Date. deactivate-ms) expected-stamp (DateTime. deactivate-ms DateTimeZone/UTC)] (enqueue-command (command-names :deactivate-node) 3 {:certname "foo.local" :producer_timestamp input-stamp}) (is (svc-utils/wait-for-server-processing svc-utils/*server* 5000)) ;; While we're here, check the value in the database too... (is (= expected-stamp (jdbc/with-transacted-connection (:scf-read-db (cli-svc/shared-globals pdb)) :repeatable-read (from-sql-date (scf-store/node-deactivated-time "foo.local"))))) (is (= expected-stamp (-> (client/get (str (utils/base-url->str svc-utils/*base-url*) "/nodes") {:accept :json :throw-exceptions true :throw-entire-message true :query-params {"query" (json/generate-string ["or" ["=" ["node" "active"] true] ["=" ["node" "active"] false]])}}) :body json/parse-string first (get "deactivated") (pt/from-string))))))) (deftest command-response-channel (svc-utils/with-puppetdb-instance (let [pdb (get-service svc-utils/*server* :PuppetDBServer) dispatcher (get-service svc-utils/*server* :PuppetDBCommandDispatcher) enqueue-command (partial enqueue-command dispatcher) response-mult (response-mult dispatcher) response-chan (async/chan) command-uuid (ks/uuid)] (async/tap response-mult response-chan) (enqueue-command (command-names :deactivate-node) 3 {:certname "foo.local" :producer_timestamp (java.util.Date.)} command-uuid) (let [received-uuid (async/alt!! response-chan ([msg] (:id msg)) (async/timeout 2000) ::timeout)] (is (= command-uuid received-uuid)))))) ;; Local Variables: ;; mode: clojure ;; eval: (define-clojure-indent (test-msg-handler (quote defun)) ;; (test-msg-handler-with-opts (quote defun)) ;; (doverseq (quote defun)))) ;; End:
[ { "context": "d use something like [environ](https://github.com/weavejester/environ)\nto store these values locally outside of", "end": 729, "score": 0.994905412197113, "start": 718, "tag": "USERNAME", "value": "weavejester" }, { "context": " :coinbase_account_id \\\"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\\\"})\n```\" \n [client opts]\n (->> (build-post-req", "end": 10209, "score": 0.9992597103118896, "start": 10171, "tag": "KEY", "value": "7d0f7d8e-dd34-4d9c-a846-06f431c381ba\\\"" }, { "context": " :coinbase_account_id \\\"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\\\"})\n```\"\n [client opts]\n (->> (build-post-request", "end": 10665, "score": 0.9994907975196838, "start": 10627, "tag": "KEY", "value": "7d0f7d8e-dd34-4d9c-a846-06f431c381ba\\\"" } ]
src/coinbase_pro_clj/core.clj
bpringe/coinbase-pro-clojure
21
(ns coinbase-pro-clj.core "Public and private endpoint functions and websocket feed functionality. In all function signatures, `client` is a map with the following keys: - `:url` - rest URL - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API key - `:passphrase` - optional - your Coinbase Pro API key `key`, `secret`, and `passphrase` are only required if the request is authenticated. These values can be created in the [API settings](https://pro.coinbase.com/profile/api) of your Coinbase Pro account. **Remember not to store these values in an online repository as this will give others access to your account. You could use something like [environ](https://github.com/weavejester/environ) to store these values locally outside of your code.**" (:require [coinbase-pro-clj.utilities :refer :all] [coinbase-pro-clj.authentication :refer :all] [cheshire.core :refer :all] [clj-http.client :as http] [gniazdo.core :as ws]) (:import (org.eclipse.jetty.websocket.client WebSocketClient) (org.eclipse.jetty.util.ssl SslContextFactory))) ;; ## Convenience/config values (def rest-url "The rest URL for Coinbase Pro." "https://api.pro.coinbase.com") (def websocket-url "The websocket URL for Coinbase Pro." "wss://ws-feed.pro.coinbase.com") (def sandbox-rest-url "The sandbox rest URL for Coinbase Pro." "https://api-public.sandbox.pro.coinbase.com") (def sandbox-websocket-url "The sandbox websocket URL for Coinbase Pro." "wss://ws-feed-public.sandbox.pro.coinbase.com") (def ^:private default-channels "Default channels for websocket subscriptions, used if none is explicitly stated." ["heartbeat"]) (defn- send-request "Takes in a request, sends the http request, and returns the body of the response." [request] (-> request http/request :body)) ;; ## Public endpoints (defn get-time "[API docs](https://docs.pro.coinbase.com/#time)" [client] (-> (str (:url client) "/time") build-get-request send-request)) (defn get-products "[API docs](https://docs.pro.coinbase.com/#products)" [client] (-> (str (:url client) "/products") build-get-request send-request)) (defn get-order-book "[API docs](https://docs.pro.coinbase.com/#get-product-order-book) ```clojure (get-order-book client \"BTC-USD\") (get-order-book client \"BTC-USD\" 2) ```" ([client product-id] (get-order-book client product-id 1)) ([client product-id level] (-> (str (:url client) "/products/" product-id "/book?level=" level) build-get-request send-request))) (defn get-ticker "[API docs](https://docs.pro.coinbase.com/#get-product-ticker) ```clojure (get-ticker client \"BTC-USD\") (get-ticker client \"BTC-USD\" {:before 2 :limit 5}) ```" ([client product-id] (get-ticker client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/ticker") build-get-request (append-query-params opts) send-request))) (defn get-trades "[API docs](https://docs.pro.coinbase.com/#get-trades) ```clojure (get-trades client \"BTC-USD\") (get-trades client \"BTC-USD\" {:before 2 :limit 5}) ```" ([client product-id] (get-trades client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/trades") build-get-request (append-query-params opts) send-request))) (defn get-historic-rates "[API docs](https://docs.pro.coinbase.com/#get-historic-rates) ```clojure (get-historic-rates client \"BTC-USD\") (get-historic-rates client \"BTC-USD\" {:start \"2018-06-01\" :end \"2018-06-30\" :granularity 86400}) ```" ([client product-id] (get-historic-rates client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/candles") build-get-request (append-query-params opts) send-request))) (defn get-24hour-stats "[API docs](https://docs.pro.coinbase.com/#get-24hr-stats) ```clojure (get-24hour-stats client \"BTC-USD\") ```" [client product-id] (->> (str (:url client) "/products/" product-id "/stats") build-get-request send-request)) (defn get-currencies "[API docs](https://docs.pro.coinbase.com/#get-currencies)" [client] (send-request (build-get-request (str (:url client) "/currencies")))) ;; ## Private endpoints (defn get-accounts "[API docs](https://docs.pro.coinbase.com/#list-accounts)" [client] (->> (build-get-request (str (:url client) "/accounts")) (sign-request client) send-request)) (defn get-account "[API docs](https://docs.pro.coinbase.com/#get-an-account) ```clojure (get-account client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client account-id] (->> (build-get-request (str (:url client) "/accounts/" account-id)) (sign-request client) send-request)) (defn get-account-history "[API docs](https://docs.pro.coinbase.com/#get-account-history) ```clojure (get-account-history client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") (get-account-history client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\" {:before 2 :limit 5}) ```" ([client account-id] (get-account-history client account-id {})) ([client account-id paging-opts] (->> (build-get-request (str (:url client) "/accounts/" account-id "/ledger")) (append-query-params paging-opts) (sign-request client) send-request))) (defn get-account-holds "[API docs](https://docs.pro.coinbase.com/#get-holds) ```clojure (get-account-holds client \"BTC-USD\" \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") (get-account-holds client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\" {:before 2 :limit 5}) ```" ([client account-id] (get-account-holds client account-id {})) ([client account-id paging-opts] (->> (build-get-request (str (:url client) "/accounts/" account-id "/holds")) (append-query-params paging-opts) (sign-request client) send-request))) (defn place-order "[API docs](https://docs.pro.coinbase.com/#place-a-new-order) ```clojure (place-order client {:side \"buy\" :product_id \"BTC-USD\" :price 5000 :size 1}) ```" [client opts] (->> (build-post-request (str (:url client) "/orders") opts) (sign-request client) send-request)) (defn get-orders "[API docs](https://docs.pro.coinbase.com/#list-orders) ```clojure (get-orders client {:status [\"open\" \"pending\"]}) ```" ([client] (get-orders client {:status ["all"]})) ([client opts] (let [query-string (clojure.string/join "&" (map #(str "status=" %) (:status opts))) rest-opts (dissoc opts :status)] (->> (build-get-request (str (:url client) "/orders" (when-not (clojure.string/blank? query-string) "?") query-string)) (append-query-params rest-opts) (sign-request client) send-request)))) (defn cancel-order "[API docs](https://docs.pro.coinbase.com/#cancel-an-order) ```clojure (cancel-order client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client order-id] (->> (build-delete-request (str (:url client) "/orders/" order-id)) (sign-request client) send-request)) (defn cancel-all "[API docs](https://docs.pro.coinbase.com/#cancel-all) ```clojure (cancel-all client \"BTC-USD\") ```" ([client] (cancel-all client nil)) ([client product-id] (->> (build-delete-request (str (:url client) "/orders" (when-not (nil? product-id) (str "?product_id=" product-id)))) (sign-request client) send-request))) (defn get-order "[API docs](https://docs.pro.coinbase.com/#get-an-order) ```clojure (get-order client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client order-id] (->> (build-get-request (str (:url client) "/orders/" order-id)) (sign-request client) send-request)) ;; opts must contain either order_id or product_id (defn get-fills "[API docs](https://docs.pro.coinbase.com/#list-fills) Opts must contain either `:order_id` or `:product_id`. ```clojure (get-fills client {:product_id \"BTC-USD\" :before 2}) ```" ([client opts] (->> (build-get-request (str (:url client) "/fills")) (append-query-params opts) (sign-request client) send-request))) (defn get-payment-methods "[API docs](https://docs.pro.coinbase.com/#list-payment-methods)" [client] (->> (build-get-request (str (:url client) "/payment-methods")) (sign-request client) send-request)) (defn deposit-from-payment-method "[API docs](https://docs.pro.coinbase.com/#payment-method) ```clojure (deposit-from-payment-method client {:amount 10 :currency \"USD\" :payment_method_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/deposits/payment-method") opts) (sign-request client) send-request)) (defn withdraw-to-payment-method "[API docs](https://docs.pro.coinbase.com/#payment-method48) ```clojure (withdraw-to-payment-method client {:amount 10 :currency \"BTC-USD\" :payment_method_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/payment-method") opts) (sign-request client) send-request)) (defn get-coinbase-accounts "[API docs](https://docs.pro.coinbase.com/#list-accounts54)" [client] (->> (build-get-request (str (:url client) "/coinbase-accounts")) (sign-request client) send-request)) (defn deposit-from-coinbase "[API docs](https://docs.pro.coinbase.com/#coinbase) ```clojure (deposit-from-coinbase client {:amount 2 :currency \"BTC\" :coinbase_account_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/deposits/coinbase-account") opts) (sign-request client) send-request)) (defn withdraw-to-coinbase "[API docs](https://docs.pro.coinbase.com/#coinbase49) ```clojure (withdraw-to-coinbase client {:amount 2 :currency \"BTC\" :coinbase_account_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/coinbase-account") opts) (sign-request client) send-request)) (defn withdraw-to-crypto-address "[API docs](https://docs.pro.coinbase.com/#crypto) ```clojure (withdraw-to-crypto-address client {:amount 2 :currency \"BTC\" :crypto_address \"15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/crypto") opts) (sign-request client) send-request)) (defn generate-report "[API docs](https://docs.pro.coinbase.com/#create-a-new-report) ```clojure (generate-report client {:type \"fills\" :start_date \"2018-6-1\" :end_date \"2018-6-30\" :product_id \"BTC-USD\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/reports") opts) (sign-request client) send-request)) (defn get-report-status "[API docs](https://docs.pro.coinbase.com/#get-report-status) ```clojure (get-report-status client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client report-id] (->> (build-get-request (str (:url client) "/reports/" report-id)) (sign-request client) send-request)) (defn get-trailing-volume "[API docs](https://docs.pro.coinbase.com/#trailing-volume)" [client] (->> (build-get-request (str (:url client) "/users/self/trailing-volume")) (sign-request client) send-request)) ;; ## Websocket feed (defn- create-subscribe-message "Creates the subscribe message and signs the message if key, secret, and passphrase are provided." [opts] (let [message {:type "subscribe" :product_ids (:product_ids opts) :channels (or (:channels opts) default-channels)}] (if (contains-many? opts :key :secret :passphrase) (sign-message message opts) message))) (defn- create-unsubscribe-message "Creates the unsubscribe message." [opts] (merge opts {:type "unsubscribe"})) (defn subscribe "[API docs](https://docs.pro.coinbase.com/#subscribe) - `connection` is created with [[create-websocket-connection]] - `opts` is a map with the following keys: - `:product_ids` - either this or `:channels` or both must be provided (see the Coinbase Pro API docs) - a vector of strings - `:channels` - either this or `:product_ids` or both must be provided (see the Coinbase Pro API docs) - a vector of strings or maps with `:name` (string) and `:product_ids` (vector of strings) - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API key - `:passphrase` - optional - your Coinbase Pro API key ```clojure (subscribe connection {:product_ids [\"BTC-USD\"]}) ```" [connection opts] (->> (create-subscribe-message opts) edn->json (ws/send-msg connection))) (defn unsubscribe "[API docs](https://docs.pro.coinbase.com/#subscribe) - `connection` is created with [[create-websocket-connection]]. - `opts` takes the equivalent shape as [[subscribe]]. ```clojure (unsubscribe connection {:product_ids [\"BTC-USD\"]}) ```" [connection opts] (->> (create-unsubscribe-message opts) edn->json (ws/send-msg connection))) (defn close "`connection` is created with [[create-websocket-connection]]." [connection] (ws/close connection)) (defn- create-on-receive "Returns a function that returns nil if user-on-receive is nil, otherwise returns a function that takes the received message, converts it to edn, then passes it to the user-on-receive function" [user-on-receive] (if (nil? user-on-receive) (constantly nil) (fn [msg] (-> msg json->edn ; convert to edn before passing to user defined on-receive user-on-receive)))) (defn- get-socket-connection "Creates the socket client using the Java WebSocketClient and SslContextFactory, starts the client, then connects it to the websocket URL." [opts] (let [client (WebSocketClient. (SslContextFactory.))] (.setMaxTextMessageSize (.getPolicy client) (* 1024 1024)) (.start client) (ws/connect (:url opts) :client client :on-connect (or (:on-connect opts) (constantly nil)) :on-receive (create-on-receive (:on-receive opts)) :on-close (or (:on-close opts) (constantly nil)) :on-error (or (:on-error opts) (constantly nil))))) (defn create-websocket-connection "[API docs](https://docs.pro.coinbase.com/#websocket-feed) `opts` is a map that takes the following keys: - `:url` - the websocket URL - `:product_ids` - either this or `:channels` or both must be provided (see the Coinbase Pro API docs) - a vector of strings - `:channels` - either this or `:product_ids` or both must be provided (see the Coinbase Pro API docs) - a vector of strings or maps with `:name` (string) and `:product_ids` (vector of strings) - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API secret - `:passphrase` - optional - your Coinbase Pro API passphrase - `:on-receive` - optional - A unary function called when a message is received. The argument is received as edn. - `:on-connect` - optional - A unary function called after the connection has been established. The argument is a [WebSocketSession](https://www.eclipse.org/jetty/javadoc/9.4.8.v20171121/org/eclipse/jetty/websocket/common/WebSocketSession.html). - `:on-error` - optional - A unary function called in case of errors. The argument is a `Throwable` describing the error. - `:on-close` - optional - A binary function called when the connection is closed. Arguments are an `int` status code and a `String` description of reason. ```clojure (def conn (create-websocket-connection {:product_ids [\"BTC-USD\"] :url \"wss://ws-feed.pro.coinbase.com\" :on-receive (fn [x] (prn 'received x))})) ```" [opts] (let [connection (get-socket-connection opts)] ;; subscribe immediately so the connection isn't lost (subscribe connection opts) connection))
86064
(ns coinbase-pro-clj.core "Public and private endpoint functions and websocket feed functionality. In all function signatures, `client` is a map with the following keys: - `:url` - rest URL - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API key - `:passphrase` - optional - your Coinbase Pro API key `key`, `secret`, and `passphrase` are only required if the request is authenticated. These values can be created in the [API settings](https://pro.coinbase.com/profile/api) of your Coinbase Pro account. **Remember not to store these values in an online repository as this will give others access to your account. You could use something like [environ](https://github.com/weavejester/environ) to store these values locally outside of your code.**" (:require [coinbase-pro-clj.utilities :refer :all] [coinbase-pro-clj.authentication :refer :all] [cheshire.core :refer :all] [clj-http.client :as http] [gniazdo.core :as ws]) (:import (org.eclipse.jetty.websocket.client WebSocketClient) (org.eclipse.jetty.util.ssl SslContextFactory))) ;; ## Convenience/config values (def rest-url "The rest URL for Coinbase Pro." "https://api.pro.coinbase.com") (def websocket-url "The websocket URL for Coinbase Pro." "wss://ws-feed.pro.coinbase.com") (def sandbox-rest-url "The sandbox rest URL for Coinbase Pro." "https://api-public.sandbox.pro.coinbase.com") (def sandbox-websocket-url "The sandbox websocket URL for Coinbase Pro." "wss://ws-feed-public.sandbox.pro.coinbase.com") (def ^:private default-channels "Default channels for websocket subscriptions, used if none is explicitly stated." ["heartbeat"]) (defn- send-request "Takes in a request, sends the http request, and returns the body of the response." [request] (-> request http/request :body)) ;; ## Public endpoints (defn get-time "[API docs](https://docs.pro.coinbase.com/#time)" [client] (-> (str (:url client) "/time") build-get-request send-request)) (defn get-products "[API docs](https://docs.pro.coinbase.com/#products)" [client] (-> (str (:url client) "/products") build-get-request send-request)) (defn get-order-book "[API docs](https://docs.pro.coinbase.com/#get-product-order-book) ```clojure (get-order-book client \"BTC-USD\") (get-order-book client \"BTC-USD\" 2) ```" ([client product-id] (get-order-book client product-id 1)) ([client product-id level] (-> (str (:url client) "/products/" product-id "/book?level=" level) build-get-request send-request))) (defn get-ticker "[API docs](https://docs.pro.coinbase.com/#get-product-ticker) ```clojure (get-ticker client \"BTC-USD\") (get-ticker client \"BTC-USD\" {:before 2 :limit 5}) ```" ([client product-id] (get-ticker client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/ticker") build-get-request (append-query-params opts) send-request))) (defn get-trades "[API docs](https://docs.pro.coinbase.com/#get-trades) ```clojure (get-trades client \"BTC-USD\") (get-trades client \"BTC-USD\" {:before 2 :limit 5}) ```" ([client product-id] (get-trades client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/trades") build-get-request (append-query-params opts) send-request))) (defn get-historic-rates "[API docs](https://docs.pro.coinbase.com/#get-historic-rates) ```clojure (get-historic-rates client \"BTC-USD\") (get-historic-rates client \"BTC-USD\" {:start \"2018-06-01\" :end \"2018-06-30\" :granularity 86400}) ```" ([client product-id] (get-historic-rates client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/candles") build-get-request (append-query-params opts) send-request))) (defn get-24hour-stats "[API docs](https://docs.pro.coinbase.com/#get-24hr-stats) ```clojure (get-24hour-stats client \"BTC-USD\") ```" [client product-id] (->> (str (:url client) "/products/" product-id "/stats") build-get-request send-request)) (defn get-currencies "[API docs](https://docs.pro.coinbase.com/#get-currencies)" [client] (send-request (build-get-request (str (:url client) "/currencies")))) ;; ## Private endpoints (defn get-accounts "[API docs](https://docs.pro.coinbase.com/#list-accounts)" [client] (->> (build-get-request (str (:url client) "/accounts")) (sign-request client) send-request)) (defn get-account "[API docs](https://docs.pro.coinbase.com/#get-an-account) ```clojure (get-account client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client account-id] (->> (build-get-request (str (:url client) "/accounts/" account-id)) (sign-request client) send-request)) (defn get-account-history "[API docs](https://docs.pro.coinbase.com/#get-account-history) ```clojure (get-account-history client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") (get-account-history client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\" {:before 2 :limit 5}) ```" ([client account-id] (get-account-history client account-id {})) ([client account-id paging-opts] (->> (build-get-request (str (:url client) "/accounts/" account-id "/ledger")) (append-query-params paging-opts) (sign-request client) send-request))) (defn get-account-holds "[API docs](https://docs.pro.coinbase.com/#get-holds) ```clojure (get-account-holds client \"BTC-USD\" \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") (get-account-holds client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\" {:before 2 :limit 5}) ```" ([client account-id] (get-account-holds client account-id {})) ([client account-id paging-opts] (->> (build-get-request (str (:url client) "/accounts/" account-id "/holds")) (append-query-params paging-opts) (sign-request client) send-request))) (defn place-order "[API docs](https://docs.pro.coinbase.com/#place-a-new-order) ```clojure (place-order client {:side \"buy\" :product_id \"BTC-USD\" :price 5000 :size 1}) ```" [client opts] (->> (build-post-request (str (:url client) "/orders") opts) (sign-request client) send-request)) (defn get-orders "[API docs](https://docs.pro.coinbase.com/#list-orders) ```clojure (get-orders client {:status [\"open\" \"pending\"]}) ```" ([client] (get-orders client {:status ["all"]})) ([client opts] (let [query-string (clojure.string/join "&" (map #(str "status=" %) (:status opts))) rest-opts (dissoc opts :status)] (->> (build-get-request (str (:url client) "/orders" (when-not (clojure.string/blank? query-string) "?") query-string)) (append-query-params rest-opts) (sign-request client) send-request)))) (defn cancel-order "[API docs](https://docs.pro.coinbase.com/#cancel-an-order) ```clojure (cancel-order client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client order-id] (->> (build-delete-request (str (:url client) "/orders/" order-id)) (sign-request client) send-request)) (defn cancel-all "[API docs](https://docs.pro.coinbase.com/#cancel-all) ```clojure (cancel-all client \"BTC-USD\") ```" ([client] (cancel-all client nil)) ([client product-id] (->> (build-delete-request (str (:url client) "/orders" (when-not (nil? product-id) (str "?product_id=" product-id)))) (sign-request client) send-request))) (defn get-order "[API docs](https://docs.pro.coinbase.com/#get-an-order) ```clojure (get-order client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client order-id] (->> (build-get-request (str (:url client) "/orders/" order-id)) (sign-request client) send-request)) ;; opts must contain either order_id or product_id (defn get-fills "[API docs](https://docs.pro.coinbase.com/#list-fills) Opts must contain either `:order_id` or `:product_id`. ```clojure (get-fills client {:product_id \"BTC-USD\" :before 2}) ```" ([client opts] (->> (build-get-request (str (:url client) "/fills")) (append-query-params opts) (sign-request client) send-request))) (defn get-payment-methods "[API docs](https://docs.pro.coinbase.com/#list-payment-methods)" [client] (->> (build-get-request (str (:url client) "/payment-methods")) (sign-request client) send-request)) (defn deposit-from-payment-method "[API docs](https://docs.pro.coinbase.com/#payment-method) ```clojure (deposit-from-payment-method client {:amount 10 :currency \"USD\" :payment_method_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/deposits/payment-method") opts) (sign-request client) send-request)) (defn withdraw-to-payment-method "[API docs](https://docs.pro.coinbase.com/#payment-method48) ```clojure (withdraw-to-payment-method client {:amount 10 :currency \"BTC-USD\" :payment_method_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/payment-method") opts) (sign-request client) send-request)) (defn get-coinbase-accounts "[API docs](https://docs.pro.coinbase.com/#list-accounts54)" [client] (->> (build-get-request (str (:url client) "/coinbase-accounts")) (sign-request client) send-request)) (defn deposit-from-coinbase "[API docs](https://docs.pro.coinbase.com/#coinbase) ```clojure (deposit-from-coinbase client {:amount 2 :currency \"BTC\" :coinbase_account_id \"<KEY>}) ```" [client opts] (->> (build-post-request (str (:url client) "/deposits/coinbase-account") opts) (sign-request client) send-request)) (defn withdraw-to-coinbase "[API docs](https://docs.pro.coinbase.com/#coinbase49) ```clojure (withdraw-to-coinbase client {:amount 2 :currency \"BTC\" :coinbase_account_id \"<KEY>}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/coinbase-account") opts) (sign-request client) send-request)) (defn withdraw-to-crypto-address "[API docs](https://docs.pro.coinbase.com/#crypto) ```clojure (withdraw-to-crypto-address client {:amount 2 :currency \"BTC\" :crypto_address \"15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/crypto") opts) (sign-request client) send-request)) (defn generate-report "[API docs](https://docs.pro.coinbase.com/#create-a-new-report) ```clojure (generate-report client {:type \"fills\" :start_date \"2018-6-1\" :end_date \"2018-6-30\" :product_id \"BTC-USD\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/reports") opts) (sign-request client) send-request)) (defn get-report-status "[API docs](https://docs.pro.coinbase.com/#get-report-status) ```clojure (get-report-status client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client report-id] (->> (build-get-request (str (:url client) "/reports/" report-id)) (sign-request client) send-request)) (defn get-trailing-volume "[API docs](https://docs.pro.coinbase.com/#trailing-volume)" [client] (->> (build-get-request (str (:url client) "/users/self/trailing-volume")) (sign-request client) send-request)) ;; ## Websocket feed (defn- create-subscribe-message "Creates the subscribe message and signs the message if key, secret, and passphrase are provided." [opts] (let [message {:type "subscribe" :product_ids (:product_ids opts) :channels (or (:channels opts) default-channels)}] (if (contains-many? opts :key :secret :passphrase) (sign-message message opts) message))) (defn- create-unsubscribe-message "Creates the unsubscribe message." [opts] (merge opts {:type "unsubscribe"})) (defn subscribe "[API docs](https://docs.pro.coinbase.com/#subscribe) - `connection` is created with [[create-websocket-connection]] - `opts` is a map with the following keys: - `:product_ids` - either this or `:channels` or both must be provided (see the Coinbase Pro API docs) - a vector of strings - `:channels` - either this or `:product_ids` or both must be provided (see the Coinbase Pro API docs) - a vector of strings or maps with `:name` (string) and `:product_ids` (vector of strings) - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API key - `:passphrase` - optional - your Coinbase Pro API key ```clojure (subscribe connection {:product_ids [\"BTC-USD\"]}) ```" [connection opts] (->> (create-subscribe-message opts) edn->json (ws/send-msg connection))) (defn unsubscribe "[API docs](https://docs.pro.coinbase.com/#subscribe) - `connection` is created with [[create-websocket-connection]]. - `opts` takes the equivalent shape as [[subscribe]]. ```clojure (unsubscribe connection {:product_ids [\"BTC-USD\"]}) ```" [connection opts] (->> (create-unsubscribe-message opts) edn->json (ws/send-msg connection))) (defn close "`connection` is created with [[create-websocket-connection]]." [connection] (ws/close connection)) (defn- create-on-receive "Returns a function that returns nil if user-on-receive is nil, otherwise returns a function that takes the received message, converts it to edn, then passes it to the user-on-receive function" [user-on-receive] (if (nil? user-on-receive) (constantly nil) (fn [msg] (-> msg json->edn ; convert to edn before passing to user defined on-receive user-on-receive)))) (defn- get-socket-connection "Creates the socket client using the Java WebSocketClient and SslContextFactory, starts the client, then connects it to the websocket URL." [opts] (let [client (WebSocketClient. (SslContextFactory.))] (.setMaxTextMessageSize (.getPolicy client) (* 1024 1024)) (.start client) (ws/connect (:url opts) :client client :on-connect (or (:on-connect opts) (constantly nil)) :on-receive (create-on-receive (:on-receive opts)) :on-close (or (:on-close opts) (constantly nil)) :on-error (or (:on-error opts) (constantly nil))))) (defn create-websocket-connection "[API docs](https://docs.pro.coinbase.com/#websocket-feed) `opts` is a map that takes the following keys: - `:url` - the websocket URL - `:product_ids` - either this or `:channels` or both must be provided (see the Coinbase Pro API docs) - a vector of strings - `:channels` - either this or `:product_ids` or both must be provided (see the Coinbase Pro API docs) - a vector of strings or maps with `:name` (string) and `:product_ids` (vector of strings) - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API secret - `:passphrase` - optional - your Coinbase Pro API passphrase - `:on-receive` - optional - A unary function called when a message is received. The argument is received as edn. - `:on-connect` - optional - A unary function called after the connection has been established. The argument is a [WebSocketSession](https://www.eclipse.org/jetty/javadoc/9.4.8.v20171121/org/eclipse/jetty/websocket/common/WebSocketSession.html). - `:on-error` - optional - A unary function called in case of errors. The argument is a `Throwable` describing the error. - `:on-close` - optional - A binary function called when the connection is closed. Arguments are an `int` status code and a `String` description of reason. ```clojure (def conn (create-websocket-connection {:product_ids [\"BTC-USD\"] :url \"wss://ws-feed.pro.coinbase.com\" :on-receive (fn [x] (prn 'received x))})) ```" [opts] (let [connection (get-socket-connection opts)] ;; subscribe immediately so the connection isn't lost (subscribe connection opts) connection))
true
(ns coinbase-pro-clj.core "Public and private endpoint functions and websocket feed functionality. In all function signatures, `client` is a map with the following keys: - `:url` - rest URL - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API key - `:passphrase` - optional - your Coinbase Pro API key `key`, `secret`, and `passphrase` are only required if the request is authenticated. These values can be created in the [API settings](https://pro.coinbase.com/profile/api) of your Coinbase Pro account. **Remember not to store these values in an online repository as this will give others access to your account. You could use something like [environ](https://github.com/weavejester/environ) to store these values locally outside of your code.**" (:require [coinbase-pro-clj.utilities :refer :all] [coinbase-pro-clj.authentication :refer :all] [cheshire.core :refer :all] [clj-http.client :as http] [gniazdo.core :as ws]) (:import (org.eclipse.jetty.websocket.client WebSocketClient) (org.eclipse.jetty.util.ssl SslContextFactory))) ;; ## Convenience/config values (def rest-url "The rest URL for Coinbase Pro." "https://api.pro.coinbase.com") (def websocket-url "The websocket URL for Coinbase Pro." "wss://ws-feed.pro.coinbase.com") (def sandbox-rest-url "The sandbox rest URL for Coinbase Pro." "https://api-public.sandbox.pro.coinbase.com") (def sandbox-websocket-url "The sandbox websocket URL for Coinbase Pro." "wss://ws-feed-public.sandbox.pro.coinbase.com") (def ^:private default-channels "Default channels for websocket subscriptions, used if none is explicitly stated." ["heartbeat"]) (defn- send-request "Takes in a request, sends the http request, and returns the body of the response." [request] (-> request http/request :body)) ;; ## Public endpoints (defn get-time "[API docs](https://docs.pro.coinbase.com/#time)" [client] (-> (str (:url client) "/time") build-get-request send-request)) (defn get-products "[API docs](https://docs.pro.coinbase.com/#products)" [client] (-> (str (:url client) "/products") build-get-request send-request)) (defn get-order-book "[API docs](https://docs.pro.coinbase.com/#get-product-order-book) ```clojure (get-order-book client \"BTC-USD\") (get-order-book client \"BTC-USD\" 2) ```" ([client product-id] (get-order-book client product-id 1)) ([client product-id level] (-> (str (:url client) "/products/" product-id "/book?level=" level) build-get-request send-request))) (defn get-ticker "[API docs](https://docs.pro.coinbase.com/#get-product-ticker) ```clojure (get-ticker client \"BTC-USD\") (get-ticker client \"BTC-USD\" {:before 2 :limit 5}) ```" ([client product-id] (get-ticker client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/ticker") build-get-request (append-query-params opts) send-request))) (defn get-trades "[API docs](https://docs.pro.coinbase.com/#get-trades) ```clojure (get-trades client \"BTC-USD\") (get-trades client \"BTC-USD\" {:before 2 :limit 5}) ```" ([client product-id] (get-trades client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/trades") build-get-request (append-query-params opts) send-request))) (defn get-historic-rates "[API docs](https://docs.pro.coinbase.com/#get-historic-rates) ```clojure (get-historic-rates client \"BTC-USD\") (get-historic-rates client \"BTC-USD\" {:start \"2018-06-01\" :end \"2018-06-30\" :granularity 86400}) ```" ([client product-id] (get-historic-rates client product-id {})) ([client product-id opts] (->> (str (:url client) "/products/" product-id "/candles") build-get-request (append-query-params opts) send-request))) (defn get-24hour-stats "[API docs](https://docs.pro.coinbase.com/#get-24hr-stats) ```clojure (get-24hour-stats client \"BTC-USD\") ```" [client product-id] (->> (str (:url client) "/products/" product-id "/stats") build-get-request send-request)) (defn get-currencies "[API docs](https://docs.pro.coinbase.com/#get-currencies)" [client] (send-request (build-get-request (str (:url client) "/currencies")))) ;; ## Private endpoints (defn get-accounts "[API docs](https://docs.pro.coinbase.com/#list-accounts)" [client] (->> (build-get-request (str (:url client) "/accounts")) (sign-request client) send-request)) (defn get-account "[API docs](https://docs.pro.coinbase.com/#get-an-account) ```clojure (get-account client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client account-id] (->> (build-get-request (str (:url client) "/accounts/" account-id)) (sign-request client) send-request)) (defn get-account-history "[API docs](https://docs.pro.coinbase.com/#get-account-history) ```clojure (get-account-history client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") (get-account-history client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\" {:before 2 :limit 5}) ```" ([client account-id] (get-account-history client account-id {})) ([client account-id paging-opts] (->> (build-get-request (str (:url client) "/accounts/" account-id "/ledger")) (append-query-params paging-opts) (sign-request client) send-request))) (defn get-account-holds "[API docs](https://docs.pro.coinbase.com/#get-holds) ```clojure (get-account-holds client \"BTC-USD\" \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") (get-account-holds client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\" {:before 2 :limit 5}) ```" ([client account-id] (get-account-holds client account-id {})) ([client account-id paging-opts] (->> (build-get-request (str (:url client) "/accounts/" account-id "/holds")) (append-query-params paging-opts) (sign-request client) send-request))) (defn place-order "[API docs](https://docs.pro.coinbase.com/#place-a-new-order) ```clojure (place-order client {:side \"buy\" :product_id \"BTC-USD\" :price 5000 :size 1}) ```" [client opts] (->> (build-post-request (str (:url client) "/orders") opts) (sign-request client) send-request)) (defn get-orders "[API docs](https://docs.pro.coinbase.com/#list-orders) ```clojure (get-orders client {:status [\"open\" \"pending\"]}) ```" ([client] (get-orders client {:status ["all"]})) ([client opts] (let [query-string (clojure.string/join "&" (map #(str "status=" %) (:status opts))) rest-opts (dissoc opts :status)] (->> (build-get-request (str (:url client) "/orders" (when-not (clojure.string/blank? query-string) "?") query-string)) (append-query-params rest-opts) (sign-request client) send-request)))) (defn cancel-order "[API docs](https://docs.pro.coinbase.com/#cancel-an-order) ```clojure (cancel-order client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client order-id] (->> (build-delete-request (str (:url client) "/orders/" order-id)) (sign-request client) send-request)) (defn cancel-all "[API docs](https://docs.pro.coinbase.com/#cancel-all) ```clojure (cancel-all client \"BTC-USD\") ```" ([client] (cancel-all client nil)) ([client product-id] (->> (build-delete-request (str (:url client) "/orders" (when-not (nil? product-id) (str "?product_id=" product-id)))) (sign-request client) send-request))) (defn get-order "[API docs](https://docs.pro.coinbase.com/#get-an-order) ```clojure (get-order client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client order-id] (->> (build-get-request (str (:url client) "/orders/" order-id)) (sign-request client) send-request)) ;; opts must contain either order_id or product_id (defn get-fills "[API docs](https://docs.pro.coinbase.com/#list-fills) Opts must contain either `:order_id` or `:product_id`. ```clojure (get-fills client {:product_id \"BTC-USD\" :before 2}) ```" ([client opts] (->> (build-get-request (str (:url client) "/fills")) (append-query-params opts) (sign-request client) send-request))) (defn get-payment-methods "[API docs](https://docs.pro.coinbase.com/#list-payment-methods)" [client] (->> (build-get-request (str (:url client) "/payment-methods")) (sign-request client) send-request)) (defn deposit-from-payment-method "[API docs](https://docs.pro.coinbase.com/#payment-method) ```clojure (deposit-from-payment-method client {:amount 10 :currency \"USD\" :payment_method_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/deposits/payment-method") opts) (sign-request client) send-request)) (defn withdraw-to-payment-method "[API docs](https://docs.pro.coinbase.com/#payment-method48) ```clojure (withdraw-to-payment-method client {:amount 10 :currency \"BTC-USD\" :payment_method_id \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/payment-method") opts) (sign-request client) send-request)) (defn get-coinbase-accounts "[API docs](https://docs.pro.coinbase.com/#list-accounts54)" [client] (->> (build-get-request (str (:url client) "/coinbase-accounts")) (sign-request client) send-request)) (defn deposit-from-coinbase "[API docs](https://docs.pro.coinbase.com/#coinbase) ```clojure (deposit-from-coinbase client {:amount 2 :currency \"BTC\" :coinbase_account_id \"PI:KEY:<KEY>END_PI}) ```" [client opts] (->> (build-post-request (str (:url client) "/deposits/coinbase-account") opts) (sign-request client) send-request)) (defn withdraw-to-coinbase "[API docs](https://docs.pro.coinbase.com/#coinbase49) ```clojure (withdraw-to-coinbase client {:amount 2 :currency \"BTC\" :coinbase_account_id \"PI:KEY:<KEY>END_PI}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/coinbase-account") opts) (sign-request client) send-request)) (defn withdraw-to-crypto-address "[API docs](https://docs.pro.coinbase.com/#crypto) ```clojure (withdraw-to-crypto-address client {:amount 2 :currency \"BTC\" :crypto_address \"15USXR6S4DhSWVHUxXRCuTkD1SA6qAdy\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/withdrawals/crypto") opts) (sign-request client) send-request)) (defn generate-report "[API docs](https://docs.pro.coinbase.com/#create-a-new-report) ```clojure (generate-report client {:type \"fills\" :start_date \"2018-6-1\" :end_date \"2018-6-30\" :product_id \"BTC-USD\"}) ```" [client opts] (->> (build-post-request (str (:url client) "/reports") opts) (sign-request client) send-request)) (defn get-report-status "[API docs](https://docs.pro.coinbase.com/#get-report-status) ```clojure (get-report-status client \"7d0f7d8e-dd34-4d9c-a846-06f431c381ba\") ```" [client report-id] (->> (build-get-request (str (:url client) "/reports/" report-id)) (sign-request client) send-request)) (defn get-trailing-volume "[API docs](https://docs.pro.coinbase.com/#trailing-volume)" [client] (->> (build-get-request (str (:url client) "/users/self/trailing-volume")) (sign-request client) send-request)) ;; ## Websocket feed (defn- create-subscribe-message "Creates the subscribe message and signs the message if key, secret, and passphrase are provided." [opts] (let [message {:type "subscribe" :product_ids (:product_ids opts) :channels (or (:channels opts) default-channels)}] (if (contains-many? opts :key :secret :passphrase) (sign-message message opts) message))) (defn- create-unsubscribe-message "Creates the unsubscribe message." [opts] (merge opts {:type "unsubscribe"})) (defn subscribe "[API docs](https://docs.pro.coinbase.com/#subscribe) - `connection` is created with [[create-websocket-connection]] - `opts` is a map with the following keys: - `:product_ids` - either this or `:channels` or both must be provided (see the Coinbase Pro API docs) - a vector of strings - `:channels` - either this or `:product_ids` or both must be provided (see the Coinbase Pro API docs) - a vector of strings or maps with `:name` (string) and `:product_ids` (vector of strings) - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API key - `:passphrase` - optional - your Coinbase Pro API key ```clojure (subscribe connection {:product_ids [\"BTC-USD\"]}) ```" [connection opts] (->> (create-subscribe-message opts) edn->json (ws/send-msg connection))) (defn unsubscribe "[API docs](https://docs.pro.coinbase.com/#subscribe) - `connection` is created with [[create-websocket-connection]]. - `opts` takes the equivalent shape as [[subscribe]]. ```clojure (unsubscribe connection {:product_ids [\"BTC-USD\"]}) ```" [connection opts] (->> (create-unsubscribe-message opts) edn->json (ws/send-msg connection))) (defn close "`connection` is created with [[create-websocket-connection]]." [connection] (ws/close connection)) (defn- create-on-receive "Returns a function that returns nil if user-on-receive is nil, otherwise returns a function that takes the received message, converts it to edn, then passes it to the user-on-receive function" [user-on-receive] (if (nil? user-on-receive) (constantly nil) (fn [msg] (-> msg json->edn ; convert to edn before passing to user defined on-receive user-on-receive)))) (defn- get-socket-connection "Creates the socket client using the Java WebSocketClient and SslContextFactory, starts the client, then connects it to the websocket URL." [opts] (let [client (WebSocketClient. (SslContextFactory.))] (.setMaxTextMessageSize (.getPolicy client) (* 1024 1024)) (.start client) (ws/connect (:url opts) :client client :on-connect (or (:on-connect opts) (constantly nil)) :on-receive (create-on-receive (:on-receive opts)) :on-close (or (:on-close opts) (constantly nil)) :on-error (or (:on-error opts) (constantly nil))))) (defn create-websocket-connection "[API docs](https://docs.pro.coinbase.com/#websocket-feed) `opts` is a map that takes the following keys: - `:url` - the websocket URL - `:product_ids` - either this or `:channels` or both must be provided (see the Coinbase Pro API docs) - a vector of strings - `:channels` - either this or `:product_ids` or both must be provided (see the Coinbase Pro API docs) - a vector of strings or maps with `:name` (string) and `:product_ids` (vector of strings) - `:key` - optional - your Coinbase Pro API key - `:secret` - optional - your Coinbase Pro API secret - `:passphrase` - optional - your Coinbase Pro API passphrase - `:on-receive` - optional - A unary function called when a message is received. The argument is received as edn. - `:on-connect` - optional - A unary function called after the connection has been established. The argument is a [WebSocketSession](https://www.eclipse.org/jetty/javadoc/9.4.8.v20171121/org/eclipse/jetty/websocket/common/WebSocketSession.html). - `:on-error` - optional - A unary function called in case of errors. The argument is a `Throwable` describing the error. - `:on-close` - optional - A binary function called when the connection is closed. Arguments are an `int` status code and a `String` description of reason. ```clojure (def conn (create-websocket-connection {:product_ids [\"BTC-USD\"] :url \"wss://ws-feed.pro.coinbase.com\" :on-receive (fn [x] (prn 'received x))})) ```" [opts] (let [connection (get-socket-connection opts)] ;; subscribe immediately so the connection isn't lost (subscribe connection opts) connection))
[ { "context": " (compile-query test1)\n [[:person {:age 34 :name \"Mary\" :other true :test 123}]\n [:person {:age 67 :nam", "end": 5442, "score": 0.9996603727340698, "start": 5438, "tag": "NAME", "value": "Mary" }, { "context": "other true :test 123}]\n [:person {:age 67 :name \"Peter\" :other false :test 0}]\n [:person {:age 21 :name", "end": 5500, "score": 0.999527096748352, "start": 5495, "tag": "NAME", "value": "Peter" }, { "context": ":other false :test 0}]\n [:person {:age 21 :name \"Hackle\" :other true}]\n [:person {:age 18 :name \"Oliver\"", "end": 5558, "score": 0.9996230602264404, "start": 5552, "tag": "NAME", "value": "Hackle" }, { "context": "\"Hackle\" :other true}]\n [:person {:age 18 :name \"Oliver\" :other false :foo :bar}]])\n\n(runtest\n (compile-q", "end": 5607, "score": 0.9995747208595276, "start": 5601, "tag": "NAME", "value": "Oliver" }, { "context": " (compile-query test2)\n [[:person {:age 34 :name \"Mary\" :other true :test 123 :country \"HKG\"}]\n [:count", "end": 5700, "score": 0.9997069835662842, "start": 5696, "tag": "NAME", "value": "Mary" }, { "context": "country-name \"India\"}]\n [:person {:age 67 :name \"Peter\" :other false :test 0 :country \"RUS\"}]\n [:countr", "end": 5888, "score": 0.9995546936988831, "start": 5883, "tag": "NAME", "value": "Peter" }, { "context": "country-name \"Japan\"}]\n [:person {:age 21 :name \"Hackle\" :other true :country \"JAP\"}]\n [:person {:age 18", "end": 6018, "score": 0.9995641708374023, "start": 6012, "tag": "NAME", "value": "Hackle" }, { "context": " true :country \"JAP\"}]\n [:person {:age 18 :name \"Oliver\" :other false :foo :bar :country \"RUS\"}]\n [:coun", "end": 6082, "score": 0.9994276762008667, "start": 6076, "tag": "NAME", "value": "Oliver" } ]
onyx-stream-sql/src/onyx_stream_sql/core.clj
lemonteaa/onyx-streaming-sql
0
(ns onyx-stream-sql.core (:require [onyx-local-rt.api :as api] [clojure.pprint :as pp])) ;; ^:export the function if using in ClojureScript. (defn ^:export my-inc [segment] (update-in segment [:n] inc)) (def job {:workflow [[:in :inc] [:inc :out]] :catalog [{:onyx/name :in :onyx/type :input :onyx/batch-size 20} {:onyx/name :inc :onyx/type :function :onyx/fn ::my-inc :onyx/batch-size 20} {:onyx/name :out :onyx/type :output :onyx/batch-size 20}] :lifecycles []}) (pp/pprint (-> (api/init job) (api/new-segment :in {:n 41}) (api/new-segment :in {:n 84}) (api/drain) (api/stop) (api/env-summary))) (defn add-segment [env [input-name segment]] (api/new-segment env input-name {:src input-name :data segment})) (defn runtest [job segments] (let [env (api/init job) nextenv (reduce add-segment env segments)] (-> nextenv (api/drain) (api/stop) (api/env-summary)))) ;; => ;; {:next-action :lifecycle/start-task?, ;; :tasks ;; {:in {:inbox []}, ;; :inc {:inbox []}, ;; :out {:inbox [], :outputs [{:n 42} {:n 85}]}}} (def test1 {:select [:b/age :b/name] :from [:person :b] :where [:age-large]}) (def test2 {:select [:b/age :b/name :c/country-name] :from [:person :b] :join {:target [:country :c] :on-key [:c/country-code :b/country]} :where [:age-large]}) (defn gen-input [name] {:onyx/name name :onyx/type :input :onyx/batch-size 1}) (defn gen-output [name] {:onyx/name name :onyx/type :output :onyx/batch-size 1}) (defn sum-init-fn [window] {:src-hash {} :dst-hash {}}) (defn sum-aggregation-fn [window segment] (do (if (= (:src segment) :person) (let [k (-> segment :data :country)] {:value k :loc :src-hash :segment segment}) (let [k (-> segment :data :country-code)] {:value k :loc :dst-hash :segment segment})))) ;; Now just pull out the value and add it to the previous state (defn sum-application-fn [window state value] (update-in state [(:loc value) (:value value)] (constantly (:segment value)))) ;; sum aggregation referenced in the window definition. (def sum {:aggregation/init sum-init-fn :aggregation/create-state-update sum-aggregation-fn :aggregation/apply-state-update sum-application-fn}) ;;(defn dump-window! [event window trigger x state] ;; (doall (map pp/pprint [event window trigger x state]))) (defn dump-window! [event window trigger x state] (if (= (:event-type x) :new-segment) (let [segment (:segment x) src (:src segment) data (:data segment) lookup-dst (get-in state [:dst-hash (:country data) :data] false) lookup-src (get-in state [:src-hash (:country-code data) :data] false)] (cond (and (= src :person) lookup-dst) {:person data :country lookup-dst} (and (= src :country) lookup-src) {:person lookup-src :country data})))) (defn rev [[a b]] [b a]) (defn grab-alias [sql] (->> [(:from sql) (get-in sql [:join :target])] (map rev) (into {}))) ;(defn run-process [sql segment] ; (let [ks (map #(keyword (name %)) (:select sql))] ; (select-keys (:data segment) ks))) (defn run-process [sql segment] (let [alias (grab-alias sql) ks (:select sql)] (into {} (for [k ks :let [k-ns (keyword (namespace k)) k-n (keyword (name k)) entity (get alias k-ns)]] [k (get-in segment [entity k-n])])))) (defn compile-query [sql] (let [input-name (first (:from sql)) output-name :out has-join? (contains? sql :join) join-name (if has-join? (-> sql (get-in [:join :target]) (first)))] {:workflow (cond-> [] true (conj [input-name (if has-join? :join :proc)]) has-join? (conj [join-name :join]) has-join? (conj [:join :proc]) true (conj [:proc output-name])) :catalog (cond-> [] true (conj (gen-input input-name)) has-join? (conj (gen-input join-name)) has-join? (conj {:onyx/name :join :onyx/type :function :onyx/fn :clojure.core/identity :onyx/batch-size 1}) true (conj {:onyx/name :proc :onyx/type :function :onyx/fn ::run-process :streamql/sql sql :onyx/params [:streamql/sql] :onyx/batch-size 1}) true (conj (gen-output output-name))) :lifecycles [] :windows [{:window/id :collect-segments :window/task :join :window/type :global :window/aggregation ::sum}] :triggers [{:trigger/window-id :collect-segments :trigger/id :sync :trigger/on :onyx.triggers/segment :trigger/threshold [1 :elements] :trigger/emit ::dump-window!}]})) (runtest (compile-query test1) [[:person {:age 34 :name "Mary" :other true :test 123}] [:person {:age 67 :name "Peter" :other false :test 0}] [:person {:age 21 :name "Hackle" :other true}] [:person {:age 18 :name "Oliver" :other false :foo :bar}]]) (runtest (compile-query test2) [[:person {:age 34 :name "Mary" :other true :test 123 :country "HKG"}] [:country {:country-code "RUS" :country-name "Russia"}] [:country {:country-code "IND" :country-name "India"}] [:person {:age 67 :name "Peter" :other false :test 0 :country "RUS"}] [:country {:country-code "JAP" :country-name "Japan"}] [:person {:age 21 :name "Hackle" :other true :country "JAP"}] [:person {:age 18 :name "Oliver" :other false :foo :bar :country "RUS"}] [:country {:country-code "HKG" :country-name "Hong Kong"}]])
40430
(ns onyx-stream-sql.core (:require [onyx-local-rt.api :as api] [clojure.pprint :as pp])) ;; ^:export the function if using in ClojureScript. (defn ^:export my-inc [segment] (update-in segment [:n] inc)) (def job {:workflow [[:in :inc] [:inc :out]] :catalog [{:onyx/name :in :onyx/type :input :onyx/batch-size 20} {:onyx/name :inc :onyx/type :function :onyx/fn ::my-inc :onyx/batch-size 20} {:onyx/name :out :onyx/type :output :onyx/batch-size 20}] :lifecycles []}) (pp/pprint (-> (api/init job) (api/new-segment :in {:n 41}) (api/new-segment :in {:n 84}) (api/drain) (api/stop) (api/env-summary))) (defn add-segment [env [input-name segment]] (api/new-segment env input-name {:src input-name :data segment})) (defn runtest [job segments] (let [env (api/init job) nextenv (reduce add-segment env segments)] (-> nextenv (api/drain) (api/stop) (api/env-summary)))) ;; => ;; {:next-action :lifecycle/start-task?, ;; :tasks ;; {:in {:inbox []}, ;; :inc {:inbox []}, ;; :out {:inbox [], :outputs [{:n 42} {:n 85}]}}} (def test1 {:select [:b/age :b/name] :from [:person :b] :where [:age-large]}) (def test2 {:select [:b/age :b/name :c/country-name] :from [:person :b] :join {:target [:country :c] :on-key [:c/country-code :b/country]} :where [:age-large]}) (defn gen-input [name] {:onyx/name name :onyx/type :input :onyx/batch-size 1}) (defn gen-output [name] {:onyx/name name :onyx/type :output :onyx/batch-size 1}) (defn sum-init-fn [window] {:src-hash {} :dst-hash {}}) (defn sum-aggregation-fn [window segment] (do (if (= (:src segment) :person) (let [k (-> segment :data :country)] {:value k :loc :src-hash :segment segment}) (let [k (-> segment :data :country-code)] {:value k :loc :dst-hash :segment segment})))) ;; Now just pull out the value and add it to the previous state (defn sum-application-fn [window state value] (update-in state [(:loc value) (:value value)] (constantly (:segment value)))) ;; sum aggregation referenced in the window definition. (def sum {:aggregation/init sum-init-fn :aggregation/create-state-update sum-aggregation-fn :aggregation/apply-state-update sum-application-fn}) ;;(defn dump-window! [event window trigger x state] ;; (doall (map pp/pprint [event window trigger x state]))) (defn dump-window! [event window trigger x state] (if (= (:event-type x) :new-segment) (let [segment (:segment x) src (:src segment) data (:data segment) lookup-dst (get-in state [:dst-hash (:country data) :data] false) lookup-src (get-in state [:src-hash (:country-code data) :data] false)] (cond (and (= src :person) lookup-dst) {:person data :country lookup-dst} (and (= src :country) lookup-src) {:person lookup-src :country data})))) (defn rev [[a b]] [b a]) (defn grab-alias [sql] (->> [(:from sql) (get-in sql [:join :target])] (map rev) (into {}))) ;(defn run-process [sql segment] ; (let [ks (map #(keyword (name %)) (:select sql))] ; (select-keys (:data segment) ks))) (defn run-process [sql segment] (let [alias (grab-alias sql) ks (:select sql)] (into {} (for [k ks :let [k-ns (keyword (namespace k)) k-n (keyword (name k)) entity (get alias k-ns)]] [k (get-in segment [entity k-n])])))) (defn compile-query [sql] (let [input-name (first (:from sql)) output-name :out has-join? (contains? sql :join) join-name (if has-join? (-> sql (get-in [:join :target]) (first)))] {:workflow (cond-> [] true (conj [input-name (if has-join? :join :proc)]) has-join? (conj [join-name :join]) has-join? (conj [:join :proc]) true (conj [:proc output-name])) :catalog (cond-> [] true (conj (gen-input input-name)) has-join? (conj (gen-input join-name)) has-join? (conj {:onyx/name :join :onyx/type :function :onyx/fn :clojure.core/identity :onyx/batch-size 1}) true (conj {:onyx/name :proc :onyx/type :function :onyx/fn ::run-process :streamql/sql sql :onyx/params [:streamql/sql] :onyx/batch-size 1}) true (conj (gen-output output-name))) :lifecycles [] :windows [{:window/id :collect-segments :window/task :join :window/type :global :window/aggregation ::sum}] :triggers [{:trigger/window-id :collect-segments :trigger/id :sync :trigger/on :onyx.triggers/segment :trigger/threshold [1 :elements] :trigger/emit ::dump-window!}]})) (runtest (compile-query test1) [[:person {:age 34 :name "<NAME>" :other true :test 123}] [:person {:age 67 :name "<NAME>" :other false :test 0}] [:person {:age 21 :name "<NAME>" :other true}] [:person {:age 18 :name "<NAME>" :other false :foo :bar}]]) (runtest (compile-query test2) [[:person {:age 34 :name "<NAME>" :other true :test 123 :country "HKG"}] [:country {:country-code "RUS" :country-name "Russia"}] [:country {:country-code "IND" :country-name "India"}] [:person {:age 67 :name "<NAME>" :other false :test 0 :country "RUS"}] [:country {:country-code "JAP" :country-name "Japan"}] [:person {:age 21 :name "<NAME>" :other true :country "JAP"}] [:person {:age 18 :name "<NAME>" :other false :foo :bar :country "RUS"}] [:country {:country-code "HKG" :country-name "Hong Kong"}]])
true
(ns onyx-stream-sql.core (:require [onyx-local-rt.api :as api] [clojure.pprint :as pp])) ;; ^:export the function if using in ClojureScript. (defn ^:export my-inc [segment] (update-in segment [:n] inc)) (def job {:workflow [[:in :inc] [:inc :out]] :catalog [{:onyx/name :in :onyx/type :input :onyx/batch-size 20} {:onyx/name :inc :onyx/type :function :onyx/fn ::my-inc :onyx/batch-size 20} {:onyx/name :out :onyx/type :output :onyx/batch-size 20}] :lifecycles []}) (pp/pprint (-> (api/init job) (api/new-segment :in {:n 41}) (api/new-segment :in {:n 84}) (api/drain) (api/stop) (api/env-summary))) (defn add-segment [env [input-name segment]] (api/new-segment env input-name {:src input-name :data segment})) (defn runtest [job segments] (let [env (api/init job) nextenv (reduce add-segment env segments)] (-> nextenv (api/drain) (api/stop) (api/env-summary)))) ;; => ;; {:next-action :lifecycle/start-task?, ;; :tasks ;; {:in {:inbox []}, ;; :inc {:inbox []}, ;; :out {:inbox [], :outputs [{:n 42} {:n 85}]}}} (def test1 {:select [:b/age :b/name] :from [:person :b] :where [:age-large]}) (def test2 {:select [:b/age :b/name :c/country-name] :from [:person :b] :join {:target [:country :c] :on-key [:c/country-code :b/country]} :where [:age-large]}) (defn gen-input [name] {:onyx/name name :onyx/type :input :onyx/batch-size 1}) (defn gen-output [name] {:onyx/name name :onyx/type :output :onyx/batch-size 1}) (defn sum-init-fn [window] {:src-hash {} :dst-hash {}}) (defn sum-aggregation-fn [window segment] (do (if (= (:src segment) :person) (let [k (-> segment :data :country)] {:value k :loc :src-hash :segment segment}) (let [k (-> segment :data :country-code)] {:value k :loc :dst-hash :segment segment})))) ;; Now just pull out the value and add it to the previous state (defn sum-application-fn [window state value] (update-in state [(:loc value) (:value value)] (constantly (:segment value)))) ;; sum aggregation referenced in the window definition. (def sum {:aggregation/init sum-init-fn :aggregation/create-state-update sum-aggregation-fn :aggregation/apply-state-update sum-application-fn}) ;;(defn dump-window! [event window trigger x state] ;; (doall (map pp/pprint [event window trigger x state]))) (defn dump-window! [event window trigger x state] (if (= (:event-type x) :new-segment) (let [segment (:segment x) src (:src segment) data (:data segment) lookup-dst (get-in state [:dst-hash (:country data) :data] false) lookup-src (get-in state [:src-hash (:country-code data) :data] false)] (cond (and (= src :person) lookup-dst) {:person data :country lookup-dst} (and (= src :country) lookup-src) {:person lookup-src :country data})))) (defn rev [[a b]] [b a]) (defn grab-alias [sql] (->> [(:from sql) (get-in sql [:join :target])] (map rev) (into {}))) ;(defn run-process [sql segment] ; (let [ks (map #(keyword (name %)) (:select sql))] ; (select-keys (:data segment) ks))) (defn run-process [sql segment] (let [alias (grab-alias sql) ks (:select sql)] (into {} (for [k ks :let [k-ns (keyword (namespace k)) k-n (keyword (name k)) entity (get alias k-ns)]] [k (get-in segment [entity k-n])])))) (defn compile-query [sql] (let [input-name (first (:from sql)) output-name :out has-join? (contains? sql :join) join-name (if has-join? (-> sql (get-in [:join :target]) (first)))] {:workflow (cond-> [] true (conj [input-name (if has-join? :join :proc)]) has-join? (conj [join-name :join]) has-join? (conj [:join :proc]) true (conj [:proc output-name])) :catalog (cond-> [] true (conj (gen-input input-name)) has-join? (conj (gen-input join-name)) has-join? (conj {:onyx/name :join :onyx/type :function :onyx/fn :clojure.core/identity :onyx/batch-size 1}) true (conj {:onyx/name :proc :onyx/type :function :onyx/fn ::run-process :streamql/sql sql :onyx/params [:streamql/sql] :onyx/batch-size 1}) true (conj (gen-output output-name))) :lifecycles [] :windows [{:window/id :collect-segments :window/task :join :window/type :global :window/aggregation ::sum}] :triggers [{:trigger/window-id :collect-segments :trigger/id :sync :trigger/on :onyx.triggers/segment :trigger/threshold [1 :elements] :trigger/emit ::dump-window!}]})) (runtest (compile-query test1) [[:person {:age 34 :name "PI:NAME:<NAME>END_PI" :other true :test 123}] [:person {:age 67 :name "PI:NAME:<NAME>END_PI" :other false :test 0}] [:person {:age 21 :name "PI:NAME:<NAME>END_PI" :other true}] [:person {:age 18 :name "PI:NAME:<NAME>END_PI" :other false :foo :bar}]]) (runtest (compile-query test2) [[:person {:age 34 :name "PI:NAME:<NAME>END_PI" :other true :test 123 :country "HKG"}] [:country {:country-code "RUS" :country-name "Russia"}] [:country {:country-code "IND" :country-name "India"}] [:person {:age 67 :name "PI:NAME:<NAME>END_PI" :other false :test 0 :country "RUS"}] [:country {:country-code "JAP" :country-name "Japan"}] [:person {:age 21 :name "PI:NAME:<NAME>END_PI" :other true :country "JAP"}] [:person {:age 18 :name "PI:NAME:<NAME>END_PI" :other false :foo :bar :country "RUS"}] [:country {:country-code "HKG" :country-name "Hong Kong"}]])
[ { "context": "4-74838d6ba8ef\"\n :userName \"karim\"\n :locale \"en\"\n ", "end": 364, "score": 0.9996086359024048, "start": 359, "tag": "USERNAME", "value": "karim" }, { "context": "n\"\n :name {:familyName \"Smith\"\n :givenName \"J", "end": 456, "score": 0.9998350143432617, "start": 451, "tag": "NAME", "value": "Smith" }, { "context": "h\"\n :givenName \"John\"\n :formatted \"J", "end": 509, "score": 0.9998468160629272, "start": 505, "tag": "NAME", "value": "John" }, { "context": "n\"\n :formatted \"John Smith\"}\n :displayName \"Kamaro\"\n ", "end": 568, "score": 0.999747633934021, "start": 558, "tag": "NAME", "value": "John Smith" }, { "context": " \"John Smith\"}\n :displayName \"Kamaro\"\n :emails [{:value \"work@", "end": 611, "score": 0.9984354972839355, "start": 605, "tag": "NAME", "value": "Kamaro" }, { "context": "amaro\"\n :emails [{:value \"work@work.com\" :type \"work\" :primary true}\n ", "end": 669, "score": 0.9999183416366577, "start": 656, "tag": "EMAIL", "value": "work@work.com" }, { "context": " true}\n {:value \"mobile@mobile.com\" :type \"mobile\"}]\n :active ", "end": 759, "score": 0.9999101758003235, "start": 742, "tag": "EMAIL", "value": "mobile@mobile.com" }, { "context": ":2.0:User\n {:managerUserName \"manager@manager.com\"\n :status \"on going", "end": 1411, "score": 0.9999266862869263, "start": 1392, "tag": "EMAIL", "value": "manager@manager.com" }, { "context": "60b-6f006908daa6\"\n {:name \"familyName\"\n :mapped-to \"last_name\"\n ", "end": 2047, "score": 0.9726299047470093, "start": 2037, "tag": "NAME", "value": "familyName" }, { "context": " \"familyName\"\n :mapped-to \"last_name\"\n :collection \"user\"}}}\n ", "end": 2085, "score": 0.7251851558685303, "start": 2081, "tag": "NAME", "value": "last" }, { "context": "\"familyName\"\n :mapped-to \"last_name\"\n :collection \"user\"}}}\n #u", "end": 2090, "score": 0.6003060936927795, "start": 2086, "tag": "NAME", "value": "name" } ]
src/cljs/scimmer/app_db.cljs
elarous/scimmer
1
(ns scimmer.app-db (:require [malli.util :as mu] [malli.core :as m])) (def db {:schema nil :schema-saved? true :schemas nil :extensions {} :resource {:id "0ea136ad-061d-45f1-8d92-db5627a156f2" :externalId "8a61fbf4-543c-4ed2-94a4-74838d6ba8ef" :userName "karim" :locale "en" :name {:familyName "Smith" :givenName "John" :formatted "John Smith"} :displayName "Kamaro" :emails [{:value "work@work.com" :type "work" :primary true} {:value "mobile@mobile.com" :type "mobile"}] :active true :title "Engineer" :phoneNumbers [{:value "12341234" :type "work"} {:value "000000" :type "mobile"}] :urn:ietf:params:scim:schemas:extension:enterprise:2.0:User {:department "Tech" :organization "Google. Inc" :employeeNumber "003FTDH2" :manager {:value "0F2342SLDJF23"}} :urn:ietf:params:scim:schemas:extension:company:2.0:User {:managerUserName "manager@manager.com" :status "on going" :grade "leader" :seniorityDate "12-12-2000" :contractStartDate "11-11-2011"}}}) (comment (def schema ;; Reference of the map under :schema in the state {#uuid "0ea136ad-061d-45f1-8d92-db5627a156f2" {:type :single :name "id" :mapped-to "uuid" :collection "user"} #uuid "aaaaaaa-061d-45f1-8d92-db5627a156f2" {:type :object :name "name" :sub-attrs {#uuid "459e1f73-4356-4422-b60b-6f006908daa6" {:name "familyName" :mapped-to "last_name" :collection "user"}}} #uuid "bbbabbb-061d-45f1-8d92-db5627a156f2" {:type :array :name "phoneNumbers" :sub-items {#uuid "de72b3bd-4ce3-4ea0-b90b-337d4fbebc5f" {:mapped-to "mobile_phone" :type "mobile" :collection "user"}}}}))
47365
(ns scimmer.app-db (:require [malli.util :as mu] [malli.core :as m])) (def db {:schema nil :schema-saved? true :schemas nil :extensions {} :resource {:id "0ea136ad-061d-45f1-8d92-db5627a156f2" :externalId "8a61fbf4-543c-4ed2-94a4-74838d6ba8ef" :userName "karim" :locale "en" :name {:familyName "<NAME>" :givenName "<NAME>" :formatted "<NAME>"} :displayName "<NAME>" :emails [{:value "<EMAIL>" :type "work" :primary true} {:value "<EMAIL>" :type "mobile"}] :active true :title "Engineer" :phoneNumbers [{:value "12341234" :type "work"} {:value "000000" :type "mobile"}] :urn:ietf:params:scim:schemas:extension:enterprise:2.0:User {:department "Tech" :organization "Google. Inc" :employeeNumber "003FTDH2" :manager {:value "0F2342SLDJF23"}} :urn:ietf:params:scim:schemas:extension:company:2.0:User {:managerUserName "<EMAIL>" :status "on going" :grade "leader" :seniorityDate "12-12-2000" :contractStartDate "11-11-2011"}}}) (comment (def schema ;; Reference of the map under :schema in the state {#uuid "0ea136ad-061d-45f1-8d92-db5627a156f2" {:type :single :name "id" :mapped-to "uuid" :collection "user"} #uuid "aaaaaaa-061d-45f1-8d92-db5627a156f2" {:type :object :name "name" :sub-attrs {#uuid "459e1f73-4356-4422-b60b-6f006908daa6" {:name "<NAME>" :mapped-to "<NAME>_<NAME>" :collection "user"}}} #uuid "bbbabbb-061d-45f1-8d92-db5627a156f2" {:type :array :name "phoneNumbers" :sub-items {#uuid "de72b3bd-4ce3-4ea0-b90b-337d4fbebc5f" {:mapped-to "mobile_phone" :type "mobile" :collection "user"}}}}))
true
(ns scimmer.app-db (:require [malli.util :as mu] [malli.core :as m])) (def db {:schema nil :schema-saved? true :schemas nil :extensions {} :resource {:id "0ea136ad-061d-45f1-8d92-db5627a156f2" :externalId "8a61fbf4-543c-4ed2-94a4-74838d6ba8ef" :userName "karim" :locale "en" :name {:familyName "PI:NAME:<NAME>END_PI" :givenName "PI:NAME:<NAME>END_PI" :formatted "PI:NAME:<NAME>END_PI"} :displayName "PI:NAME:<NAME>END_PI" :emails [{:value "PI:EMAIL:<EMAIL>END_PI" :type "work" :primary true} {:value "PI:EMAIL:<EMAIL>END_PI" :type "mobile"}] :active true :title "Engineer" :phoneNumbers [{:value "12341234" :type "work"} {:value "000000" :type "mobile"}] :urn:ietf:params:scim:schemas:extension:enterprise:2.0:User {:department "Tech" :organization "Google. Inc" :employeeNumber "003FTDH2" :manager {:value "0F2342SLDJF23"}} :urn:ietf:params:scim:schemas:extension:company:2.0:User {:managerUserName "PI:EMAIL:<EMAIL>END_PI" :status "on going" :grade "leader" :seniorityDate "12-12-2000" :contractStartDate "11-11-2011"}}}) (comment (def schema ;; Reference of the map under :schema in the state {#uuid "0ea136ad-061d-45f1-8d92-db5627a156f2" {:type :single :name "id" :mapped-to "uuid" :collection "user"} #uuid "aaaaaaa-061d-45f1-8d92-db5627a156f2" {:type :object :name "name" :sub-attrs {#uuid "459e1f73-4356-4422-b60b-6f006908daa6" {:name "PI:NAME:<NAME>END_PI" :mapped-to "PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI" :collection "user"}}} #uuid "bbbabbb-061d-45f1-8d92-db5627a156f2" {:type :array :name "phoneNumbers" :sub-items {#uuid "de72b3bd-4ce3-4ea0-b90b-337d4fbebc5f" {:mapped-to "mobile_phone" :type "mobile" :collection "user"}}}}))
[ { "context": "e-prefixed-test\n (is (= {:user/id 1 :user/login \"user\"} (f/ensure-prefixed :user {:id 1 :login \"user\"})", "end": 924, "score": 0.8792320489883423, "start": 920, "tag": "USERNAME", "value": "user" }, { "context": "n \"user\"} (f/ensure-prefixed :user {:id 1 :login \"user\"})))\n (is (= {:user/id 1 :user.person/name \"user", "end": 971, "score": 0.88546222448349, "start": 967, "tag": "USERNAME", "value": "user" }, { "context": "user\"})))\n (is (= {:user/id 1 :user.person/name \"user\"} (f/ensure-prefixed :user {:id 1 :person/name \"u", "end": 1021, "score": 0.5333040952682495, "start": 1017, "tag": "USERNAME", "value": "user" }, { "context": "r\"} (f/ensure-prefixed :user {:id 1 :person/name \"user\"})))\n (is (= {:user.person/id 1 :user.person/nam", "end": 1074, "score": 0.7707589864730835, "start": 1070, "tag": "USERNAME", "value": "user" }, { "context": "))\n (is (= {:user.person/id 1 :user.person/name \"user\"} (f/ensure-prefixed :user/person {:id 1 :name \"u", "end": 1131, "score": 0.7785810232162476, "start": 1127, "tag": "USERNAME", "value": "user" }, { "context": "r\"} (f/ensure-prefixed :user/person {:id 1 :name \"user\"})))\n (is (= {:user/id 1 :user/login \"user\"} (f/", "end": 1184, "score": 0.9138852953910828, "start": 1180, "tag": "USERNAME", "value": "user" }, { "context": "= ? AND name = ?)\" (f/format-clause {:id 1 :name \"John\"})))\n (is (= \"(name IN (?, ?, ?))\" (f/format-cla", "end": 4942, "score": 0.9996926188468933, "start": 4938, "tag": "NAME", "value": "John" }, { "context": "= \"(name IN (?, ?, ?))\" (f/format-clause {:name [\"John\" \"Sam\" \"Jack\"]})))\n (is (= \"(name NOT IN (?, ?, ", "end": 5009, "score": 0.9995123147964478, "start": 5005, "tag": "NAME", "value": "John" }, { "context": "e IN (?, ?, ?))\" (f/format-clause {:name [\"John\" \"Sam\" \"Jack\"]})))\n (is (= \"(name NOT IN (?, ?, ?))\" (", "end": 5015, "score": 0.9996417760848999, "start": 5012, "tag": "NAME", "value": "Sam" }, { "context": "?, ?, ?))\" (f/format-clause {:name [\"John\" \"Sam\" \"Jack\"]})))\n (is (= \"(name NOT IN (?, ?, ?))\" (f/forma", "end": 5022, "score": 0.9993605613708496, "start": 5018, "tag": "NAME", "value": "Jack" }, { "context": " IN (?, ?, ?))\" (f/format-clause {:name [:not-in \"John\" \"Sam\" \"Jack\"]})))\n (is (= \"(name ILIKE ?)\" (f/f", "end": 5102, "score": 0.9994472861289978, "start": 5098, "tag": "NAME", "value": "John" }, { "context": " ?, ?))\" (f/format-clause {:name [:not-in \"John\" \"Sam\" \"Jack\"]})))\n (is (= \"(name ILIKE ?)\" (f/format-", "end": 5108, "score": 0.9995694756507874, "start": 5105, "tag": "NAME", "value": "Sam" }, { "context": ")\" (f/format-clause {:name [:not-in \"John\" \"Sam\" \"Jack\"]})))\n (is (= \"(name ILIKE ?)\" (f/format-clause ", "end": 5115, "score": 0.9983854293823242, "start": 5111, "tag": "NAME", "value": "Jack" }, { "context": "\"(name ILIKE ?)\" (f/format-clause {:name [:ilike \"John%\"]})))\n (is (= \"((birthday BETWEEN ? AND ?))\" (f", "end": 5185, "score": 0.9964834451675415, "start": 5181, "tag": "NAME", "value": "John" }, { "context": "ND role = ?)\" (f/format-clause {:or {:id 1 :name \"John\"} :role \"admin\"})))\n (is (= \"(((id = ? OR name =", "end": 5389, "score": 0.9997836947441101, "start": 5385, "tag": "NAME", "value": "John" }, { "context": " = ?))\" (f/format-clause '(and {:or {:id 1 :name \"John\"}} {:role \"admin\"})))))\n\n(deftest conjunct-clause", "end": 5507, "score": 0.9997671246528625, "start": 5503, "tag": "NAME", "value": "John" }, { "context": " {:ids '(string-agg :id \",\")})))\n (is (= [1 \"John\"] (f/extract-values {:id 1 :name \"John\"})))\n ", "end": 10185, "score": 0.8738768696784973, "start": 10181, "tag": "NAME", "value": "John" }, { "context": "(is (= [1 \"John\"] (f/extract-values {:id 1 :name \"John\"})))\n (is (= [1 \"John%\"] (f/extract-values {", "end": 10224, "score": 0.8930311799049377, "start": 10220, "tag": "NAME", "value": "John" }, { "context": "1\" \"1990-01-01\"] (f/extract-values {:name [:like \"John%\"] :birthday [:between \"1980-01-01\" \"1990-01-01\"]", "end": 10392, "score": 0.6263435482978821, "start": 10388, "tag": "NAME", "value": "John" }, { "context": "een \"1980-01-01\" \"1990-01-01\"]})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\"] (f/ext", "end": 10466, "score": 0.9998486638069153, "start": 10462, "tag": "NAME", "value": "John" }, { "context": "80-01-01\" \"1990-01-01\"]})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\"] (f/extract-va", "end": 10473, "score": 0.9998026490211487, "start": 10469, "tag": "NAME", "value": "Jane" }, { "context": "1\" \"1990-01-01\"]})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\"] (f/extract-values {:n", "end": 10481, "score": 0.9997454881668091, "start": 10476, "tag": "NAME", "value": "Boris" }, { "context": "0-01-01\" \"1990-01-01\"] (f/extract-values {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\"", "end": 10541, "score": 0.9998583793640137, "start": 10537, "tag": "NAME", "value": "John" }, { "context": "\" \"1990-01-01\"] (f/extract-values {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\" \"1990-", "end": 10548, "score": 0.9997953772544861, "start": 10544, "tag": "NAME", "value": "Jane" }, { "context": "-01-01\"] (f/extract-values {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\" \"1990-01-01\"]}", "end": 10556, "score": 0.999755859375, "start": 10551, "tag": "NAME", "value": "Boris" }, { "context": "een \"1980-01-01\" \"1990-01-01\"]})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\" \"admin\"", "end": 10629, "score": 0.9998503923416138, "start": 10625, "tag": "NAME", "value": "John" }, { "context": "80-01-01\" \"1990-01-01\"]})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\" \"admin\"] (f/ex", "end": 10636, "score": 0.99980628490448, "start": 10632, "tag": "NAME", "value": "Jane" }, { "context": "1\" \"1990-01-01\"]})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\" \"admin\"] (f/extract-va", "end": 10644, "score": 0.9997422099113464, "start": 10639, "tag": "NAME", "value": "Boris" }, { "context": "0-01-01\" \"admin\"] (f/extract-values {:or {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\"", "end": 10717, "score": 0.999861478805542, "start": 10713, "tag": "NAME", "value": "John" }, { "context": "\" \"admin\"] (f/extract-values {:or {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\" \"1990-", "end": 10724, "score": 0.9997978210449219, "start": 10720, "tag": "NAME", "value": "Jane" }, { "context": "n\"] (f/extract-values {:or {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\" \"1990-01-01\"]}", "end": 10732, "score": 0.9997637867927551, "start": 10727, "tag": "NAME", "value": "Boris" }, { "context": "\"]} :active true :role \"admin\"})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\" \"admin\"", "end": 10833, "score": 0.9998581409454346, "start": 10829, "tag": "NAME", "value": "John" }, { "context": "tive true :role \"admin\"})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\" \"admin\"] (f/ex", "end": 10840, "score": 0.9998058080673218, "start": 10836, "tag": "NAME", "value": "Jane" }, { "context": "ue :role \"admin\"})))\n (is (= [\"John\" \"Jane\" \"Boris\" \"1980-01-01\" \"1990-01-01\" \"admin\"] (f/extract-va", "end": 10848, "score": 0.9997676014900208, "start": 10843, "tag": "NAME", "value": "Boris" }, { "context": "1\" \"admin\"] (f/extract-values '(and {:or {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\"", "end": 10927, "score": 0.9998606443405151, "start": 10923, "tag": "NAME", "value": "John" }, { "context": "in\"] (f/extract-values '(and {:or {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\" \"1990-", "end": 10934, "score": 0.9997801780700684, "start": 10930, "tag": "NAME", "value": "Jane" }, { "context": "/extract-values '(and {:or {:name [\"John\" \"Jane\" \"Boris\"] :birthday [:between \"1980-01-01\" \"1990-01-01\"]}", "end": 10942, "score": 0.9997063875198364, "start": 10937, "tag": "NAME", "value": "Boris" }, { "context": ":person] {:user/id :person/id}])))\n (is (= [\"John\"] (f/extract-values [[:users :user] :left-join [:", "end": 11275, "score": 0.9975213408470154, "start": 11271, "tag": "NAME", "value": "John" }, { "context": "rs :sub] {:user/id :sub/supervisor-id :user/name \"John\"}]))))\n (testing \"from query\"\n (is (= [] ", "end": 11382, "score": 0.9996606111526489, "start": 11378, "tag": "NAME", "value": "John" } ]
test/norm/sql/format_test.clj
kurbatov/norm
4
(ns norm.sql.format-test (:require [clojure.test :as t :refer [deftest testing is]] [norm.sql.format :as f] [norm.sql :as sql])) (deftest prefix-test (is (= :user/id (f/prefix :user :id))) (is (= :supervisor.person/id (f/prefix :supervisor :person/id))) (is (= :employee.supervisor/id (f/prefix :employee/supervisor :id))) (is (= :employee.supervisor.person/id (f/prefix :employee/supervisor :person/id)))) (deftest prefixed-test (is (f/prefixed? :user :user/name)) (is (f/prefixed? :user :user.person/name)) (is (f/prefixed? :user :user.person.contact/value)) (is (f/prefixed? :user/person :user.person/name)) (is (f/prefixed? :user/person :user.person.contact/value)) (is (not (f/prefixed? :user :name))) (is (not (f/prefixed? :user :person/name))) (is (not (f/prefixed? :user/person :person/name)))) (deftest ensure-prefixed-test (is (= {:user/id 1 :user/login "user"} (f/ensure-prefixed :user {:id 1 :login "user"}))) (is (= {:user/id 1 :user.person/name "user"} (f/ensure-prefixed :user {:id 1 :person/name "user"}))) (is (= {:user.person/id 1 :user.person/name "user"} (f/ensure-prefixed :user/person {:id 1 :name "user"}))) (is (= {:user/id 1 :user/login "user"} (f/ensure-prefixed :user {:user/id 1 :user/login "user"}))) (is (= {:or {:user/id 1 :user/login "user"}} (f/ensure-prefixed :user {:or {:id 1 :login "user"}})) "Predicates should not be prefixed.")) (deftest format-alias-test (is (= "id" (f/format-alias :id)) "Alias unquoted.") (is (= "person/id" (f/format-alias :person/id)) "Namespace separated with a slash.") (is (= "user.person/id" (f/format-alias :user.person/id)) "Complex namespace separated with a slash.") (is (= "id" (f/format-alias "id")) "Accept string alliases.") (is (= "person.id" (f/format-alias "person.id")) "String aliases stay as is.")) (deftest format-field-test (is (= "NULL" (f/format-field nil)) "nil should be inlined") (is (= "id" (f/format-field :id)) "Plain field doesn't get quoted.") (is (= "\"user\".id" (f/format-field :user/id)) "Namespace is a quoted prefix.") (is (= "name AS \"full-name\"" (f/format-field :name :full-name)) "Alias gets quoted.") (is (= "name AS \"full-name\"" (f/format-field [:name :full-name])) "Aliased field may be supplied as a vector.") (is (= "\"employee\".name AS \"full-name\"" (f/format-field :employee/name :full-name))) (is (= "\"employee\".name AS \"user/full-name\"" (f/format-field :employee/name :user/full-name))) (is (= "NOW()" (f/format-field '(now))) "Stored procedure without arguments should be inlined.") (is (= "MAX(?, ?)" (f/format-field '(max 1 3))) "Constant arguments of stored procedure should be parametrized.") (is (= "MAX(working, done)" (f/format-field '(max :working :done))) "Fields should be inlined in stored procedure arguments.") (is (= "COUNT(id)" (f/format-field '(count :id))) "Aggregation should be applied.") (is (= "COUNT(\"user\".id)" (f/format-field '(count :user/id))) "Namespace gets quoted inside an aggregation.") (is (= "CURRENT_SCHEMA() AS \"current-schema\"" (f/format-field ['(current-schema) :current-schema])) "Stored procedure should be aliased") (is (= "COUNT(id) AS \"count\"" (f/format-field ['(count :id) :count])) "Aggregation is aliased") (is (= "COUNT(\"user\".id) AS \"user/count\"" (f/format-field ['(count :user/id) :user/count]))) (is (= "STRING_AGG(\"cu\".column_name, ?) AS \"column-list\"" (f/format-field ['(string-agg :cu/column-name ",") :column-list]))) (is (= "(\"employee\".id IS NOT NULL) AS \"employee\"" (f/format-field ['(not= :employee/id nil) :employee]))) (is (= "(debit AND true)" (f/format-field '(and :debit true)))) (is (= "COALESCE((debit AND true), ?) AS \"remainder\"" (f/format-field ['(coalesce (and :debit true) -1) :remainder]))) (is (= "SUM((amount * ISNULL((debit_place_id / debit_place_id), ?))) AS \"remainder\"" (f/format-field ['(sum (* :amount (isnull (/ :debit-place-id :debit-place-id) -1))) :remainder]))) (is (= "?" (f/format-field 0)) "Constant should be represented by a placeholder.") (is (= "?" (f/format-field "string")) "Constant should be represented by a placeholder.") (is (= "(SELECT id AS \"id\" FROM users AS \"users\" WHERE (role = ?))" (f/format-field (sql/select nil :users [:id] {:role "admin"}))) "Query should be wrapped in parens.")) (deftest format-clause-test (is (= "(id = ?)" (f/format-clause {:id 1}))) (is (= "(id <> ?)" (f/format-clause {:id [:not= 1]}))) (is (= "(id IS NULL)" (f/format-clause {:id nil}))) (is (= "(id IS NOT NULL)" (f/format-clause {:id [:not= nil]}))) (is (= "(active IS true)" (f/format-clause {:active true}))) (is (= "(active IS false)" (f/format-clause {:active false}))) (is (= "(\"user\".id = \"employee\".id)" (f/format-clause {:user/id :employee/id}))) (is (= "(id = ? AND name = ?)" (f/format-clause {:id 1 :name "John"}))) (is (= "(name IN (?, ?, ?))" (f/format-clause {:name ["John" "Sam" "Jack"]}))) (is (= "(name NOT IN (?, ?, ?))" (f/format-clause {:name [:not-in "John" "Sam" "Jack"]}))) (is (= "(name ILIKE ?)" (f/format-clause {:name [:ilike "John%"]}))) (is (= "((birthday BETWEEN ? AND ?))" (f/format-clause {:birthday [:between "1988-01-01" "1988-02-01"]}))) (is (= "((id = ? OR name = ?) AND role = ?)" (f/format-clause {:or {:id 1 :name "John"} :role "admin"}))) (is (= "(((id = ? OR name = ?)) AND (role = ?))" (f/format-clause '(and {:or {:id 1 :name "John"}} {:role "admin"}))))) (deftest conjunct-clauses-test (is (= {:id 1} (f/conjunct-clauses {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} nil))) (is (= {:id 1} (f/conjunct-clauses nil {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} nil))) (is (= {:id 1} (f/conjunct-clauses {} {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} {}))) (is (= {:id 1} (f/conjunct-clauses nil {:id 1} {}))) (is (= (list 'and {:role "admin"} {:id 1}) (f/conjunct-clauses {:role "admin"} {:id 1}))) (is (= (list 'and (list 'and {:role "admin"} {:id 1}) {:active true}) (f/conjunct-clauses {:role "admin"} {:id 1} {:active true})))) (deftest format-source-test (testing "Simple case" (is (= "users AS \"users\"" (f/format-source :users))) (is (= "schema_name.users_secrets AS \"schema_name.users_secrets\"" (f/format-source :schema-name/users-secrets)))) (testing "Aliasing" (is (= "users AS \"user\"" (f/format-source :users :user))) (is (= "users AS \"user\"" (f/format-source [:users :user])))) (testing "Joins" (is (= "(users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".id = \"people\".id))" (f/format-source :users :left-join :people {:users/id :people/id}))) (is (= "(users AS \"users\" LEFT JOIN people AS \"person\" ON (\"users\".id = \"person\".id))" (f/format-source :users :left-join [:people :person] {:users/id :person/id}))) (is (= "(users AS \"user\" LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :left-join [:people :person] {:user/id :person/id}))) (is (= "(users AS \"user\" INNER JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :inner-join [:people :person] {:user/id :person/id})))) (testing "Nested joins" (is (= "(users AS \"user\" LEFT JOIN (people AS \"person\" LEFT JOIN contacts AS \"contact\" ON (\"person\".id = \"contact\".person_id)) ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :left-join [[:people :person] :left-join [:contacts :contact] {:person/id :contact/person-id}] {:user/id :person/id}))) (is (= "((users AS \"user\" LEFT JOIN secrets AS \"secret\" ON (\"user\".id = \"secret\".user_id)) LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [[:users :user] :left-join [:secrets :secret] {:user/id :secret/user-id}] :left-join [:people :person] {:user/id :person/id}))) (is (= "((users AS \"user\" LEFT JOIN secrets AS \"secret\" ON (\"user\".id = \"secret\".user_id)) LEFT JOIN (people AS \"person\" LEFT JOIN contacts AS \"contact\" ON (\"person\".id = \"contact\".person_id)) ON (\"user\".id = \"person\".id))" (f/format-source [[:users :user] :left-join [:secrets :secret] {:user/id :secret/user-id}] :left-join [[:people :person] :left-join [:contacts :contact] {:person/id :contact/person-id}] {:user/id :person/id})))) (testing "Subselect" (is (= "(SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (role = ?)) AS \"admin\"" (f/format-source [(sql/select nil :users [:id :name] {:role "admin"}) :admin]))))) (deftest format-order-test (is (= "id" (f/format-order :id))) (is (= "\"user\".id" (f/format-order :user/id))) (is (= "\"user\".id, \"user\".name" (f/format-order :user/id :user/name))) (is (= "id" (f/format-order [:id]))) (is (= "id, name" (f/format-order [:id :name]))) (is (= "\"user\".id, \"user\".name" (f/format-order [:user/id :user/name]))) (is (= "id ASC" (f/format-order {:id :asc}))) (is (= "id ASC, name DESC" (f/format-order {:id :asc :name :desc}))) (is (= "\"user\".id ASC, \"person\".name DESC" (f/format-order {:user/id :asc :person/name :desc})))) (deftest extract-values-test (testing "Extract values" (testing "from fields" (is (= [] (f/extract-values [:id :name]))) (is (= [] (f/extract-values [[:user/id :id] [:person/name :name]]))) (is (= [] (f/extract-values [['(now) :now]]))) (is (= [] (f/extract-values [['(count :id) :count]]))) (is (= [","] (f/extract-values [['(string-agg :id ",") :ids]])))) (testing "from clause" (is (= [] (f/extract-values {}))) (is (= [1] (f/extract-values {:id 1}))) (is (= [] (f/extract-values {:id nil}))) (is (= [] (f/extract-values {:active true}))) (is (= [] (f/extract-values {:user/id :employee/id}))) (is (= [] (f/extract-values {:in-progress [:> :done]}))) (is (= [] (f/extract-values {:start [:> '(now)]}))) (is (= [","] (f/extract-values {:ids '(string-agg :id ",")}))) (is (= [1 "John"] (f/extract-values {:id 1 :name "John"}))) (is (= [1 "John%"] (f/extract-values {:id 1 :name [:like "John%"]}))) (is (= ["John%" "1980-01-01" "1990-01-01"] (f/extract-values {:name [:like "John%"] :birthday [:between "1980-01-01" "1990-01-01"]}))) (is (= ["John" "Jane" "Boris" "1980-01-01" "1990-01-01"] (f/extract-values {:name ["John" "Jane" "Boris"] :birthday [:between "1980-01-01" "1990-01-01"]}))) (is (= ["John" "Jane" "Boris" "1980-01-01" "1990-01-01" "admin"] (f/extract-values {:or {:name ["John" "Jane" "Boris"] :birthday [:between "1980-01-01" "1990-01-01"]} :active true :role "admin"}))) (is (= ["John" "Jane" "Boris" "1980-01-01" "1990-01-01" "admin"] (f/extract-values '(and {:or {:name ["John" "Jane" "Boris"] :birthday [:between "1980-01-01" "1990-01-01"]}} {:active true :role "admin"}))))) (testing "from target" (is (= [] (f/extract-values :users))) (is (= [] (f/extract-values [:users :user]))) (is (= [] (f/extract-values [[:users :user] :left-join [:people :person] {:user/id :person/id}]))) (is (= ["John"] (f/extract-values [[:users :user] :left-join [:users :sub] {:user/id :sub/supervisor-id :user/name "John"}])))) (testing "from query" (is (= [] (f/extract-values (sql/select nil :users [:id])))) (is (= ["admin" 60 20] (f/extract-values [(sql/select nil :users [:id] {:role "admin"} {:id :asc} 20 60)])))) (testing "from sub-query" (is (= ["admin" 60 20] (f/extract-values {:id [:in (sql/select nil :users [:id] {:role "admin"} {:id :asc} 20 60)]}))))))
54166
(ns norm.sql.format-test (:require [clojure.test :as t :refer [deftest testing is]] [norm.sql.format :as f] [norm.sql :as sql])) (deftest prefix-test (is (= :user/id (f/prefix :user :id))) (is (= :supervisor.person/id (f/prefix :supervisor :person/id))) (is (= :employee.supervisor/id (f/prefix :employee/supervisor :id))) (is (= :employee.supervisor.person/id (f/prefix :employee/supervisor :person/id)))) (deftest prefixed-test (is (f/prefixed? :user :user/name)) (is (f/prefixed? :user :user.person/name)) (is (f/prefixed? :user :user.person.contact/value)) (is (f/prefixed? :user/person :user.person/name)) (is (f/prefixed? :user/person :user.person.contact/value)) (is (not (f/prefixed? :user :name))) (is (not (f/prefixed? :user :person/name))) (is (not (f/prefixed? :user/person :person/name)))) (deftest ensure-prefixed-test (is (= {:user/id 1 :user/login "user"} (f/ensure-prefixed :user {:id 1 :login "user"}))) (is (= {:user/id 1 :user.person/name "user"} (f/ensure-prefixed :user {:id 1 :person/name "user"}))) (is (= {:user.person/id 1 :user.person/name "user"} (f/ensure-prefixed :user/person {:id 1 :name "user"}))) (is (= {:user/id 1 :user/login "user"} (f/ensure-prefixed :user {:user/id 1 :user/login "user"}))) (is (= {:or {:user/id 1 :user/login "user"}} (f/ensure-prefixed :user {:or {:id 1 :login "user"}})) "Predicates should not be prefixed.")) (deftest format-alias-test (is (= "id" (f/format-alias :id)) "Alias unquoted.") (is (= "person/id" (f/format-alias :person/id)) "Namespace separated with a slash.") (is (= "user.person/id" (f/format-alias :user.person/id)) "Complex namespace separated with a slash.") (is (= "id" (f/format-alias "id")) "Accept string alliases.") (is (= "person.id" (f/format-alias "person.id")) "String aliases stay as is.")) (deftest format-field-test (is (= "NULL" (f/format-field nil)) "nil should be inlined") (is (= "id" (f/format-field :id)) "Plain field doesn't get quoted.") (is (= "\"user\".id" (f/format-field :user/id)) "Namespace is a quoted prefix.") (is (= "name AS \"full-name\"" (f/format-field :name :full-name)) "Alias gets quoted.") (is (= "name AS \"full-name\"" (f/format-field [:name :full-name])) "Aliased field may be supplied as a vector.") (is (= "\"employee\".name AS \"full-name\"" (f/format-field :employee/name :full-name))) (is (= "\"employee\".name AS \"user/full-name\"" (f/format-field :employee/name :user/full-name))) (is (= "NOW()" (f/format-field '(now))) "Stored procedure without arguments should be inlined.") (is (= "MAX(?, ?)" (f/format-field '(max 1 3))) "Constant arguments of stored procedure should be parametrized.") (is (= "MAX(working, done)" (f/format-field '(max :working :done))) "Fields should be inlined in stored procedure arguments.") (is (= "COUNT(id)" (f/format-field '(count :id))) "Aggregation should be applied.") (is (= "COUNT(\"user\".id)" (f/format-field '(count :user/id))) "Namespace gets quoted inside an aggregation.") (is (= "CURRENT_SCHEMA() AS \"current-schema\"" (f/format-field ['(current-schema) :current-schema])) "Stored procedure should be aliased") (is (= "COUNT(id) AS \"count\"" (f/format-field ['(count :id) :count])) "Aggregation is aliased") (is (= "COUNT(\"user\".id) AS \"user/count\"" (f/format-field ['(count :user/id) :user/count]))) (is (= "STRING_AGG(\"cu\".column_name, ?) AS \"column-list\"" (f/format-field ['(string-agg :cu/column-name ",") :column-list]))) (is (= "(\"employee\".id IS NOT NULL) AS \"employee\"" (f/format-field ['(not= :employee/id nil) :employee]))) (is (= "(debit AND true)" (f/format-field '(and :debit true)))) (is (= "COALESCE((debit AND true), ?) AS \"remainder\"" (f/format-field ['(coalesce (and :debit true) -1) :remainder]))) (is (= "SUM((amount * ISNULL((debit_place_id / debit_place_id), ?))) AS \"remainder\"" (f/format-field ['(sum (* :amount (isnull (/ :debit-place-id :debit-place-id) -1))) :remainder]))) (is (= "?" (f/format-field 0)) "Constant should be represented by a placeholder.") (is (= "?" (f/format-field "string")) "Constant should be represented by a placeholder.") (is (= "(SELECT id AS \"id\" FROM users AS \"users\" WHERE (role = ?))" (f/format-field (sql/select nil :users [:id] {:role "admin"}))) "Query should be wrapped in parens.")) (deftest format-clause-test (is (= "(id = ?)" (f/format-clause {:id 1}))) (is (= "(id <> ?)" (f/format-clause {:id [:not= 1]}))) (is (= "(id IS NULL)" (f/format-clause {:id nil}))) (is (= "(id IS NOT NULL)" (f/format-clause {:id [:not= nil]}))) (is (= "(active IS true)" (f/format-clause {:active true}))) (is (= "(active IS false)" (f/format-clause {:active false}))) (is (= "(\"user\".id = \"employee\".id)" (f/format-clause {:user/id :employee/id}))) (is (= "(id = ? AND name = ?)" (f/format-clause {:id 1 :name "<NAME>"}))) (is (= "(name IN (?, ?, ?))" (f/format-clause {:name ["<NAME>" "<NAME>" "<NAME>"]}))) (is (= "(name NOT IN (?, ?, ?))" (f/format-clause {:name [:not-in "<NAME>" "<NAME>" "<NAME>"]}))) (is (= "(name ILIKE ?)" (f/format-clause {:name [:ilike "<NAME>%"]}))) (is (= "((birthday BETWEEN ? AND ?))" (f/format-clause {:birthday [:between "1988-01-01" "1988-02-01"]}))) (is (= "((id = ? OR name = ?) AND role = ?)" (f/format-clause {:or {:id 1 :name "<NAME>"} :role "admin"}))) (is (= "(((id = ? OR name = ?)) AND (role = ?))" (f/format-clause '(and {:or {:id 1 :name "<NAME>"}} {:role "admin"}))))) (deftest conjunct-clauses-test (is (= {:id 1} (f/conjunct-clauses {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} nil))) (is (= {:id 1} (f/conjunct-clauses nil {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} nil))) (is (= {:id 1} (f/conjunct-clauses {} {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} {}))) (is (= {:id 1} (f/conjunct-clauses nil {:id 1} {}))) (is (= (list 'and {:role "admin"} {:id 1}) (f/conjunct-clauses {:role "admin"} {:id 1}))) (is (= (list 'and (list 'and {:role "admin"} {:id 1}) {:active true}) (f/conjunct-clauses {:role "admin"} {:id 1} {:active true})))) (deftest format-source-test (testing "Simple case" (is (= "users AS \"users\"" (f/format-source :users))) (is (= "schema_name.users_secrets AS \"schema_name.users_secrets\"" (f/format-source :schema-name/users-secrets)))) (testing "Aliasing" (is (= "users AS \"user\"" (f/format-source :users :user))) (is (= "users AS \"user\"" (f/format-source [:users :user])))) (testing "Joins" (is (= "(users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".id = \"people\".id))" (f/format-source :users :left-join :people {:users/id :people/id}))) (is (= "(users AS \"users\" LEFT JOIN people AS \"person\" ON (\"users\".id = \"person\".id))" (f/format-source :users :left-join [:people :person] {:users/id :person/id}))) (is (= "(users AS \"user\" LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :left-join [:people :person] {:user/id :person/id}))) (is (= "(users AS \"user\" INNER JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :inner-join [:people :person] {:user/id :person/id})))) (testing "Nested joins" (is (= "(users AS \"user\" LEFT JOIN (people AS \"person\" LEFT JOIN contacts AS \"contact\" ON (\"person\".id = \"contact\".person_id)) ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :left-join [[:people :person] :left-join [:contacts :contact] {:person/id :contact/person-id}] {:user/id :person/id}))) (is (= "((users AS \"user\" LEFT JOIN secrets AS \"secret\" ON (\"user\".id = \"secret\".user_id)) LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [[:users :user] :left-join [:secrets :secret] {:user/id :secret/user-id}] :left-join [:people :person] {:user/id :person/id}))) (is (= "((users AS \"user\" LEFT JOIN secrets AS \"secret\" ON (\"user\".id = \"secret\".user_id)) LEFT JOIN (people AS \"person\" LEFT JOIN contacts AS \"contact\" ON (\"person\".id = \"contact\".person_id)) ON (\"user\".id = \"person\".id))" (f/format-source [[:users :user] :left-join [:secrets :secret] {:user/id :secret/user-id}] :left-join [[:people :person] :left-join [:contacts :contact] {:person/id :contact/person-id}] {:user/id :person/id})))) (testing "Subselect" (is (= "(SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (role = ?)) AS \"admin\"" (f/format-source [(sql/select nil :users [:id :name] {:role "admin"}) :admin]))))) (deftest format-order-test (is (= "id" (f/format-order :id))) (is (= "\"user\".id" (f/format-order :user/id))) (is (= "\"user\".id, \"user\".name" (f/format-order :user/id :user/name))) (is (= "id" (f/format-order [:id]))) (is (= "id, name" (f/format-order [:id :name]))) (is (= "\"user\".id, \"user\".name" (f/format-order [:user/id :user/name]))) (is (= "id ASC" (f/format-order {:id :asc}))) (is (= "id ASC, name DESC" (f/format-order {:id :asc :name :desc}))) (is (= "\"user\".id ASC, \"person\".name DESC" (f/format-order {:user/id :asc :person/name :desc})))) (deftest extract-values-test (testing "Extract values" (testing "from fields" (is (= [] (f/extract-values [:id :name]))) (is (= [] (f/extract-values [[:user/id :id] [:person/name :name]]))) (is (= [] (f/extract-values [['(now) :now]]))) (is (= [] (f/extract-values [['(count :id) :count]]))) (is (= [","] (f/extract-values [['(string-agg :id ",") :ids]])))) (testing "from clause" (is (= [] (f/extract-values {}))) (is (= [1] (f/extract-values {:id 1}))) (is (= [] (f/extract-values {:id nil}))) (is (= [] (f/extract-values {:active true}))) (is (= [] (f/extract-values {:user/id :employee/id}))) (is (= [] (f/extract-values {:in-progress [:> :done]}))) (is (= [] (f/extract-values {:start [:> '(now)]}))) (is (= [","] (f/extract-values {:ids '(string-agg :id ",")}))) (is (= [1 "<NAME>"] (f/extract-values {:id 1 :name "<NAME>"}))) (is (= [1 "John%"] (f/extract-values {:id 1 :name [:like "John%"]}))) (is (= ["John%" "1980-01-01" "1990-01-01"] (f/extract-values {:name [:like "<NAME>%"] :birthday [:between "1980-01-01" "1990-01-01"]}))) (is (= ["<NAME>" "<NAME>" "<NAME>" "1980-01-01" "1990-01-01"] (f/extract-values {:name ["<NAME>" "<NAME>" "<NAME>"] :birthday [:between "1980-01-01" "1990-01-01"]}))) (is (= ["<NAME>" "<NAME>" "<NAME>" "1980-01-01" "1990-01-01" "admin"] (f/extract-values {:or {:name ["<NAME>" "<NAME>" "<NAME>"] :birthday [:between "1980-01-01" "1990-01-01"]} :active true :role "admin"}))) (is (= ["<NAME>" "<NAME>" "<NAME>" "1980-01-01" "1990-01-01" "admin"] (f/extract-values '(and {:or {:name ["<NAME>" "<NAME>" "<NAME>"] :birthday [:between "1980-01-01" "1990-01-01"]}} {:active true :role "admin"}))))) (testing "from target" (is (= [] (f/extract-values :users))) (is (= [] (f/extract-values [:users :user]))) (is (= [] (f/extract-values [[:users :user] :left-join [:people :person] {:user/id :person/id}]))) (is (= ["<NAME>"] (f/extract-values [[:users :user] :left-join [:users :sub] {:user/id :sub/supervisor-id :user/name "<NAME>"}])))) (testing "from query" (is (= [] (f/extract-values (sql/select nil :users [:id])))) (is (= ["admin" 60 20] (f/extract-values [(sql/select nil :users [:id] {:role "admin"} {:id :asc} 20 60)])))) (testing "from sub-query" (is (= ["admin" 60 20] (f/extract-values {:id [:in (sql/select nil :users [:id] {:role "admin"} {:id :asc} 20 60)]}))))))
true
(ns norm.sql.format-test (:require [clojure.test :as t :refer [deftest testing is]] [norm.sql.format :as f] [norm.sql :as sql])) (deftest prefix-test (is (= :user/id (f/prefix :user :id))) (is (= :supervisor.person/id (f/prefix :supervisor :person/id))) (is (= :employee.supervisor/id (f/prefix :employee/supervisor :id))) (is (= :employee.supervisor.person/id (f/prefix :employee/supervisor :person/id)))) (deftest prefixed-test (is (f/prefixed? :user :user/name)) (is (f/prefixed? :user :user.person/name)) (is (f/prefixed? :user :user.person.contact/value)) (is (f/prefixed? :user/person :user.person/name)) (is (f/prefixed? :user/person :user.person.contact/value)) (is (not (f/prefixed? :user :name))) (is (not (f/prefixed? :user :person/name))) (is (not (f/prefixed? :user/person :person/name)))) (deftest ensure-prefixed-test (is (= {:user/id 1 :user/login "user"} (f/ensure-prefixed :user {:id 1 :login "user"}))) (is (= {:user/id 1 :user.person/name "user"} (f/ensure-prefixed :user {:id 1 :person/name "user"}))) (is (= {:user.person/id 1 :user.person/name "user"} (f/ensure-prefixed :user/person {:id 1 :name "user"}))) (is (= {:user/id 1 :user/login "user"} (f/ensure-prefixed :user {:user/id 1 :user/login "user"}))) (is (= {:or {:user/id 1 :user/login "user"}} (f/ensure-prefixed :user {:or {:id 1 :login "user"}})) "Predicates should not be prefixed.")) (deftest format-alias-test (is (= "id" (f/format-alias :id)) "Alias unquoted.") (is (= "person/id" (f/format-alias :person/id)) "Namespace separated with a slash.") (is (= "user.person/id" (f/format-alias :user.person/id)) "Complex namespace separated with a slash.") (is (= "id" (f/format-alias "id")) "Accept string alliases.") (is (= "person.id" (f/format-alias "person.id")) "String aliases stay as is.")) (deftest format-field-test (is (= "NULL" (f/format-field nil)) "nil should be inlined") (is (= "id" (f/format-field :id)) "Plain field doesn't get quoted.") (is (= "\"user\".id" (f/format-field :user/id)) "Namespace is a quoted prefix.") (is (= "name AS \"full-name\"" (f/format-field :name :full-name)) "Alias gets quoted.") (is (= "name AS \"full-name\"" (f/format-field [:name :full-name])) "Aliased field may be supplied as a vector.") (is (= "\"employee\".name AS \"full-name\"" (f/format-field :employee/name :full-name))) (is (= "\"employee\".name AS \"user/full-name\"" (f/format-field :employee/name :user/full-name))) (is (= "NOW()" (f/format-field '(now))) "Stored procedure without arguments should be inlined.") (is (= "MAX(?, ?)" (f/format-field '(max 1 3))) "Constant arguments of stored procedure should be parametrized.") (is (= "MAX(working, done)" (f/format-field '(max :working :done))) "Fields should be inlined in stored procedure arguments.") (is (= "COUNT(id)" (f/format-field '(count :id))) "Aggregation should be applied.") (is (= "COUNT(\"user\".id)" (f/format-field '(count :user/id))) "Namespace gets quoted inside an aggregation.") (is (= "CURRENT_SCHEMA() AS \"current-schema\"" (f/format-field ['(current-schema) :current-schema])) "Stored procedure should be aliased") (is (= "COUNT(id) AS \"count\"" (f/format-field ['(count :id) :count])) "Aggregation is aliased") (is (= "COUNT(\"user\".id) AS \"user/count\"" (f/format-field ['(count :user/id) :user/count]))) (is (= "STRING_AGG(\"cu\".column_name, ?) AS \"column-list\"" (f/format-field ['(string-agg :cu/column-name ",") :column-list]))) (is (= "(\"employee\".id IS NOT NULL) AS \"employee\"" (f/format-field ['(not= :employee/id nil) :employee]))) (is (= "(debit AND true)" (f/format-field '(and :debit true)))) (is (= "COALESCE((debit AND true), ?) AS \"remainder\"" (f/format-field ['(coalesce (and :debit true) -1) :remainder]))) (is (= "SUM((amount * ISNULL((debit_place_id / debit_place_id), ?))) AS \"remainder\"" (f/format-field ['(sum (* :amount (isnull (/ :debit-place-id :debit-place-id) -1))) :remainder]))) (is (= "?" (f/format-field 0)) "Constant should be represented by a placeholder.") (is (= "?" (f/format-field "string")) "Constant should be represented by a placeholder.") (is (= "(SELECT id AS \"id\" FROM users AS \"users\" WHERE (role = ?))" (f/format-field (sql/select nil :users [:id] {:role "admin"}))) "Query should be wrapped in parens.")) (deftest format-clause-test (is (= "(id = ?)" (f/format-clause {:id 1}))) (is (= "(id <> ?)" (f/format-clause {:id [:not= 1]}))) (is (= "(id IS NULL)" (f/format-clause {:id nil}))) (is (= "(id IS NOT NULL)" (f/format-clause {:id [:not= nil]}))) (is (= "(active IS true)" (f/format-clause {:active true}))) (is (= "(active IS false)" (f/format-clause {:active false}))) (is (= "(\"user\".id = \"employee\".id)" (f/format-clause {:user/id :employee/id}))) (is (= "(id = ? AND name = ?)" (f/format-clause {:id 1 :name "PI:NAME:<NAME>END_PI"}))) (is (= "(name IN (?, ?, ?))" (f/format-clause {:name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}))) (is (= "(name NOT IN (?, ?, ?))" (f/format-clause {:name [:not-in "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}))) (is (= "(name ILIKE ?)" (f/format-clause {:name [:ilike "PI:NAME:<NAME>END_PI%"]}))) (is (= "((birthday BETWEEN ? AND ?))" (f/format-clause {:birthday [:between "1988-01-01" "1988-02-01"]}))) (is (= "((id = ? OR name = ?) AND role = ?)" (f/format-clause {:or {:id 1 :name "PI:NAME:<NAME>END_PI"} :role "admin"}))) (is (= "(((id = ? OR name = ?)) AND (role = ?))" (f/format-clause '(and {:or {:id 1 :name "PI:NAME:<NAME>END_PI"}} {:role "admin"}))))) (deftest conjunct-clauses-test (is (= {:id 1} (f/conjunct-clauses {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} nil))) (is (= {:id 1} (f/conjunct-clauses nil {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} nil))) (is (= {:id 1} (f/conjunct-clauses {} {:id 1}))) (is (= {:id 1} (f/conjunct-clauses {:id 1} {}))) (is (= {:id 1} (f/conjunct-clauses nil {:id 1} {}))) (is (= (list 'and {:role "admin"} {:id 1}) (f/conjunct-clauses {:role "admin"} {:id 1}))) (is (= (list 'and (list 'and {:role "admin"} {:id 1}) {:active true}) (f/conjunct-clauses {:role "admin"} {:id 1} {:active true})))) (deftest format-source-test (testing "Simple case" (is (= "users AS \"users\"" (f/format-source :users))) (is (= "schema_name.users_secrets AS \"schema_name.users_secrets\"" (f/format-source :schema-name/users-secrets)))) (testing "Aliasing" (is (= "users AS \"user\"" (f/format-source :users :user))) (is (= "users AS \"user\"" (f/format-source [:users :user])))) (testing "Joins" (is (= "(users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".id = \"people\".id))" (f/format-source :users :left-join :people {:users/id :people/id}))) (is (= "(users AS \"users\" LEFT JOIN people AS \"person\" ON (\"users\".id = \"person\".id))" (f/format-source :users :left-join [:people :person] {:users/id :person/id}))) (is (= "(users AS \"user\" LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :left-join [:people :person] {:user/id :person/id}))) (is (= "(users AS \"user\" INNER JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :inner-join [:people :person] {:user/id :person/id})))) (testing "Nested joins" (is (= "(users AS \"user\" LEFT JOIN (people AS \"person\" LEFT JOIN contacts AS \"contact\" ON (\"person\".id = \"contact\".person_id)) ON (\"user\".id = \"person\".id))" (f/format-source [:users :user] :left-join [[:people :person] :left-join [:contacts :contact] {:person/id :contact/person-id}] {:user/id :person/id}))) (is (= "((users AS \"user\" LEFT JOIN secrets AS \"secret\" ON (\"user\".id = \"secret\".user_id)) LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))" (f/format-source [[:users :user] :left-join [:secrets :secret] {:user/id :secret/user-id}] :left-join [:people :person] {:user/id :person/id}))) (is (= "((users AS \"user\" LEFT JOIN secrets AS \"secret\" ON (\"user\".id = \"secret\".user_id)) LEFT JOIN (people AS \"person\" LEFT JOIN contacts AS \"contact\" ON (\"person\".id = \"contact\".person_id)) ON (\"user\".id = \"person\".id))" (f/format-source [[:users :user] :left-join [:secrets :secret] {:user/id :secret/user-id}] :left-join [[:people :person] :left-join [:contacts :contact] {:person/id :contact/person-id}] {:user/id :person/id})))) (testing "Subselect" (is (= "(SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (role = ?)) AS \"admin\"" (f/format-source [(sql/select nil :users [:id :name] {:role "admin"}) :admin]))))) (deftest format-order-test (is (= "id" (f/format-order :id))) (is (= "\"user\".id" (f/format-order :user/id))) (is (= "\"user\".id, \"user\".name" (f/format-order :user/id :user/name))) (is (= "id" (f/format-order [:id]))) (is (= "id, name" (f/format-order [:id :name]))) (is (= "\"user\".id, \"user\".name" (f/format-order [:user/id :user/name]))) (is (= "id ASC" (f/format-order {:id :asc}))) (is (= "id ASC, name DESC" (f/format-order {:id :asc :name :desc}))) (is (= "\"user\".id ASC, \"person\".name DESC" (f/format-order {:user/id :asc :person/name :desc})))) (deftest extract-values-test (testing "Extract values" (testing "from fields" (is (= [] (f/extract-values [:id :name]))) (is (= [] (f/extract-values [[:user/id :id] [:person/name :name]]))) (is (= [] (f/extract-values [['(now) :now]]))) (is (= [] (f/extract-values [['(count :id) :count]]))) (is (= [","] (f/extract-values [['(string-agg :id ",") :ids]])))) (testing "from clause" (is (= [] (f/extract-values {}))) (is (= [1] (f/extract-values {:id 1}))) (is (= [] (f/extract-values {:id nil}))) (is (= [] (f/extract-values {:active true}))) (is (= [] (f/extract-values {:user/id :employee/id}))) (is (= [] (f/extract-values {:in-progress [:> :done]}))) (is (= [] (f/extract-values {:start [:> '(now)]}))) (is (= [","] (f/extract-values {:ids '(string-agg :id ",")}))) (is (= [1 "PI:NAME:<NAME>END_PI"] (f/extract-values {:id 1 :name "PI:NAME:<NAME>END_PI"}))) (is (= [1 "John%"] (f/extract-values {:id 1 :name [:like "John%"]}))) (is (= ["John%" "1980-01-01" "1990-01-01"] (f/extract-values {:name [:like "PI:NAME:<NAME>END_PI%"] :birthday [:between "1980-01-01" "1990-01-01"]}))) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "1980-01-01" "1990-01-01"] (f/extract-values {:name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] :birthday [:between "1980-01-01" "1990-01-01"]}))) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "1980-01-01" "1990-01-01" "admin"] (f/extract-values {:or {:name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] :birthday [:between "1980-01-01" "1990-01-01"]} :active true :role "admin"}))) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "1980-01-01" "1990-01-01" "admin"] (f/extract-values '(and {:or {:name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] :birthday [:between "1980-01-01" "1990-01-01"]}} {:active true :role "admin"}))))) (testing "from target" (is (= [] (f/extract-values :users))) (is (= [] (f/extract-values [:users :user]))) (is (= [] (f/extract-values [[:users :user] :left-join [:people :person] {:user/id :person/id}]))) (is (= ["PI:NAME:<NAME>END_PI"] (f/extract-values [[:users :user] :left-join [:users :sub] {:user/id :sub/supervisor-id :user/name "PI:NAME:<NAME>END_PI"}])))) (testing "from query" (is (= [] (f/extract-values (sql/select nil :users [:id])))) (is (= ["admin" 60 20] (f/extract-values [(sql/select nil :users [:id] {:role "admin"} {:id :asc} 20 60)])))) (testing "from sub-query" (is (= ["admin" 60 20] (f/extract-values {:id [:in (sql/select nil :users [:id] {:role "admin"} {:id :asc} 20 60)]}))))))
[ { "context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 28, "score": 0.8075883984565735, "start": 25, "tag": "NAME", "value": "Net" } ]
src/test/clojure/pigpen/functional/map_test.clj
magomimmo/PigPen
1
;; ;; ;; Copyright 2013 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.functional.map-test (:use clojure.test) (:require [pigpen.extensions.test :refer [test-diff]] [pigpen.core :as pig] [pigpen.fold :as fold])) (deftest test-map (let [data (pig/return [{:x 1, :y 2} {:x 2, :y 4}]) command (pig/map (fn [{:keys [x y]}] (+ x y)) data)] (test-diff (pig/dump command) '[3 6]))) (deftest test-mapcat (let [data (pig/return [{:x 1, :y 2} {:x 2, :y 4}]) command (pig/mapcat (juxt :x :y) data)] (test-diff (pig/dump command) '[1 2 2 4]))) (deftest test-map-indexed (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/map-indexed vector data)] (test-diff (pig/dump command) '[[0 {:a 2}] [1 {:a 1}] [2 {:a 3}]])) (let [command (->> (pig/return [{:a 2} {:a 1} {:a 3}]) (pig/sort-by :a) (pig/map-indexed vector))] (test-diff (pig/dump command) '[[0 {:a 1}] [1 {:a 2}] [2 {:a 3}]]))) (deftest test-sort (let [data (pig/return [2 1 4 3]) command (pig/sort data)] (test-diff (pig/dump command) '[1 2 3 4])) (let [data (pig/return [2 1 4 3]) command (pig/sort :desc data)] (test-diff (pig/dump command) '[4 3 2 1]))) (deftest test-sort-by (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/sort-by :a data)] (test-diff (pig/dump command) '[{:a 1} {:a 2} {:a 3}])) (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/sort-by :a :desc data)] (test-diff (pig/dump command) '[{:a 3} {:a 2} {:a 1}])) (let [data (pig/return [1 2 3 1 2 3 1 2 3]) command (pig/sort-by identity data)] (is (= (pig/dump command) [1 1 1 2 2 2 3 3 3])))) (deftest test-map+fold (is (= (pig/dump (->> (pig/return [-2 -1 0 1 2]) (pig/map #(> % 0)) (pig/fold (->> (fold/filter identity) (fold/count))))) [2]))) (deftest test-map+reduce (is (= (pig/dump (->> (pig/return [-2 -1 0 1 2]) (pig/map inc) (pig/fold (->> (fold/filter #(> % 0)) (fold/count))))) [3])))
12069
;; ;; ;; Copyright 2013 <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.functional.map-test (:use clojure.test) (:require [pigpen.extensions.test :refer [test-diff]] [pigpen.core :as pig] [pigpen.fold :as fold])) (deftest test-map (let [data (pig/return [{:x 1, :y 2} {:x 2, :y 4}]) command (pig/map (fn [{:keys [x y]}] (+ x y)) data)] (test-diff (pig/dump command) '[3 6]))) (deftest test-mapcat (let [data (pig/return [{:x 1, :y 2} {:x 2, :y 4}]) command (pig/mapcat (juxt :x :y) data)] (test-diff (pig/dump command) '[1 2 2 4]))) (deftest test-map-indexed (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/map-indexed vector data)] (test-diff (pig/dump command) '[[0 {:a 2}] [1 {:a 1}] [2 {:a 3}]])) (let [command (->> (pig/return [{:a 2} {:a 1} {:a 3}]) (pig/sort-by :a) (pig/map-indexed vector))] (test-diff (pig/dump command) '[[0 {:a 1}] [1 {:a 2}] [2 {:a 3}]]))) (deftest test-sort (let [data (pig/return [2 1 4 3]) command (pig/sort data)] (test-diff (pig/dump command) '[1 2 3 4])) (let [data (pig/return [2 1 4 3]) command (pig/sort :desc data)] (test-diff (pig/dump command) '[4 3 2 1]))) (deftest test-sort-by (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/sort-by :a data)] (test-diff (pig/dump command) '[{:a 1} {:a 2} {:a 3}])) (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/sort-by :a :desc data)] (test-diff (pig/dump command) '[{:a 3} {:a 2} {:a 1}])) (let [data (pig/return [1 2 3 1 2 3 1 2 3]) command (pig/sort-by identity data)] (is (= (pig/dump command) [1 1 1 2 2 2 3 3 3])))) (deftest test-map+fold (is (= (pig/dump (->> (pig/return [-2 -1 0 1 2]) (pig/map #(> % 0)) (pig/fold (->> (fold/filter identity) (fold/count))))) [2]))) (deftest test-map+reduce (is (= (pig/dump (->> (pig/return [-2 -1 0 1 2]) (pig/map inc) (pig/fold (->> (fold/filter #(> % 0)) (fold/count))))) [3])))
true
;; ;; ;; Copyright 2013 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.functional.map-test (:use clojure.test) (:require [pigpen.extensions.test :refer [test-diff]] [pigpen.core :as pig] [pigpen.fold :as fold])) (deftest test-map (let [data (pig/return [{:x 1, :y 2} {:x 2, :y 4}]) command (pig/map (fn [{:keys [x y]}] (+ x y)) data)] (test-diff (pig/dump command) '[3 6]))) (deftest test-mapcat (let [data (pig/return [{:x 1, :y 2} {:x 2, :y 4}]) command (pig/mapcat (juxt :x :y) data)] (test-diff (pig/dump command) '[1 2 2 4]))) (deftest test-map-indexed (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/map-indexed vector data)] (test-diff (pig/dump command) '[[0 {:a 2}] [1 {:a 1}] [2 {:a 3}]])) (let [command (->> (pig/return [{:a 2} {:a 1} {:a 3}]) (pig/sort-by :a) (pig/map-indexed vector))] (test-diff (pig/dump command) '[[0 {:a 1}] [1 {:a 2}] [2 {:a 3}]]))) (deftest test-sort (let [data (pig/return [2 1 4 3]) command (pig/sort data)] (test-diff (pig/dump command) '[1 2 3 4])) (let [data (pig/return [2 1 4 3]) command (pig/sort :desc data)] (test-diff (pig/dump command) '[4 3 2 1]))) (deftest test-sort-by (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/sort-by :a data)] (test-diff (pig/dump command) '[{:a 1} {:a 2} {:a 3}])) (let [data (pig/return [{:a 2} {:a 1} {:a 3}]) command (pig/sort-by :a :desc data)] (test-diff (pig/dump command) '[{:a 3} {:a 2} {:a 1}])) (let [data (pig/return [1 2 3 1 2 3 1 2 3]) command (pig/sort-by identity data)] (is (= (pig/dump command) [1 1 1 2 2 2 3 3 3])))) (deftest test-map+fold (is (= (pig/dump (->> (pig/return [-2 -1 0 1 2]) (pig/map #(> % 0)) (pig/fold (->> (fold/filter identity) (fold/count))))) [2]))) (deftest test-map+reduce (is (= (pig/dump (->> (pig/return [-2 -1 0 1 2]) (pig/map inc) (pig/fold (->> (fold/filter #(> % 0)) (fold/count))))) [3])))
[ { "context": " interpolating \n polynomials\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2018-10-18\"}\n \n (:require [clojur", "end": 360, "score": 0.950040876865387, "start": 324, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/mudstone/scripts/expresso.clj
palisades-lakes/mudstone
0
;; clj src/scripts/clojure/mudstone/scripts/plots.clj (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns mudstone.scripts.expresso {:doc "solve symbolic systems of equations for interpolating polynomials" :author "palisades dot lakes at gmail dot com" :version "2018-10-18"} (:require [clojure.pprint :as pp] #_[numeric.expresso.core :as nec])) ;;---------------------------------------------------------------- ;; Affine monomial yy ;(def affine-monomial ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1 (+ a0 (* a1 x1))))))) ; ;#{{a1 (+ (* y1 ; (+ (/ x1) ; (* (** (/ x1) 2) ; -1 ; x0 ; (/ (+ (/ x1) (- x0) -1))))) ; (* y0 ; (/ (+ (/ x1) (- x0) -1)) ; (/ x1))), ; a0 (* (/ (+ (/ x1) (- x0) -1)) ; (+ (* y1 (/ x1) x0) ; (- y0)))}} ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; affine-monomial )) ; ;; a1 ;(+ (* (/ x1) ; (+ y1 ; (* y0 ; (/ (+ (/ x1) (- x0) -1))))) ; (* (/ (** x1 2)) ; -1 x0 ; (/ (+ (/ x1) (- x0) -1)) ; y1)) ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1-y0 (* a1 x1-x0))))))) ; !!! WRONG ANSWER: !!! ;[a1 (* y1-y0 (/ x1-x0))] ;[a0 (+ y0 (* -1 y1-y0 x1-x0 x0))] ; ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1-y0 (* a1 x1-x0))))))) ; ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= (+ y1 (- y0)) (* a1 (- x1 x0)))))))) ; ;(def e0 (nec/ex (- y0 a0 (* a1 x0)))) ;(def e1 (nec/ex (- y1 a0 (* a1 x1)))) ;(def e0 (nec/ex (- y0 (+ a0 (* a1 x0))))) ;(def e1 (nec/ex (- y1 (+ a0 (* a1 x1))))) ;(def e1-e0 (nec/ex (= 0 (- ~e0 ~e1)))) ;(def e1+e0 (nec/ex (= 0 (+ ~e0 ~e1)))) ; ;(try ; (nec/solve ; '[a0 a1] ; e1-e0 ; e1+e0 ; ) ; (catch Throwable t ; (.printStackTrace t) ; (throw t))) ; ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= 0 (+ ~e0 ~e1))) ; (nec/ex (= 0 (- ~e0 ~e1)))))) ; ;(nec/expression? '(= (- y1 y0) (* a (- x1 x0)))) ;(nec/simplify ; (nec/solve '[a] '(= (- y1 y0) (* a (- x1 x0))))) ;;---------------------------------------------------------------- ;; Affine monomial yd ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= d1 a1))))) ; ;(nec/ex ; ~(nec/differentiate ; '[x1] ; (nec/ex (+ a0 (* a1 x1))))) ; ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= d1 ; ~(nec/differentiate ; '[x1] ; (nec/ex (+ a0 (* a1 x1))))))))) ;;---------------------------------------------------------------- #_(nec/solve 'blue (nec/ex (= pencils (+ green white blue red))) (nec/ex (= (/ pencils 10) green)) (nec/ex (= (/ pencils 2) white)) (nec/ex (= (/ pencils 4) blue)) (nec/ex (= red 45))) ;=> #{{blue 75N}}
69992
;; clj src/scripts/clojure/mudstone/scripts/plots.clj (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns mudstone.scripts.expresso {:doc "solve symbolic systems of equations for interpolating polynomials" :author "<EMAIL>" :version "2018-10-18"} (:require [clojure.pprint :as pp] #_[numeric.expresso.core :as nec])) ;;---------------------------------------------------------------- ;; Affine monomial yy ;(def affine-monomial ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1 (+ a0 (* a1 x1))))))) ; ;#{{a1 (+ (* y1 ; (+ (/ x1) ; (* (** (/ x1) 2) ; -1 ; x0 ; (/ (+ (/ x1) (- x0) -1))))) ; (* y0 ; (/ (+ (/ x1) (- x0) -1)) ; (/ x1))), ; a0 (* (/ (+ (/ x1) (- x0) -1)) ; (+ (* y1 (/ x1) x0) ; (- y0)))}} ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; affine-monomial )) ; ;; a1 ;(+ (* (/ x1) ; (+ y1 ; (* y0 ; (/ (+ (/ x1) (- x0) -1))))) ; (* (/ (** x1 2)) ; -1 x0 ; (/ (+ (/ x1) (- x0) -1)) ; y1)) ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1-y0 (* a1 x1-x0))))))) ; !!! WRONG ANSWER: !!! ;[a1 (* y1-y0 (/ x1-x0))] ;[a0 (+ y0 (* -1 y1-y0 x1-x0 x0))] ; ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1-y0 (* a1 x1-x0))))))) ; ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= (+ y1 (- y0)) (* a1 (- x1 x0)))))))) ; ;(def e0 (nec/ex (- y0 a0 (* a1 x0)))) ;(def e1 (nec/ex (- y1 a0 (* a1 x1)))) ;(def e0 (nec/ex (- y0 (+ a0 (* a1 x0))))) ;(def e1 (nec/ex (- y1 (+ a0 (* a1 x1))))) ;(def e1-e0 (nec/ex (= 0 (- ~e0 ~e1)))) ;(def e1+e0 (nec/ex (= 0 (+ ~e0 ~e1)))) ; ;(try ; (nec/solve ; '[a0 a1] ; e1-e0 ; e1+e0 ; ) ; (catch Throwable t ; (.printStackTrace t) ; (throw t))) ; ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= 0 (+ ~e0 ~e1))) ; (nec/ex (= 0 (- ~e0 ~e1)))))) ; ;(nec/expression? '(= (- y1 y0) (* a (- x1 x0)))) ;(nec/simplify ; (nec/solve '[a] '(= (- y1 y0) (* a (- x1 x0))))) ;;---------------------------------------------------------------- ;; Affine monomial yd ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= d1 a1))))) ; ;(nec/ex ; ~(nec/differentiate ; '[x1] ; (nec/ex (+ a0 (* a1 x1))))) ; ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= d1 ; ~(nec/differentiate ; '[x1] ; (nec/ex (+ a0 (* a1 x1))))))))) ;;---------------------------------------------------------------- #_(nec/solve 'blue (nec/ex (= pencils (+ green white blue red))) (nec/ex (= (/ pencils 10) green)) (nec/ex (= (/ pencils 2) white)) (nec/ex (= (/ pencils 4) blue)) (nec/ex (= red 45))) ;=> #{{blue 75N}}
true
;; clj src/scripts/clojure/mudstone/scripts/plots.clj (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns mudstone.scripts.expresso {:doc "solve symbolic systems of equations for interpolating polynomials" :author "PI:EMAIL:<EMAIL>END_PI" :version "2018-10-18"} (:require [clojure.pprint :as pp] #_[numeric.expresso.core :as nec])) ;;---------------------------------------------------------------- ;; Affine monomial yy ;(def affine-monomial ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1 (+ a0 (* a1 x1))))))) ; ;#{{a1 (+ (* y1 ; (+ (/ x1) ; (* (** (/ x1) 2) ; -1 ; x0 ; (/ (+ (/ x1) (- x0) -1))))) ; (* y0 ; (/ (+ (/ x1) (- x0) -1)) ; (/ x1))), ; a0 (* (/ (+ (/ x1) (- x0) -1)) ; (+ (* y1 (/ x1) x0) ; (- y0)))}} ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; affine-monomial )) ; ;; a1 ;(+ (* (/ x1) ; (+ y1 ; (* y0 ; (/ (+ (/ x1) (- x0) -1))))) ; (* (/ (** x1 2)) ; -1 x0 ; (/ (+ (/ x1) (- x0) -1)) ; y1)) ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1-y0 (* a1 x1-x0))))))) ; !!! WRONG ANSWER: !!! ;[a1 (* y1-y0 (/ x1-x0))] ;[a0 (+ y0 (* -1 y1-y0 x1-x0 x0))] ; ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= y1-y0 (* a1 x1-x0))))))) ; ;(pp/pprint ; (map ; (fn [[v expr]] [v (nec/simplify expr)]) ; (first ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= (+ y1 (- y0)) (* a1 (- x1 x0)))))))) ; ;(def e0 (nec/ex (- y0 a0 (* a1 x0)))) ;(def e1 (nec/ex (- y1 a0 (* a1 x1)))) ;(def e0 (nec/ex (- y0 (+ a0 (* a1 x0))))) ;(def e1 (nec/ex (- y1 (+ a0 (* a1 x1))))) ;(def e1-e0 (nec/ex (= 0 (- ~e0 ~e1)))) ;(def e1+e0 (nec/ex (= 0 (+ ~e0 ~e1)))) ; ;(try ; (nec/solve ; '[a0 a1] ; e1-e0 ; e1+e0 ; ) ; (catch Throwable t ; (.printStackTrace t) ; (throw t))) ; ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= 0 (+ ~e0 ~e1))) ; (nec/ex (= 0 (- ~e0 ~e1)))))) ; ;(nec/expression? '(= (- y1 y0) (* a (- x1 x0)))) ;(nec/simplify ; (nec/solve '[a] '(= (- y1 y0) (* a (- x1 x0))))) ;;---------------------------------------------------------------- ;; Affine monomial yd ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= d1 a1))))) ; ;(nec/ex ; ~(nec/differentiate ; '[x1] ; (nec/ex (+ a0 (* a1 x1))))) ; ;(pp/pprint ; (nec/simplify ; (nec/solve ; '[a0 a1] ; (nec/ex (= y0 (+ a0 (* a1 x0)))) ; (nec/ex (= d1 ; ~(nec/differentiate ; '[x1] ; (nec/ex (+ a0 (* a1 x1))))))))) ;;---------------------------------------------------------------- #_(nec/solve 'blue (nec/ex (= pencils (+ green white blue red))) (nec/ex (= (/ pencils 10) green)) (nec/ex (= (/ pencils 2) white)) (nec/ex (= (/ pencils 4) blue)) (nec/ex (= red 45))) ;=> #{{blue 75N}}
[ { "context": "; Written by Raju\n; Run using following command\n; clojure arithmeti", "end": 17, "score": 0.9998317360877991, "start": 13, "tag": "NAME", "value": "Raju" } ]
Chapter09/arithmeticProgression.clj
PacktPublishing/Learning-Functional-Data-Structures-and-Algorithms
31
; Written by Raju ; Run using following command ; clojure arithmeticProgression.clj ;Arithmetic progression in Clojure (defn arithmeticProgression [ft cd] ( lazy-seq (cons ft (arithmeticProgression (+ ft cd) cd)))) (println (take 10 (arithmeticProgression 2 3)))
56349
; Written by <NAME> ; Run using following command ; clojure arithmeticProgression.clj ;Arithmetic progression in Clojure (defn arithmeticProgression [ft cd] ( lazy-seq (cons ft (arithmeticProgression (+ ft cd) cd)))) (println (take 10 (arithmeticProgression 2 3)))
true
; Written by PI:NAME:<NAME>END_PI ; Run using following command ; clojure arithmeticProgression.clj ;Arithmetic progression in Clojure (defn arithmeticProgression [ft cd] ( lazy-seq (cons ft (arithmeticProgression (+ ft cd) cd)))) (println (take 10 (arithmeticProgression 2 3)))
[ { "context": "hey [this x]\n (str \"Bonjour \" x \"!\")))\n my-spy (protocol/spy Greeter p", "end": 484, "score": 0.9814656376838684, "start": 477, "tag": "NAME", "value": "Bonjour" }, { "context": "]\n\n (is (spy/not-called? hey-spy))\n (is (= \"Bonjour Alex!\" (hey my-spy \"Alex\")))\n (is (spy/called-", "end": 656, "score": 0.9691001772880554, "start": 649, "tag": "NAME", "value": "Bonjour" }, { "context": "(is (spy/not-called? hey-spy))\n (is (= \"Bonjour Alex!\" (hey my-spy \"Alex\")))\n (is (spy/called-once-wi", "end": 661, "score": 0.9527881145477295, "start": 657, "tag": "NAME", "value": "Alex" }, { "context": "hey-spy))\n (is (= \"Bonjour Alex!\" (hey my-spy \"Alex\")))\n (is (spy/called-once-with? hey-spy my-spy", "end": 681, "score": 0.9990678429603577, "start": 677, "tag": "NAME", "value": "Alex" }, { "context": "))\n (is (spy/called-once-with? hey-spy my-spy \"Alex\")))\n\n\n (let [my-spy (protocol/spy Greeter\n ", "end": 737, "score": 0.9983475208282471, "start": 733, "tag": "NAME", "value": "Alex" }, { "context": "this x]\n (str \"Hola \" x \"!\"))))\n hey-spy (:hey (protocol/spies", "end": 922, "score": 0.9151279926300049, "start": 918, "tag": "NAME", "value": "Hola" }, { "context": ")]\n (is (spy/not-called? hey-spy))\n (is (= \"Hola Juan!\" (hey my-spy \"Juan\")))\n (is (spy/called-", "end": 1034, "score": 0.933891773223877, "start": 1030, "tag": "NAME", "value": "Hola" }, { "context": " (is (spy/not-called? hey-spy))\n (is (= \"Hola Juan!\" (hey my-spy \"Juan\")))\n (is (spy/called-once-wi", "end": 1039, "score": 0.9089198112487793, "start": 1035, "tag": "NAME", "value": "Juan" }, { "context": "d? hey-spy))\n (is (= \"Hola Juan!\" (hey my-spy \"Juan\")))\n (is (spy/called-once-with? hey-spy my-spy", "end": 1059, "score": 0.9895480871200562, "start": 1055, "tag": "NAME", "value": "Juan" }, { "context": "))\n (is (spy/called-once-with? hey-spy my-spy \"Juan\")))\n\n (let [kwg (->KeywordGreeter)\n kwg-s", "end": 1115, "score": 0.9878811836242676, "start": 1111, "tag": "NAME", "value": "Juan" } ]
test/clj/spy/protocol_test.clj
zyegfryed/spy
1
(ns spy.protocol-test (:require [clojure.test :refer [deftest is testing]] [spy.core :as spy] [spy.protocol :as protocol] [spy.my-protocol :as my-protocol])) (defprotocol Greeter (hey [this x])) (defrecord KeywordGreeter [] Greeter (hey [this x] (keyword (str "hello-" (name x))))) (deftest spy-fns-test (let [protocol-to-spy-on (reify Greeter (hey [this x] (str "Bonjour " x "!"))) my-spy (protocol/spy Greeter protocol-to-spy-on) hey-spy (:hey (protocol/spies my-spy))] (is (spy/not-called? hey-spy)) (is (= "Bonjour Alex!" (hey my-spy "Alex"))) (is (spy/called-once-with? hey-spy my-spy "Alex"))) (let [my-spy (protocol/spy Greeter (reify Greeter (hey [this x] (str "Hola " x "!")))) hey-spy (:hey (protocol/spies my-spy))] (is (spy/not-called? hey-spy)) (is (= "Hola Juan!" (hey my-spy "Juan"))) (is (spy/called-once-with? hey-spy my-spy "Juan"))) (let [kwg (->KeywordGreeter) kwg-spy (protocol/spy Greeter kwg) hey-spy (:hey (protocol/spies kwg-spy))] (is (= :hello-ajk (hey kwg-spy :ajk))) (is (= [[kwg-spy :ajk]] (spy/calls hey-spy))) (is (= [:hello-ajk] (spy/responses hey-spy))))) (deftest protocol-in-different-ns-test (let [target-instance (reify my-protocol/MyProtocolInADifferentNs (hello-from-different-ns [this] :working!)) spy-instance (protocol/spy my-protocol/MyProtocolInADifferentNs target-instance) f (-> spy-instance protocol/spies :hello-from-different-ns)] (is (spy/not-called? f)) (is (= :working! (my-protocol/hello-from-different-ns spy-instance))) (is (= [[spy-instance]] (spy/calls f))) (is (= [:working!] (spy/responses f))))) (defprotocol OverloadedMethods (hello [this a] [this a b c])) (defprotocol AllSorts (foo [this a] [this a b c]) (bar [this]) (baz [this one two])) (deftest proto-with-overloaded-methods-test (let [target-instance (reify OverloadedMethods (hello [this a] :hello-a) (hello [this a b c] :hello-a-b-c)) spy-instance (protocol/spy OverloadedMethods target-instance) f (-> spy-instance protocol/spies :hello)] (is (spy/not-called? f)) (is (= :hello-a (hello spy-instance :a))) (is (= :hello-a-b-c (hello spy-instance :a :b :c))))) (deftest protocol-methods-test (let [p @(resolve 'spy.protocol-test/Greeter) methods (protocol/protocol-methods p)] (is (= {:hey {:name 'hey :arglists [['this 'x]] :var #'spy.protocol-test/hey}} methods))) (let [p @(resolve 'spy.protocol-test/OverloadedMethods) methods (protocol/protocol-methods p)] (is (= {:hello {:name 'hello :arglists [['this 'a] ['this 'a 'b 'c]] :var #'spy.protocol-test/hello}} methods))) (let [p @(resolve 'spy.protocol-test/AllSorts) methods (protocol/protocol-methods p)] (is (= {:foo {:name 'foo :arglists [['this 'a] ['this 'a 'b 'c]] :var #'spy.protocol-test/foo} :bar {:name 'bar :arglists [['this]] :var #'spy.protocol-test/bar} :baz {:name 'baz :arglists [['this 'one 'two]] :var #'spy.protocol-test/baz}} methods))))
34466
(ns spy.protocol-test (:require [clojure.test :refer [deftest is testing]] [spy.core :as spy] [spy.protocol :as protocol] [spy.my-protocol :as my-protocol])) (defprotocol Greeter (hey [this x])) (defrecord KeywordGreeter [] Greeter (hey [this x] (keyword (str "hello-" (name x))))) (deftest spy-fns-test (let [protocol-to-spy-on (reify Greeter (hey [this x] (str "<NAME> " x "!"))) my-spy (protocol/spy Greeter protocol-to-spy-on) hey-spy (:hey (protocol/spies my-spy))] (is (spy/not-called? hey-spy)) (is (= "<NAME> <NAME>!" (hey my-spy "<NAME>"))) (is (spy/called-once-with? hey-spy my-spy "<NAME>"))) (let [my-spy (protocol/spy Greeter (reify Greeter (hey [this x] (str "<NAME> " x "!")))) hey-spy (:hey (protocol/spies my-spy))] (is (spy/not-called? hey-spy)) (is (= "<NAME> <NAME>!" (hey my-spy "<NAME>"))) (is (spy/called-once-with? hey-spy my-spy "<NAME>"))) (let [kwg (->KeywordGreeter) kwg-spy (protocol/spy Greeter kwg) hey-spy (:hey (protocol/spies kwg-spy))] (is (= :hello-ajk (hey kwg-spy :ajk))) (is (= [[kwg-spy :ajk]] (spy/calls hey-spy))) (is (= [:hello-ajk] (spy/responses hey-spy))))) (deftest protocol-in-different-ns-test (let [target-instance (reify my-protocol/MyProtocolInADifferentNs (hello-from-different-ns [this] :working!)) spy-instance (protocol/spy my-protocol/MyProtocolInADifferentNs target-instance) f (-> spy-instance protocol/spies :hello-from-different-ns)] (is (spy/not-called? f)) (is (= :working! (my-protocol/hello-from-different-ns spy-instance))) (is (= [[spy-instance]] (spy/calls f))) (is (= [:working!] (spy/responses f))))) (defprotocol OverloadedMethods (hello [this a] [this a b c])) (defprotocol AllSorts (foo [this a] [this a b c]) (bar [this]) (baz [this one two])) (deftest proto-with-overloaded-methods-test (let [target-instance (reify OverloadedMethods (hello [this a] :hello-a) (hello [this a b c] :hello-a-b-c)) spy-instance (protocol/spy OverloadedMethods target-instance) f (-> spy-instance protocol/spies :hello)] (is (spy/not-called? f)) (is (= :hello-a (hello spy-instance :a))) (is (= :hello-a-b-c (hello spy-instance :a :b :c))))) (deftest protocol-methods-test (let [p @(resolve 'spy.protocol-test/Greeter) methods (protocol/protocol-methods p)] (is (= {:hey {:name 'hey :arglists [['this 'x]] :var #'spy.protocol-test/hey}} methods))) (let [p @(resolve 'spy.protocol-test/OverloadedMethods) methods (protocol/protocol-methods p)] (is (= {:hello {:name 'hello :arglists [['this 'a] ['this 'a 'b 'c]] :var #'spy.protocol-test/hello}} methods))) (let [p @(resolve 'spy.protocol-test/AllSorts) methods (protocol/protocol-methods p)] (is (= {:foo {:name 'foo :arglists [['this 'a] ['this 'a 'b 'c]] :var #'spy.protocol-test/foo} :bar {:name 'bar :arglists [['this]] :var #'spy.protocol-test/bar} :baz {:name 'baz :arglists [['this 'one 'two]] :var #'spy.protocol-test/baz}} methods))))
true
(ns spy.protocol-test (:require [clojure.test :refer [deftest is testing]] [spy.core :as spy] [spy.protocol :as protocol] [spy.my-protocol :as my-protocol])) (defprotocol Greeter (hey [this x])) (defrecord KeywordGreeter [] Greeter (hey [this x] (keyword (str "hello-" (name x))))) (deftest spy-fns-test (let [protocol-to-spy-on (reify Greeter (hey [this x] (str "PI:NAME:<NAME>END_PI " x "!"))) my-spy (protocol/spy Greeter protocol-to-spy-on) hey-spy (:hey (protocol/spies my-spy))] (is (spy/not-called? hey-spy)) (is (= "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI!" (hey my-spy "PI:NAME:<NAME>END_PI"))) (is (spy/called-once-with? hey-spy my-spy "PI:NAME:<NAME>END_PI"))) (let [my-spy (protocol/spy Greeter (reify Greeter (hey [this x] (str "PI:NAME:<NAME>END_PI " x "!")))) hey-spy (:hey (protocol/spies my-spy))] (is (spy/not-called? hey-spy)) (is (= "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI!" (hey my-spy "PI:NAME:<NAME>END_PI"))) (is (spy/called-once-with? hey-spy my-spy "PI:NAME:<NAME>END_PI"))) (let [kwg (->KeywordGreeter) kwg-spy (protocol/spy Greeter kwg) hey-spy (:hey (protocol/spies kwg-spy))] (is (= :hello-ajk (hey kwg-spy :ajk))) (is (= [[kwg-spy :ajk]] (spy/calls hey-spy))) (is (= [:hello-ajk] (spy/responses hey-spy))))) (deftest protocol-in-different-ns-test (let [target-instance (reify my-protocol/MyProtocolInADifferentNs (hello-from-different-ns [this] :working!)) spy-instance (protocol/spy my-protocol/MyProtocolInADifferentNs target-instance) f (-> spy-instance protocol/spies :hello-from-different-ns)] (is (spy/not-called? f)) (is (= :working! (my-protocol/hello-from-different-ns spy-instance))) (is (= [[spy-instance]] (spy/calls f))) (is (= [:working!] (spy/responses f))))) (defprotocol OverloadedMethods (hello [this a] [this a b c])) (defprotocol AllSorts (foo [this a] [this a b c]) (bar [this]) (baz [this one two])) (deftest proto-with-overloaded-methods-test (let [target-instance (reify OverloadedMethods (hello [this a] :hello-a) (hello [this a b c] :hello-a-b-c)) spy-instance (protocol/spy OverloadedMethods target-instance) f (-> spy-instance protocol/spies :hello)] (is (spy/not-called? f)) (is (= :hello-a (hello spy-instance :a))) (is (= :hello-a-b-c (hello spy-instance :a :b :c))))) (deftest protocol-methods-test (let [p @(resolve 'spy.protocol-test/Greeter) methods (protocol/protocol-methods p)] (is (= {:hey {:name 'hey :arglists [['this 'x]] :var #'spy.protocol-test/hey}} methods))) (let [p @(resolve 'spy.protocol-test/OverloadedMethods) methods (protocol/protocol-methods p)] (is (= {:hello {:name 'hello :arglists [['this 'a] ['this 'a 'b 'c]] :var #'spy.protocol-test/hello}} methods))) (let [p @(resolve 'spy.protocol-test/AllSorts) methods (protocol/protocol-methods p)] (is (= {:foo {:name 'foo :arglists [['this 'a] ['this 'a 'b 'c]] :var #'spy.protocol-test/foo} :bar {:name 'bar :arglists [['this]] :var #'spy.protocol-test/bar} :baz {:name 'baz :arglists [['this 'one 'two]] :var #'spy.protocol-test/baz}} methods))))
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2", "end": 107, "score": 0.9965744614601135, "start": 98, "tag": "NAME", "value": "Xebia B.V" } ]
src/integration/clojure/com/xebia/visualreview/itest_util.clj
andstepanuk/VisualReview
290
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 Xebia B.V. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.itest-util (:require [com.xebia.visualreview.starter :as starter])) (def test-server-port 7001) (defn start-server [] (starter/start-server test-server-port)) (defn stop-server [] (starter/stop-server))
107676
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 <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 com.xebia.visualreview.itest-util (:require [com.xebia.visualreview.starter :as starter])) (def test-server-port 7001) (defn start-server [] (starter/start-server test-server-port)) (defn stop-server [] (starter/stop-server))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 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 com.xebia.visualreview.itest-util (:require [com.xebia.visualreview.starter :as starter])) (def test-server-port 7001) (defn start-server [] (starter/start-server test-server-port)) (defn stop-server [] (starter/stop-server))
[ { "context": "t.com/#narrow/stream/194466-crux\")\n(def url-mail \"crux@juxt.pro\")\n(def url-examples-gist \"https://gist.githubuser", "end": 222, "score": 0.9999228715896606, "start": 209, "tag": "EMAIL", "value": "crux@juxt.pro" }, { "context": "examples-gist \"https://gist.githubusercontent.com/spacegangster/b68f72e3c81524a71af1f3033ea7507e/raw/572396dec079", "end": 297, "score": 0.9994723200798035, "start": 284, "tag": "USERNAME", "value": "spacegangster" } ]
crux-console/src/crux_ui/config.cljs
iojtaylor/crux
13
(ns crux-ui.config (:require ["./ua-regexp.js" :as ua-rgx])) (def url-docs "https://juxt.pro/crux/docs/index.html") (def url-chat "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux") (def url-mail "crux@juxt.pro") (def url-examples-gist "https://gist.githubusercontent.com/spacegangster/b68f72e3c81524a71af1f3033ea7507e/raw/572396dec0791500c965fea443b2f26a60f500d4/examples.edn") (def ^:const ua-regex ua-rgx) (def ^:const user-agent js/navigator.userAgent) (def ^:const ua-info (re-find ua-regex user-agent)) (def ^:const browser-vendor-string (second ua-info)) (def ^:const browser-version-string (nth ua-info 2)) (def ^:const browser-vendor (case browser-vendor-string "Chrome" :browser/chrome "Firefox" :browser/firefox "Opera" :browser/opera "Safari" :browser/safari "Edge" :browser/edge :browser/unknown)) (def ^:const supports-input-datetime? (not (#{:browser/firefox :browser/ie :browser/safari :browser/unknown} browser-vendor)))
16765
(ns crux-ui.config (:require ["./ua-regexp.js" :as ua-rgx])) (def url-docs "https://juxt.pro/crux/docs/index.html") (def url-chat "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux") (def url-mail "<EMAIL>") (def url-examples-gist "https://gist.githubusercontent.com/spacegangster/b68f72e3c81524a71af1f3033ea7507e/raw/572396dec0791500c965fea443b2f26a60f500d4/examples.edn") (def ^:const ua-regex ua-rgx) (def ^:const user-agent js/navigator.userAgent) (def ^:const ua-info (re-find ua-regex user-agent)) (def ^:const browser-vendor-string (second ua-info)) (def ^:const browser-version-string (nth ua-info 2)) (def ^:const browser-vendor (case browser-vendor-string "Chrome" :browser/chrome "Firefox" :browser/firefox "Opera" :browser/opera "Safari" :browser/safari "Edge" :browser/edge :browser/unknown)) (def ^:const supports-input-datetime? (not (#{:browser/firefox :browser/ie :browser/safari :browser/unknown} browser-vendor)))
true
(ns crux-ui.config (:require ["./ua-regexp.js" :as ua-rgx])) (def url-docs "https://juxt.pro/crux/docs/index.html") (def url-chat "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux") (def url-mail "PI:EMAIL:<EMAIL>END_PI") (def url-examples-gist "https://gist.githubusercontent.com/spacegangster/b68f72e3c81524a71af1f3033ea7507e/raw/572396dec0791500c965fea443b2f26a60f500d4/examples.edn") (def ^:const ua-regex ua-rgx) (def ^:const user-agent js/navigator.userAgent) (def ^:const ua-info (re-find ua-regex user-agent)) (def ^:const browser-vendor-string (second ua-info)) (def ^:const browser-version-string (nth ua-info 2)) (def ^:const browser-vendor (case browser-vendor-string "Chrome" :browser/chrome "Firefox" :browser/firefox "Opera" :browser/opera "Safari" :browser/safari "Edge" :browser/edge :browser/unknown)) (def ^:const supports-input-datetime? (not (#{:browser/firefox :browser/ie :browser/safari :browser/unknown} browser-vendor)))
[ { "context": "\"name\" \"\")\n (aset $scope \"name_input\" {:label \"姓名\" :max-length 6})\n ))\n\t\n\n(ng/value \"hello\" \"hipho", "end": 1637, "score": 0.8521796464920044, "start": 1635, "tag": "NAME", "value": "姓名" } ]
hello_world/src/hello_world/core.cljs
hackerzhuli/clojure-front
0
(ns hello-world.core (:require-macros [hello-world.macros :as ng])) (enable-console-print!) (println "Hello world!") (println (.guid js/jshelper)) ;英文字符算1个字节 ;其他字符算3个字节 ;因为其他字符,一般情况是中文,在utf-8(数据库的存储格式)中,是3个字节 (defn str-byte-length [s] (reduce + (map #(if (> (.charCodeAt s %) 0xff) 3 1) (range (.-length s))))) (println "byte-length" (str-byte-length "english 中文结合")) ;return an error string if something is wrong ;return nil if no error (defn check-length [s min-length max-length] (let [len (str-byte-length s)] (if (and (not (nil? min-length)) (< len min-length)) "太短了" (if (and (not (nil? max-length)) (> len max-length)) "太长了" nil)))) (println (check-length "hhjkhjkh" 2 10)) (ng/module "magic" []) (ng/directive "magic" "magicTextInput" { :scope {:data "=" :model "="} :template "<div> <span class=\"field-label\"> {{label()}} </span> <input type=\"text\" ng-model=\"model\"> <br> <span class=\"field-error\"> {{error()}} </span> </div>" :controller (fn [$scope] (let [data (aget $scope "data")] (aset $scope "label" (fn [] (get data :label))) (aset $scope "hehe" (fn[] "hehe")) (aset $scope "error" (fn [] (let [s (aget $scope "model") checks (list #(check-length % (get data :min-length) (get data :max-length)))] (first (filter #(not (nil? %)) (map #(% s) checks))) ))) ))}) (ng/module "hello" ["magic"]) (ng/controller "hello" "MainController" (fn [$scope] (aset $scope "text" "This is soooo simplllle.") (aset $scope "name" "") (aset $scope "name_input" {:label "姓名" :max-length 6}) )) (ng/value "hello" "hiphop" {:a 10}) (ng/directive "hello" "rock" { :scope {:name "="} :template "<div>{{name}} rocks.</div>" :controller (fn [$scope, hiphop] (println (clj->js (list 1 2 3) )) (println (map #(* % 2) (array 1 2 3 4))) (println (aget hiphop "a"))) })
65902
(ns hello-world.core (:require-macros [hello-world.macros :as ng])) (enable-console-print!) (println "Hello world!") (println (.guid js/jshelper)) ;英文字符算1个字节 ;其他字符算3个字节 ;因为其他字符,一般情况是中文,在utf-8(数据库的存储格式)中,是3个字节 (defn str-byte-length [s] (reduce + (map #(if (> (.charCodeAt s %) 0xff) 3 1) (range (.-length s))))) (println "byte-length" (str-byte-length "english 中文结合")) ;return an error string if something is wrong ;return nil if no error (defn check-length [s min-length max-length] (let [len (str-byte-length s)] (if (and (not (nil? min-length)) (< len min-length)) "太短了" (if (and (not (nil? max-length)) (> len max-length)) "太长了" nil)))) (println (check-length "hhjkhjkh" 2 10)) (ng/module "magic" []) (ng/directive "magic" "magicTextInput" { :scope {:data "=" :model "="} :template "<div> <span class=\"field-label\"> {{label()}} </span> <input type=\"text\" ng-model=\"model\"> <br> <span class=\"field-error\"> {{error()}} </span> </div>" :controller (fn [$scope] (let [data (aget $scope "data")] (aset $scope "label" (fn [] (get data :label))) (aset $scope "hehe" (fn[] "hehe")) (aset $scope "error" (fn [] (let [s (aget $scope "model") checks (list #(check-length % (get data :min-length) (get data :max-length)))] (first (filter #(not (nil? %)) (map #(% s) checks))) ))) ))}) (ng/module "hello" ["magic"]) (ng/controller "hello" "MainController" (fn [$scope] (aset $scope "text" "This is soooo simplllle.") (aset $scope "name" "") (aset $scope "name_input" {:label "<NAME>" :max-length 6}) )) (ng/value "hello" "hiphop" {:a 10}) (ng/directive "hello" "rock" { :scope {:name "="} :template "<div>{{name}} rocks.</div>" :controller (fn [$scope, hiphop] (println (clj->js (list 1 2 3) )) (println (map #(* % 2) (array 1 2 3 4))) (println (aget hiphop "a"))) })
true
(ns hello-world.core (:require-macros [hello-world.macros :as ng])) (enable-console-print!) (println "Hello world!") (println (.guid js/jshelper)) ;英文字符算1个字节 ;其他字符算3个字节 ;因为其他字符,一般情况是中文,在utf-8(数据库的存储格式)中,是3个字节 (defn str-byte-length [s] (reduce + (map #(if (> (.charCodeAt s %) 0xff) 3 1) (range (.-length s))))) (println "byte-length" (str-byte-length "english 中文结合")) ;return an error string if something is wrong ;return nil if no error (defn check-length [s min-length max-length] (let [len (str-byte-length s)] (if (and (not (nil? min-length)) (< len min-length)) "太短了" (if (and (not (nil? max-length)) (> len max-length)) "太长了" nil)))) (println (check-length "hhjkhjkh" 2 10)) (ng/module "magic" []) (ng/directive "magic" "magicTextInput" { :scope {:data "=" :model "="} :template "<div> <span class=\"field-label\"> {{label()}} </span> <input type=\"text\" ng-model=\"model\"> <br> <span class=\"field-error\"> {{error()}} </span> </div>" :controller (fn [$scope] (let [data (aget $scope "data")] (aset $scope "label" (fn [] (get data :label))) (aset $scope "hehe" (fn[] "hehe")) (aset $scope "error" (fn [] (let [s (aget $scope "model") checks (list #(check-length % (get data :min-length) (get data :max-length)))] (first (filter #(not (nil? %)) (map #(% s) checks))) ))) ))}) (ng/module "hello" ["magic"]) (ng/controller "hello" "MainController" (fn [$scope] (aset $scope "text" "This is soooo simplllle.") (aset $scope "name" "") (aset $scope "name_input" {:label "PI:NAME:<NAME>END_PI" :max-length 6}) )) (ng/value "hello" "hiphop" {:a 10}) (ng/directive "hello" "rock" { :scope {:name "="} :template "<div>{{name}} rocks.</div>" :controller (fn [$scope, hiphop] (println (clj->js (list 1 2 3) )) (println (map #(* % 2) (array 1 2 3 4))) (println (aget hiphop "a"))) })
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2017-11-10\"\n :date \"2017-11-", "end": 113, "score": 0.7687832713127136, "start": 87, "tag": "EMAIL", "value": "wahpenayo at gmail dot com" } ]
src/scripts/clojure/taiga/scripts/quantiles/measure.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :since "2017-11-10" :date "2017-11-15" :doc "Train a probability measure regression forest, given a mean regression forest."} taiga.scripts.quantiles.measure (:require [zana.api :as z] [taiga.scripts.quantiles.defs :as defs])) ;;---------------------------------------------------------------- (z/seconds (str *ns*) (defs/real-probability-measure defs/n)) ;;----------------------------------------------------------------
30975
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL>" :since "2017-11-10" :date "2017-11-15" :doc "Train a probability measure regression forest, given a mean regression forest."} taiga.scripts.quantiles.measure (:require [zana.api :as z] [taiga.scripts.quantiles.defs :as defs])) ;;---------------------------------------------------------------- (z/seconds (str *ns*) (defs/real-probability-measure defs/n)) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI" :since "2017-11-10" :date "2017-11-15" :doc "Train a probability measure regression forest, given a mean regression forest."} taiga.scripts.quantiles.measure (:require [zana.api :as z] [taiga.scripts.quantiles.defs :as defs])) ;;---------------------------------------------------------------- (z/seconds (str *ns*) (defs/real-probability-measure defs/n)) ;;----------------------------------------------------------------
[ { "context": " MBQL filter clauses. Neat!\"\n (is (= [\"Festa\" \"Fred 62\"]\n (chain-filter venues.name {venues.pr", "end": 2445, "score": 0.9093740582466125, "start": 2438, "tag": "NAME", "value": "Fred 62" }, { "context": " \"Edwards Air Force Base\"\n \"John Wayne Airport-Orange County Airport\"]\n (t", "end": 11303, "score": 0.7541229724884033, "start": 11293, "tag": "NAME", "value": "John Wayne" }, { "context": "in 'sushi' that are expensive\"\n (is (= [[77 \"Sushi Nakazawa\"]\n [79 \"Sushi Yasuda\"]\n ", "end": 18306, "score": 0.959477961063385, "start": 18292, "tag": "NAME", "value": "Sushi Nakazawa" }, { "context": " (is (= [[77 \"Sushi Nakazawa\"]\n [79 \"Sushi Yasuda\"]\n [81 \"Tanoshi Sushi & Sake Bar\"]]\n", "end": 18340, "score": 0.8501991629600525, "start": 18328, "tag": "NAME", "value": "Sushi Yasuda" }, { "context": " [79 \"Sushi Yasuda\"]\n [81 \"Tanoshi Sushi & Sake Bar\"]]\n (mt/$ids (chain-filter", "end": 18375, "score": 0.8754794001579285, "start": 18362, "tag": "NAME", "value": "Tanoshi Sushi" }, { "context": "ushi Yasuda\"]\n [81 \"Tanoshi Sushi & Sake Bar\"]]\n (mt/$ids (chain-filter/chain-filt", "end": 18386, "score": 0.7117305994033813, "start": 18379, "tag": "NAME", "value": "ake Bar" } ]
c#-metabase/test/metabase/models/params/chain_filter_test.clj
hanakhry/Crime_Admin
0
(ns metabase.models.params.chain-filter-test (:require [clojure.test :refer :all] [metabase.models :refer [FieldValues]] [metabase.models.params.chain-filter :as chain-filter] [metabase.test :as mt] [toucan.db :as db])) (defmacro chain-filter [field field->value & options] `(chain-filter/chain-filter (mt/$ids nil ~(symbol (str \% (name field)))) (mt/$ids nil ~(into {} (for [[k v] field->value] [(symbol (str \% k)) v]))) ~@options)) (deftest chain-filter-test (testing "Show me expensive restaurants" (is (= ["Dal Rae Restaurant" "Lawry's The Prime Rib" "Pacific Dining Car - Santa Monica" "Sushi Nakazawa" "Sushi Yasuda" "Tanoshi Sushi & Sake Bar"] (chain-filter venues.name {venues.price 4})))) (testing "Show me categories that have expensive restaurants" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price 4}))) (testing "Should work with string versions of param values" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price "4"}))))) (testing "Show me categories starting with s (case-insensitive) that have expensive restaurants" (is (= ["Steakhouse"] (chain-filter categories.name {venues.price 4, categories.name [:starts-with "s" {:case-sensitive false}]})))) (testing "Show me cheap Thai restaurants" (is (= ["Kinaree Thai Bistro" "Krua Siri"] (chain-filter venues.name {venues.price 1, categories.name "Thai"})))) (testing "Show me the categories that have cheap restaurants" (is (= ["Asian" "BBQ" "Bakery" "Bar" "Burger" "Caribbean" "Deli" "Karaoke" "Mexican" "Pizza" "Southern" "Thai"] (chain-filter categories.name {venues.price 1})))) (testing "Show me cheap restaurants with the word 'taco' in their name (case-insensitive)" (is (= ["Tacos Villa Corona" "Tito's Tacos"] (chain-filter venues.name {venues.price 1, venues.name [:contains "tAcO" {:case-sensitive false}]})))) (testing "Show me the first 3 expensive restaurants" (is (= ["Dal Rae Restaurant" "Lawry's The Prime Rib" "Pacific Dining Car - Santa Monica"] (chain-filter venues.name {venues.price 4} :limit 3)))) (testing "Oh yeah, we actually support arbitrary MBQL filter clauses. Neat!" (is (= ["Festa" "Fred 62"] (chain-filter venues.name {venues.price [:between 2 3] venues.name [:starts-with "f" {:case-sensitive false}]}))))) (deftest multiple-values-test (testing "Chain filtering should support multiple values for a single parameter (as a vector or set of values)" (testing "Show me restaurants with price = 1 or 2 with the word 'BBQ' in their name (case-sensitive)" (is (= ["Baby Blues BBQ" "Beachwood BBQ & Brewing" "Bludso's BBQ"] (chain-filter venues.name {venues.price #{1 2}, venues.name [:contains "BBQ"]})))) (testing "Show me the possible values of price for Bakery *or* BBQ restaurants" (is (= [1 2 3] (chain-filter venues.price {categories.name ["Bakery" "BBQ"]})))))) (deftest auto-parse-string-params-test (testing "Parameters that come in as strings (i.e., all of them that come in via the API) should work as intended" (is (= ["Baby Blues BBQ" "Beachwood BBQ & Brewing" "Bludso's BBQ"] (chain-filter venues.name {venues.price ["1" "2"], venues.name [:contains "BBQ"]}))))) (deftest unrelated-params-test (testing "Parameters that are completely unrelated (don't apply to this Table) should just get ignored entirely" ;; there is no way to join from venues -> users so users.id should get ignored (binding [chain-filter/*enable-reverse-joins* false] (is (= [1 2 3] (chain-filter venues.price {categories.name ["Bakery" "BBQ"] users.id [1 2 3]})))))) (def megagraph "A large graph that is hugely interconnected. All nodes can get to 50 and 50 has an edge to :end. But the fastest route is [[:start 50] [50 :end]] and we should quickly identify this last route. Basically handy to demonstrate that we are doing breadth first search rather than depth first search. Depth first would identify 1 -> 2 -> 3 ... 49 -> 50 -> end" (let [big 50] (merge-with merge (reduce (fn [m [x y]] (assoc-in m [x y] [[x y]])) {} (for [x (range (inc big)) y (range (inc big)) :when (not= x y)] [x y])) {:start (reduce (fn [m x] (assoc m x [[:start x]])) {} (range (inc big)))} {big {:end [[big :end]]}}))) (def megagraph-single-path "Similar to the megagraph above, this graph only has a single path through a hugely interconnected graph. A naive graph traversal will run out of memory or take quite a long time to find the traversal: [[:start 90] [90 200] [200 :end]] There is only one path to end (from 200) and only one path to 200 from 90. If you take out the seen nodes this path will not be found as the traversal advances through all of the 50 paths from start, all of the 50 paths from 1, all of the 50 paths from 2, ..." (merge-with merge ;; every node is linked to every other node (1 ... 199) (reduce (fn [m [x y]] (assoc-in m [x y] [[x y]])) {} (for [x (range 200) y (range 200) :when (not= x y)] [x y])) {:start (reduce (fn [m x] (assoc m x [[:start x]])) {} (range 200))} ;; only 90 reaches 200 and only 200 (big) reaches the end {90 {200 [[90 200]]} 200 {:end [[200 :end]]}})) (deftest traverse-graph-test (testing "If no need to join, returns immediately" (is (nil? (#'chain-filter/traverse-graph {} :start :start 5)))) (testing "Finds a simple hop" (let [graph {:start {:end [:start->end]}}] (is (= [:start->end] (#'chain-filter/traverse-graph graph :start :end 5)))) (testing "Finds over a few hops" (let [graph {:start {:a [:start->a]} :a {:b [:a->b]} :b {:c [:b->c]} :c {:end [:c->end]}}] (is (= [:start->a :a->b :b->c :c->end] (#'chain-filter/traverse-graph graph :start :end 5))) (testing "But will not exceed the max depth" (is (nil? (#'chain-filter/traverse-graph graph :start :end 2)))))) (testing "Can find a path in a dense and large graph" (is (= [[:start 50] [50 :end]] (#'chain-filter/traverse-graph megagraph :start :end 5))) (is (= [[:start 90] [90 200] [200 :end]] (#'chain-filter/traverse-graph megagraph-single-path :start :end 5)))) (testing "Returns nil if there is no path" (let [graph {:start {1 [[:start 1]]} 1 {2 [[1 2]]} ;; no way to get to 3 3 {4 [[3 4]]} 4 {:end [[4 :end]]}}] (is (nil? (#'chain-filter/traverse-graph graph :start :end 5))))) (testing "Not fooled by loops" (let [graph {:start {:a [:start->a]} :a {:b [:a->b] :a [:b->a]} :b {:c [:b->c] :a [:c->a] :b [:c->b]} :c {:end [:c->end]}}] (is (= [:start->a :a->b :b->c :c->end] (#'chain-filter/traverse-graph graph :start :end 5))) (testing "But will not exceed the max depth" (is (nil? (#'chain-filter/traverse-graph graph :start :end 2)))))))) (deftest find-joins-test (mt/dataset airports (mt/$ids nil (testing "airport -> municipality" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}}] (#'chain-filter/find-joins (mt/id) $$airport $$municipality)))) (testing "airport [-> municipality -> region] -> country" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}} {:lhs {:table $$municipality, :field %municipality.region-id} :rhs {:table $$region, :field %region.id}} {:lhs {:table $$region, :field %region.country-id} :rhs {:table $$country, :field %country.id}}] (#'chain-filter/find-joins (mt/id) $$airport $$country)))) (testing "[backwards]" (testing "municipality -> airport" (is (= [{:lhs {:table $$municipality, :field %municipality.id} :rhs {:table $$airport, :field %airport.municipality-id}}] (#'chain-filter/find-joins (mt/id) $$municipality $$airport)))) (testing "country [-> region -> municipality] -> airport" (is (= [{:lhs {:table $$country, :field %country.id} :rhs {:table $$region, :field %region.country-id}} {:lhs {:table $$region, :field %region.id} :rhs {:table $$municipality, :field %municipality.region-id}} {:lhs {:table $$municipality, :field %municipality.id} :rhs {:table $$airport, :field %airport.municipality-id}}] (#'chain-filter/find-joins (mt/id) $$country $$airport)))))))) (deftest find-all-joins-test (testing "With reverse joins disabled" (binding [chain-filter/*enable-reverse-joins* false] (mt/$ids nil (is (= [{:lhs {:table $$venues, :field %venues.category_id}, :rhs {:table $$categories, :field %categories.id}}] (#'chain-filter/find-all-joins $$venues #{%categories.name %users.id})))))) (mt/dataset airports (mt/$ids nil (testing "airport [-> municipality] -> region" (testing "even though we're joining against the same Table multiple times, duplicate joins should be removed" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}} {:lhs {:table $$municipality, :field %municipality.region-id} :rhs {:table $$region, :field %region.id}}] (#'chain-filter/find-all-joins $$airport #{%region.name %municipality.name %region.id})))))))) (deftest multi-hop-test (mt/dataset airports (testing "Should be able to filter against other tables with that require multiple joins\n" (testing "single direct join: Airport -> Municipality" (is (= ["San Francisco International Airport"] (chain-filter airport.name {municipality.name ["San Francisco"]})))) (testing "2 joins required: Airport -> Municipality -> Region" (is (= ["Beale Air Force Base" "Edwards Air Force Base" "John Wayne Airport-Orange County Airport"] (take 3 (chain-filter airport.name {region.name ["California"]}))))) (testing "3 joins required: Airport -> Municipality -> Region -> Country" (is (= ["Abraham Lincoln Capital Airport" "Albuquerque International Sunport" "Altus Air Force Base"] (take 3 (chain-filter airport.name {country.name ["United States"]}))))) (testing "4 joins required: Airport -> Municipality -> Region -> Country -> Continent" (is (= ["Afonso Pena Airport" "Alejandro Velasco Astete International Airport" "Carrasco International /General C L Berisso Airport"] (take 3 (chain-filter airport.name {continent.name ["South America"]}))))) (testing "[backwards]" (testing "single direct join: Municipality -> Airport" (is (= ["San Francisco"] (chain-filter municipality.name {airport.name ["San Francisco International Airport"]})))) (testing "2 joins required: Region -> Municipality -> Airport" (is (= ["California"] (chain-filter region.name {airport.name ["San Francisco International Airport"]})))) (testing "3 joins required: Country -> Region -> Municipality -> Airport" (is (= ["United States"] (chain-filter country.name {airport.name ["San Francisco International Airport"]})))) (testing "4 joins required: Continent -> Region -> Municipality -> Airport" (is (= ["North America"] (chain-filter continent.name {airport.name ["San Francisco International Airport"]})))))))) (deftest filterable-field-ids-test (mt/$ids (testing (format "venues.price = %d categories.name = %d users.id = %d\n" %venues.price %categories.name %users.id) (is (= #{%categories.name %users.id} (chain-filter/filterable-field-ids %venues.price #{%categories.name %users.id}))) (testing "reverse joins disabled: should exclude users.id" (binding [chain-filter/*enable-reverse-joins* false] (is (= #{%categories.name} (chain-filter/filterable-field-ids %venues.price #{%categories.name %users.id}))))) (testing "return nil if filtering-field-ids is empty" (is (= nil (chain-filter/filterable-field-ids %venues.price #{}))))))) (deftest chain-filter-search-test (testing "Show me categories containing 'eak' (case-insensitive) that have expensive restaurants" (is (= ["Steakhouse"] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "eak"))))) (testing "Show me cheap restaurants including with 'taco' (case-insensitive)" (is (= ["Tacos Villa Corona" "Tito's Tacos"] (mt/$ids (chain-filter/chain-filter-search %venues.name {%venues.price 1} "tAcO"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "zzzzz"))))) (testing "Field that doesn't exist should throw a 404" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Field [\d,]+ does not exist" (chain-filter/chain-filter-search Integer/MAX_VALUE nil "s")))) (testing "Field that isn't type/Text should throw a 400" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot search against non-Text Field" (chain-filter/chain-filter-search (mt/$ids %venues.price) nil "s"))))) ;;; --------------------------------------------------- Remapping ---------------------------------------------------- (defn do-with-human-readable-values-remapping [thunk] (mt/with-column-remappings [venues.category_id (values-of categories.name)] (thunk))) (defmacro with-human-readable-values-remapping {:style/indent 0} [& body] `(do-with-human-readable-values-remapping (fn [] ~@body))) (deftest human-readable-values-remapped-chain-filter-test (with-human-readable-values-remapping (testing "Show me category IDs for categories" ;; there are no restaurants with category 1 (is (= [[2 "American"] [3 "Artisan"] [4 "Asian"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.category_id nil)))))) (testing "Show me category IDs for categories that have expensive restaurants" (is (= [[40 "Japanese"] [67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.price 4}))))) (testing "Show me the category 40 (constraints do not support remapping)" (is (= [[40 "Japanese"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.category_id 40}))))))) (deftest human-readable-values-remapped-chain-filter-search-test (with-human-readable-values-remapping (testing "Show me category IDs [whose name] contains 'bar'" (doseq [constraints [nil {}]] (testing (format "\nconstraints = %s" (pr-str constraints)) (is (= [[7 "Bar"] [74 "Wine Bar"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id constraints "bar"))))))) (testing "Show me category IDs [whose name] contains 'house' that have expensive restaurants" (is (= [[67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "house"))))) (testing "search for something crazy: should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "zzzzz"))))))) (deftest field-to-field-remapped-field-id-test (is (= (mt/id :venues :name) (#'chain-filter/remapped-field-id (mt/id :venues :id))))) (deftest field-to-field-remapped-chain-filter-test (testing "Field-to-field remapping: venues.category_id -> categories.name\n" (testing "Show me venue IDs (names)" (is (= [[29 "20th Century Cafe"] [ 8 "25°" ] [93 "33 Taps" ]] (take 3 (chain-filter/chain-filter (mt/id :venues :id) nil))))) (testing "Show me expensive venue IDs (names)" (is (= [[55 "Dal Rae Restaurant"] [61 "Lawry's The Prime Rib"] [16 "Pacific Dining Car - Santa Monica"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.id {%venues.price 4})))))))) (deftest field-to-field-remapped-chain-filter-search-test (testing "Field-to-field remapping: venues.category_id -> categories.name\n" (testing "Show me venue IDs that [have a remapped name that] contains 'sushi'" (is (= [[76 "Beyond Sushi"] [80 "Blue Ribbon Sushi"] [77 "Sushi Nakazawa"]] (take 3 (chain-filter/chain-filter-search (mt/id :venues :id) nil "sushi"))))) (testing "Show me venue IDs that [have a remapped name that] contain 'sushi' that are expensive" (is (= [[77 "Sushi Nakazawa"] [79 "Sushi Yasuda"] [81 "Tanoshi Sushi & Sake Bar"]] (mt/$ids (chain-filter/chain-filter-search %venues.id {%venues.price 4} "sushi"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.id {%venues.price 4} "zzzzz"))))))) (defmacro with-fk-field-to-field-remapping {:style/indent 0} [& body] `(mt/with-column-remappings [~'venues.category_id ~'categories.name] ~@body)) (deftest fk-field-to-field-remapped-field-id-test (with-fk-field-to-field-remapping (is (= (mt/id :categories :name) (#'chain-filter/remapped-field-id (mt/id :venues :category_id)))))) (deftest fk-field-to-field-remapped-chain-filter-test (with-fk-field-to-field-remapping (testing "Show me category IDs for categories" ;; there are no restaurants with category 1 (is (= [[2 "American"] [3 "Artisan"] [4 "Asian"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.category_id nil)))))) (testing "Show me category IDs for categories that have expensive restaurants" (is (= [[40 "Japanese"] [67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.price 4}))))) (testing "Show me the category 40 (constraints do not support remapping)" (is (= [[40 "Japanese"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.category_id 40}))))))) (deftest fk-field-to-field-remapped-chain-filter-search-test (with-fk-field-to-field-remapping (testing "Show me categories containing 'ar'" (doseq [constraints [nil {}]] (testing (format "\nconstraints = %s" (pr-str constraints)) (is (= [[3 "Artisan"] [7 "Bar"] [14 "Caribbean"]] (take 3 (mt/$ids (chain-filter/chain-filter-search %venues.category_id constraints "ar")))))))) (testing "Show me categories containing 'house' that have expensive restaurants" (is (= [[67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "house"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "zzzzz"))))))) (deftest use-cached-field-values-test (testing "chain-filter should use cached FieldValues if applicable (#13832)" (mt/with-temp-vals-in-db FieldValues (db/select-one-id FieldValues :field_id (mt/id :categories :name)) {:values ["Good" "Bad"]} (testing "values" (is (= ["Good" "Bad"] (chain-filter categories.name nil))) (testing "shouldn't use cached FieldValues for queries with constraints" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price 4}))))) (testing "search" (is (= ["Good"] (mt/$ids (chain-filter/chain-filter-search %categories.name nil "ood")))) (testing "shouldn't use cached FieldValues for queries with constraints" (is (= ["Steakhouse"] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "o"))))))))) (deftest time-interval-test (testing "chain-filter should accept time interval strings like `past32weeks` for temporal Fields" (mt/$ids (is (= [:time-interval $checkins.date -32 :week {:include-current false}] (#'chain-filter/filter-clause $$checkins %checkins.date "past32weeks"))))))
32500
(ns metabase.models.params.chain-filter-test (:require [clojure.test :refer :all] [metabase.models :refer [FieldValues]] [metabase.models.params.chain-filter :as chain-filter] [metabase.test :as mt] [toucan.db :as db])) (defmacro chain-filter [field field->value & options] `(chain-filter/chain-filter (mt/$ids nil ~(symbol (str \% (name field)))) (mt/$ids nil ~(into {} (for [[k v] field->value] [(symbol (str \% k)) v]))) ~@options)) (deftest chain-filter-test (testing "Show me expensive restaurants" (is (= ["Dal Rae Restaurant" "Lawry's The Prime Rib" "Pacific Dining Car - Santa Monica" "Sushi Nakazawa" "Sushi Yasuda" "Tanoshi Sushi & Sake Bar"] (chain-filter venues.name {venues.price 4})))) (testing "Show me categories that have expensive restaurants" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price 4}))) (testing "Should work with string versions of param values" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price "4"}))))) (testing "Show me categories starting with s (case-insensitive) that have expensive restaurants" (is (= ["Steakhouse"] (chain-filter categories.name {venues.price 4, categories.name [:starts-with "s" {:case-sensitive false}]})))) (testing "Show me cheap Thai restaurants" (is (= ["Kinaree Thai Bistro" "Krua Siri"] (chain-filter venues.name {venues.price 1, categories.name "Thai"})))) (testing "Show me the categories that have cheap restaurants" (is (= ["Asian" "BBQ" "Bakery" "Bar" "Burger" "Caribbean" "Deli" "Karaoke" "Mexican" "Pizza" "Southern" "Thai"] (chain-filter categories.name {venues.price 1})))) (testing "Show me cheap restaurants with the word 'taco' in their name (case-insensitive)" (is (= ["Tacos Villa Corona" "Tito's Tacos"] (chain-filter venues.name {venues.price 1, venues.name [:contains "tAcO" {:case-sensitive false}]})))) (testing "Show me the first 3 expensive restaurants" (is (= ["Dal Rae Restaurant" "Lawry's The Prime Rib" "Pacific Dining Car - Santa Monica"] (chain-filter venues.name {venues.price 4} :limit 3)))) (testing "Oh yeah, we actually support arbitrary MBQL filter clauses. Neat!" (is (= ["Festa" "<NAME>"] (chain-filter venues.name {venues.price [:between 2 3] venues.name [:starts-with "f" {:case-sensitive false}]}))))) (deftest multiple-values-test (testing "Chain filtering should support multiple values for a single parameter (as a vector or set of values)" (testing "Show me restaurants with price = 1 or 2 with the word 'BBQ' in their name (case-sensitive)" (is (= ["Baby Blues BBQ" "Beachwood BBQ & Brewing" "Bludso's BBQ"] (chain-filter venues.name {venues.price #{1 2}, venues.name [:contains "BBQ"]})))) (testing "Show me the possible values of price for Bakery *or* BBQ restaurants" (is (= [1 2 3] (chain-filter venues.price {categories.name ["Bakery" "BBQ"]})))))) (deftest auto-parse-string-params-test (testing "Parameters that come in as strings (i.e., all of them that come in via the API) should work as intended" (is (= ["Baby Blues BBQ" "Beachwood BBQ & Brewing" "Bludso's BBQ"] (chain-filter venues.name {venues.price ["1" "2"], venues.name [:contains "BBQ"]}))))) (deftest unrelated-params-test (testing "Parameters that are completely unrelated (don't apply to this Table) should just get ignored entirely" ;; there is no way to join from venues -> users so users.id should get ignored (binding [chain-filter/*enable-reverse-joins* false] (is (= [1 2 3] (chain-filter venues.price {categories.name ["Bakery" "BBQ"] users.id [1 2 3]})))))) (def megagraph "A large graph that is hugely interconnected. All nodes can get to 50 and 50 has an edge to :end. But the fastest route is [[:start 50] [50 :end]] and we should quickly identify this last route. Basically handy to demonstrate that we are doing breadth first search rather than depth first search. Depth first would identify 1 -> 2 -> 3 ... 49 -> 50 -> end" (let [big 50] (merge-with merge (reduce (fn [m [x y]] (assoc-in m [x y] [[x y]])) {} (for [x (range (inc big)) y (range (inc big)) :when (not= x y)] [x y])) {:start (reduce (fn [m x] (assoc m x [[:start x]])) {} (range (inc big)))} {big {:end [[big :end]]}}))) (def megagraph-single-path "Similar to the megagraph above, this graph only has a single path through a hugely interconnected graph. A naive graph traversal will run out of memory or take quite a long time to find the traversal: [[:start 90] [90 200] [200 :end]] There is only one path to end (from 200) and only one path to 200 from 90. If you take out the seen nodes this path will not be found as the traversal advances through all of the 50 paths from start, all of the 50 paths from 1, all of the 50 paths from 2, ..." (merge-with merge ;; every node is linked to every other node (1 ... 199) (reduce (fn [m [x y]] (assoc-in m [x y] [[x y]])) {} (for [x (range 200) y (range 200) :when (not= x y)] [x y])) {:start (reduce (fn [m x] (assoc m x [[:start x]])) {} (range 200))} ;; only 90 reaches 200 and only 200 (big) reaches the end {90 {200 [[90 200]]} 200 {:end [[200 :end]]}})) (deftest traverse-graph-test (testing "If no need to join, returns immediately" (is (nil? (#'chain-filter/traverse-graph {} :start :start 5)))) (testing "Finds a simple hop" (let [graph {:start {:end [:start->end]}}] (is (= [:start->end] (#'chain-filter/traverse-graph graph :start :end 5)))) (testing "Finds over a few hops" (let [graph {:start {:a [:start->a]} :a {:b [:a->b]} :b {:c [:b->c]} :c {:end [:c->end]}}] (is (= [:start->a :a->b :b->c :c->end] (#'chain-filter/traverse-graph graph :start :end 5))) (testing "But will not exceed the max depth" (is (nil? (#'chain-filter/traverse-graph graph :start :end 2)))))) (testing "Can find a path in a dense and large graph" (is (= [[:start 50] [50 :end]] (#'chain-filter/traverse-graph megagraph :start :end 5))) (is (= [[:start 90] [90 200] [200 :end]] (#'chain-filter/traverse-graph megagraph-single-path :start :end 5)))) (testing "Returns nil if there is no path" (let [graph {:start {1 [[:start 1]]} 1 {2 [[1 2]]} ;; no way to get to 3 3 {4 [[3 4]]} 4 {:end [[4 :end]]}}] (is (nil? (#'chain-filter/traverse-graph graph :start :end 5))))) (testing "Not fooled by loops" (let [graph {:start {:a [:start->a]} :a {:b [:a->b] :a [:b->a]} :b {:c [:b->c] :a [:c->a] :b [:c->b]} :c {:end [:c->end]}}] (is (= [:start->a :a->b :b->c :c->end] (#'chain-filter/traverse-graph graph :start :end 5))) (testing "But will not exceed the max depth" (is (nil? (#'chain-filter/traverse-graph graph :start :end 2)))))))) (deftest find-joins-test (mt/dataset airports (mt/$ids nil (testing "airport -> municipality" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}}] (#'chain-filter/find-joins (mt/id) $$airport $$municipality)))) (testing "airport [-> municipality -> region] -> country" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}} {:lhs {:table $$municipality, :field %municipality.region-id} :rhs {:table $$region, :field %region.id}} {:lhs {:table $$region, :field %region.country-id} :rhs {:table $$country, :field %country.id}}] (#'chain-filter/find-joins (mt/id) $$airport $$country)))) (testing "[backwards]" (testing "municipality -> airport" (is (= [{:lhs {:table $$municipality, :field %municipality.id} :rhs {:table $$airport, :field %airport.municipality-id}}] (#'chain-filter/find-joins (mt/id) $$municipality $$airport)))) (testing "country [-> region -> municipality] -> airport" (is (= [{:lhs {:table $$country, :field %country.id} :rhs {:table $$region, :field %region.country-id}} {:lhs {:table $$region, :field %region.id} :rhs {:table $$municipality, :field %municipality.region-id}} {:lhs {:table $$municipality, :field %municipality.id} :rhs {:table $$airport, :field %airport.municipality-id}}] (#'chain-filter/find-joins (mt/id) $$country $$airport)))))))) (deftest find-all-joins-test (testing "With reverse joins disabled" (binding [chain-filter/*enable-reverse-joins* false] (mt/$ids nil (is (= [{:lhs {:table $$venues, :field %venues.category_id}, :rhs {:table $$categories, :field %categories.id}}] (#'chain-filter/find-all-joins $$venues #{%categories.name %users.id})))))) (mt/dataset airports (mt/$ids nil (testing "airport [-> municipality] -> region" (testing "even though we're joining against the same Table multiple times, duplicate joins should be removed" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}} {:lhs {:table $$municipality, :field %municipality.region-id} :rhs {:table $$region, :field %region.id}}] (#'chain-filter/find-all-joins $$airport #{%region.name %municipality.name %region.id})))))))) (deftest multi-hop-test (mt/dataset airports (testing "Should be able to filter against other tables with that require multiple joins\n" (testing "single direct join: Airport -> Municipality" (is (= ["San Francisco International Airport"] (chain-filter airport.name {municipality.name ["San Francisco"]})))) (testing "2 joins required: Airport -> Municipality -> Region" (is (= ["Beale Air Force Base" "Edwards Air Force Base" "<NAME> Airport-Orange County Airport"] (take 3 (chain-filter airport.name {region.name ["California"]}))))) (testing "3 joins required: Airport -> Municipality -> Region -> Country" (is (= ["Abraham Lincoln Capital Airport" "Albuquerque International Sunport" "Altus Air Force Base"] (take 3 (chain-filter airport.name {country.name ["United States"]}))))) (testing "4 joins required: Airport -> Municipality -> Region -> Country -> Continent" (is (= ["Afonso Pena Airport" "Alejandro Velasco Astete International Airport" "Carrasco International /General C L Berisso Airport"] (take 3 (chain-filter airport.name {continent.name ["South America"]}))))) (testing "[backwards]" (testing "single direct join: Municipality -> Airport" (is (= ["San Francisco"] (chain-filter municipality.name {airport.name ["San Francisco International Airport"]})))) (testing "2 joins required: Region -> Municipality -> Airport" (is (= ["California"] (chain-filter region.name {airport.name ["San Francisco International Airport"]})))) (testing "3 joins required: Country -> Region -> Municipality -> Airport" (is (= ["United States"] (chain-filter country.name {airport.name ["San Francisco International Airport"]})))) (testing "4 joins required: Continent -> Region -> Municipality -> Airport" (is (= ["North America"] (chain-filter continent.name {airport.name ["San Francisco International Airport"]})))))))) (deftest filterable-field-ids-test (mt/$ids (testing (format "venues.price = %d categories.name = %d users.id = %d\n" %venues.price %categories.name %users.id) (is (= #{%categories.name %users.id} (chain-filter/filterable-field-ids %venues.price #{%categories.name %users.id}))) (testing "reverse joins disabled: should exclude users.id" (binding [chain-filter/*enable-reverse-joins* false] (is (= #{%categories.name} (chain-filter/filterable-field-ids %venues.price #{%categories.name %users.id}))))) (testing "return nil if filtering-field-ids is empty" (is (= nil (chain-filter/filterable-field-ids %venues.price #{}))))))) (deftest chain-filter-search-test (testing "Show me categories containing 'eak' (case-insensitive) that have expensive restaurants" (is (= ["Steakhouse"] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "eak"))))) (testing "Show me cheap restaurants including with 'taco' (case-insensitive)" (is (= ["Tacos Villa Corona" "Tito's Tacos"] (mt/$ids (chain-filter/chain-filter-search %venues.name {%venues.price 1} "tAcO"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "zzzzz"))))) (testing "Field that doesn't exist should throw a 404" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Field [\d,]+ does not exist" (chain-filter/chain-filter-search Integer/MAX_VALUE nil "s")))) (testing "Field that isn't type/Text should throw a 400" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot search against non-Text Field" (chain-filter/chain-filter-search (mt/$ids %venues.price) nil "s"))))) ;;; --------------------------------------------------- Remapping ---------------------------------------------------- (defn do-with-human-readable-values-remapping [thunk] (mt/with-column-remappings [venues.category_id (values-of categories.name)] (thunk))) (defmacro with-human-readable-values-remapping {:style/indent 0} [& body] `(do-with-human-readable-values-remapping (fn [] ~@body))) (deftest human-readable-values-remapped-chain-filter-test (with-human-readable-values-remapping (testing "Show me category IDs for categories" ;; there are no restaurants with category 1 (is (= [[2 "American"] [3 "Artisan"] [4 "Asian"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.category_id nil)))))) (testing "Show me category IDs for categories that have expensive restaurants" (is (= [[40 "Japanese"] [67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.price 4}))))) (testing "Show me the category 40 (constraints do not support remapping)" (is (= [[40 "Japanese"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.category_id 40}))))))) (deftest human-readable-values-remapped-chain-filter-search-test (with-human-readable-values-remapping (testing "Show me category IDs [whose name] contains 'bar'" (doseq [constraints [nil {}]] (testing (format "\nconstraints = %s" (pr-str constraints)) (is (= [[7 "Bar"] [74 "Wine Bar"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id constraints "bar"))))))) (testing "Show me category IDs [whose name] contains 'house' that have expensive restaurants" (is (= [[67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "house"))))) (testing "search for something crazy: should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "zzzzz"))))))) (deftest field-to-field-remapped-field-id-test (is (= (mt/id :venues :name) (#'chain-filter/remapped-field-id (mt/id :venues :id))))) (deftest field-to-field-remapped-chain-filter-test (testing "Field-to-field remapping: venues.category_id -> categories.name\n" (testing "Show me venue IDs (names)" (is (= [[29 "20th Century Cafe"] [ 8 "25°" ] [93 "33 Taps" ]] (take 3 (chain-filter/chain-filter (mt/id :venues :id) nil))))) (testing "Show me expensive venue IDs (names)" (is (= [[55 "Dal Rae Restaurant"] [61 "Lawry's The Prime Rib"] [16 "Pacific Dining Car - Santa Monica"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.id {%venues.price 4})))))))) (deftest field-to-field-remapped-chain-filter-search-test (testing "Field-to-field remapping: venues.category_id -> categories.name\n" (testing "Show me venue IDs that [have a remapped name that] contains 'sushi'" (is (= [[76 "Beyond Sushi"] [80 "Blue Ribbon Sushi"] [77 "Sushi Nakazawa"]] (take 3 (chain-filter/chain-filter-search (mt/id :venues :id) nil "sushi"))))) (testing "Show me venue IDs that [have a remapped name that] contain 'sushi' that are expensive" (is (= [[77 "<NAME>"] [79 "<NAME>"] [81 "<NAME> & S<NAME>"]] (mt/$ids (chain-filter/chain-filter-search %venues.id {%venues.price 4} "sushi"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.id {%venues.price 4} "zzzzz"))))))) (defmacro with-fk-field-to-field-remapping {:style/indent 0} [& body] `(mt/with-column-remappings [~'venues.category_id ~'categories.name] ~@body)) (deftest fk-field-to-field-remapped-field-id-test (with-fk-field-to-field-remapping (is (= (mt/id :categories :name) (#'chain-filter/remapped-field-id (mt/id :venues :category_id)))))) (deftest fk-field-to-field-remapped-chain-filter-test (with-fk-field-to-field-remapping (testing "Show me category IDs for categories" ;; there are no restaurants with category 1 (is (= [[2 "American"] [3 "Artisan"] [4 "Asian"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.category_id nil)))))) (testing "Show me category IDs for categories that have expensive restaurants" (is (= [[40 "Japanese"] [67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.price 4}))))) (testing "Show me the category 40 (constraints do not support remapping)" (is (= [[40 "Japanese"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.category_id 40}))))))) (deftest fk-field-to-field-remapped-chain-filter-search-test (with-fk-field-to-field-remapping (testing "Show me categories containing 'ar'" (doseq [constraints [nil {}]] (testing (format "\nconstraints = %s" (pr-str constraints)) (is (= [[3 "Artisan"] [7 "Bar"] [14 "Caribbean"]] (take 3 (mt/$ids (chain-filter/chain-filter-search %venues.category_id constraints "ar")))))))) (testing "Show me categories containing 'house' that have expensive restaurants" (is (= [[67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "house"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "zzzzz"))))))) (deftest use-cached-field-values-test (testing "chain-filter should use cached FieldValues if applicable (#13832)" (mt/with-temp-vals-in-db FieldValues (db/select-one-id FieldValues :field_id (mt/id :categories :name)) {:values ["Good" "Bad"]} (testing "values" (is (= ["Good" "Bad"] (chain-filter categories.name nil))) (testing "shouldn't use cached FieldValues for queries with constraints" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price 4}))))) (testing "search" (is (= ["Good"] (mt/$ids (chain-filter/chain-filter-search %categories.name nil "ood")))) (testing "shouldn't use cached FieldValues for queries with constraints" (is (= ["Steakhouse"] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "o"))))))))) (deftest time-interval-test (testing "chain-filter should accept time interval strings like `past32weeks` for temporal Fields" (mt/$ids (is (= [:time-interval $checkins.date -32 :week {:include-current false}] (#'chain-filter/filter-clause $$checkins %checkins.date "past32weeks"))))))
true
(ns metabase.models.params.chain-filter-test (:require [clojure.test :refer :all] [metabase.models :refer [FieldValues]] [metabase.models.params.chain-filter :as chain-filter] [metabase.test :as mt] [toucan.db :as db])) (defmacro chain-filter [field field->value & options] `(chain-filter/chain-filter (mt/$ids nil ~(symbol (str \% (name field)))) (mt/$ids nil ~(into {} (for [[k v] field->value] [(symbol (str \% k)) v]))) ~@options)) (deftest chain-filter-test (testing "Show me expensive restaurants" (is (= ["Dal Rae Restaurant" "Lawry's The Prime Rib" "Pacific Dining Car - Santa Monica" "Sushi Nakazawa" "Sushi Yasuda" "Tanoshi Sushi & Sake Bar"] (chain-filter venues.name {venues.price 4})))) (testing "Show me categories that have expensive restaurants" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price 4}))) (testing "Should work with string versions of param values" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price "4"}))))) (testing "Show me categories starting with s (case-insensitive) that have expensive restaurants" (is (= ["Steakhouse"] (chain-filter categories.name {venues.price 4, categories.name [:starts-with "s" {:case-sensitive false}]})))) (testing "Show me cheap Thai restaurants" (is (= ["Kinaree Thai Bistro" "Krua Siri"] (chain-filter venues.name {venues.price 1, categories.name "Thai"})))) (testing "Show me the categories that have cheap restaurants" (is (= ["Asian" "BBQ" "Bakery" "Bar" "Burger" "Caribbean" "Deli" "Karaoke" "Mexican" "Pizza" "Southern" "Thai"] (chain-filter categories.name {venues.price 1})))) (testing "Show me cheap restaurants with the word 'taco' in their name (case-insensitive)" (is (= ["Tacos Villa Corona" "Tito's Tacos"] (chain-filter venues.name {venues.price 1, venues.name [:contains "tAcO" {:case-sensitive false}]})))) (testing "Show me the first 3 expensive restaurants" (is (= ["Dal Rae Restaurant" "Lawry's The Prime Rib" "Pacific Dining Car - Santa Monica"] (chain-filter venues.name {venues.price 4} :limit 3)))) (testing "Oh yeah, we actually support arbitrary MBQL filter clauses. Neat!" (is (= ["Festa" "PI:NAME:<NAME>END_PI"] (chain-filter venues.name {venues.price [:between 2 3] venues.name [:starts-with "f" {:case-sensitive false}]}))))) (deftest multiple-values-test (testing "Chain filtering should support multiple values for a single parameter (as a vector or set of values)" (testing "Show me restaurants with price = 1 or 2 with the word 'BBQ' in their name (case-sensitive)" (is (= ["Baby Blues BBQ" "Beachwood BBQ & Brewing" "Bludso's BBQ"] (chain-filter venues.name {venues.price #{1 2}, venues.name [:contains "BBQ"]})))) (testing "Show me the possible values of price for Bakery *or* BBQ restaurants" (is (= [1 2 3] (chain-filter venues.price {categories.name ["Bakery" "BBQ"]})))))) (deftest auto-parse-string-params-test (testing "Parameters that come in as strings (i.e., all of them that come in via the API) should work as intended" (is (= ["Baby Blues BBQ" "Beachwood BBQ & Brewing" "Bludso's BBQ"] (chain-filter venues.name {venues.price ["1" "2"], venues.name [:contains "BBQ"]}))))) (deftest unrelated-params-test (testing "Parameters that are completely unrelated (don't apply to this Table) should just get ignored entirely" ;; there is no way to join from venues -> users so users.id should get ignored (binding [chain-filter/*enable-reverse-joins* false] (is (= [1 2 3] (chain-filter venues.price {categories.name ["Bakery" "BBQ"] users.id [1 2 3]})))))) (def megagraph "A large graph that is hugely interconnected. All nodes can get to 50 and 50 has an edge to :end. But the fastest route is [[:start 50] [50 :end]] and we should quickly identify this last route. Basically handy to demonstrate that we are doing breadth first search rather than depth first search. Depth first would identify 1 -> 2 -> 3 ... 49 -> 50 -> end" (let [big 50] (merge-with merge (reduce (fn [m [x y]] (assoc-in m [x y] [[x y]])) {} (for [x (range (inc big)) y (range (inc big)) :when (not= x y)] [x y])) {:start (reduce (fn [m x] (assoc m x [[:start x]])) {} (range (inc big)))} {big {:end [[big :end]]}}))) (def megagraph-single-path "Similar to the megagraph above, this graph only has a single path through a hugely interconnected graph. A naive graph traversal will run out of memory or take quite a long time to find the traversal: [[:start 90] [90 200] [200 :end]] There is only one path to end (from 200) and only one path to 200 from 90. If you take out the seen nodes this path will not be found as the traversal advances through all of the 50 paths from start, all of the 50 paths from 1, all of the 50 paths from 2, ..." (merge-with merge ;; every node is linked to every other node (1 ... 199) (reduce (fn [m [x y]] (assoc-in m [x y] [[x y]])) {} (for [x (range 200) y (range 200) :when (not= x y)] [x y])) {:start (reduce (fn [m x] (assoc m x [[:start x]])) {} (range 200))} ;; only 90 reaches 200 and only 200 (big) reaches the end {90 {200 [[90 200]]} 200 {:end [[200 :end]]}})) (deftest traverse-graph-test (testing "If no need to join, returns immediately" (is (nil? (#'chain-filter/traverse-graph {} :start :start 5)))) (testing "Finds a simple hop" (let [graph {:start {:end [:start->end]}}] (is (= [:start->end] (#'chain-filter/traverse-graph graph :start :end 5)))) (testing "Finds over a few hops" (let [graph {:start {:a [:start->a]} :a {:b [:a->b]} :b {:c [:b->c]} :c {:end [:c->end]}}] (is (= [:start->a :a->b :b->c :c->end] (#'chain-filter/traverse-graph graph :start :end 5))) (testing "But will not exceed the max depth" (is (nil? (#'chain-filter/traverse-graph graph :start :end 2)))))) (testing "Can find a path in a dense and large graph" (is (= [[:start 50] [50 :end]] (#'chain-filter/traverse-graph megagraph :start :end 5))) (is (= [[:start 90] [90 200] [200 :end]] (#'chain-filter/traverse-graph megagraph-single-path :start :end 5)))) (testing "Returns nil if there is no path" (let [graph {:start {1 [[:start 1]]} 1 {2 [[1 2]]} ;; no way to get to 3 3 {4 [[3 4]]} 4 {:end [[4 :end]]}}] (is (nil? (#'chain-filter/traverse-graph graph :start :end 5))))) (testing "Not fooled by loops" (let [graph {:start {:a [:start->a]} :a {:b [:a->b] :a [:b->a]} :b {:c [:b->c] :a [:c->a] :b [:c->b]} :c {:end [:c->end]}}] (is (= [:start->a :a->b :b->c :c->end] (#'chain-filter/traverse-graph graph :start :end 5))) (testing "But will not exceed the max depth" (is (nil? (#'chain-filter/traverse-graph graph :start :end 2)))))))) (deftest find-joins-test (mt/dataset airports (mt/$ids nil (testing "airport -> municipality" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}}] (#'chain-filter/find-joins (mt/id) $$airport $$municipality)))) (testing "airport [-> municipality -> region] -> country" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}} {:lhs {:table $$municipality, :field %municipality.region-id} :rhs {:table $$region, :field %region.id}} {:lhs {:table $$region, :field %region.country-id} :rhs {:table $$country, :field %country.id}}] (#'chain-filter/find-joins (mt/id) $$airport $$country)))) (testing "[backwards]" (testing "municipality -> airport" (is (= [{:lhs {:table $$municipality, :field %municipality.id} :rhs {:table $$airport, :field %airport.municipality-id}}] (#'chain-filter/find-joins (mt/id) $$municipality $$airport)))) (testing "country [-> region -> municipality] -> airport" (is (= [{:lhs {:table $$country, :field %country.id} :rhs {:table $$region, :field %region.country-id}} {:lhs {:table $$region, :field %region.id} :rhs {:table $$municipality, :field %municipality.region-id}} {:lhs {:table $$municipality, :field %municipality.id} :rhs {:table $$airport, :field %airport.municipality-id}}] (#'chain-filter/find-joins (mt/id) $$country $$airport)))))))) (deftest find-all-joins-test (testing "With reverse joins disabled" (binding [chain-filter/*enable-reverse-joins* false] (mt/$ids nil (is (= [{:lhs {:table $$venues, :field %venues.category_id}, :rhs {:table $$categories, :field %categories.id}}] (#'chain-filter/find-all-joins $$venues #{%categories.name %users.id})))))) (mt/dataset airports (mt/$ids nil (testing "airport [-> municipality] -> region" (testing "even though we're joining against the same Table multiple times, duplicate joins should be removed" (is (= [{:lhs {:table $$airport, :field %airport.municipality-id} :rhs {:table $$municipality, :field %municipality.id}} {:lhs {:table $$municipality, :field %municipality.region-id} :rhs {:table $$region, :field %region.id}}] (#'chain-filter/find-all-joins $$airport #{%region.name %municipality.name %region.id})))))))) (deftest multi-hop-test (mt/dataset airports (testing "Should be able to filter against other tables with that require multiple joins\n" (testing "single direct join: Airport -> Municipality" (is (= ["San Francisco International Airport"] (chain-filter airport.name {municipality.name ["San Francisco"]})))) (testing "2 joins required: Airport -> Municipality -> Region" (is (= ["Beale Air Force Base" "Edwards Air Force Base" "PI:NAME:<NAME>END_PI Airport-Orange County Airport"] (take 3 (chain-filter airport.name {region.name ["California"]}))))) (testing "3 joins required: Airport -> Municipality -> Region -> Country" (is (= ["Abraham Lincoln Capital Airport" "Albuquerque International Sunport" "Altus Air Force Base"] (take 3 (chain-filter airport.name {country.name ["United States"]}))))) (testing "4 joins required: Airport -> Municipality -> Region -> Country -> Continent" (is (= ["Afonso Pena Airport" "Alejandro Velasco Astete International Airport" "Carrasco International /General C L Berisso Airport"] (take 3 (chain-filter airport.name {continent.name ["South America"]}))))) (testing "[backwards]" (testing "single direct join: Municipality -> Airport" (is (= ["San Francisco"] (chain-filter municipality.name {airport.name ["San Francisco International Airport"]})))) (testing "2 joins required: Region -> Municipality -> Airport" (is (= ["California"] (chain-filter region.name {airport.name ["San Francisco International Airport"]})))) (testing "3 joins required: Country -> Region -> Municipality -> Airport" (is (= ["United States"] (chain-filter country.name {airport.name ["San Francisco International Airport"]})))) (testing "4 joins required: Continent -> Region -> Municipality -> Airport" (is (= ["North America"] (chain-filter continent.name {airport.name ["San Francisco International Airport"]})))))))) (deftest filterable-field-ids-test (mt/$ids (testing (format "venues.price = %d categories.name = %d users.id = %d\n" %venues.price %categories.name %users.id) (is (= #{%categories.name %users.id} (chain-filter/filterable-field-ids %venues.price #{%categories.name %users.id}))) (testing "reverse joins disabled: should exclude users.id" (binding [chain-filter/*enable-reverse-joins* false] (is (= #{%categories.name} (chain-filter/filterable-field-ids %venues.price #{%categories.name %users.id}))))) (testing "return nil if filtering-field-ids is empty" (is (= nil (chain-filter/filterable-field-ids %venues.price #{}))))))) (deftest chain-filter-search-test (testing "Show me categories containing 'eak' (case-insensitive) that have expensive restaurants" (is (= ["Steakhouse"] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "eak"))))) (testing "Show me cheap restaurants including with 'taco' (case-insensitive)" (is (= ["Tacos Villa Corona" "Tito's Tacos"] (mt/$ids (chain-filter/chain-filter-search %venues.name {%venues.price 1} "tAcO"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "zzzzz"))))) (testing "Field that doesn't exist should throw a 404" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Field [\d,]+ does not exist" (chain-filter/chain-filter-search Integer/MAX_VALUE nil "s")))) (testing "Field that isn't type/Text should throw a 400" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot search against non-Text Field" (chain-filter/chain-filter-search (mt/$ids %venues.price) nil "s"))))) ;;; --------------------------------------------------- Remapping ---------------------------------------------------- (defn do-with-human-readable-values-remapping [thunk] (mt/with-column-remappings [venues.category_id (values-of categories.name)] (thunk))) (defmacro with-human-readable-values-remapping {:style/indent 0} [& body] `(do-with-human-readable-values-remapping (fn [] ~@body))) (deftest human-readable-values-remapped-chain-filter-test (with-human-readable-values-remapping (testing "Show me category IDs for categories" ;; there are no restaurants with category 1 (is (= [[2 "American"] [3 "Artisan"] [4 "Asian"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.category_id nil)))))) (testing "Show me category IDs for categories that have expensive restaurants" (is (= [[40 "Japanese"] [67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.price 4}))))) (testing "Show me the category 40 (constraints do not support remapping)" (is (= [[40 "Japanese"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.category_id 40}))))))) (deftest human-readable-values-remapped-chain-filter-search-test (with-human-readable-values-remapping (testing "Show me category IDs [whose name] contains 'bar'" (doseq [constraints [nil {}]] (testing (format "\nconstraints = %s" (pr-str constraints)) (is (= [[7 "Bar"] [74 "Wine Bar"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id constraints "bar"))))))) (testing "Show me category IDs [whose name] contains 'house' that have expensive restaurants" (is (= [[67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "house"))))) (testing "search for something crazy: should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "zzzzz"))))))) (deftest field-to-field-remapped-field-id-test (is (= (mt/id :venues :name) (#'chain-filter/remapped-field-id (mt/id :venues :id))))) (deftest field-to-field-remapped-chain-filter-test (testing "Field-to-field remapping: venues.category_id -> categories.name\n" (testing "Show me venue IDs (names)" (is (= [[29 "20th Century Cafe"] [ 8 "25°" ] [93 "33 Taps" ]] (take 3 (chain-filter/chain-filter (mt/id :venues :id) nil))))) (testing "Show me expensive venue IDs (names)" (is (= [[55 "Dal Rae Restaurant"] [61 "Lawry's The Prime Rib"] [16 "Pacific Dining Car - Santa Monica"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.id {%venues.price 4})))))))) (deftest field-to-field-remapped-chain-filter-search-test (testing "Field-to-field remapping: venues.category_id -> categories.name\n" (testing "Show me venue IDs that [have a remapped name that] contains 'sushi'" (is (= [[76 "Beyond Sushi"] [80 "Blue Ribbon Sushi"] [77 "Sushi Nakazawa"]] (take 3 (chain-filter/chain-filter-search (mt/id :venues :id) nil "sushi"))))) (testing "Show me venue IDs that [have a remapped name that] contain 'sushi' that are expensive" (is (= [[77 "PI:NAME:<NAME>END_PI"] [79 "PI:NAME:<NAME>END_PI"] [81 "PI:NAME:<NAME>END_PI & SPI:NAME:<NAME>END_PI"]] (mt/$ids (chain-filter/chain-filter-search %venues.id {%venues.price 4} "sushi"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.id {%venues.price 4} "zzzzz"))))))) (defmacro with-fk-field-to-field-remapping {:style/indent 0} [& body] `(mt/with-column-remappings [~'venues.category_id ~'categories.name] ~@body)) (deftest fk-field-to-field-remapped-field-id-test (with-fk-field-to-field-remapping (is (= (mt/id :categories :name) (#'chain-filter/remapped-field-id (mt/id :venues :category_id)))))) (deftest fk-field-to-field-remapped-chain-filter-test (with-fk-field-to-field-remapping (testing "Show me category IDs for categories" ;; there are no restaurants with category 1 (is (= [[2 "American"] [3 "Artisan"] [4 "Asian"]] (take 3 (mt/$ids (chain-filter/chain-filter %venues.category_id nil)))))) (testing "Show me category IDs for categories that have expensive restaurants" (is (= [[40 "Japanese"] [67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.price 4}))))) (testing "Show me the category 40 (constraints do not support remapping)" (is (= [[40 "Japanese"]] (mt/$ids (chain-filter/chain-filter %venues.category_id {%venues.category_id 40}))))))) (deftest fk-field-to-field-remapped-chain-filter-search-test (with-fk-field-to-field-remapping (testing "Show me categories containing 'ar'" (doseq [constraints [nil {}]] (testing (format "\nconstraints = %s" (pr-str constraints)) (is (= [[3 "Artisan"] [7 "Bar"] [14 "Caribbean"]] (take 3 (mt/$ids (chain-filter/chain-filter-search %venues.category_id constraints "ar")))))))) (testing "Show me categories containing 'house' that have expensive restaurants" (is (= [[67 "Steakhouse"]] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "house"))))) (testing "search for something crazy = should return empty results" (is (= [] (mt/$ids (chain-filter/chain-filter-search %venues.category_id {%venues.price 4} "zzzzz"))))))) (deftest use-cached-field-values-test (testing "chain-filter should use cached FieldValues if applicable (#13832)" (mt/with-temp-vals-in-db FieldValues (db/select-one-id FieldValues :field_id (mt/id :categories :name)) {:values ["Good" "Bad"]} (testing "values" (is (= ["Good" "Bad"] (chain-filter categories.name nil))) (testing "shouldn't use cached FieldValues for queries with constraints" (is (= ["Japanese" "Steakhouse"] (chain-filter categories.name {venues.price 4}))))) (testing "search" (is (= ["Good"] (mt/$ids (chain-filter/chain-filter-search %categories.name nil "ood")))) (testing "shouldn't use cached FieldValues for queries with constraints" (is (= ["Steakhouse"] (mt/$ids (chain-filter/chain-filter-search %categories.name {%venues.price 4} "o"))))))))) (deftest time-interval-test (testing "chain-filter should accept time interval strings like `past32weeks` for temporal Fields" (mt/$ids (is (= [:time-interval $checkins.date -32 :week {:include-current false}] (#'chain-filter/filter-clause $$checkins %checkins.date "past32weeks"))))))
[ { "context": " (info \"address: \" address)\n (info \"password: \" password)\n (info \"web3: \" web3)\n\n\n {:web3/call {:web", "end": 1030, "score": 0.9989548921585083, "start": 1022, "tag": "PASSWORD", "value": "password" }, { "context": "ize])\n (rf/dispatch [:blockchain/unlock-account \"0xd1c1db1ac98ae37005bf0752ed3458e418baa7f9\" \"try\" 999999]))\n", "end": 1806, "score": 0.9954415559768677, "start": 1764, "tag": "KEY", "value": "0xd1c1db1ac98ae37005bf0752ed3458e418baa7f9" } ]
src/cljs/ethervine/events.cljs
mohamedhayibor/ethervine
0
(ns ethervine.events (:require [re-frame.core :as rf] [ethervine.db :as init-db] [ajax.core :as ajax] [day8.re-frame.http-fx] [cljsjs.web3] [cljs-web3.core :as web3] [cljs-web3.eth :as web3-eth] [cljs-web3.personal :as web3-personal] [day8.re-frame.http-fx] [district0x.re-frame.web3-fx] [taoensso.timbre :as timbre :refer-macros [info]])) (def web3-event-scream "Firing event to web3") (def web3 (web3/create-web3 "http://localhost:6777")) (def interceptors [rf/trim-v]) (rf/reg-event-fx :initialize (fn [_ _] (info "Initialized") {:db init-db/default-db})) (rf/reg-event-db :blockchain/unlock-account interceptors (fn [{:keys [db] :as args} [address password]] (info web3-event-scream {:args args}) ; (println "init-db: " init-db/default-db) ; (println "init-db/web3 " (:web3 init-db/default-db)) (info "address: " address) (info "password: " password) (info "web3: " web3) {:web3/call {:web3 (:web3 init-db/default-db) :fns [{:fn web3-personal/unlock-account :args [address password 99999] :on-success [:blockchain/account-unlocked] :on-error [:log-error]}]}} (info "Exited from web3-call"))) (rf/reg-event-db :blockchain/account-unlocked interceptors (fn [{:keys [db]}] (info "SUCCESS: account unlocked >>>>") (info "DB: " db))) (rf/reg-event-db :log-error interceptors (fn [{:keys [db]}] (info "ULTIMATE FAIL: unlock account unsuccessful") (info "DB: " db))) (comment (rf/dispatch [:initialize]) (rf/dispatch [:blockchain/unlock-account "0xd1c1db1ac98ae37005bf0752ed3458e418baa7f9" "try" 999999]))
15181
(ns ethervine.events (:require [re-frame.core :as rf] [ethervine.db :as init-db] [ajax.core :as ajax] [day8.re-frame.http-fx] [cljsjs.web3] [cljs-web3.core :as web3] [cljs-web3.eth :as web3-eth] [cljs-web3.personal :as web3-personal] [day8.re-frame.http-fx] [district0x.re-frame.web3-fx] [taoensso.timbre :as timbre :refer-macros [info]])) (def web3-event-scream "Firing event to web3") (def web3 (web3/create-web3 "http://localhost:6777")) (def interceptors [rf/trim-v]) (rf/reg-event-fx :initialize (fn [_ _] (info "Initialized") {:db init-db/default-db})) (rf/reg-event-db :blockchain/unlock-account interceptors (fn [{:keys [db] :as args} [address password]] (info web3-event-scream {:args args}) ; (println "init-db: " init-db/default-db) ; (println "init-db/web3 " (:web3 init-db/default-db)) (info "address: " address) (info "password: " <PASSWORD>) (info "web3: " web3) {:web3/call {:web3 (:web3 init-db/default-db) :fns [{:fn web3-personal/unlock-account :args [address password 99999] :on-success [:blockchain/account-unlocked] :on-error [:log-error]}]}} (info "Exited from web3-call"))) (rf/reg-event-db :blockchain/account-unlocked interceptors (fn [{:keys [db]}] (info "SUCCESS: account unlocked >>>>") (info "DB: " db))) (rf/reg-event-db :log-error interceptors (fn [{:keys [db]}] (info "ULTIMATE FAIL: unlock account unsuccessful") (info "DB: " db))) (comment (rf/dispatch [:initialize]) (rf/dispatch [:blockchain/unlock-account "<KEY>" "try" 999999]))
true
(ns ethervine.events (:require [re-frame.core :as rf] [ethervine.db :as init-db] [ajax.core :as ajax] [day8.re-frame.http-fx] [cljsjs.web3] [cljs-web3.core :as web3] [cljs-web3.eth :as web3-eth] [cljs-web3.personal :as web3-personal] [day8.re-frame.http-fx] [district0x.re-frame.web3-fx] [taoensso.timbre :as timbre :refer-macros [info]])) (def web3-event-scream "Firing event to web3") (def web3 (web3/create-web3 "http://localhost:6777")) (def interceptors [rf/trim-v]) (rf/reg-event-fx :initialize (fn [_ _] (info "Initialized") {:db init-db/default-db})) (rf/reg-event-db :blockchain/unlock-account interceptors (fn [{:keys [db] :as args} [address password]] (info web3-event-scream {:args args}) ; (println "init-db: " init-db/default-db) ; (println "init-db/web3 " (:web3 init-db/default-db)) (info "address: " address) (info "password: " PI:PASSWORD:<PASSWORD>END_PI) (info "web3: " web3) {:web3/call {:web3 (:web3 init-db/default-db) :fns [{:fn web3-personal/unlock-account :args [address password 99999] :on-success [:blockchain/account-unlocked] :on-error [:log-error]}]}} (info "Exited from web3-call"))) (rf/reg-event-db :blockchain/account-unlocked interceptors (fn [{:keys [db]}] (info "SUCCESS: account unlocked >>>>") (info "DB: " db))) (rf/reg-event-db :log-error interceptors (fn [{:keys [db]}] (info "ULTIMATE FAIL: unlock account unsuccessful") (info "DB: " db))) (comment (rf/dispatch [:initialize]) (rf/dispatch [:blockchain/unlock-account "PI:KEY:<KEY>END_PI" "try" 999999]))
[ { "context": "SNAPSHOT\"\n :description \"DemocracyWorks Project - Chris Roeder - April 2016\"\n :url \"http://example.com/FIXME\"\n ", "end": 92, "score": 0.9998166561126709, "start": 80, "tag": "NAME", "value": "Chris Roeder" } ]
todo-list/project.clj
croeder/To-Do-List
0
(defproject todo-list "0.1.0-SNAPSHOT" :description "DemocracyWorks Project - Chris Roeder - April 2016" :url "http://example.com/FIXME" :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.7.0"] [compojure "1.5.0"] [ring/ring-defaults "0.1.5"] [hiccup "1.0.5"] [org.clojure/java.jdbc "0.4.1"] [org.postgresql/postgresql "9.4-1201-jdbc41"]] :plugins [[lein-ring "0.9.7"]] :ring {:handler todo-list.handler/app} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring/ring-mock "0.3.0"]] }})
96182
(defproject todo-list "0.1.0-SNAPSHOT" :description "DemocracyWorks Project - <NAME> - April 2016" :url "http://example.com/FIXME" :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.7.0"] [compojure "1.5.0"] [ring/ring-defaults "0.1.5"] [hiccup "1.0.5"] [org.clojure/java.jdbc "0.4.1"] [org.postgresql/postgresql "9.4-1201-jdbc41"]] :plugins [[lein-ring "0.9.7"]] :ring {:handler todo-list.handler/app} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring/ring-mock "0.3.0"]] }})
true
(defproject todo-list "0.1.0-SNAPSHOT" :description "DemocracyWorks Project - PI:NAME:<NAME>END_PI - April 2016" :url "http://example.com/FIXME" :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.7.0"] [compojure "1.5.0"] [ring/ring-defaults "0.1.5"] [hiccup "1.0.5"] [org.clojure/java.jdbc "0.4.1"] [org.postgresql/postgresql "9.4-1201-jdbc41"]] :plugins [[lein-ring "0.9.7"]] :ring {:handler todo-list.handler/app} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring/ring-mock "0.3.0"]] }})
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.bixby.cons.con7\n", "end": 597, "score": 0.9998470544815063, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/bixby/cons/con7.clj
llnek/skaro
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.bixby.cons.con7 (:gen-class) (:require [czlab.table.core :as tbl] [czlab.bixby.core :as b] [clojure.java.io :as io] [io.aviso.ansi :as ansi] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.bixby.cons.con1 :as c1] [czlab.bixby.cons.con2 :as c2] [czlab.basal.core :as c :refer [is?]]) (:import [czlab.basal DataError] [java.io File] [java.util ResourceBundle List Locale])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* false) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- get-cmd-info "Collect all cmdline usage messages." [rcb pod?] (->> (concat (if-not pod? '() '(["usage.debug"] ["usage.debug.desc"] ["usage.start"] ["usage.start.desc"] ["usage.stop"] ["usage.stop.desc"])) '(["usage.gen"] [ "usage.gen.desc"] ["usage.version"] [ "usage.version.desc"] ;;["usage.testjce"] ["usage.testjce.desc"] ["usage.help"] ["usage.help.desc"])) (apply u/rstr* rcb) (partition 2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- usage "Echo usage." [pod?] (let [walls ["" " " ""] rcb (b/get-rc-base) style {:middle ["" "" ""] :bottom ["" "" ""] :top ["" "" ""] :dash " " :body-walls walls :header-walls walls}] (-> (b/banner) ansi/bold-magenta c/prn!!) (c/prn!! "%s\n" (u/rstr rcb "bixby.desc")) (c/prn!! "%s" (u/rstr rcb "cmds.header")) ;; prepend blanks to act as headers (c/prn!! "%s\n" (c/strim (with-out-str (-> (concat '(("" "")) (get-cmd-info rcb pod?)) (tbl/table :style style))))) (c/prn!! "%s\n" (u/rstr rcb "cmds.trailer")) ;;the table module causes some agent stuff to hang ;;the vm without exiting, so shut them down (shutdown-agents))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn -main "Main function." [& args] (let [[options args] (u/parse-options args) ver (u/load-resource b/c-verprops) rcb (u/get-resource b/c-rcb-base) home (io/file (or (:home options) (u/get-user-dir))) verStr (c/stror (some-> ver (.getString "version")) "?")] (u/set-sys-prop! "bixby.user.dir" (u/fpath home)) (u/set-sys-prop! "bixby.version" verStr) (b/set-rc-base! rcb) (let [cfg (if-some [f (c/try! (b/get-conf-file))] (b/slurp-conf f))] (try (if (empty? args) (u/throw-BadData "CmdError!")) (let [pk (get-in cfg [:info :digest]) [f _] (->> (c/_1 args) keyword c1/bixby-tasks)] (if (fn? f) (binding [c1/*pkey-object* pk c1/*config-object* cfg] (f (drop 1 args))) (u/throw-BadData "CmdError!"))) (catch Throwable _ (if (is? DataError _) (usage cfg) (u/prn-stk _))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
35454
;; 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.bixby.cons.con7 (:gen-class) (:require [czlab.table.core :as tbl] [czlab.bixby.core :as b] [clojure.java.io :as io] [io.aviso.ansi :as ansi] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.bixby.cons.con1 :as c1] [czlab.bixby.cons.con2 :as c2] [czlab.basal.core :as c :refer [is?]]) (:import [czlab.basal DataError] [java.io File] [java.util ResourceBundle List Locale])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* false) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- get-cmd-info "Collect all cmdline usage messages." [rcb pod?] (->> (concat (if-not pod? '() '(["usage.debug"] ["usage.debug.desc"] ["usage.start"] ["usage.start.desc"] ["usage.stop"] ["usage.stop.desc"])) '(["usage.gen"] [ "usage.gen.desc"] ["usage.version"] [ "usage.version.desc"] ;;["usage.testjce"] ["usage.testjce.desc"] ["usage.help"] ["usage.help.desc"])) (apply u/rstr* rcb) (partition 2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- usage "Echo usage." [pod?] (let [walls ["" " " ""] rcb (b/get-rc-base) style {:middle ["" "" ""] :bottom ["" "" ""] :top ["" "" ""] :dash " " :body-walls walls :header-walls walls}] (-> (b/banner) ansi/bold-magenta c/prn!!) (c/prn!! "%s\n" (u/rstr rcb "bixby.desc")) (c/prn!! "%s" (u/rstr rcb "cmds.header")) ;; prepend blanks to act as headers (c/prn!! "%s\n" (c/strim (with-out-str (-> (concat '(("" "")) (get-cmd-info rcb pod?)) (tbl/table :style style))))) (c/prn!! "%s\n" (u/rstr rcb "cmds.trailer")) ;;the table module causes some agent stuff to hang ;;the vm without exiting, so shut them down (shutdown-agents))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn -main "Main function." [& args] (let [[options args] (u/parse-options args) ver (u/load-resource b/c-verprops) rcb (u/get-resource b/c-rcb-base) home (io/file (or (:home options) (u/get-user-dir))) verStr (c/stror (some-> ver (.getString "version")) "?")] (u/set-sys-prop! "bixby.user.dir" (u/fpath home)) (u/set-sys-prop! "bixby.version" verStr) (b/set-rc-base! rcb) (let [cfg (if-some [f (c/try! (b/get-conf-file))] (b/slurp-conf f))] (try (if (empty? args) (u/throw-BadData "CmdError!")) (let [pk (get-in cfg [:info :digest]) [f _] (->> (c/_1 args) keyword c1/bixby-tasks)] (if (fn? f) (binding [c1/*pkey-object* pk c1/*config-object* cfg] (f (drop 1 args))) (u/throw-BadData "CmdError!"))) (catch Throwable _ (if (is? DataError _) (usage cfg) (u/prn-stk _))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;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.bixby.cons.con7 (:gen-class) (:require [czlab.table.core :as tbl] [czlab.bixby.core :as b] [clojure.java.io :as io] [io.aviso.ansi :as ansi] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.bixby.cons.con1 :as c1] [czlab.bixby.cons.con2 :as c2] [czlab.basal.core :as c :refer [is?]]) (:import [czlab.basal DataError] [java.io File] [java.util ResourceBundle List Locale])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* false) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- get-cmd-info "Collect all cmdline usage messages." [rcb pod?] (->> (concat (if-not pod? '() '(["usage.debug"] ["usage.debug.desc"] ["usage.start"] ["usage.start.desc"] ["usage.stop"] ["usage.stop.desc"])) '(["usage.gen"] [ "usage.gen.desc"] ["usage.version"] [ "usage.version.desc"] ;;["usage.testjce"] ["usage.testjce.desc"] ["usage.help"] ["usage.help.desc"])) (apply u/rstr* rcb) (partition 2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- usage "Echo usage." [pod?] (let [walls ["" " " ""] rcb (b/get-rc-base) style {:middle ["" "" ""] :bottom ["" "" ""] :top ["" "" ""] :dash " " :body-walls walls :header-walls walls}] (-> (b/banner) ansi/bold-magenta c/prn!!) (c/prn!! "%s\n" (u/rstr rcb "bixby.desc")) (c/prn!! "%s" (u/rstr rcb "cmds.header")) ;; prepend blanks to act as headers (c/prn!! "%s\n" (c/strim (with-out-str (-> (concat '(("" "")) (get-cmd-info rcb pod?)) (tbl/table :style style))))) (c/prn!! "%s\n" (u/rstr rcb "cmds.trailer")) ;;the table module causes some agent stuff to hang ;;the vm without exiting, so shut them down (shutdown-agents))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn -main "Main function." [& args] (let [[options args] (u/parse-options args) ver (u/load-resource b/c-verprops) rcb (u/get-resource b/c-rcb-base) home (io/file (or (:home options) (u/get-user-dir))) verStr (c/stror (some-> ver (.getString "version")) "?")] (u/set-sys-prop! "bixby.user.dir" (u/fpath home)) (u/set-sys-prop! "bixby.version" verStr) (b/set-rc-base! rcb) (let [cfg (if-some [f (c/try! (b/get-conf-file))] (b/slurp-conf f))] (try (if (empty? args) (u/throw-BadData "CmdError!")) (let [pk (get-in cfg [:info :digest]) [f _] (->> (c/_1 args) keyword c1/bixby-tasks)] (if (fn? f) (binding [c1/*pkey-object* pk c1/*config-object* cfg] (f (drop 1 args))) (u/throw-BadData "CmdError!"))) (catch Throwable _ (if (is? DataError _) (usage cfg) (u/prn-stk _))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": ";;\n;; Copyright Christophe Roeder, August 2014\n\n\n(ns clojure-craft.craft-pos)\n(use ", "end": 33, "score": 0.9998748898506165, "start": 16, "tag": "NAME", "value": "Christophe Roeder" } ]
src/clojure_craft/craft_pos.clj
croeder/clojure_craft
0
;; ;; Copyright Christophe Roeder, August 2014 (ns clojure-craft.craft-pos) (use 'clojure.java.io) (use '[clojure.string :only (join split)]) (use 'clojure.xml) ;(def pos-base "/home/croeder/git/craft/craft-1.0/genia-xml/pos") ;(def txt-base "/home/croeder/git/craft/craft-1.0/articles/txt") ;;(def sample-pos-file (str pos-base "/" "11532192.txt.xml")) ;(def sample-pos-file (str pos-base "/" "short.txt.xml")) ;(def sample-text-file (str txt-base "/" "11532192.txt")) (defrecord Token [token-number part-of-speech text start end dependency anno-list] ) (defn print-token [t] (str " token:" :token-number t)) (defrecord Sentence [filename sentence-number text start end tokens] ) (defn print-sentence-1 [sentence-record] (str "sentence: " (:sentence-number sentence-record) "file:" (:filename sentence-record) " tokens: " (count (:tokens sentence-record)))) (defn print-sentence-2 [sentence-record] (conj (map (fn [token-number token] (str "sentence: " (:sentence-number sentence-record) " token:" token-number " " (:token-number token))) (iterate inc 0) (:tokens sentence-record)) (str "sentence number" (:sentence-number sentence-record)))) (defn print-sentence [sentence-record] (print-sentence-1 sentence-record)) ;; ;(defn- print-sentences [output article-text] ; (map (fn [sentence-number sentence] ; (print-sentence sentence sentence-number)) ; (iterate inc 0) output)) ;(defn print-sentence [s] ; (let [start (str "sentence:" (s :sentence-number))] ; (reduce (fn [collector tkn] ; (str collector " token:" (tkn :token-number))) ; (s :tokens)))) (defn read-craft-file "returns a list of xml structures " [file] (try (xml-seq (parse (java.io.File. file))) (catch Exception e (println "error reading craft xml file:" file) (println (.getMessage e)) ;(.printStackTrace e) (println "continuing") nil))) ; :TOK, :attrs {:cat JJ}, :content [specific]} (defn- parse-tokens "...returns a vector of Tokens" [sentence sentence-number filename] (map (fn [token-xml token-number] (Token. token-number (:cat (:attrs token-xml)) (first (:content token-xml)) 0 0 nil nil)) sentence (iterate inc 1))) (defn load-from-xml "Load pos from xml only. Returns a vector of vectors of Tokens. returns nil on error" ;; ... { ... :content {:tag :sentence, :attrs nil, :content [{:tag :tok, :attrs {:cat "NN"}, :content ["Abstract"]}]} } [pos-filename text-filename] (let [parse-results (read-craft-file pos-filename) in-data (cond parse-results (:content (first parse-results)) :t (list))] (map (fn [sentence sentence-number] (parse-tokens (:content sentence) sentence-number text-filename)) in-data (iterate inc 1)))) (defn- add-token-spans-sentence "Input: a list of token-records from a sentence, the article text, and the offset of the sentence start Description: adds span information for each token discovered in the article text starting at sentence-offset. Returns: (updated list of token-records packaged in a sentence-record)" [sentence-tokens text sentence-offset sentence-number] (loop [tokens (rest sentence-tokens) token (first sentence-tokens) index sentence-offset token-start 0 token-end 0 new-tokens []] (let [token-start (.indexOf text (:text token) index) token-end (+ token-start (.length (:text token))) new-token (cond (> token-start -1) (Token. (:token-number token) (:part-of-speech token) (:text token) token-start token-end nil nil) (<= token-start -1) ;; error (Token. (:token-number token) (:part-of-speech token) (:text token) 0 0 nil nil) ) local-new-tokens (conj new-tokens new-token)] (cond (not (empty? tokens)) (recur (rest tokens) (first tokens) token-end token-start token-end local-new-tokens) :t (Sentence. "foo.txt" sentence-number nil sentence-offset token-end local-new-tokens))))) (defn add-token-spans "takes article text and a list of tokens, adds span information to the tokens returns an updated list of the tokens and a list of sentence records" [results text] (loop [sentence-list (first results) sentences-lists (rest results) new-sentences [] sentence-offset 0 sentence-number 0] (let [sentence (add-token-spans-sentence sentence-list text sentence-offset sentence-number)] (cond (not (empty? sentences-lists)) (recur (first sentences-lists) (rest sentences-lists) (conj new-sentences sentence) (:end sentence) ; sentence-offset = (:end sentence) (inc sentence-number)) :t (conj new-sentences sentence))))) (defn- test-sentence [token-list sentence-number article-text] (map (fn [token count] (let [extracted-token-text (.substring article-text (:start token) (:end token)) token-text (:text token)] (cond (.equals token-text extracted-token-text) ;(println "good " sentence-number (:token-number token) token-text) nil :t ;(println "bad " sentence-number (:token-number token) ; (str "\"" extracted-token-text "\"") (str "\"" token-text "\"") ; (:start token) (:end token))))) (list sentence-number (:token-number token) (str "\"" extracted-token-text "\"") (str "\"" token-text "\"") )))) token-list (iterate inc 1) )) (defn- test-article-spans [output article-text] (map (fn [sentence sentence-number] (test-sentence (:tokens sentence) sentence-number article-text)) output (iterate inc 1) )) ;;;;;;;;;;;;;;;;;;;; ;(defn- test-run [] ; (test-article-spans ; (add-token-spans ; (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file)) ; (slurp sample-text-file))) ;(defn- print-run [] ; (add-token-spans ; (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file))) ;(defn- simple-run [] ;(print-sentences (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file)) ;) ;;;;;;;;;;;;; (defn load-pos [pos-file text-file] (let [xml-parse (load-from-xml pos-file text-file)] (cond xml-parse (add-token-spans xml-parse (slurp text-file)) :t nil )))
29366
;; ;; Copyright <NAME>, August 2014 (ns clojure-craft.craft-pos) (use 'clojure.java.io) (use '[clojure.string :only (join split)]) (use 'clojure.xml) ;(def pos-base "/home/croeder/git/craft/craft-1.0/genia-xml/pos") ;(def txt-base "/home/croeder/git/craft/craft-1.0/articles/txt") ;;(def sample-pos-file (str pos-base "/" "11532192.txt.xml")) ;(def sample-pos-file (str pos-base "/" "short.txt.xml")) ;(def sample-text-file (str txt-base "/" "11532192.txt")) (defrecord Token [token-number part-of-speech text start end dependency anno-list] ) (defn print-token [t] (str " token:" :token-number t)) (defrecord Sentence [filename sentence-number text start end tokens] ) (defn print-sentence-1 [sentence-record] (str "sentence: " (:sentence-number sentence-record) "file:" (:filename sentence-record) " tokens: " (count (:tokens sentence-record)))) (defn print-sentence-2 [sentence-record] (conj (map (fn [token-number token] (str "sentence: " (:sentence-number sentence-record) " token:" token-number " " (:token-number token))) (iterate inc 0) (:tokens sentence-record)) (str "sentence number" (:sentence-number sentence-record)))) (defn print-sentence [sentence-record] (print-sentence-1 sentence-record)) ;; ;(defn- print-sentences [output article-text] ; (map (fn [sentence-number sentence] ; (print-sentence sentence sentence-number)) ; (iterate inc 0) output)) ;(defn print-sentence [s] ; (let [start (str "sentence:" (s :sentence-number))] ; (reduce (fn [collector tkn] ; (str collector " token:" (tkn :token-number))) ; (s :tokens)))) (defn read-craft-file "returns a list of xml structures " [file] (try (xml-seq (parse (java.io.File. file))) (catch Exception e (println "error reading craft xml file:" file) (println (.getMessage e)) ;(.printStackTrace e) (println "continuing") nil))) ; :TOK, :attrs {:cat JJ}, :content [specific]} (defn- parse-tokens "...returns a vector of Tokens" [sentence sentence-number filename] (map (fn [token-xml token-number] (Token. token-number (:cat (:attrs token-xml)) (first (:content token-xml)) 0 0 nil nil)) sentence (iterate inc 1))) (defn load-from-xml "Load pos from xml only. Returns a vector of vectors of Tokens. returns nil on error" ;; ... { ... :content {:tag :sentence, :attrs nil, :content [{:tag :tok, :attrs {:cat "NN"}, :content ["Abstract"]}]} } [pos-filename text-filename] (let [parse-results (read-craft-file pos-filename) in-data (cond parse-results (:content (first parse-results)) :t (list))] (map (fn [sentence sentence-number] (parse-tokens (:content sentence) sentence-number text-filename)) in-data (iterate inc 1)))) (defn- add-token-spans-sentence "Input: a list of token-records from a sentence, the article text, and the offset of the sentence start Description: adds span information for each token discovered in the article text starting at sentence-offset. Returns: (updated list of token-records packaged in a sentence-record)" [sentence-tokens text sentence-offset sentence-number] (loop [tokens (rest sentence-tokens) token (first sentence-tokens) index sentence-offset token-start 0 token-end 0 new-tokens []] (let [token-start (.indexOf text (:text token) index) token-end (+ token-start (.length (:text token))) new-token (cond (> token-start -1) (Token. (:token-number token) (:part-of-speech token) (:text token) token-start token-end nil nil) (<= token-start -1) ;; error (Token. (:token-number token) (:part-of-speech token) (:text token) 0 0 nil nil) ) local-new-tokens (conj new-tokens new-token)] (cond (not (empty? tokens)) (recur (rest tokens) (first tokens) token-end token-start token-end local-new-tokens) :t (Sentence. "foo.txt" sentence-number nil sentence-offset token-end local-new-tokens))))) (defn add-token-spans "takes article text and a list of tokens, adds span information to the tokens returns an updated list of the tokens and a list of sentence records" [results text] (loop [sentence-list (first results) sentences-lists (rest results) new-sentences [] sentence-offset 0 sentence-number 0] (let [sentence (add-token-spans-sentence sentence-list text sentence-offset sentence-number)] (cond (not (empty? sentences-lists)) (recur (first sentences-lists) (rest sentences-lists) (conj new-sentences sentence) (:end sentence) ; sentence-offset = (:end sentence) (inc sentence-number)) :t (conj new-sentences sentence))))) (defn- test-sentence [token-list sentence-number article-text] (map (fn [token count] (let [extracted-token-text (.substring article-text (:start token) (:end token)) token-text (:text token)] (cond (.equals token-text extracted-token-text) ;(println "good " sentence-number (:token-number token) token-text) nil :t ;(println "bad " sentence-number (:token-number token) ; (str "\"" extracted-token-text "\"") (str "\"" token-text "\"") ; (:start token) (:end token))))) (list sentence-number (:token-number token) (str "\"" extracted-token-text "\"") (str "\"" token-text "\"") )))) token-list (iterate inc 1) )) (defn- test-article-spans [output article-text] (map (fn [sentence sentence-number] (test-sentence (:tokens sentence) sentence-number article-text)) output (iterate inc 1) )) ;;;;;;;;;;;;;;;;;;;; ;(defn- test-run [] ; (test-article-spans ; (add-token-spans ; (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file)) ; (slurp sample-text-file))) ;(defn- print-run [] ; (add-token-spans ; (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file))) ;(defn- simple-run [] ;(print-sentences (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file)) ;) ;;;;;;;;;;;;; (defn load-pos [pos-file text-file] (let [xml-parse (load-from-xml pos-file text-file)] (cond xml-parse (add-token-spans xml-parse (slurp text-file)) :t nil )))
true
;; ;; Copyright PI:NAME:<NAME>END_PI, August 2014 (ns clojure-craft.craft-pos) (use 'clojure.java.io) (use '[clojure.string :only (join split)]) (use 'clojure.xml) ;(def pos-base "/home/croeder/git/craft/craft-1.0/genia-xml/pos") ;(def txt-base "/home/croeder/git/craft/craft-1.0/articles/txt") ;;(def sample-pos-file (str pos-base "/" "11532192.txt.xml")) ;(def sample-pos-file (str pos-base "/" "short.txt.xml")) ;(def sample-text-file (str txt-base "/" "11532192.txt")) (defrecord Token [token-number part-of-speech text start end dependency anno-list] ) (defn print-token [t] (str " token:" :token-number t)) (defrecord Sentence [filename sentence-number text start end tokens] ) (defn print-sentence-1 [sentence-record] (str "sentence: " (:sentence-number sentence-record) "file:" (:filename sentence-record) " tokens: " (count (:tokens sentence-record)))) (defn print-sentence-2 [sentence-record] (conj (map (fn [token-number token] (str "sentence: " (:sentence-number sentence-record) " token:" token-number " " (:token-number token))) (iterate inc 0) (:tokens sentence-record)) (str "sentence number" (:sentence-number sentence-record)))) (defn print-sentence [sentence-record] (print-sentence-1 sentence-record)) ;; ;(defn- print-sentences [output article-text] ; (map (fn [sentence-number sentence] ; (print-sentence sentence sentence-number)) ; (iterate inc 0) output)) ;(defn print-sentence [s] ; (let [start (str "sentence:" (s :sentence-number))] ; (reduce (fn [collector tkn] ; (str collector " token:" (tkn :token-number))) ; (s :tokens)))) (defn read-craft-file "returns a list of xml structures " [file] (try (xml-seq (parse (java.io.File. file))) (catch Exception e (println "error reading craft xml file:" file) (println (.getMessage e)) ;(.printStackTrace e) (println "continuing") nil))) ; :TOK, :attrs {:cat JJ}, :content [specific]} (defn- parse-tokens "...returns a vector of Tokens" [sentence sentence-number filename] (map (fn [token-xml token-number] (Token. token-number (:cat (:attrs token-xml)) (first (:content token-xml)) 0 0 nil nil)) sentence (iterate inc 1))) (defn load-from-xml "Load pos from xml only. Returns a vector of vectors of Tokens. returns nil on error" ;; ... { ... :content {:tag :sentence, :attrs nil, :content [{:tag :tok, :attrs {:cat "NN"}, :content ["Abstract"]}]} } [pos-filename text-filename] (let [parse-results (read-craft-file pos-filename) in-data (cond parse-results (:content (first parse-results)) :t (list))] (map (fn [sentence sentence-number] (parse-tokens (:content sentence) sentence-number text-filename)) in-data (iterate inc 1)))) (defn- add-token-spans-sentence "Input: a list of token-records from a sentence, the article text, and the offset of the sentence start Description: adds span information for each token discovered in the article text starting at sentence-offset. Returns: (updated list of token-records packaged in a sentence-record)" [sentence-tokens text sentence-offset sentence-number] (loop [tokens (rest sentence-tokens) token (first sentence-tokens) index sentence-offset token-start 0 token-end 0 new-tokens []] (let [token-start (.indexOf text (:text token) index) token-end (+ token-start (.length (:text token))) new-token (cond (> token-start -1) (Token. (:token-number token) (:part-of-speech token) (:text token) token-start token-end nil nil) (<= token-start -1) ;; error (Token. (:token-number token) (:part-of-speech token) (:text token) 0 0 nil nil) ) local-new-tokens (conj new-tokens new-token)] (cond (not (empty? tokens)) (recur (rest tokens) (first tokens) token-end token-start token-end local-new-tokens) :t (Sentence. "foo.txt" sentence-number nil sentence-offset token-end local-new-tokens))))) (defn add-token-spans "takes article text and a list of tokens, adds span information to the tokens returns an updated list of the tokens and a list of sentence records" [results text] (loop [sentence-list (first results) sentences-lists (rest results) new-sentences [] sentence-offset 0 sentence-number 0] (let [sentence (add-token-spans-sentence sentence-list text sentence-offset sentence-number)] (cond (not (empty? sentences-lists)) (recur (first sentences-lists) (rest sentences-lists) (conj new-sentences sentence) (:end sentence) ; sentence-offset = (:end sentence) (inc sentence-number)) :t (conj new-sentences sentence))))) (defn- test-sentence [token-list sentence-number article-text] (map (fn [token count] (let [extracted-token-text (.substring article-text (:start token) (:end token)) token-text (:text token)] (cond (.equals token-text extracted-token-text) ;(println "good " sentence-number (:token-number token) token-text) nil :t ;(println "bad " sentence-number (:token-number token) ; (str "\"" extracted-token-text "\"") (str "\"" token-text "\"") ; (:start token) (:end token))))) (list sentence-number (:token-number token) (str "\"" extracted-token-text "\"") (str "\"" token-text "\"") )))) token-list (iterate inc 1) )) (defn- test-article-spans [output article-text] (map (fn [sentence sentence-number] (test-sentence (:tokens sentence) sentence-number article-text)) output (iterate inc 1) )) ;;;;;;;;;;;;;;;;;;;; ;(defn- test-run [] ; (test-article-spans ; (add-token-spans ; (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file)) ; (slurp sample-text-file))) ;(defn- print-run [] ; (add-token-spans ; (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file))) ;(defn- simple-run [] ;(print-sentences (load-from-xml sample-pos-file sample-text-file) ; (slurp sample-text-file)) ;) ;;;;;;;;;;;;; (defn load-pos [pos-file text-file] (let [xml-parse (load-from-xml pos-file text-file)] (cond xml-parse (add-token-spans xml-parse (slurp text-file)) :t nil )))
[ { "context": "ources/data/sample.tsv has records like:\n;; ...\n;; brown\tbrian\t:m\t:child\t:east\n;; smith\tbill\t:f\t:child\t:so", "end": 185, "score": 0.9663559794425964, "start": 180, "tag": "NAME", "value": "brown" }, { "context": "data/sample.tsv has records like:\n;; ...\n;; brown\tbrian\t:m\t:child\t:east\n;; smith\tbill\t:f\t:child\t:south\n;;", "end": 191, "score": 0.9993036389350891, "start": 186, "tag": "NAME", "value": "brian" }, { "context": "rds like:\n;; ...\n;; brown\tbrian\t:m\t:child\t:east\n;; smith\tbill\t:f\t:child\t:south\n;; jones\tjill\t:f\t:parent\t:w", "end": 216, "score": 0.9991512298583984, "start": 211, "tag": "NAME", "value": "smith" }, { "context": "e:\n;; ...\n;; brown\tbrian\t:m\t:child\t:east\n;; smith\tbill\t:f\t:child\t:south\n;; jones\tjill\t:f\t:parent\t:west\n;", "end": 221, "score": 0.9990376234054565, "start": 217, "tag": "NAME", "value": "bill" }, { "context": "\t:m\t:child\t:east\n;; smith\tbill\t:f\t:child\t:south\n;; jones\tjill\t:f\t:parent\t:west\n;; ...\n\n;; user> (time (def", "end": 247, "score": 0.9992294907569885, "start": 242, "tag": "NAME", "value": "jones" }, { "context": "ild\t:east\n;; smith\tbill\t:f\t:child\t:south\n;; jones\tjill\t:f\t:parent\t:west\n;; ...\n\n;; user> (time (def file", "end": 252, "score": 0.9978471398353577, "start": 248, "tag": "NAME", "value": "jill" }, { "context": " (get-children-names-in-family \"brown\"))\n;; [\"sue\" \"walter\" ... \"jill\"]\n;; user> (-> file-as-vec in", "end": 1501, "score": 0.9985787868499756, "start": 1498, "tag": "NAME", "value": "sue" }, { "context": "get-children-names-in-family \"brown\"))\n;; [\"sue\" \"walter\" ... \"jill\"]\n;; user> (-> file-as-vec into-record", "end": 1510, "score": 0.9995152950286865, "start": 1504, "tag": "NAME", "value": "walter" }, { "context": "names-in-family \"brown\"))\n;; [\"sue\" \"walter\" ... \"jill\"]\n;; user> (-> file-as-vec into-records\n;; ", "end": 1521, "score": 0.6610797643661499, "start": 1517, "tag": "NAME", "value": "jill" }, { "context": " (get-children-names-in-family \"brown\"))\n;; [\"sue\" \"walter\" ... \"jill\"]\n", "end": 1623, "score": 0.9980183839797974, "start": 1620, "tag": "NAME", "value": "sue" }, { "context": "get-children-names-in-family \"brown\"))\n;; [\"sue\" \"walter\" ... \"jill\"]\n", "end": 1632, "score": 0.999365508556366, "start": 1626, "tag": "NAME", "value": "walter" } ]
src/m_clj/c3/io.clj
PacktPublishing/Mastering-Clojure
12
(ns m-clj.c3.io (:require [iota :as i] [clojure.string :as cs] [clojure.core.reducers :as r])) ;;; resources/data/sample.tsv has records like: ;; ... ;; brown brian :m :child :east ;; smith bill :f :child :south ;; jones jill :f :parent :west ;; ... ;; user> (time (def file-as-seq (i/seq "resources/data/sample.tsv"))) ;; "Elapsed time: 0.905326 msecs" ;; #'user/file-as-seq ;; user> (time (def file-as-vec (i/vec "resources/data/sample.tsv"))) ;; "Elapsed time: 4.95506 msecs" ;; #'user/file-as-vec ;; user> (time (def first-100-lines (doall (take 100 file-as-seq)))) ;; "Elapsed time: 63.470598 msecs" ;; #'user/first-100-lines ;; user> (time (def first-100-lines (doall (take 100 file-as-vec)))) ;; "Elapsed time: 0.984128 msecs" ;; #'user/first-100-lines ;;; Example 3.15 (defn into-records [file] (->> file (r/filter identity) (r/map #(cs/split % #"[\t]")))) ;;; Example 3.16 (defn count-females [coll] (->> coll (r/map #(-> (nth % 2) ({":m" 0 ":f" 1}))) (r/fold +))) ;; user> (-> file-as-seq into-records count-females) ;; 10090 ;; user> (-> file-as-vec into-records count-females) ;; 10090 ;;; Example 3.17 (defn get-children-names-in-family [coll family] (->> coll (r/filter #(and (= (nth % 0) family) (= (nth % 3) ":child"))) (r/map #(nth % 1)) (into []))) ;; user> (-> file-as-seq into-records ;; (get-children-names-in-family "brown")) ;; ["sue" "walter" ... "jill"] ;; user> (-> file-as-vec into-records ;; (get-children-names-in-family "brown")) ;; ["sue" "walter" ... "jill"]
115494
(ns m-clj.c3.io (:require [iota :as i] [clojure.string :as cs] [clojure.core.reducers :as r])) ;;; resources/data/sample.tsv has records like: ;; ... ;; <NAME> <NAME> :m :child :east ;; <NAME> <NAME> :f :child :south ;; <NAME> <NAME> :f :parent :west ;; ... ;; user> (time (def file-as-seq (i/seq "resources/data/sample.tsv"))) ;; "Elapsed time: 0.905326 msecs" ;; #'user/file-as-seq ;; user> (time (def file-as-vec (i/vec "resources/data/sample.tsv"))) ;; "Elapsed time: 4.95506 msecs" ;; #'user/file-as-vec ;; user> (time (def first-100-lines (doall (take 100 file-as-seq)))) ;; "Elapsed time: 63.470598 msecs" ;; #'user/first-100-lines ;; user> (time (def first-100-lines (doall (take 100 file-as-vec)))) ;; "Elapsed time: 0.984128 msecs" ;; #'user/first-100-lines ;;; Example 3.15 (defn into-records [file] (->> file (r/filter identity) (r/map #(cs/split % #"[\t]")))) ;;; Example 3.16 (defn count-females [coll] (->> coll (r/map #(-> (nth % 2) ({":m" 0 ":f" 1}))) (r/fold +))) ;; user> (-> file-as-seq into-records count-females) ;; 10090 ;; user> (-> file-as-vec into-records count-females) ;; 10090 ;;; Example 3.17 (defn get-children-names-in-family [coll family] (->> coll (r/filter #(and (= (nth % 0) family) (= (nth % 3) ":child"))) (r/map #(nth % 1)) (into []))) ;; user> (-> file-as-seq into-records ;; (get-children-names-in-family "brown")) ;; ["<NAME>" "<NAME>" ... "<NAME>"] ;; user> (-> file-as-vec into-records ;; (get-children-names-in-family "brown")) ;; ["<NAME>" "<NAME>" ... "jill"]
true
(ns m-clj.c3.io (:require [iota :as i] [clojure.string :as cs] [clojure.core.reducers :as r])) ;;; resources/data/sample.tsv has records like: ;; ... ;; PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI :m :child :east ;; PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI :f :child :south ;; PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI :f :parent :west ;; ... ;; user> (time (def file-as-seq (i/seq "resources/data/sample.tsv"))) ;; "Elapsed time: 0.905326 msecs" ;; #'user/file-as-seq ;; user> (time (def file-as-vec (i/vec "resources/data/sample.tsv"))) ;; "Elapsed time: 4.95506 msecs" ;; #'user/file-as-vec ;; user> (time (def first-100-lines (doall (take 100 file-as-seq)))) ;; "Elapsed time: 63.470598 msecs" ;; #'user/first-100-lines ;; user> (time (def first-100-lines (doall (take 100 file-as-vec)))) ;; "Elapsed time: 0.984128 msecs" ;; #'user/first-100-lines ;;; Example 3.15 (defn into-records [file] (->> file (r/filter identity) (r/map #(cs/split % #"[\t]")))) ;;; Example 3.16 (defn count-females [coll] (->> coll (r/map #(-> (nth % 2) ({":m" 0 ":f" 1}))) (r/fold +))) ;; user> (-> file-as-seq into-records count-females) ;; 10090 ;; user> (-> file-as-vec into-records count-females) ;; 10090 ;;; Example 3.17 (defn get-children-names-in-family [coll family] (->> coll (r/filter #(and (= (nth % 0) family) (= (nth % 3) ":child"))) (r/map #(nth % 1)) (into []))) ;; user> (-> file-as-seq into-records ;; (get-children-names-in-family "brown")) ;; ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ... "PI:NAME:<NAME>END_PI"] ;; user> (-> file-as-vec into-records ;; (get-children-names-in-family "brown")) ;; ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ... "jill"]
[ { "context": "ge.login.subs :as l-s]))\n\n(def valid-private-key \"MIICXAIBAAKBgHbEH/pdZfQqUDmkt5xX+gSH8aKPdDaDJs7pBmh9R9D6F+46oaMouMekrb4VLBQRP3OhrP+D+RmJUmQD0OOiUl32RosEAC3DGfjIRgYCNK5oWL/dcg+jCDXg4no19KrvVUkNkE3dqp2JMhIJF/d2k47xUdh5OoIlLl2MeveLpg+VAgMBAAECgYBu2Mf71ZYlmCR+WHUiT55DAlqNXZSamDftX+IiPeN8cR9KsqBP9t7XPqUGRx53sE1nb9tWM+eXZOpn/IPHIaX7TkyvTZy3DGo2ACl7HzjOEK/gqYLdUAETSPmjQvaLIcEF3jG0W0cgIVOrNP1aJoexRLHb5nnYq6OaN79B+OA7gQJBANYzZAb3QWGi1FaeUAPdjf7oZxbdyjsuTw37kZdPMqFOiaflyoXNv4+YJjRA2LSdg7LQ0q9UrJmWuWRVm+Y2aaECQQCN8TP+tovWtdTo66licq1PljN2Yyhk22pe4fPLyQX6mL95ymTjGr2FRL2RpdNV5OKbmbek6vkZ62FuAR1ivSl1AkEAgB4m4x+65Io/FTwFwfoft2sMVhn8nt84+7UPxP/i2aafIWSJePSyclHf7/slYwqfvjG3ApXT0t3bL48g+1ZqYQJAGFkp3CWgM0KZtSLHuZWGWUKgrUwxH6vrwT7tPSXMmsIdBl1LlRF/NR8njZZufCt5G8vwjp+n/2Q7IE2cptVgCQJBAJbLXDiWzZQD8SL79/ty7WBxoS5QSogUxH4UkcoDVRGNCxQLN/za9tyIZx0Lbu38SfYVlW902bhJuBy7V8jy4wk=\")\n\n(rf/reg-event-db\n ::initialize-test-db-with-data", "end": 1157, "score": 0.9991509318351746, "start": 343, "tag": "KEY", "value": "MIICXAIBAAKBgHbEH/pdZfQqUDmkt5xX+gSH8aKPdDaDJs7pBmh9R9D6F+46oaMouMekrb4VLBQRP3OhrP+D+RmJUmQD0OOiUl32RosEAC3DGfjIRgYCNK5oWL/dcg+jCDXg4no19KrvVUkNkE3dqp2JMhIJF/d2k47xUdh5OoIlLl2MeveLpg+VAgMBAAECgYBu2Mf71ZYlmCR+WHUiT55DAlqNXZSamDftX+IiPeN8cR9KsqBP9t7XPqUGRx53sE1nb9tWM+eXZOpn/IPHIaX7TkyvTZy3DGo2ACl7HzjOEK/gqYLdUAETSPmjQvaLIcEF3jG0W0cgIVOrNP1aJoexRLHb5nnYq6OaN79B+OA7gQJBANYzZAb3QWGi1FaeUAPdjf7oZxbdyjsuTw37kZdPMqFOiaflyoXNv4+YJjRA2LSdg7LQ0q9UrJmWuWRVm+Y2aaECQQCN8TP+tovWtdTo66licq1PljN2Yyhk22pe4fPLyQX6mL95ymTjGr2FRL2RpdNV5OKbmbek6vkZ62FuAR1ivSl1AkEAgB4m4x+65Io/FTwFwfoft2sMVhn8nt84+7UPxP/i2aafIWSJePSyclHf7/slYwqfvjG3ApXT0t3bL48g+1ZqYQJAGFkp3CWgM0KZtSLHuZWGWUKgrUwxH6vrwT7tPSXMmsIdBl1LlRF/NR8njZZufCt5G8vwjp+n/2Q7IE2cptVgCQJBAJbLXDiWzZQD8SL79/ty7WBxoS5QSogUxH4UkcoDVRGNCxQLN/za9tyIZx0Lbu38SfYVlW902bhJuBy7V8jy4wk=\")" }, { "context": " [::l-s/data :plain])\n params {:username \"ybaroj\"}]\n\n (rf/dispatch [::l-e/login-request params", "end": 2112, "score": 0.9981145262718201, "start": 2106, "tag": "USERNAME", "value": "ybaroj" }, { "context": "l-s/response-body])\n params {:username \"ybaroj\"\n :plain \"base64-encoded-invali", "end": 2476, "score": 0.9996830821037292, "start": 2470, "tag": "USERNAME", "value": "ybaroj" }, { "context": "l-s/response-body])\n params {:username \"yb\" :plain \"\"}]\n\n (rf/dispatch-sync [::l-e/log", "end": 3024, "score": 0.9994662404060364, "start": 3022, "tag": "USERNAME", "value": "yb" }, { "context": "ubscribe [::s/token])\n params {:username \"pact-verifier-user\"\n :plain \"0123456789abcdef0123456", "end": 3556, "score": 0.9996262192726135, "start": 3538, "tag": "USERNAME", "value": "pact-verifier-user" } ]
test/cljs/bilgge/login/events_test.cljs
brsyuksel/bilgge-ui
9
(ns bilgge.login.events-test (:require [cljs.test :refer-macros [deftest testing is]] [re-frame.core :as rf] [day8.re-frame.test :as rf-test] [bilgge.events :as e] [bilgge.subs :as s] [bilgge.login.events :as l-e] [bilgge.login.subs :as l-s])) (def valid-private-key "MIICXAIBAAKBgHbEH/pdZfQqUDmkt5xX+gSH8aKPdDaDJs7pBmh9R9D6F+46oaMouMekrb4VLBQRP3OhrP+D+RmJUmQD0OOiUl32RosEAC3DGfjIRgYCNK5oWL/dcg+jCDXg4no19KrvVUkNkE3dqp2JMhIJF/d2k47xUdh5OoIlLl2MeveLpg+VAgMBAAECgYBu2Mf71ZYlmCR+WHUiT55DAlqNXZSamDftX+IiPeN8cR9KsqBP9t7XPqUGRx53sE1nb9tWM+eXZOpn/IPHIaX7TkyvTZy3DGo2ACl7HzjOEK/gqYLdUAETSPmjQvaLIcEF3jG0W0cgIVOrNP1aJoexRLHb5nnYq6OaN79B+OA7gQJBANYzZAb3QWGi1FaeUAPdjf7oZxbdyjsuTw37kZdPMqFOiaflyoXNv4+YJjRA2LSdg7LQ0q9UrJmWuWRVm+Y2aaECQQCN8TP+tovWtdTo66licq1PljN2Yyhk22pe4fPLyQX6mL95ymTjGr2FRL2RpdNV5OKbmbek6vkZ62FuAR1ivSl1AkEAgB4m4x+65Io/FTwFwfoft2sMVhn8nt84+7UPxP/i2aafIWSJePSyclHf7/slYwqfvjG3ApXT0t3bL48g+1ZqYQJAGFkp3CWgM0KZtSLHuZWGWUKgrUwxH6vrwT7tPSXMmsIdBl1LlRF/NR8njZZufCt5G8vwjp+n/2Q7IE2cptVgCQJBAJbLXDiWzZQD8SL79/ty7WBxoS5QSogUxH4UkcoDVRGNCxQLN/za9tyIZx0Lbu38SfYVlW902bhJuBy7V8jy4wk=") (rf/reg-event-db ::initialize-test-db-with-data (fn [db [_ data]] data)) (deftest login-with-not-existing-user (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [success? (rf/subscribe [::l-s/success?]) response (rf/subscribe [::l-s/response-body]) status (rf/subscribe [::l-s/response-status]) params {:username "not-existing"}] (rf/dispatch [::l-e/login-request params]) (rf-test/wait-for [::l-e/login-request-not-ok] (is (false? @success?)) (is (= 404 @status)) (is (= "not_found" (:reason @response))) (is (= ["user not found"] (:messages @response))))))) (deftest login-decrypt-cipher (rf-test/run-test-async (rf/dispatch-sync [::initialize-test-db-with-data {:private-key valid-private-key}]) (let [plain (rf/subscribe [::l-s/data :plain]) params {:username "ybaroj"}] (rf/dispatch [::l-e/login-request params]) (rf-test/wait-for [::l-e/login-request-ok] (is (some? @plain)))))) #_(deftest login-authenticate-with-invalid-plain (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [response (rf/subscribe [::l-s/response-body]) params {:username "ybaroj" :plain "base64-encoded-invalid-plain-text"}] (rf/dispatch-sync [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-not-ok] (is (= "decryption" (:reason @response))) (is (= ["plain does not match"] (:messages @response))))))) #_(deftest login-authenticate-validation-error (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [response (rf/subscribe [::l-s/response-body]) params {:username "yb" :plain ""}] (rf/dispatch-sync [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-not-ok] (is (= "validation" (:reason @response))) (is (= ["plain can not be empty"] (:messages @response))))))) (deftest login-authenticate-success (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [success? (rf/subscribe [::l-s/success?]) token (rf/subscribe [::s/token]) params {:username "pact-verifier-user" :plain "0123456789abcdef0123456789abcdef"}] (rf/dispatch [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-ok] (is (true? @success?)) (is (= "your-jwt" @token))))))
10457
(ns bilgge.login.events-test (:require [cljs.test :refer-macros [deftest testing is]] [re-frame.core :as rf] [day8.re-frame.test :as rf-test] [bilgge.events :as e] [bilgge.subs :as s] [bilgge.login.events :as l-e] [bilgge.login.subs :as l-s])) (def valid-private-key "<KEY> (rf/reg-event-db ::initialize-test-db-with-data (fn [db [_ data]] data)) (deftest login-with-not-existing-user (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [success? (rf/subscribe [::l-s/success?]) response (rf/subscribe [::l-s/response-body]) status (rf/subscribe [::l-s/response-status]) params {:username "not-existing"}] (rf/dispatch [::l-e/login-request params]) (rf-test/wait-for [::l-e/login-request-not-ok] (is (false? @success?)) (is (= 404 @status)) (is (= "not_found" (:reason @response))) (is (= ["user not found"] (:messages @response))))))) (deftest login-decrypt-cipher (rf-test/run-test-async (rf/dispatch-sync [::initialize-test-db-with-data {:private-key valid-private-key}]) (let [plain (rf/subscribe [::l-s/data :plain]) params {:username "ybaroj"}] (rf/dispatch [::l-e/login-request params]) (rf-test/wait-for [::l-e/login-request-ok] (is (some? @plain)))))) #_(deftest login-authenticate-with-invalid-plain (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [response (rf/subscribe [::l-s/response-body]) params {:username "ybaroj" :plain "base64-encoded-invalid-plain-text"}] (rf/dispatch-sync [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-not-ok] (is (= "decryption" (:reason @response))) (is (= ["plain does not match"] (:messages @response))))))) #_(deftest login-authenticate-validation-error (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [response (rf/subscribe [::l-s/response-body]) params {:username "yb" :plain ""}] (rf/dispatch-sync [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-not-ok] (is (= "validation" (:reason @response))) (is (= ["plain can not be empty"] (:messages @response))))))) (deftest login-authenticate-success (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [success? (rf/subscribe [::l-s/success?]) token (rf/subscribe [::s/token]) params {:username "pact-verifier-user" :plain "0123456789abcdef0123456789abcdef"}] (rf/dispatch [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-ok] (is (true? @success?)) (is (= "your-jwt" @token))))))
true
(ns bilgge.login.events-test (:require [cljs.test :refer-macros [deftest testing is]] [re-frame.core :as rf] [day8.re-frame.test :as rf-test] [bilgge.events :as e] [bilgge.subs :as s] [bilgge.login.events :as l-e] [bilgge.login.subs :as l-s])) (def valid-private-key "PI:KEY:<KEY>END_PI (rf/reg-event-db ::initialize-test-db-with-data (fn [db [_ data]] data)) (deftest login-with-not-existing-user (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [success? (rf/subscribe [::l-s/success?]) response (rf/subscribe [::l-s/response-body]) status (rf/subscribe [::l-s/response-status]) params {:username "not-existing"}] (rf/dispatch [::l-e/login-request params]) (rf-test/wait-for [::l-e/login-request-not-ok] (is (false? @success?)) (is (= 404 @status)) (is (= "not_found" (:reason @response))) (is (= ["user not found"] (:messages @response))))))) (deftest login-decrypt-cipher (rf-test/run-test-async (rf/dispatch-sync [::initialize-test-db-with-data {:private-key valid-private-key}]) (let [plain (rf/subscribe [::l-s/data :plain]) params {:username "ybaroj"}] (rf/dispatch [::l-e/login-request params]) (rf-test/wait-for [::l-e/login-request-ok] (is (some? @plain)))))) #_(deftest login-authenticate-with-invalid-plain (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [response (rf/subscribe [::l-s/response-body]) params {:username "ybaroj" :plain "base64-encoded-invalid-plain-text"}] (rf/dispatch-sync [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-not-ok] (is (= "decryption" (:reason @response))) (is (= ["plain does not match"] (:messages @response))))))) #_(deftest login-authenticate-validation-error (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [response (rf/subscribe [::l-s/response-body]) params {:username "yb" :plain ""}] (rf/dispatch-sync [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-not-ok] (is (= "validation" (:reason @response))) (is (= ["plain can not be empty"] (:messages @response))))))) (deftest login-authenticate-success (rf-test/run-test-async (rf/dispatch-sync [::e/initialize-db]) (let [success? (rf/subscribe [::l-s/success?]) token (rf/subscribe [::s/token]) params {:username "pact-verifier-user" :plain "0123456789abcdef0123456789abcdef"}] (rf/dispatch [::l-e/login-authenticate params]) (rf-test/wait-for [::l-e/login-authenticate-ok] (is (true? @success?)) (is (= "your-jwt" @token))))))
[ { "context": "g/lxc\")\n certfile (<< \"~{root}/servercerts/127.0.0.1.crt\")\n out (<< \"~{root}/certificate.p12\")\n", "end": 1276, "score": 0.9995772242546082, "start": 1267, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " {:keys [password bind]} lxd\n pass (<< \"pass:~{password}\")]\n (letfn [(remove-remote []\n ", "end": 1460, "score": 0.8106417059898376, "start": 1456, "tag": "PASSWORD", "value": "pass" }, { "context": "eys [password bind]} lxd\n pass (<< \"pass:~{password}\")]\n (letfn [(remove-remote []\n (", "end": 1471, "score": 0.7508943676948547, "start": 1463, "tag": "PASSWORD", "value": "password" } ]
src/re_cipes/infra/lxd.clj
re-ops/re-cipes
7
(ns re-cipes.infra.lxd "Setting up lxd locally and adding it to the local lxc client" (:require re-cipes.hardening [re-cog.resources.ufw :refer (add-interface enable-forwarding)] [re-cog.facts.config :refer (configuration)] [re-cog.resources.file :refer (template)] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.exec :refer [run]])) (require-recipe) (def-inline server "Installing lxd" [] (let [{:keys [lxd]} (configuration)] (letfn [(init [] (script (pipe (~cat-bin "/tmp/preseed.yaml") ("/usr/bin/lxd" "init" "--preseed"))))] (package "lxd" :present) (package "zfsutils-linux" :present) (template "/tmp/resources/templates/lxd/preseed.mustache" "/tmp/preseed.yaml" lxd) (run init)))) (def-inline {:depends #'re-cipes.hardening/firewall} bridging "Enable bridge networking" [] (add-interface "lxdbr0" :in :allow) (add-interface "lxdbr0" :out :allow) (enable-forwarding)) (def-inline {:depends #'re-cipes.infra.lxd/server} remote "add local lxd instance locally" [] (let [{:keys [lxd home user]} (configuration) root (<< "~{home}/snap/lxd/current/.config/lxc") certfile (<< "~{root}/servercerts/127.0.0.1.crt") out (<< "~{root}/certificate.p12") key (<< "~{root}/client.key") crt (<< "~{root}/client.crt") {:keys [password bind]} lxd pass (<< "pass:~{password}")] (letfn [(remove-remote [] (script (set! ID @("id" "-u")) (if (= "0" $ID) (pipe ("sudo" "-u" ~user "/usr/bin/lxc" "remote" "remove" ~bind) "true") (pipe ("/usr/bin/lxc" "remote" "remove" ~bind) "true")))) (add-remote [] (script (set! ID @("id" "-u")) (if (= "0" $ID) ("sudo" "-u" ~user "/usr/bin/lxc" "remote" "add" ~bind "--password" ~password "--accept-certificate") ("/usr/bin/lxc" "remote" "add" ~bind "--password" ~password "--accept-certificate")))) (export [] (script (set! ID @("id" "-u")) (if (= "0" $ID) ("sudo" "-u" ~user ~openssl-bin "pkcs12" "-export" "-out" ~out "-inkey" ~key "-in" ~crt "-certfile" ~certfile "-passout" ~pass) (~openssl-bin "pkcs12" "-export" "-out" ~out "-inkey" ~key "-in" ~crt "-certfile" ~certfile "-passout" ~pass))))] (run remove-remote) (run add-remote) (run export))))
101363
(ns re-cipes.infra.lxd "Setting up lxd locally and adding it to the local lxc client" (:require re-cipes.hardening [re-cog.resources.ufw :refer (add-interface enable-forwarding)] [re-cog.facts.config :refer (configuration)] [re-cog.resources.file :refer (template)] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.exec :refer [run]])) (require-recipe) (def-inline server "Installing lxd" [] (let [{:keys [lxd]} (configuration)] (letfn [(init [] (script (pipe (~cat-bin "/tmp/preseed.yaml") ("/usr/bin/lxd" "init" "--preseed"))))] (package "lxd" :present) (package "zfsutils-linux" :present) (template "/tmp/resources/templates/lxd/preseed.mustache" "/tmp/preseed.yaml" lxd) (run init)))) (def-inline {:depends #'re-cipes.hardening/firewall} bridging "Enable bridge networking" [] (add-interface "lxdbr0" :in :allow) (add-interface "lxdbr0" :out :allow) (enable-forwarding)) (def-inline {:depends #'re-cipes.infra.lxd/server} remote "add local lxd instance locally" [] (let [{:keys [lxd home user]} (configuration) root (<< "~{home}/snap/lxd/current/.config/lxc") certfile (<< "~{root}/servercerts/127.0.0.1.crt") out (<< "~{root}/certificate.p12") key (<< "~{root}/client.key") crt (<< "~{root}/client.crt") {:keys [password bind]} lxd pass (<< "<PASSWORD>:~{<PASSWORD>}")] (letfn [(remove-remote [] (script (set! ID @("id" "-u")) (if (= "0" $ID) (pipe ("sudo" "-u" ~user "/usr/bin/lxc" "remote" "remove" ~bind) "true") (pipe ("/usr/bin/lxc" "remote" "remove" ~bind) "true")))) (add-remote [] (script (set! ID @("id" "-u")) (if (= "0" $ID) ("sudo" "-u" ~user "/usr/bin/lxc" "remote" "add" ~bind "--password" ~password "--accept-certificate") ("/usr/bin/lxc" "remote" "add" ~bind "--password" ~password "--accept-certificate")))) (export [] (script (set! ID @("id" "-u")) (if (= "0" $ID) ("sudo" "-u" ~user ~openssl-bin "pkcs12" "-export" "-out" ~out "-inkey" ~key "-in" ~crt "-certfile" ~certfile "-passout" ~pass) (~openssl-bin "pkcs12" "-export" "-out" ~out "-inkey" ~key "-in" ~crt "-certfile" ~certfile "-passout" ~pass))))] (run remove-remote) (run add-remote) (run export))))
true
(ns re-cipes.infra.lxd "Setting up lxd locally and adding it to the local lxc client" (:require re-cipes.hardening [re-cog.resources.ufw :refer (add-interface enable-forwarding)] [re-cog.facts.config :refer (configuration)] [re-cog.resources.file :refer (template)] [re-cog.common.recipe :refer (require-recipe)] [re-cog.resources.exec :refer [run]])) (require-recipe) (def-inline server "Installing lxd" [] (let [{:keys [lxd]} (configuration)] (letfn [(init [] (script (pipe (~cat-bin "/tmp/preseed.yaml") ("/usr/bin/lxd" "init" "--preseed"))))] (package "lxd" :present) (package "zfsutils-linux" :present) (template "/tmp/resources/templates/lxd/preseed.mustache" "/tmp/preseed.yaml" lxd) (run init)))) (def-inline {:depends #'re-cipes.hardening/firewall} bridging "Enable bridge networking" [] (add-interface "lxdbr0" :in :allow) (add-interface "lxdbr0" :out :allow) (enable-forwarding)) (def-inline {:depends #'re-cipes.infra.lxd/server} remote "add local lxd instance locally" [] (let [{:keys [lxd home user]} (configuration) root (<< "~{home}/snap/lxd/current/.config/lxc") certfile (<< "~{root}/servercerts/127.0.0.1.crt") out (<< "~{root}/certificate.p12") key (<< "~{root}/client.key") crt (<< "~{root}/client.crt") {:keys [password bind]} lxd pass (<< "PI:PASSWORD:<PASSWORD>END_PI:~{PI:PASSWORD:<PASSWORD>END_PI}")] (letfn [(remove-remote [] (script (set! ID @("id" "-u")) (if (= "0" $ID) (pipe ("sudo" "-u" ~user "/usr/bin/lxc" "remote" "remove" ~bind) "true") (pipe ("/usr/bin/lxc" "remote" "remove" ~bind) "true")))) (add-remote [] (script (set! ID @("id" "-u")) (if (= "0" $ID) ("sudo" "-u" ~user "/usr/bin/lxc" "remote" "add" ~bind "--password" ~password "--accept-certificate") ("/usr/bin/lxc" "remote" "add" ~bind "--password" ~password "--accept-certificate")))) (export [] (script (set! ID @("id" "-u")) (if (= "0" $ID) ("sudo" "-u" ~user ~openssl-bin "pkcs12" "-export" "-out" ~out "-inkey" ~key "-in" ~crt "-certfile" ~certfile "-passout" ~pass) (~openssl-bin "pkcs12" "-export" "-out" ~out "-inkey" ~key "-in" ~crt "-certfile" ~certfile "-passout" ~pass))))] (run remove-remote) (run add-remote) (run export))))
[ { "context": " be used in real-time.\n Code based on research by Franky of scene.at\n\n Parameters:\n * length (number)", "end": 19266, "score": 0.5520531535148621, "start": 19261, "tag": "NAME", "value": "Frank" } ]
src/phzr/math.cljs
dparis/phzr
120
(ns phzr.math (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser]) (:refer-clojure :exclude [min max])) (defn angle-between- "Find the angle of a segment from (x1, y1) -> (x2, y2). Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The angle, in radians." ([x-1 y-1 x-2 y-2] (phaser->clj (.angleBetween js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn angle-between-points- "Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). Parameters: * point-1 (Phaser.Point) - No description * point-2 (Phaser.Point) - No description Returns: number - The angle, in radians." ([point-1 point-2] (phaser->clj (.angleBetweenPoints js/Phaser.Math (clj->phaser point-1) (clj->phaser point-2))))) (defn angle-between-points-y- "Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). Parameters: * point-1 (Phaser.Point) - No description * point-2 (Phaser.Point) - No description Returns: number - The angle, in radians." ([point-1 point-2] (phaser->clj (.angleBetweenPointsY js/Phaser.Math (clj->phaser point-1) (clj->phaser point-2))))) (defn angle-between-y- "Find the angle of a segment from (x1, y1) -> (x2, y2). Note that the difference between this method and Math.angleBetween is that this assumes the y coordinate travels down the screen. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The angle, in radians." ([x-1 y-1 x-2 y-2] (phaser->clj (.angleBetweenY js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn average- "Averages all values passed to the function and returns the result. Returns: number - The average of all given values." ([] (phaser->clj (.average js/Phaser.Math)))) (defn bezier-interpolation- "A Bezier Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.bezierInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn catmull-rom-interpolation- "A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.catmullRomInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn ceil-to- " Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.ceilTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn chance-roll- "Generate a random bool result based on the chance value. Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. Parameters: * chance (number) - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). Returns: boolean - True if the roll passed, or false otherwise." ([chance] (phaser->clj (.chanceRoll js/Phaser.Math (clj->phaser chance))))) (defn clamp- "Force a value within the boundaries by clamping `x` to the range `[a, b]`. Parameters: * x (number) - No description * a (number) - No description * b (number) - No description Returns: number - " ([x a b] (phaser->clj (.clamp js/Phaser.Math (clj->phaser x) (clj->phaser a) (clj->phaser b))))) (defn clamp-bottom- "Clamp `x` to the range `[a, Infinity)`. Roughly the same as `Math.max(x, a)`, except for NaN handling. Parameters: * x (number) - No description * a (number) - No description Returns: number - " ([x a] (phaser->clj (.clampBottom js/Phaser.Math (clj->phaser x) (clj->phaser a))))) (defn deg-to-rad- "Convert degrees to radians. Parameters: * degrees (number) - Angle in degrees. Returns: number - Angle in radians." ([degrees] (phaser->clj (.degToRad js/Phaser.Math (clj->phaser degrees))))) (defn difference- "The (absolute) difference between two values. Parameters: * a (number) - No description * b (number) - No description Returns: number - " ([a b] (phaser->clj (.difference js/Phaser.Math (clj->phaser a) (clj->phaser b))))) (defn distance- "Returns the euclidian distance between the two given set of coordinates. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The distance between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distance js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn distance-pow- "Returns the distance between the two given set of coordinates at the power given. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description * pow (number) {optional} - No description Returns: number - The distance between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distancePow js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2)))) ([x-1 y-1 x-2 y-2 pow] (phaser->clj (.distancePow js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2) (clj->phaser pow))))) (defn distance-sq- "Returns the euclidean distance squared between the two given set of coordinates (cuts out a square root operation before returning). Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The distance squared between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distanceSq js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn factorial- " Parameters: * value (number) - the number you want to evaluate Returns: number - " ([value] (phaser->clj (.factorial js/Phaser.Math (clj->phaser value))))) (defn floor-to- " Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.floorTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn fuzzy-ceil- " Parameters: * val (number) - No description * epsilon (number) {optional} - No description Returns: boolean - ceiling(val-epsilon)" ([val] (phaser->clj (.fuzzyCeil js/Phaser.Math (clj->phaser val)))) ([val epsilon] (phaser->clj (.fuzzyCeil js/Phaser.Math (clj->phaser val) (clj->phaser epsilon))))) (defn fuzzy-equal- "Two number are fuzzyEqual if their difference is less than epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if |a-b|<epsilon" ([a b] (phaser->clj (.fuzzyEqual js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyEqual js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn fuzzy-floor- " Parameters: * val (number) - No description * epsilon (number) {optional} - No description Returns: boolean - floor(val-epsilon)" ([val] (phaser->clj (.fuzzyFloor js/Phaser.Math (clj->phaser val)))) ([val epsilon] (phaser->clj (.fuzzyFloor js/Phaser.Math (clj->phaser val) (clj->phaser epsilon))))) (defn fuzzy-greater-than- "`a` is fuzzyGreaterThan `b` if it is more than b - epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if a>b+epsilon" ([a b] (phaser->clj (.fuzzyGreaterThan js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyGreaterThan js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn fuzzy-less-than- "`a` is fuzzyLessThan `b` if it is less than b + epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if a<b+epsilon" ([a b] (phaser->clj (.fuzzyLessThan js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyLessThan js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn is-even- "Returns true if the number given is even. Parameters: * n (integer) - The number to check. Returns: boolean - True if the given number is even. False if the given number is odd." ([n] (phaser->clj (.isEven js/Phaser.Math (clj->phaser n))))) (defn is-odd- "Returns true if the number given is odd. Parameters: * n (integer) - The number to check. Returns: boolean - True if the given number is odd. False if the given number is even." ([n] (phaser->clj (.isOdd js/Phaser.Math (clj->phaser n))))) (defn linear- "Calculates a linear (interpolation) value over t. Parameters: * p-0 (number) - No description * p-1 (number) - No description * t (number) - No description Returns: number - " ([p-0 p-1 t] (phaser->clj (.linear js/Phaser.Math (clj->phaser p-0) (clj->phaser p-1) (clj->phaser t))))) (defn linear-interpolation- "A Linear Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.linearInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn map-linear- "Linear mapping from range <a1, a2> to range <b1, b2> Parameters: * x (number) - the value to map * a-1 (number) - first endpoint of the range <a1, a2> * a-2 (number) - final endpoint of the range <a1, a2> * b-1 (number) - first endpoint of the range <b1, b2> * b-2 (number) - final endpoint of the range <b1, b2> Returns: number - " ([x a-1 a-2 b-1 b-2] (phaser->clj (.mapLinear js/Phaser.Math (clj->phaser x) (clj->phaser a-1) (clj->phaser a-2) (clj->phaser b-1) (clj->phaser b-2))))) (defn max- "Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.max` function when appropriate. Returns: number - The largest value from those given." ([] (phaser->clj (.max js/Phaser.Math)))) (defn max-add- "Adds the given amount to the value, but never lets the value go over the specified maximum. Parameters: * value (number) - The value to add the amount to. * amount (number) - The amount to add to the value. * max (number) - The maximum the value is allowed to be. Returns: number - " ([value amount max] (phaser->clj (.maxAdd js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser max))))) (defn max-property- "Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. It will find the largest matching property value from the given objects. Returns: number - The largest value from those given." ([] (phaser->clj (.maxProperty js/Phaser.Math)))) (defn min- "Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.min` function when appropriate. Returns: number - The lowest value from those given." ([] (phaser->clj (.min js/Phaser.Math)))) (defn min-property- "Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. It will find the lowest matching property value from the given objects. Returns: number - The lowest value from those given." ([] (phaser->clj (.minProperty js/Phaser.Math)))) (defn min-sub- "Subtracts the given amount from the value, but never lets the value go below the specified minimum. Parameters: * value (number) - The base value. * amount (number) - The amount to subtract from the base value. * min (number) - The minimum the value is allowed to be. Returns: number - The new value." ([value amount min] (phaser->clj (.minSub js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser min))))) (defn normalize-angle- "Normalizes an angle to the [0,2pi) range. Parameters: * angle-rad (number) - The angle to normalize, in radians. Returns: number - Returns the angle, fit within the [0,2pi] range, in radians." ([angle-rad] (phaser->clj (.normalizeAngle js/Phaser.Math (clj->phaser angle-rad))))) (defn percent- "Work out what percentage value `a` is of value `b` using the given base. Parameters: * a (number) - The value to work out the percentage for. * b (number) - The value you wish to get the percentage of. * base (number) {optional} - The base value. Returns: number - The percentage a is of b, between 0 and 1." ([a b] (phaser->clj (.percent js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b base] (phaser->clj (.percent js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser base))))) (defn rad-to-deg- "Convert degrees to radians. Parameters: * radians (number) - Angle in radians. Returns: number - Angle in degrees" ([radians] (phaser->clj (.radToDeg js/Phaser.Math (clj->phaser radians))))) (defn reverse-angle- "Reverses an angle. Parameters: * angle-rad (number) - The angle to reverse, in radians. Returns: number - Returns the reverse angle, in radians." ([angle-rad] (phaser->clj (.reverseAngle js/Phaser.Math (clj->phaser angle-rad))))) (defn round-away-from-zero- "Round to the next whole number _away_ from zero. Parameters: * value (number) - Any number. Returns: integer - The rounded value of that number." ([value] (phaser->clj (.roundAwayFromZero js/Phaser.Math (clj->phaser value))))) (defn round-to- "Round to some place comparative to a `base`, default is 10 for decimal place. The `place` is represented by the power applied to `base` to get that place. e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 roundTo(2000/7,3) === 0 roundTo(2000/7,2) == 300 roundTo(2000/7,1) == 290 roundTo(2000/7,0) == 286 roundTo(2000/7,-1) == 285.7 roundTo(2000/7,-2) == 285.71 roundTo(2000/7,-3) == 285.714 roundTo(2000/7,-4) == 285.7143 roundTo(2000/7,-5) == 285.71429 roundTo(2000/7,3,2) == 288 -- 100100000 roundTo(2000/7,2,2) == 284 -- 100011100 roundTo(2000/7,1,2) == 286 -- 100011110 roundTo(2000/7,0,2) == 286 -- 100011110 roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed because we are rounding 100011.1011011011011011 which rounds up. Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.roundTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn shear- " Parameters: * n (number) - No description Returns: number - n mod 1" ([n] (phaser->clj (.shear js/Phaser.Math (clj->phaser n))))) (defn sign- "A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. This works differently from `Math.sign` for values of NaN and -0, etc. Parameters: * x (number) - No description Returns: integer - An integer in {-1, 0, 1}" ([x] (phaser->clj (.sign js/Phaser.Math (clj->phaser x))))) (defn sin-cos-generator- "Generate a sine and cosine table simultaneously and extremely quickly. The parameters allow you to specify the length, amplitude and frequency of the wave. This generator is fast enough to be used in real-time. Code based on research by Franky of scene.at Parameters: * length (number) - The length of the wave * sin-amplitude (number) - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value * cos-amplitude (number) - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value * frequency (number) - The frequency of the sine and cosine table data Returns: Object - Returns the table data." ([length sin-amplitude cos-amplitude frequency] (phaser->clj (.sinCosGenerator js/Phaser.Math (clj->phaser length) (clj->phaser sin-amplitude) (clj->phaser cos-amplitude) (clj->phaser frequency))))) (defn smootherstep- "Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep Parameters: * x (number) - No description * min (number) - No description * max (number) - No description Returns: number - " ([x min max] (phaser->clj (.smootherstep js/Phaser.Math (clj->phaser x) (clj->phaser min) (clj->phaser max))))) (defn smoothstep- "Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep Parameters: * x (number) - No description * min (number) - No description * max (number) - No description Returns: number - " ([x min max] (phaser->clj (.smoothstep js/Phaser.Math (clj->phaser x) (clj->phaser min) (clj->phaser max))))) (defn snap-to- "Snap a value to nearest grid slice, using rounding. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapTo js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapTo js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn snap-to-ceil- "Snap a value to nearest grid slice, using ceil. Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapToCeil js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapToCeil js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn snap-to-floor- "Snap a value to nearest grid slice, using floor. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapToFloor js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapToFloor js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn within- "Checks if two values are within the given tolerance of each other. Parameters: * a (number) - The first number to check * b (number) - The second number to check * tolerance (number) - The tolerance. Anything equal to or less than this is considered within the range. Returns: boolean - True if a is <= tolerance of b." ([a b tolerance] (phaser->clj (.within js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser tolerance))))) (defn wrap- "Ensures that the value always stays between min and max, by wrapping the value around. If `max` is not larger than `min` the result is 0. Parameters: * value (number) - The value to wrap. * min (number) - The minimum the value is allowed to be. * max (number) - The maximum the value is allowed to be, should be larger than `min`. Returns: number - The wrapped value." ([value min max] (phaser->clj (.wrap js/Phaser.Math (clj->phaser value) (clj->phaser min) (clj->phaser max))))) (defn wrap-angle- "Keeps an angle value between -180 and +180; or -PI and PI if radians. Parameters: * angle (number) - The angle value to wrap * radians (boolean) {optional} - Set to `true` if the angle is given in radians, otherwise degrees is expected. Returns: number - The new angle value; will be the same as the input angle if it was within bounds." ([angle] (phaser->clj (.wrapAngle js/Phaser.Math (clj->phaser angle)))) ([angle radians] (phaser->clj (.wrapAngle js/Phaser.Math (clj->phaser angle) (clj->phaser radians))))) (defn wrap-value- "Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. Parameters: * value (number) - The value to add the amount to. * amount (number) - The amount to add to the value. * max (number) - The maximum the value is allowed to be. Returns: number - The wrapped value." ([value amount max] (phaser->clj (.wrapValue js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser max)))))
36711
(ns phzr.math (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser]) (:refer-clojure :exclude [min max])) (defn angle-between- "Find the angle of a segment from (x1, y1) -> (x2, y2). Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The angle, in radians." ([x-1 y-1 x-2 y-2] (phaser->clj (.angleBetween js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn angle-between-points- "Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). Parameters: * point-1 (Phaser.Point) - No description * point-2 (Phaser.Point) - No description Returns: number - The angle, in radians." ([point-1 point-2] (phaser->clj (.angleBetweenPoints js/Phaser.Math (clj->phaser point-1) (clj->phaser point-2))))) (defn angle-between-points-y- "Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). Parameters: * point-1 (Phaser.Point) - No description * point-2 (Phaser.Point) - No description Returns: number - The angle, in radians." ([point-1 point-2] (phaser->clj (.angleBetweenPointsY js/Phaser.Math (clj->phaser point-1) (clj->phaser point-2))))) (defn angle-between-y- "Find the angle of a segment from (x1, y1) -> (x2, y2). Note that the difference between this method and Math.angleBetween is that this assumes the y coordinate travels down the screen. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The angle, in radians." ([x-1 y-1 x-2 y-2] (phaser->clj (.angleBetweenY js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn average- "Averages all values passed to the function and returns the result. Returns: number - The average of all given values." ([] (phaser->clj (.average js/Phaser.Math)))) (defn bezier-interpolation- "A Bezier Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.bezierInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn catmull-rom-interpolation- "A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.catmullRomInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn ceil-to- " Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.ceilTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn chance-roll- "Generate a random bool result based on the chance value. Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. Parameters: * chance (number) - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). Returns: boolean - True if the roll passed, or false otherwise." ([chance] (phaser->clj (.chanceRoll js/Phaser.Math (clj->phaser chance))))) (defn clamp- "Force a value within the boundaries by clamping `x` to the range `[a, b]`. Parameters: * x (number) - No description * a (number) - No description * b (number) - No description Returns: number - " ([x a b] (phaser->clj (.clamp js/Phaser.Math (clj->phaser x) (clj->phaser a) (clj->phaser b))))) (defn clamp-bottom- "Clamp `x` to the range `[a, Infinity)`. Roughly the same as `Math.max(x, a)`, except for NaN handling. Parameters: * x (number) - No description * a (number) - No description Returns: number - " ([x a] (phaser->clj (.clampBottom js/Phaser.Math (clj->phaser x) (clj->phaser a))))) (defn deg-to-rad- "Convert degrees to radians. Parameters: * degrees (number) - Angle in degrees. Returns: number - Angle in radians." ([degrees] (phaser->clj (.degToRad js/Phaser.Math (clj->phaser degrees))))) (defn difference- "The (absolute) difference between two values. Parameters: * a (number) - No description * b (number) - No description Returns: number - " ([a b] (phaser->clj (.difference js/Phaser.Math (clj->phaser a) (clj->phaser b))))) (defn distance- "Returns the euclidian distance between the two given set of coordinates. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The distance between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distance js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn distance-pow- "Returns the distance between the two given set of coordinates at the power given. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description * pow (number) {optional} - No description Returns: number - The distance between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distancePow js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2)))) ([x-1 y-1 x-2 y-2 pow] (phaser->clj (.distancePow js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2) (clj->phaser pow))))) (defn distance-sq- "Returns the euclidean distance squared between the two given set of coordinates (cuts out a square root operation before returning). Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The distance squared between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distanceSq js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn factorial- " Parameters: * value (number) - the number you want to evaluate Returns: number - " ([value] (phaser->clj (.factorial js/Phaser.Math (clj->phaser value))))) (defn floor-to- " Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.floorTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn fuzzy-ceil- " Parameters: * val (number) - No description * epsilon (number) {optional} - No description Returns: boolean - ceiling(val-epsilon)" ([val] (phaser->clj (.fuzzyCeil js/Phaser.Math (clj->phaser val)))) ([val epsilon] (phaser->clj (.fuzzyCeil js/Phaser.Math (clj->phaser val) (clj->phaser epsilon))))) (defn fuzzy-equal- "Two number are fuzzyEqual if their difference is less than epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if |a-b|<epsilon" ([a b] (phaser->clj (.fuzzyEqual js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyEqual js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn fuzzy-floor- " Parameters: * val (number) - No description * epsilon (number) {optional} - No description Returns: boolean - floor(val-epsilon)" ([val] (phaser->clj (.fuzzyFloor js/Phaser.Math (clj->phaser val)))) ([val epsilon] (phaser->clj (.fuzzyFloor js/Phaser.Math (clj->phaser val) (clj->phaser epsilon))))) (defn fuzzy-greater-than- "`a` is fuzzyGreaterThan `b` if it is more than b - epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if a>b+epsilon" ([a b] (phaser->clj (.fuzzyGreaterThan js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyGreaterThan js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn fuzzy-less-than- "`a` is fuzzyLessThan `b` if it is less than b + epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if a<b+epsilon" ([a b] (phaser->clj (.fuzzyLessThan js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyLessThan js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn is-even- "Returns true if the number given is even. Parameters: * n (integer) - The number to check. Returns: boolean - True if the given number is even. False if the given number is odd." ([n] (phaser->clj (.isEven js/Phaser.Math (clj->phaser n))))) (defn is-odd- "Returns true if the number given is odd. Parameters: * n (integer) - The number to check. Returns: boolean - True if the given number is odd. False if the given number is even." ([n] (phaser->clj (.isOdd js/Phaser.Math (clj->phaser n))))) (defn linear- "Calculates a linear (interpolation) value over t. Parameters: * p-0 (number) - No description * p-1 (number) - No description * t (number) - No description Returns: number - " ([p-0 p-1 t] (phaser->clj (.linear js/Phaser.Math (clj->phaser p-0) (clj->phaser p-1) (clj->phaser t))))) (defn linear-interpolation- "A Linear Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.linearInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn map-linear- "Linear mapping from range <a1, a2> to range <b1, b2> Parameters: * x (number) - the value to map * a-1 (number) - first endpoint of the range <a1, a2> * a-2 (number) - final endpoint of the range <a1, a2> * b-1 (number) - first endpoint of the range <b1, b2> * b-2 (number) - final endpoint of the range <b1, b2> Returns: number - " ([x a-1 a-2 b-1 b-2] (phaser->clj (.mapLinear js/Phaser.Math (clj->phaser x) (clj->phaser a-1) (clj->phaser a-2) (clj->phaser b-1) (clj->phaser b-2))))) (defn max- "Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.max` function when appropriate. Returns: number - The largest value from those given." ([] (phaser->clj (.max js/Phaser.Math)))) (defn max-add- "Adds the given amount to the value, but never lets the value go over the specified maximum. Parameters: * value (number) - The value to add the amount to. * amount (number) - The amount to add to the value. * max (number) - The maximum the value is allowed to be. Returns: number - " ([value amount max] (phaser->clj (.maxAdd js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser max))))) (defn max-property- "Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. It will find the largest matching property value from the given objects. Returns: number - The largest value from those given." ([] (phaser->clj (.maxProperty js/Phaser.Math)))) (defn min- "Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.min` function when appropriate. Returns: number - The lowest value from those given." ([] (phaser->clj (.min js/Phaser.Math)))) (defn min-property- "Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. It will find the lowest matching property value from the given objects. Returns: number - The lowest value from those given." ([] (phaser->clj (.minProperty js/Phaser.Math)))) (defn min-sub- "Subtracts the given amount from the value, but never lets the value go below the specified minimum. Parameters: * value (number) - The base value. * amount (number) - The amount to subtract from the base value. * min (number) - The minimum the value is allowed to be. Returns: number - The new value." ([value amount min] (phaser->clj (.minSub js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser min))))) (defn normalize-angle- "Normalizes an angle to the [0,2pi) range. Parameters: * angle-rad (number) - The angle to normalize, in radians. Returns: number - Returns the angle, fit within the [0,2pi] range, in radians." ([angle-rad] (phaser->clj (.normalizeAngle js/Phaser.Math (clj->phaser angle-rad))))) (defn percent- "Work out what percentage value `a` is of value `b` using the given base. Parameters: * a (number) - The value to work out the percentage for. * b (number) - The value you wish to get the percentage of. * base (number) {optional} - The base value. Returns: number - The percentage a is of b, between 0 and 1." ([a b] (phaser->clj (.percent js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b base] (phaser->clj (.percent js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser base))))) (defn rad-to-deg- "Convert degrees to radians. Parameters: * radians (number) - Angle in radians. Returns: number - Angle in degrees" ([radians] (phaser->clj (.radToDeg js/Phaser.Math (clj->phaser radians))))) (defn reverse-angle- "Reverses an angle. Parameters: * angle-rad (number) - The angle to reverse, in radians. Returns: number - Returns the reverse angle, in radians." ([angle-rad] (phaser->clj (.reverseAngle js/Phaser.Math (clj->phaser angle-rad))))) (defn round-away-from-zero- "Round to the next whole number _away_ from zero. Parameters: * value (number) - Any number. Returns: integer - The rounded value of that number." ([value] (phaser->clj (.roundAwayFromZero js/Phaser.Math (clj->phaser value))))) (defn round-to- "Round to some place comparative to a `base`, default is 10 for decimal place. The `place` is represented by the power applied to `base` to get that place. e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 roundTo(2000/7,3) === 0 roundTo(2000/7,2) == 300 roundTo(2000/7,1) == 290 roundTo(2000/7,0) == 286 roundTo(2000/7,-1) == 285.7 roundTo(2000/7,-2) == 285.71 roundTo(2000/7,-3) == 285.714 roundTo(2000/7,-4) == 285.7143 roundTo(2000/7,-5) == 285.71429 roundTo(2000/7,3,2) == 288 -- 100100000 roundTo(2000/7,2,2) == 284 -- 100011100 roundTo(2000/7,1,2) == 286 -- 100011110 roundTo(2000/7,0,2) == 286 -- 100011110 roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed because we are rounding 100011.1011011011011011 which rounds up. Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.roundTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn shear- " Parameters: * n (number) - No description Returns: number - n mod 1" ([n] (phaser->clj (.shear js/Phaser.Math (clj->phaser n))))) (defn sign- "A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. This works differently from `Math.sign` for values of NaN and -0, etc. Parameters: * x (number) - No description Returns: integer - An integer in {-1, 0, 1}" ([x] (phaser->clj (.sign js/Phaser.Math (clj->phaser x))))) (defn sin-cos-generator- "Generate a sine and cosine table simultaneously and extremely quickly. The parameters allow you to specify the length, amplitude and frequency of the wave. This generator is fast enough to be used in real-time. Code based on research by <NAME>y of scene.at Parameters: * length (number) - The length of the wave * sin-amplitude (number) - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value * cos-amplitude (number) - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value * frequency (number) - The frequency of the sine and cosine table data Returns: Object - Returns the table data." ([length sin-amplitude cos-amplitude frequency] (phaser->clj (.sinCosGenerator js/Phaser.Math (clj->phaser length) (clj->phaser sin-amplitude) (clj->phaser cos-amplitude) (clj->phaser frequency))))) (defn smootherstep- "Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep Parameters: * x (number) - No description * min (number) - No description * max (number) - No description Returns: number - " ([x min max] (phaser->clj (.smootherstep js/Phaser.Math (clj->phaser x) (clj->phaser min) (clj->phaser max))))) (defn smoothstep- "Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep Parameters: * x (number) - No description * min (number) - No description * max (number) - No description Returns: number - " ([x min max] (phaser->clj (.smoothstep js/Phaser.Math (clj->phaser x) (clj->phaser min) (clj->phaser max))))) (defn snap-to- "Snap a value to nearest grid slice, using rounding. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapTo js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapTo js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn snap-to-ceil- "Snap a value to nearest grid slice, using ceil. Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapToCeil js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapToCeil js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn snap-to-floor- "Snap a value to nearest grid slice, using floor. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapToFloor js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapToFloor js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn within- "Checks if two values are within the given tolerance of each other. Parameters: * a (number) - The first number to check * b (number) - The second number to check * tolerance (number) - The tolerance. Anything equal to or less than this is considered within the range. Returns: boolean - True if a is <= tolerance of b." ([a b tolerance] (phaser->clj (.within js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser tolerance))))) (defn wrap- "Ensures that the value always stays between min and max, by wrapping the value around. If `max` is not larger than `min` the result is 0. Parameters: * value (number) - The value to wrap. * min (number) - The minimum the value is allowed to be. * max (number) - The maximum the value is allowed to be, should be larger than `min`. Returns: number - The wrapped value." ([value min max] (phaser->clj (.wrap js/Phaser.Math (clj->phaser value) (clj->phaser min) (clj->phaser max))))) (defn wrap-angle- "Keeps an angle value between -180 and +180; or -PI and PI if radians. Parameters: * angle (number) - The angle value to wrap * radians (boolean) {optional} - Set to `true` if the angle is given in radians, otherwise degrees is expected. Returns: number - The new angle value; will be the same as the input angle if it was within bounds." ([angle] (phaser->clj (.wrapAngle js/Phaser.Math (clj->phaser angle)))) ([angle radians] (phaser->clj (.wrapAngle js/Phaser.Math (clj->phaser angle) (clj->phaser radians))))) (defn wrap-value- "Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. Parameters: * value (number) - The value to add the amount to. * amount (number) - The amount to add to the value. * max (number) - The maximum the value is allowed to be. Returns: number - The wrapped value." ([value amount max] (phaser->clj (.wrapValue js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser max)))))
true
(ns phzr.math (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser]) (:refer-clojure :exclude [min max])) (defn angle-between- "Find the angle of a segment from (x1, y1) -> (x2, y2). Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The angle, in radians." ([x-1 y-1 x-2 y-2] (phaser->clj (.angleBetween js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn angle-between-points- "Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). Parameters: * point-1 (Phaser.Point) - No description * point-2 (Phaser.Point) - No description Returns: number - The angle, in radians." ([point-1 point-2] (phaser->clj (.angleBetweenPoints js/Phaser.Math (clj->phaser point-1) (clj->phaser point-2))))) (defn angle-between-points-y- "Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). Parameters: * point-1 (Phaser.Point) - No description * point-2 (Phaser.Point) - No description Returns: number - The angle, in radians." ([point-1 point-2] (phaser->clj (.angleBetweenPointsY js/Phaser.Math (clj->phaser point-1) (clj->phaser point-2))))) (defn angle-between-y- "Find the angle of a segment from (x1, y1) -> (x2, y2). Note that the difference between this method and Math.angleBetween is that this assumes the y coordinate travels down the screen. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The angle, in radians." ([x-1 y-1 x-2 y-2] (phaser->clj (.angleBetweenY js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn average- "Averages all values passed to the function and returns the result. Returns: number - The average of all given values." ([] (phaser->clj (.average js/Phaser.Math)))) (defn bezier-interpolation- "A Bezier Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.bezierInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn catmull-rom-interpolation- "A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.catmullRomInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn ceil-to- " Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.ceilTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn chance-roll- "Generate a random bool result based on the chance value. Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. Parameters: * chance (number) - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). Returns: boolean - True if the roll passed, or false otherwise." ([chance] (phaser->clj (.chanceRoll js/Phaser.Math (clj->phaser chance))))) (defn clamp- "Force a value within the boundaries by clamping `x` to the range `[a, b]`. Parameters: * x (number) - No description * a (number) - No description * b (number) - No description Returns: number - " ([x a b] (phaser->clj (.clamp js/Phaser.Math (clj->phaser x) (clj->phaser a) (clj->phaser b))))) (defn clamp-bottom- "Clamp `x` to the range `[a, Infinity)`. Roughly the same as `Math.max(x, a)`, except for NaN handling. Parameters: * x (number) - No description * a (number) - No description Returns: number - " ([x a] (phaser->clj (.clampBottom js/Phaser.Math (clj->phaser x) (clj->phaser a))))) (defn deg-to-rad- "Convert degrees to radians. Parameters: * degrees (number) - Angle in degrees. Returns: number - Angle in radians." ([degrees] (phaser->clj (.degToRad js/Phaser.Math (clj->phaser degrees))))) (defn difference- "The (absolute) difference between two values. Parameters: * a (number) - No description * b (number) - No description Returns: number - " ([a b] (phaser->clj (.difference js/Phaser.Math (clj->phaser a) (clj->phaser b))))) (defn distance- "Returns the euclidian distance between the two given set of coordinates. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The distance between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distance js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn distance-pow- "Returns the distance between the two given set of coordinates at the power given. Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description * pow (number) {optional} - No description Returns: number - The distance between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distancePow js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2)))) ([x-1 y-1 x-2 y-2 pow] (phaser->clj (.distancePow js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2) (clj->phaser pow))))) (defn distance-sq- "Returns the euclidean distance squared between the two given set of coordinates (cuts out a square root operation before returning). Parameters: * x-1 (number) - No description * y-1 (number) - No description * x-2 (number) - No description * y-2 (number) - No description Returns: number - The distance squared between the two sets of coordinates." ([x-1 y-1 x-2 y-2] (phaser->clj (.distanceSq js/Phaser.Math (clj->phaser x-1) (clj->phaser y-1) (clj->phaser x-2) (clj->phaser y-2))))) (defn factorial- " Parameters: * value (number) - the number you want to evaluate Returns: number - " ([value] (phaser->clj (.factorial js/Phaser.Math (clj->phaser value))))) (defn floor-to- " Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.floorTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn fuzzy-ceil- " Parameters: * val (number) - No description * epsilon (number) {optional} - No description Returns: boolean - ceiling(val-epsilon)" ([val] (phaser->clj (.fuzzyCeil js/Phaser.Math (clj->phaser val)))) ([val epsilon] (phaser->clj (.fuzzyCeil js/Phaser.Math (clj->phaser val) (clj->phaser epsilon))))) (defn fuzzy-equal- "Two number are fuzzyEqual if their difference is less than epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if |a-b|<epsilon" ([a b] (phaser->clj (.fuzzyEqual js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyEqual js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn fuzzy-floor- " Parameters: * val (number) - No description * epsilon (number) {optional} - No description Returns: boolean - floor(val-epsilon)" ([val] (phaser->clj (.fuzzyFloor js/Phaser.Math (clj->phaser val)))) ([val epsilon] (phaser->clj (.fuzzyFloor js/Phaser.Math (clj->phaser val) (clj->phaser epsilon))))) (defn fuzzy-greater-than- "`a` is fuzzyGreaterThan `b` if it is more than b - epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if a>b+epsilon" ([a b] (phaser->clj (.fuzzyGreaterThan js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyGreaterThan js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn fuzzy-less-than- "`a` is fuzzyLessThan `b` if it is less than b + epsilon. Parameters: * a (number) - No description * b (number) - No description * epsilon (number) {optional} - No description Returns: boolean - True if a<b+epsilon" ([a b] (phaser->clj (.fuzzyLessThan js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b epsilon] (phaser->clj (.fuzzyLessThan js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser epsilon))))) (defn is-even- "Returns true if the number given is even. Parameters: * n (integer) - The number to check. Returns: boolean - True if the given number is even. False if the given number is odd." ([n] (phaser->clj (.isEven js/Phaser.Math (clj->phaser n))))) (defn is-odd- "Returns true if the number given is odd. Parameters: * n (integer) - The number to check. Returns: boolean - True if the given number is odd. False if the given number is even." ([n] (phaser->clj (.isOdd js/Phaser.Math (clj->phaser n))))) (defn linear- "Calculates a linear (interpolation) value over t. Parameters: * p-0 (number) - No description * p-1 (number) - No description * t (number) - No description Returns: number - " ([p-0 p-1 t] (phaser->clj (.linear js/Phaser.Math (clj->phaser p-0) (clj->phaser p-1) (clj->phaser t))))) (defn linear-interpolation- "A Linear Interpolation Method, mostly used by Phaser.Tween. Parameters: * v (Array) - The input array of values to interpolate between. * k (number) - The percentage of interpolation, between 0 and 1. Returns: number - The interpolated value" ([v k] (phaser->clj (.linearInterpolation js/Phaser.Math (clj->phaser v) (clj->phaser k))))) (defn map-linear- "Linear mapping from range <a1, a2> to range <b1, b2> Parameters: * x (number) - the value to map * a-1 (number) - first endpoint of the range <a1, a2> * a-2 (number) - final endpoint of the range <a1, a2> * b-1 (number) - first endpoint of the range <b1, b2> * b-2 (number) - final endpoint of the range <b1, b2> Returns: number - " ([x a-1 a-2 b-1 b-2] (phaser->clj (.mapLinear js/Phaser.Math (clj->phaser x) (clj->phaser a-1) (clj->phaser a-2) (clj->phaser b-1) (clj->phaser b-2))))) (defn max- "Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.max` function when appropriate. Returns: number - The largest value from those given." ([] (phaser->clj (.max js/Phaser.Math)))) (defn max-add- "Adds the given amount to the value, but never lets the value go over the specified maximum. Parameters: * value (number) - The value to add the amount to. * amount (number) - The amount to add to the value. * max (number) - The maximum the value is allowed to be. Returns: number - " ([value amount max] (phaser->clj (.maxAdd js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser max))))) (defn max-property- "Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. It will find the largest matching property value from the given objects. Returns: number - The largest value from those given." ([] (phaser->clj (.maxProperty js/Phaser.Math)))) (defn min- "Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. Prefer the standard `Math.min` function when appropriate. Returns: number - The lowest value from those given." ([] (phaser->clj (.min js/Phaser.Math)))) (defn min-property- "Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. It will find the lowest matching property value from the given objects. Returns: number - The lowest value from those given." ([] (phaser->clj (.minProperty js/Phaser.Math)))) (defn min-sub- "Subtracts the given amount from the value, but never lets the value go below the specified minimum. Parameters: * value (number) - The base value. * amount (number) - The amount to subtract from the base value. * min (number) - The minimum the value is allowed to be. Returns: number - The new value." ([value amount min] (phaser->clj (.minSub js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser min))))) (defn normalize-angle- "Normalizes an angle to the [0,2pi) range. Parameters: * angle-rad (number) - The angle to normalize, in radians. Returns: number - Returns the angle, fit within the [0,2pi] range, in radians." ([angle-rad] (phaser->clj (.normalizeAngle js/Phaser.Math (clj->phaser angle-rad))))) (defn percent- "Work out what percentage value `a` is of value `b` using the given base. Parameters: * a (number) - The value to work out the percentage for. * b (number) - The value you wish to get the percentage of. * base (number) {optional} - The base value. Returns: number - The percentage a is of b, between 0 and 1." ([a b] (phaser->clj (.percent js/Phaser.Math (clj->phaser a) (clj->phaser b)))) ([a b base] (phaser->clj (.percent js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser base))))) (defn rad-to-deg- "Convert degrees to radians. Parameters: * radians (number) - Angle in radians. Returns: number - Angle in degrees" ([radians] (phaser->clj (.radToDeg js/Phaser.Math (clj->phaser radians))))) (defn reverse-angle- "Reverses an angle. Parameters: * angle-rad (number) - The angle to reverse, in radians. Returns: number - Returns the reverse angle, in radians." ([angle-rad] (phaser->clj (.reverseAngle js/Phaser.Math (clj->phaser angle-rad))))) (defn round-away-from-zero- "Round to the next whole number _away_ from zero. Parameters: * value (number) - Any number. Returns: integer - The rounded value of that number." ([value] (phaser->clj (.roundAwayFromZero js/Phaser.Math (clj->phaser value))))) (defn round-to- "Round to some place comparative to a `base`, default is 10 for decimal place. The `place` is represented by the power applied to `base` to get that place. e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 roundTo(2000/7,3) === 0 roundTo(2000/7,2) == 300 roundTo(2000/7,1) == 290 roundTo(2000/7,0) == 286 roundTo(2000/7,-1) == 285.7 roundTo(2000/7,-2) == 285.71 roundTo(2000/7,-3) == 285.714 roundTo(2000/7,-4) == 285.7143 roundTo(2000/7,-5) == 285.71429 roundTo(2000/7,3,2) == 288 -- 100100000 roundTo(2000/7,2,2) == 284 -- 100011100 roundTo(2000/7,1,2) == 286 -- 100011110 roundTo(2000/7,0,2) == 286 -- 100011110 roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed because we are rounding 100011.1011011011011011 which rounds up. Parameters: * value (number) - The value to round. * place (number) - The place to round to. * base (number) - The base to round in... default is 10 for decimal. Returns: number - " ([value place base] (phaser->clj (.roundTo js/Phaser.Math (clj->phaser value) (clj->phaser place) (clj->phaser base))))) (defn shear- " Parameters: * n (number) - No description Returns: number - n mod 1" ([n] (phaser->clj (.shear js/Phaser.Math (clj->phaser n))))) (defn sign- "A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. This works differently from `Math.sign` for values of NaN and -0, etc. Parameters: * x (number) - No description Returns: integer - An integer in {-1, 0, 1}" ([x] (phaser->clj (.sign js/Phaser.Math (clj->phaser x))))) (defn sin-cos-generator- "Generate a sine and cosine table simultaneously and extremely quickly. The parameters allow you to specify the length, amplitude and frequency of the wave. This generator is fast enough to be used in real-time. Code based on research by PI:NAME:<NAME>END_PIy of scene.at Parameters: * length (number) - The length of the wave * sin-amplitude (number) - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value * cos-amplitude (number) - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value * frequency (number) - The frequency of the sine and cosine table data Returns: Object - Returns the table data." ([length sin-amplitude cos-amplitude frequency] (phaser->clj (.sinCosGenerator js/Phaser.Math (clj->phaser length) (clj->phaser sin-amplitude) (clj->phaser cos-amplitude) (clj->phaser frequency))))) (defn smootherstep- "Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep Parameters: * x (number) - No description * min (number) - No description * max (number) - No description Returns: number - " ([x min max] (phaser->clj (.smootherstep js/Phaser.Math (clj->phaser x) (clj->phaser min) (clj->phaser max))))) (defn smoothstep- "Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep Parameters: * x (number) - No description * min (number) - No description * max (number) - No description Returns: number - " ([x min max] (phaser->clj (.smoothstep js/Phaser.Math (clj->phaser x) (clj->phaser min) (clj->phaser max))))) (defn snap-to- "Snap a value to nearest grid slice, using rounding. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapTo js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapTo js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn snap-to-ceil- "Snap a value to nearest grid slice, using ceil. Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapToCeil js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapToCeil js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn snap-to-floor- "Snap a value to nearest grid slice, using floor. Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15. Parameters: * input (number) - The value to snap. * gap (number) - The interval gap of the grid. * start (number) {optional} - Optional starting offset for gap. Returns: number - " ([input gap] (phaser->clj (.snapToFloor js/Phaser.Math (clj->phaser input) (clj->phaser gap)))) ([input gap start] (phaser->clj (.snapToFloor js/Phaser.Math (clj->phaser input) (clj->phaser gap) (clj->phaser start))))) (defn within- "Checks if two values are within the given tolerance of each other. Parameters: * a (number) - The first number to check * b (number) - The second number to check * tolerance (number) - The tolerance. Anything equal to or less than this is considered within the range. Returns: boolean - True if a is <= tolerance of b." ([a b tolerance] (phaser->clj (.within js/Phaser.Math (clj->phaser a) (clj->phaser b) (clj->phaser tolerance))))) (defn wrap- "Ensures that the value always stays between min and max, by wrapping the value around. If `max` is not larger than `min` the result is 0. Parameters: * value (number) - The value to wrap. * min (number) - The minimum the value is allowed to be. * max (number) - The maximum the value is allowed to be, should be larger than `min`. Returns: number - The wrapped value." ([value min max] (phaser->clj (.wrap js/Phaser.Math (clj->phaser value) (clj->phaser min) (clj->phaser max))))) (defn wrap-angle- "Keeps an angle value between -180 and +180; or -PI and PI if radians. Parameters: * angle (number) - The angle value to wrap * radians (boolean) {optional} - Set to `true` if the angle is given in radians, otherwise degrees is expected. Returns: number - The new angle value; will be the same as the input angle if it was within bounds." ([angle] (phaser->clj (.wrapAngle js/Phaser.Math (clj->phaser angle)))) ([angle radians] (phaser->clj (.wrapAngle js/Phaser.Math (clj->phaser angle) (clj->phaser radians))))) (defn wrap-value- "Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. Parameters: * value (number) - The value to add the amount to. * amount (number) - The amount to add to the value. * max (number) - The maximum the value is allowed to be. Returns: number - The wrapped value." ([value amount max] (phaser->clj (.wrapValue js/Phaser.Math (clj->phaser value) (clj->phaser amount) (clj->phaser max)))))
[ { "context": "eftest test-modify-vals\n (let [resource {:ip \"1.2.3.4\"\n :url \"http://1.2.3.4/uri\"\n ", "end": 664, "score": 0.9916224479675293, "start": 657, "tag": "IP_ADDRESS", "value": "1.2.3.4" }, { "context": ":ip \"1.2.3.4\"\n :url \"http://1.2.3.4/uri\"\n :dns \"https://example.co", "end": 706, "score": 0.9043890833854675, "start": 699, "tag": "IP_ADDRESS", "value": "1.2.3.4" }, { "context": "\"\n :multi {:level {:map \"https://1.2.3.4/untouched\"}}}\n modifiers [[#\"1.2.3.4\" \"", "end": 810, "score": 0.8016043901443481, "start": 807, "tag": "IP_ADDRESS", "value": "1.2" }, { "context": " :multi {:level {:map \"https://1.2.3.4/untouched\"}}}\n modifiers [[#\"1.2.3.4\" \"4.3", "end": 814, "score": 0.6653481721878052, "start": 813, "tag": "IP_ADDRESS", "value": "4" }, { "context": "tps://1.2.3.4/untouched\"}}}\n modifiers [[#\"1.2.3.4\" \"4.3.2.1\"]\n [#\"example.com\" \"n", "end": 858, "score": 0.9963425397872925, "start": 851, "tag": "IP_ADDRESS", "value": "1.2.3.4" }, { "context": "3.4/untouched\"}}}\n modifiers [[#\"1.2.3.4\" \"4.3.2.1\"]\n [#\"example.com\" \"nuv.la\"]]\n ", "end": 868, "score": 0.9944621920585632, "start": 861, "tag": "IP_ADDRESS", "value": "4.3.2.1" }, { "context": "y-vals resource modifiers)]\n (is (= m {:ip \"4.3.2.1\"\n :url \"http://4.3.2.1/uri\"\n ", "end": 992, "score": 0.9982949495315552, "start": 985, "tag": "IP_ADDRESS", "value": "4.3.2.1" }, { "context": " m {:ip \"4.3.2.1\"\n :url \"http://4.3.2.1/uri\"\n :dns \"https://nuv.la\"\n ", "end": 1030, "score": 0.9726343154907227, "start": 1023, "tag": "IP_ADDRESS", "value": "4.3.2.1" }, { "context": "v.la\"\n :multi {:level {:map \"https://1.2.3.4/untouched\"}}}))))\n\n\n(deftest test-->config-resour", "end": 1125, "score": 0.7572163343429565, "start": 1118, "tag": "IP_ADDRESS", "value": "1.2.3.4" }, { "context": "configuration/slipstream\" \"-e\" \"clientURL=https://159.100.242.202/downloads/slipstreamclient.tgz\" \"/etc/slipstream/", "end": 2677, "score": 0.999254584312439, "start": 2662, "tag": "IP_ADDRESS", "value": "159.100.242.202" } ]
cimi-tools/test/com/sixsq/slipstream/tools/cli/utils_test.clj
slipstream/SlipStreamServer
6
(ns com.sixsq.slipstream.tools.cli.utils-test (:require [clojure.set :as set] [clojure.test :refer [are deftest is]] [clojure.tools.cli :as cli] [com.sixsq.slipstream.tools.cli.ssconfig :as ss] [com.sixsq.slipstream.tools.cli.utils :as u]) (:import (java.util.regex Pattern))) (deftest check-split-credentials (are [creds expected] (= (u/split-creds creds) expected) nil [nil nil] true [nil nil] 10 [nil nil] "" ["" nil] "user:pass" ["user" "pass"])) (deftest test-modify-vals (let [resource {:ip "1.2.3.4" :url "http://1.2.3.4/uri" :dns "https://example.com" :multi {:level {:map "https://1.2.3.4/untouched"}}} modifiers [[#"1.2.3.4" "4.3.2.1"] [#"example.com" "nuv.la"]] m (u/modify-vals resource modifiers)] (is (= m {:ip "4.3.2.1" :url "http://4.3.2.1/uri" :dns "https://nuv.la" :multi {:level {:map "https://1.2.3.4/untouched"}}})))) (deftest test-->config-resource (is (= "https://example.com/api/configuration/slipstream" (u/ss-cfg-url "https://example.com")))) (deftest test-remove-attrs (is (= {} (u/remove-attrs {}))) (is (= {:foo "bar"} (u/remove-attrs {:foo "bar"}))) (is (= {:cloudServiceType "foo"} (u/remove-attrs {:cloudServiceType "foo"}))) (is (nil? (:securityGroup (u/remove-attrs {:cloudServiceType "ec2" :securityGroup "secure"})))) (is (nil? (:pdiskEndpoint (u/remove-attrs {:cloudServiceType "nuvlabox" :pdiskEndpoint "endpoint"}))))) (deftest check-resource-type-from-str (are [expected arg] (= expected (u/resource-type-from-str arg)) nil nil nil "" nil "/uuid" "my-type" "my-type/" "my-type" "my-type/uuid" "my-type" "my-type-template/" "my-type" "my-type-template/uuid")) (deftest check-resource-type (are [expected arg] (= expected (u/resource-type arg)) "my-type" "my-type/uuid" "my-type" {:id "my-type/uuid"} "my-type" {:body {:id "my-type/uuid"}} nil {:body {}})) (deftest test-->re-match-replace (let [[pattern replacement] (u/parse-replacement "a=b")] (is (= Pattern (type pattern))) (is (= "a" (str pattern))) (is (= "b" replacement)))) (deftest check-valid-options (let [args ["-e" "id=configuration/slipstream" "-e" "clientURL=https://159.100.242.202/downloads/slipstreamclient.tgz" "/etc/slipstream/slipstream.edn"]] (let [{:keys [:errors]} (cli/parse-opts args ss/cli-options)] (is (nil? errors))))) (deftest check-parse-test (let [kvs [[:k :a] [:k :b] [:k :c] [:other :d]]] (is (= {:k #{:a :b :c} :other #{:d}} (reduce (fn [m [k v]] (u/cli-parse-sets m k v)) {} kvs))))) (deftest check-mandatory-attrs ;;can only positive test cases where the provided map contains every mandatory keys ;; otherwise we would exit (is (= {:id "id"} (ss/check-mandatory-attrs {:id "id"}))) (is (= {:id "id" :k "value"} (ss/check-mandatory-attrs {:id "id" :k "value"}))))
121179
(ns com.sixsq.slipstream.tools.cli.utils-test (:require [clojure.set :as set] [clojure.test :refer [are deftest is]] [clojure.tools.cli :as cli] [com.sixsq.slipstream.tools.cli.ssconfig :as ss] [com.sixsq.slipstream.tools.cli.utils :as u]) (:import (java.util.regex Pattern))) (deftest check-split-credentials (are [creds expected] (= (u/split-creds creds) expected) nil [nil nil] true [nil nil] 10 [nil nil] "" ["" nil] "user:pass" ["user" "pass"])) (deftest test-modify-vals (let [resource {:ip "172.16.31.10" :url "http://172.16.31.10/uri" :dns "https://example.com" :multi {:level {:map "https://1.2.3.4/untouched"}}} modifiers [[#"172.16.31.10" "172.16.58.3"] [#"example.com" "nuv.la"]] m (u/modify-vals resource modifiers)] (is (= m {:ip "172.16.58.3" :url "http://172.16.58.3/uri" :dns "https://nuv.la" :multi {:level {:map "https://172.16.31.10/untouched"}}})))) (deftest test-->config-resource (is (= "https://example.com/api/configuration/slipstream" (u/ss-cfg-url "https://example.com")))) (deftest test-remove-attrs (is (= {} (u/remove-attrs {}))) (is (= {:foo "bar"} (u/remove-attrs {:foo "bar"}))) (is (= {:cloudServiceType "foo"} (u/remove-attrs {:cloudServiceType "foo"}))) (is (nil? (:securityGroup (u/remove-attrs {:cloudServiceType "ec2" :securityGroup "secure"})))) (is (nil? (:pdiskEndpoint (u/remove-attrs {:cloudServiceType "nuvlabox" :pdiskEndpoint "endpoint"}))))) (deftest check-resource-type-from-str (are [expected arg] (= expected (u/resource-type-from-str arg)) nil nil nil "" nil "/uuid" "my-type" "my-type/" "my-type" "my-type/uuid" "my-type" "my-type-template/" "my-type" "my-type-template/uuid")) (deftest check-resource-type (are [expected arg] (= expected (u/resource-type arg)) "my-type" "my-type/uuid" "my-type" {:id "my-type/uuid"} "my-type" {:body {:id "my-type/uuid"}} nil {:body {}})) (deftest test-->re-match-replace (let [[pattern replacement] (u/parse-replacement "a=b")] (is (= Pattern (type pattern))) (is (= "a" (str pattern))) (is (= "b" replacement)))) (deftest check-valid-options (let [args ["-e" "id=configuration/slipstream" "-e" "clientURL=https://172.16.58.3/downloads/slipstreamclient.tgz" "/etc/slipstream/slipstream.edn"]] (let [{:keys [:errors]} (cli/parse-opts args ss/cli-options)] (is (nil? errors))))) (deftest check-parse-test (let [kvs [[:k :a] [:k :b] [:k :c] [:other :d]]] (is (= {:k #{:a :b :c} :other #{:d}} (reduce (fn [m [k v]] (u/cli-parse-sets m k v)) {} kvs))))) (deftest check-mandatory-attrs ;;can only positive test cases where the provided map contains every mandatory keys ;; otherwise we would exit (is (= {:id "id"} (ss/check-mandatory-attrs {:id "id"}))) (is (= {:id "id" :k "value"} (ss/check-mandatory-attrs {:id "id" :k "value"}))))
true
(ns com.sixsq.slipstream.tools.cli.utils-test (:require [clojure.set :as set] [clojure.test :refer [are deftest is]] [clojure.tools.cli :as cli] [com.sixsq.slipstream.tools.cli.ssconfig :as ss] [com.sixsq.slipstream.tools.cli.utils :as u]) (:import (java.util.regex Pattern))) (deftest check-split-credentials (are [creds expected] (= (u/split-creds creds) expected) nil [nil nil] true [nil nil] 10 [nil nil] "" ["" nil] "user:pass" ["user" "pass"])) (deftest test-modify-vals (let [resource {:ip "PI:IP_ADDRESS:172.16.31.10END_PI" :url "http://PI:IP_ADDRESS:172.16.31.10END_PI/uri" :dns "https://example.com" :multi {:level {:map "https://1.2.3.4/untouched"}}} modifiers [[#"PI:IP_ADDRESS:172.16.31.10END_PI" "PI:IP_ADDRESS:172.16.58.3END_PI"] [#"example.com" "nuv.la"]] m (u/modify-vals resource modifiers)] (is (= m {:ip "PI:IP_ADDRESS:172.16.58.3END_PI" :url "http://PI:IP_ADDRESS:172.16.58.3END_PI/uri" :dns "https://nuv.la" :multi {:level {:map "https://PI:IP_ADDRESS:172.16.31.10END_PI/untouched"}}})))) (deftest test-->config-resource (is (= "https://example.com/api/configuration/slipstream" (u/ss-cfg-url "https://example.com")))) (deftest test-remove-attrs (is (= {} (u/remove-attrs {}))) (is (= {:foo "bar"} (u/remove-attrs {:foo "bar"}))) (is (= {:cloudServiceType "foo"} (u/remove-attrs {:cloudServiceType "foo"}))) (is (nil? (:securityGroup (u/remove-attrs {:cloudServiceType "ec2" :securityGroup "secure"})))) (is (nil? (:pdiskEndpoint (u/remove-attrs {:cloudServiceType "nuvlabox" :pdiskEndpoint "endpoint"}))))) (deftest check-resource-type-from-str (are [expected arg] (= expected (u/resource-type-from-str arg)) nil nil nil "" nil "/uuid" "my-type" "my-type/" "my-type" "my-type/uuid" "my-type" "my-type-template/" "my-type" "my-type-template/uuid")) (deftest check-resource-type (are [expected arg] (= expected (u/resource-type arg)) "my-type" "my-type/uuid" "my-type" {:id "my-type/uuid"} "my-type" {:body {:id "my-type/uuid"}} nil {:body {}})) (deftest test-->re-match-replace (let [[pattern replacement] (u/parse-replacement "a=b")] (is (= Pattern (type pattern))) (is (= "a" (str pattern))) (is (= "b" replacement)))) (deftest check-valid-options (let [args ["-e" "id=configuration/slipstream" "-e" "clientURL=https://PI:IP_ADDRESS:172.16.58.3END_PI/downloads/slipstreamclient.tgz" "/etc/slipstream/slipstream.edn"]] (let [{:keys [:errors]} (cli/parse-opts args ss/cli-options)] (is (nil? errors))))) (deftest check-parse-test (let [kvs [[:k :a] [:k :b] [:k :c] [:other :d]]] (is (= {:k #{:a :b :c} :other #{:d}} (reduce (fn [m [k v]] (u/cli-parse-sets m k v)) {} kvs))))) (deftest check-mandatory-attrs ;;can only positive test cases where the provided map contains every mandatory keys ;; otherwise we would exit (is (= {:id "id"} (ss/check-mandatory-attrs {:id "id"}))) (is (= {:id "id" :k "value"} (ss/check-mandatory-attrs {:id "id" :k "value"}))))
[ { "context": "; Copyright 2016 David O'Meara\n;\n; Licensed under the Apache License, Version 2.", "end": 30, "score": 0.9998475313186646, "start": 17, "tag": "NAME", "value": "David O'Meara" } ]
src-clr/core/cross_app_domain_compiler.clj
davidomeara/fnedit
0
; Copyright 2016 David O'Meara ; ; 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 core.cross-app-domain-compiler (:gen-class :name "CrossAppDomainCompiler" :main false :methods [^:static [DummyWork [] void] ^:static [Compile [] void]])) (defn pt [s] (println s) s) (defn clojure-load-path [] (if-let [load-path (System.Environment/GetEnvironmentVariable "CLOJURE_LOAD_PATH")] load-path (do (System.Environment/SetEnvironmentVariable "CLOJURE_LOAD_PATH" "") ""))) (defn add-clojure-load-paths [& paths] (let [p (apply str (interpose System.IO.Path/PathSeparator paths)) s (str (clojure-load-path) System.IO.Path/PathSeparator p)] (System.Environment/SetEnvironmentVariable "CLOJURE_LOAD_PATH" s) s)) (defn create-target-dir [dir] (try (let [path (System.IO.Path/Combine dir ".." "target")] (System.IO.Directory/CreateDirectory path) {:target-path path}) (catch Exception e {:exception (.get_Message e)}))) (defn do-compile [path top-ns {:keys [target-path exception]}] (if target-path (binding [*compile-files* true *compile-path* target-path] ; current src directory & target added to path (add-clojure-load-paths path target-path) (try (compile top-ns) (catch Exception ex (.get_Message ex)))) exception)) (defn -DummyWork [] (+ 1 1)) (defn -Compile [] (let [{:keys [path top-ns]} (.GetData (AppDomain/CurrentDomain) "data") target-result (create-target-dir path)] (->> (do-compile path top-ns target-result) (.SetData (AppDomain/CurrentDomain) "result"))))
121886
; Copyright 2016 <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 core.cross-app-domain-compiler (:gen-class :name "CrossAppDomainCompiler" :main false :methods [^:static [DummyWork [] void] ^:static [Compile [] void]])) (defn pt [s] (println s) s) (defn clojure-load-path [] (if-let [load-path (System.Environment/GetEnvironmentVariable "CLOJURE_LOAD_PATH")] load-path (do (System.Environment/SetEnvironmentVariable "CLOJURE_LOAD_PATH" "") ""))) (defn add-clojure-load-paths [& paths] (let [p (apply str (interpose System.IO.Path/PathSeparator paths)) s (str (clojure-load-path) System.IO.Path/PathSeparator p)] (System.Environment/SetEnvironmentVariable "CLOJURE_LOAD_PATH" s) s)) (defn create-target-dir [dir] (try (let [path (System.IO.Path/Combine dir ".." "target")] (System.IO.Directory/CreateDirectory path) {:target-path path}) (catch Exception e {:exception (.get_Message e)}))) (defn do-compile [path top-ns {:keys [target-path exception]}] (if target-path (binding [*compile-files* true *compile-path* target-path] ; current src directory & target added to path (add-clojure-load-paths path target-path) (try (compile top-ns) (catch Exception ex (.get_Message ex)))) exception)) (defn -DummyWork [] (+ 1 1)) (defn -Compile [] (let [{:keys [path top-ns]} (.GetData (AppDomain/CurrentDomain) "data") target-result (create-target-dir path)] (->> (do-compile path top-ns target-result) (.SetData (AppDomain/CurrentDomain) "result"))))
true
; Copyright 2016 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 core.cross-app-domain-compiler (:gen-class :name "CrossAppDomainCompiler" :main false :methods [^:static [DummyWork [] void] ^:static [Compile [] void]])) (defn pt [s] (println s) s) (defn clojure-load-path [] (if-let [load-path (System.Environment/GetEnvironmentVariable "CLOJURE_LOAD_PATH")] load-path (do (System.Environment/SetEnvironmentVariable "CLOJURE_LOAD_PATH" "") ""))) (defn add-clojure-load-paths [& paths] (let [p (apply str (interpose System.IO.Path/PathSeparator paths)) s (str (clojure-load-path) System.IO.Path/PathSeparator p)] (System.Environment/SetEnvironmentVariable "CLOJURE_LOAD_PATH" s) s)) (defn create-target-dir [dir] (try (let [path (System.IO.Path/Combine dir ".." "target")] (System.IO.Directory/CreateDirectory path) {:target-path path}) (catch Exception e {:exception (.get_Message e)}))) (defn do-compile [path top-ns {:keys [target-path exception]}] (if target-path (binding [*compile-files* true *compile-path* target-path] ; current src directory & target added to path (add-clojure-load-paths path target-path) (try (compile top-ns) (catch Exception ex (.get_Message ex)))) exception)) (defn -DummyWork [] (+ 1 1)) (defn -Compile [] (let [{:keys [path top-ns]} (.GetData (AppDomain/CurrentDomain) "data") target-result (create-target-dir path)] (->> (do-compile path top-ns target-result) (.SetData (AppDomain/CurrentDomain) "result"))))
[ { "context": ")\n :password (or (env :patavi-broker-password) \"guest\")})\n\n(def ^:const failed \"failed\")\n\n(defn- send-u", "end": 746, "score": 0.9969365000724792, "start": 741, "tag": "PASSWORD", "value": "guest" } ]
worker/src/patavi/worker/amqp.clj
DanielReid/patavi
1
(ns patavi.worker.amqp (:require [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.consumers :as lc] [langohr.basic :as lb] [langohr.exchange :as le] [cheshire.core :as json] [clojure.core.async :refer [thread >!! <!! close! chan]] [environ.core :refer [env]] [clojure.tools.logging :as log]) (:import (org.apache.http.entity.mime MultipartEntityBuilder) (org.apache.http.entity ContentType))) (defn amqp-options [] {:host (or (env :patavi-broker-host) "localhost") :username (or (env :patavi-broker-user) "guest") :password (or (env :patavi-broker-password) "guest")}) (def ^:const failed "failed") (defn- send-update! [ch id content] (lb/publish ch "rpc_status" (str id ".status") (json/generate-string {:taskId id :eventType "progress" :eventData content}) { :content-type "application/json" })) (defn- wrap-exception [fn & params] (try (apply fn params) (catch Exception e (do (log/error e) {:index (json/generate-string {:status failed :cause (.getMessage e)})})))) (defn- multipart [result] (let [builder (MultipartEntityBuilder/create) out (java.io.ByteArrayOutputStream.)] (.addBinaryBody builder "index" (.getBytes (:index result)) ContentType/APPLICATION_JSON "index.json") (doseq [file (:files result)] (.addBinaryBody builder "file" (file "content") (ContentType/create (file "mime")) (file "name"))) (let [entity (.build builder)] (.writeTo entity out) { :bytes (.toByteArray out) :content-type (.getValue (.getContentType entity)) }))) (defn- handle-request [ch handler script-file metadata msg] (let [reply-to (:reply-to metadata) task-id (:correlation-id metadata) work (chan) updater (partial send-update! ch task-id) script-payload (json/generate-string {:script (slurp script-file)})] (lb/publish ch "" reply-to script-payload { :content-type "application/json" :correlation-id task-id }) (thread (>!! work (wrap-exception handler msg updater))) (thread (let [result (<!! work)] (if (empty? (:files result)) (lb/publish ch "" reply-to (:index result) { :content-type "application/json" :correlation-id task-id }) (let [mp (multipart result)] (lb/publish ch "" reply-to (:bytes mp) { :content-type (:content-type mp) :correlation-id task-id }))) (lb/ack ch (:delivery-tag metadata)) (close! work))))) (defn- handle-incoming [handler script-file] (fn [ch metadata ^bytes payload] (try (handle-request ch handler script-file metadata (json/parse-string (String. payload))) (catch Exception e (do (log/error e) (throw (Exception. e))))))) (defn start [service script-file handler] (let [conn (rmq/connect (amqp-options)) ch (lch/open conn)] (lb/qos ch 1) (lq/declare ch service {:exclusive false :durable true :auto-delete false}) (le/declare ch "rpc_status" "topic" { :durable false }) (lc/subscribe ch service (handle-incoming handler script-file) {:auto-ack false})))
82175
(ns patavi.worker.amqp (:require [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.consumers :as lc] [langohr.basic :as lb] [langohr.exchange :as le] [cheshire.core :as json] [clojure.core.async :refer [thread >!! <!! close! chan]] [environ.core :refer [env]] [clojure.tools.logging :as log]) (:import (org.apache.http.entity.mime MultipartEntityBuilder) (org.apache.http.entity ContentType))) (defn amqp-options [] {:host (or (env :patavi-broker-host) "localhost") :username (or (env :patavi-broker-user) "guest") :password (or (env :patavi-broker-password) "<PASSWORD>")}) (def ^:const failed "failed") (defn- send-update! [ch id content] (lb/publish ch "rpc_status" (str id ".status") (json/generate-string {:taskId id :eventType "progress" :eventData content}) { :content-type "application/json" })) (defn- wrap-exception [fn & params] (try (apply fn params) (catch Exception e (do (log/error e) {:index (json/generate-string {:status failed :cause (.getMessage e)})})))) (defn- multipart [result] (let [builder (MultipartEntityBuilder/create) out (java.io.ByteArrayOutputStream.)] (.addBinaryBody builder "index" (.getBytes (:index result)) ContentType/APPLICATION_JSON "index.json") (doseq [file (:files result)] (.addBinaryBody builder "file" (file "content") (ContentType/create (file "mime")) (file "name"))) (let [entity (.build builder)] (.writeTo entity out) { :bytes (.toByteArray out) :content-type (.getValue (.getContentType entity)) }))) (defn- handle-request [ch handler script-file metadata msg] (let [reply-to (:reply-to metadata) task-id (:correlation-id metadata) work (chan) updater (partial send-update! ch task-id) script-payload (json/generate-string {:script (slurp script-file)})] (lb/publish ch "" reply-to script-payload { :content-type "application/json" :correlation-id task-id }) (thread (>!! work (wrap-exception handler msg updater))) (thread (let [result (<!! work)] (if (empty? (:files result)) (lb/publish ch "" reply-to (:index result) { :content-type "application/json" :correlation-id task-id }) (let [mp (multipart result)] (lb/publish ch "" reply-to (:bytes mp) { :content-type (:content-type mp) :correlation-id task-id }))) (lb/ack ch (:delivery-tag metadata)) (close! work))))) (defn- handle-incoming [handler script-file] (fn [ch metadata ^bytes payload] (try (handle-request ch handler script-file metadata (json/parse-string (String. payload))) (catch Exception e (do (log/error e) (throw (Exception. e))))))) (defn start [service script-file handler] (let [conn (rmq/connect (amqp-options)) ch (lch/open conn)] (lb/qos ch 1) (lq/declare ch service {:exclusive false :durable true :auto-delete false}) (le/declare ch "rpc_status" "topic" { :durable false }) (lc/subscribe ch service (handle-incoming handler script-file) {:auto-ack false})))
true
(ns patavi.worker.amqp (:require [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.consumers :as lc] [langohr.basic :as lb] [langohr.exchange :as le] [cheshire.core :as json] [clojure.core.async :refer [thread >!! <!! close! chan]] [environ.core :refer [env]] [clojure.tools.logging :as log]) (:import (org.apache.http.entity.mime MultipartEntityBuilder) (org.apache.http.entity ContentType))) (defn amqp-options [] {:host (or (env :patavi-broker-host) "localhost") :username (or (env :patavi-broker-user) "guest") :password (or (env :patavi-broker-password) "PI:PASSWORD:<PASSWORD>END_PI")}) (def ^:const failed "failed") (defn- send-update! [ch id content] (lb/publish ch "rpc_status" (str id ".status") (json/generate-string {:taskId id :eventType "progress" :eventData content}) { :content-type "application/json" })) (defn- wrap-exception [fn & params] (try (apply fn params) (catch Exception e (do (log/error e) {:index (json/generate-string {:status failed :cause (.getMessage e)})})))) (defn- multipart [result] (let [builder (MultipartEntityBuilder/create) out (java.io.ByteArrayOutputStream.)] (.addBinaryBody builder "index" (.getBytes (:index result)) ContentType/APPLICATION_JSON "index.json") (doseq [file (:files result)] (.addBinaryBody builder "file" (file "content") (ContentType/create (file "mime")) (file "name"))) (let [entity (.build builder)] (.writeTo entity out) { :bytes (.toByteArray out) :content-type (.getValue (.getContentType entity)) }))) (defn- handle-request [ch handler script-file metadata msg] (let [reply-to (:reply-to metadata) task-id (:correlation-id metadata) work (chan) updater (partial send-update! ch task-id) script-payload (json/generate-string {:script (slurp script-file)})] (lb/publish ch "" reply-to script-payload { :content-type "application/json" :correlation-id task-id }) (thread (>!! work (wrap-exception handler msg updater))) (thread (let [result (<!! work)] (if (empty? (:files result)) (lb/publish ch "" reply-to (:index result) { :content-type "application/json" :correlation-id task-id }) (let [mp (multipart result)] (lb/publish ch "" reply-to (:bytes mp) { :content-type (:content-type mp) :correlation-id task-id }))) (lb/ack ch (:delivery-tag metadata)) (close! work))))) (defn- handle-incoming [handler script-file] (fn [ch metadata ^bytes payload] (try (handle-request ch handler script-file metadata (json/parse-string (String. payload))) (catch Exception e (do (log/error e) (throw (Exception. e))))))) (defn start [service script-file handler] (let [conn (rmq/connect (amqp-options)) ch (lch/open conn)] (lb/qos ch 1) (lq/declare ch service {:exclusive false :durable true :auto-delete false}) (le/declare ch "rpc_status" "topic" { :durable false }) (lc/subscribe ch service (handle-incoming handler script-file) {:auto-ack false})))
[ { "context": "amples Satisfiability of LTL\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 115, "score": 0.9998697638511658, "start": 101, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/lwb/ltl/examples/sat.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Linear Temporal Logic: Examples Satisfiability of LTL ; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.ltl.examples.sat (:require [lwb.ltl :refer :all] ; needed for macroexpand-1 of xor etc !! [lwb.ltl.sat :refer :all] [lwb.ltl.buechi :as ba] [lwb.ltl.kripke :as ks])) ; Operators ------------------------------------------------------------------------------------------------- (def o01 '(not P)) (ba/ba o01) (sat? o01) (sat o01) (comment (ks/texify (sat o01) "ks") ) (def o02 '(and P Q)) (ba/ba o02) (sat? o02) (sat o02) (comment (ks/texify (sat o02) "ks") ) (def o03 '(or P Q)) (ba/ba o03) (sat? o03) (sat o03) (comment (ks/texify (sat o03) "ks") ) (def o04 '(impl P Q)) (ba/ba o04) (sat? o04) (sat o04) (comment (ks/texify (sat o04) "ks") ) (def o05 '(equiv P Q)) (ba/ba o05) (sat? o05) (sat o05) (comment (ks/texify (sat o05) "ks") ) (def o06 '(xor P Q)) (ba/ba o06) (sat? o06) (sat o06) (comment (ks/texify (sat o06) "ks") ) (def o07 '(ite P Q R)) (ba/ba o07) (sat? o07) (comment (ks/texify (sat o07) "ks") ) (def o08 '(always P)) (ba/ba o08) (sat? o08) (sat o08) (comment (ks/texify (sat o08) "ks") (ks/texify (sat '(always (and P Q))) "ks") ) (def o09 '(finally P)) (ba/ba o09) (sat? o09) (comment (ks/texify (sat o09) "ks") (ks/texify (sat '(finally (or P Q))) "ks") ) (def o10 '(atnext P)) (ba/ba o10) (sat? o10) (comment (ks/texify (sat o10) "ks") (ks/texify (sat '(atnext (atnext P))) "ks") ) (def o11 '(until P Q)) (ba/ba o11) (sat? o11) (comment (ks/texify (sat o11) "ks") (ks/texify (sat '(and P (until P Q))) "ks") (ks/texify (sat '(and (until P Q) (atnext P))) "ks") ) (def o12 '(release P Q)) (sat? o12) (comment (ks/texify (sat o12) "ks") ) ; Theorems -------------------------------------------------------------------------- (def t1 '(impl (always P) P)) (sat? t1) ; => true (valid? t1) ; => true (def t2 '(impl (always P) (atnext P))) (sat? t2) ; => true (valid? t2) ; => true (def t3 '(impl (always P) (finally P))) (sat? t3) ; => true (valid? t3) ; => true (def t4 '(impl (always P) (always (always P)))) (sat? t4) ; => true (valid? t4) ; => true (def t5 '(impl (atnext P) (finally P))) (sat? t5) ; => true (valid? t5) ; => true ; Typical formulas --------------------------------------------------------------------------- ; If P then finally Q (def f1 '(impl P (finally Q))) (sat? f1) ; => true (valid? f1) ; => false (comment (ks/texify (sat f1) "ks") ) ; Infinitely often P (def f2 '(always (finally P))) (sat? f2) ; => true (valid? f2) ; => false (ba/ba f2) (sat f2) (comment (ks/texify (sat f2) "ks") ) (def f3 '(always (finally (not P)))) (sat? f3) ; => true (valid? f3) ; => false (comment (ks/texify (sat f3) "ks") ) ; Finitely often (not P) (def f4 '(finally (always P))) (sat? f4) ; => true (valid? f4) ; => false (comment (ks/texify (sat f4) "ks") ) ; playing with always and atnext (def f5 '(always (and P (atnext Q)))) (sat? f5) ; => true (valid? f5) ; => false (comment (ks/texify (sat f5) "ks") ) (def f6 '(always (and (and P (not Q)) (atnext (and (not P) Q))))) (sat? f6) ; => false ; P and Q alternating (def f7 '(and P (not Q) (always (impl P (atnext (and Q (not P))))) (always (impl Q (atnext (and P (not Q))))))) (sat? f7) ; => true (valid? f7) ; => false (comment (ks/texify (sat f7) "ks") ) ; Fairness constraints ------------------------------------------------------- ; unconditional fairness (def ufair '(always (finally Q))) (sat? ufair) ; => true (valid? ufair) ; => false (ba/ba ufair) (ba/paths (ba/ba ufair)) (comment (ks/texify (sat ufair) "ks") ) ; strong fairness (def sfair '(impl (always (finally P)) (always (finally Q)))) (sat? sfair) ; => true (valid? sfair) ; => false (comment (ks/texify (sat sfair) "ks") ; not a very interesting model!! ) ; weak fairness (def wfair '(impl (finally (always P)) (always (finally Q)))) (sat? wfair) ; => true (valid? wfair) ; => false (comment (ks/texify (sat wfair) "ks") ; not a very interesting model!! ) ; fairness (def fair (list 'and ufair sfair wfair)) (sat? fair) ; => true (valid? fair) ; => false (comment (ks/texify (sat fair) "ks") ; see ufair ) ; Example in lecture notes (def lex '(until P (and Q R))) (ba/ba lex) ;=> {:nodes [{:id 1, :accepting true} {:id 0, :init true}], ; :edges [{:from 1, :to 1, :guard #{}} {:from 0, :to 0, :guard #{P}} {:from 0, :to 1, :guard #{R Q}}]} (sat lex) ;=> {:atoms #{R Q P}, :nodes {:s_1 #{R Q}}, :initial :s_1, :edges #{[:s_1 :s_1]}}
39766
; lwb Logic WorkBench -- Linear Temporal Logic: Examples Satisfiability of LTL ; Copyright (c) 2016 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.ltl.examples.sat (:require [lwb.ltl :refer :all] ; needed for macroexpand-1 of xor etc !! [lwb.ltl.sat :refer :all] [lwb.ltl.buechi :as ba] [lwb.ltl.kripke :as ks])) ; Operators ------------------------------------------------------------------------------------------------- (def o01 '(not P)) (ba/ba o01) (sat? o01) (sat o01) (comment (ks/texify (sat o01) "ks") ) (def o02 '(and P Q)) (ba/ba o02) (sat? o02) (sat o02) (comment (ks/texify (sat o02) "ks") ) (def o03 '(or P Q)) (ba/ba o03) (sat? o03) (sat o03) (comment (ks/texify (sat o03) "ks") ) (def o04 '(impl P Q)) (ba/ba o04) (sat? o04) (sat o04) (comment (ks/texify (sat o04) "ks") ) (def o05 '(equiv P Q)) (ba/ba o05) (sat? o05) (sat o05) (comment (ks/texify (sat o05) "ks") ) (def o06 '(xor P Q)) (ba/ba o06) (sat? o06) (sat o06) (comment (ks/texify (sat o06) "ks") ) (def o07 '(ite P Q R)) (ba/ba o07) (sat? o07) (comment (ks/texify (sat o07) "ks") ) (def o08 '(always P)) (ba/ba o08) (sat? o08) (sat o08) (comment (ks/texify (sat o08) "ks") (ks/texify (sat '(always (and P Q))) "ks") ) (def o09 '(finally P)) (ba/ba o09) (sat? o09) (comment (ks/texify (sat o09) "ks") (ks/texify (sat '(finally (or P Q))) "ks") ) (def o10 '(atnext P)) (ba/ba o10) (sat? o10) (comment (ks/texify (sat o10) "ks") (ks/texify (sat '(atnext (atnext P))) "ks") ) (def o11 '(until P Q)) (ba/ba o11) (sat? o11) (comment (ks/texify (sat o11) "ks") (ks/texify (sat '(and P (until P Q))) "ks") (ks/texify (sat '(and (until P Q) (atnext P))) "ks") ) (def o12 '(release P Q)) (sat? o12) (comment (ks/texify (sat o12) "ks") ) ; Theorems -------------------------------------------------------------------------- (def t1 '(impl (always P) P)) (sat? t1) ; => true (valid? t1) ; => true (def t2 '(impl (always P) (atnext P))) (sat? t2) ; => true (valid? t2) ; => true (def t3 '(impl (always P) (finally P))) (sat? t3) ; => true (valid? t3) ; => true (def t4 '(impl (always P) (always (always P)))) (sat? t4) ; => true (valid? t4) ; => true (def t5 '(impl (atnext P) (finally P))) (sat? t5) ; => true (valid? t5) ; => true ; Typical formulas --------------------------------------------------------------------------- ; If P then finally Q (def f1 '(impl P (finally Q))) (sat? f1) ; => true (valid? f1) ; => false (comment (ks/texify (sat f1) "ks") ) ; Infinitely often P (def f2 '(always (finally P))) (sat? f2) ; => true (valid? f2) ; => false (ba/ba f2) (sat f2) (comment (ks/texify (sat f2) "ks") ) (def f3 '(always (finally (not P)))) (sat? f3) ; => true (valid? f3) ; => false (comment (ks/texify (sat f3) "ks") ) ; Finitely often (not P) (def f4 '(finally (always P))) (sat? f4) ; => true (valid? f4) ; => false (comment (ks/texify (sat f4) "ks") ) ; playing with always and atnext (def f5 '(always (and P (atnext Q)))) (sat? f5) ; => true (valid? f5) ; => false (comment (ks/texify (sat f5) "ks") ) (def f6 '(always (and (and P (not Q)) (atnext (and (not P) Q))))) (sat? f6) ; => false ; P and Q alternating (def f7 '(and P (not Q) (always (impl P (atnext (and Q (not P))))) (always (impl Q (atnext (and P (not Q))))))) (sat? f7) ; => true (valid? f7) ; => false (comment (ks/texify (sat f7) "ks") ) ; Fairness constraints ------------------------------------------------------- ; unconditional fairness (def ufair '(always (finally Q))) (sat? ufair) ; => true (valid? ufair) ; => false (ba/ba ufair) (ba/paths (ba/ba ufair)) (comment (ks/texify (sat ufair) "ks") ) ; strong fairness (def sfair '(impl (always (finally P)) (always (finally Q)))) (sat? sfair) ; => true (valid? sfair) ; => false (comment (ks/texify (sat sfair) "ks") ; not a very interesting model!! ) ; weak fairness (def wfair '(impl (finally (always P)) (always (finally Q)))) (sat? wfair) ; => true (valid? wfair) ; => false (comment (ks/texify (sat wfair) "ks") ; not a very interesting model!! ) ; fairness (def fair (list 'and ufair sfair wfair)) (sat? fair) ; => true (valid? fair) ; => false (comment (ks/texify (sat fair) "ks") ; see ufair ) ; Example in lecture notes (def lex '(until P (and Q R))) (ba/ba lex) ;=> {:nodes [{:id 1, :accepting true} {:id 0, :init true}], ; :edges [{:from 1, :to 1, :guard #{}} {:from 0, :to 0, :guard #{P}} {:from 0, :to 1, :guard #{R Q}}]} (sat lex) ;=> {:atoms #{R Q P}, :nodes {:s_1 #{R Q}}, :initial :s_1, :edges #{[:s_1 :s_1]}}
true
; lwb Logic WorkBench -- Linear Temporal Logic: Examples Satisfiability of LTL ; Copyright (c) 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.ltl.examples.sat (:require [lwb.ltl :refer :all] ; needed for macroexpand-1 of xor etc !! [lwb.ltl.sat :refer :all] [lwb.ltl.buechi :as ba] [lwb.ltl.kripke :as ks])) ; Operators ------------------------------------------------------------------------------------------------- (def o01 '(not P)) (ba/ba o01) (sat? o01) (sat o01) (comment (ks/texify (sat o01) "ks") ) (def o02 '(and P Q)) (ba/ba o02) (sat? o02) (sat o02) (comment (ks/texify (sat o02) "ks") ) (def o03 '(or P Q)) (ba/ba o03) (sat? o03) (sat o03) (comment (ks/texify (sat o03) "ks") ) (def o04 '(impl P Q)) (ba/ba o04) (sat? o04) (sat o04) (comment (ks/texify (sat o04) "ks") ) (def o05 '(equiv P Q)) (ba/ba o05) (sat? o05) (sat o05) (comment (ks/texify (sat o05) "ks") ) (def o06 '(xor P Q)) (ba/ba o06) (sat? o06) (sat o06) (comment (ks/texify (sat o06) "ks") ) (def o07 '(ite P Q R)) (ba/ba o07) (sat? o07) (comment (ks/texify (sat o07) "ks") ) (def o08 '(always P)) (ba/ba o08) (sat? o08) (sat o08) (comment (ks/texify (sat o08) "ks") (ks/texify (sat '(always (and P Q))) "ks") ) (def o09 '(finally P)) (ba/ba o09) (sat? o09) (comment (ks/texify (sat o09) "ks") (ks/texify (sat '(finally (or P Q))) "ks") ) (def o10 '(atnext P)) (ba/ba o10) (sat? o10) (comment (ks/texify (sat o10) "ks") (ks/texify (sat '(atnext (atnext P))) "ks") ) (def o11 '(until P Q)) (ba/ba o11) (sat? o11) (comment (ks/texify (sat o11) "ks") (ks/texify (sat '(and P (until P Q))) "ks") (ks/texify (sat '(and (until P Q) (atnext P))) "ks") ) (def o12 '(release P Q)) (sat? o12) (comment (ks/texify (sat o12) "ks") ) ; Theorems -------------------------------------------------------------------------- (def t1 '(impl (always P) P)) (sat? t1) ; => true (valid? t1) ; => true (def t2 '(impl (always P) (atnext P))) (sat? t2) ; => true (valid? t2) ; => true (def t3 '(impl (always P) (finally P))) (sat? t3) ; => true (valid? t3) ; => true (def t4 '(impl (always P) (always (always P)))) (sat? t4) ; => true (valid? t4) ; => true (def t5 '(impl (atnext P) (finally P))) (sat? t5) ; => true (valid? t5) ; => true ; Typical formulas --------------------------------------------------------------------------- ; If P then finally Q (def f1 '(impl P (finally Q))) (sat? f1) ; => true (valid? f1) ; => false (comment (ks/texify (sat f1) "ks") ) ; Infinitely often P (def f2 '(always (finally P))) (sat? f2) ; => true (valid? f2) ; => false (ba/ba f2) (sat f2) (comment (ks/texify (sat f2) "ks") ) (def f3 '(always (finally (not P)))) (sat? f3) ; => true (valid? f3) ; => false (comment (ks/texify (sat f3) "ks") ) ; Finitely often (not P) (def f4 '(finally (always P))) (sat? f4) ; => true (valid? f4) ; => false (comment (ks/texify (sat f4) "ks") ) ; playing with always and atnext (def f5 '(always (and P (atnext Q)))) (sat? f5) ; => true (valid? f5) ; => false (comment (ks/texify (sat f5) "ks") ) (def f6 '(always (and (and P (not Q)) (atnext (and (not P) Q))))) (sat? f6) ; => false ; P and Q alternating (def f7 '(and P (not Q) (always (impl P (atnext (and Q (not P))))) (always (impl Q (atnext (and P (not Q))))))) (sat? f7) ; => true (valid? f7) ; => false (comment (ks/texify (sat f7) "ks") ) ; Fairness constraints ------------------------------------------------------- ; unconditional fairness (def ufair '(always (finally Q))) (sat? ufair) ; => true (valid? ufair) ; => false (ba/ba ufair) (ba/paths (ba/ba ufair)) (comment (ks/texify (sat ufair) "ks") ) ; strong fairness (def sfair '(impl (always (finally P)) (always (finally Q)))) (sat? sfair) ; => true (valid? sfair) ; => false (comment (ks/texify (sat sfair) "ks") ; not a very interesting model!! ) ; weak fairness (def wfair '(impl (finally (always P)) (always (finally Q)))) (sat? wfair) ; => true (valid? wfair) ; => false (comment (ks/texify (sat wfair) "ks") ; not a very interesting model!! ) ; fairness (def fair (list 'and ufair sfair wfair)) (sat? fair) ; => true (valid? fair) ; => false (comment (ks/texify (sat fair) "ks") ; see ufair ) ; Example in lecture notes (def lex '(until P (and Q R))) (ba/ba lex) ;=> {:nodes [{:id 1, :accepting true} {:id 0, :init true}], ; :edges [{:from 1, :to 1, :guard #{}} {:from 0, :to 0, :guard #{P}} {:from 0, :to 1, :guard #{R Q}}]} (sat lex) ;=> {:atoms #{R Q P}, :nodes {:s_1 #{R Q}}, :initial :s_1, :edges #{[:s_1 :s_1]}}
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 30, "score": 0.999849259853363, "start": 19, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n; Author: Stuart Halloway\n\n(ns clojure.test-clojure.rt\n (:require clojure.", "end": 490, "score": 0.9998815655708313, "start": 475, "tag": "NAME", "value": "Stuart Halloway" } ]
Clojure/clojure/test_clojure/rt.clj
AydarLukmanov/ArcadiaGodot
123
; 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. ; Author: Stuart Halloway (ns clojure.test-clojure.rt (:require clojure.set) (:use clojure.test clojure.test-helper)) (defn bare-rt-print "Return string RT would print prior to print-initialize" [x] (with-out-str (try (push-thread-bindings {#'clojure.core/print-initialized false}) (clojure.lang.RT/print x *out*) (finally (pop-thread-bindings))))) (deftest rt-print-prior-to-print-initialize (testing "pattern literals" (is (= "#\"foo\"" (bare-rt-print #"foo"))))) (deftest error-messages (testing "binding a core var that already refers to something" (should-print-err-message #"WARNING: prefers already refers to: #'clojure.core/prefers in namespace: .*\r?\n" (defn prefers [] (throw (Exception. "rebound!"))))) ;;; RuntimeException (testing "reflection cannot resolve field" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - reference to field/property blah can't be resolved \(target class is unknown\).\r?\n" (defn foo [x] (.blah x)))) (testing "reflection cannot resolve instance method on known class" ;;; TODO: Figure out why the regexes don't match in these two tests. They look identical to me. (should-print-err-message #"Reflection warning, .*:\d+:\d+ - reference to field/property blah on System\.String can't be resolved\.\r?\n" (defn foo [^String x] (.blah x)))) (testing "reflection cannot resolve instance method because it is missing" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method zap on System\.String can't be resolved \(no such method\)\.\r?\n" (defn foo [^String x] (.zap x 1)))) (testing "reflection cannot resolve instance method because it has incompatible argument types" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System\.String can't be resolved \(argument types: System\.Double, clojure\.lang\.Symbol\)\.\r?\n" (defn foo [^String x] (.IndexOf x 12.1 'a)))) (testing "reflection cannot resolve instance method because it has unknown argument types" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System\.String can't be resolved \(argument types: unknown\)\.\r?\n" (defn foo [^String x y] (.IndexOf x y)))) (testing "reflection error prints correctly for nil arguments" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System.String can't be resolved \(argument types: unknown, unknown\)\.\r?\n" ;;; divide on java\.math\.BigDecimal (defn foo [a] (.IndexOf "abc" a nil)))) ;;; .(.Divide 1M a nil) -- we don't have an overload on this (testing "reflection cannot resolve instance method because target class is unknown" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method zap can't be resolved \(target class is unknown\)\.\r?\n" (defn foo [x] (.zap x 1)))) (testing "reflection cannot resolve static method" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to static method Format on System\.String can't be resolved \(argument types: System\.Text\.RegularExpressions\.Regex, System\.Int64\)\.\r?\n" (defn foo [] (String/Format #"boom" 12)))) ;;; (defn foo [] (Integer/valueOf #"boom")))) (testing "reflection cannot resolved constructor" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to System\.String ctor can't be resolved.\r?\n" ;;; java.lang.String (defn foo [] (String. 1 2 3))))) (def example-var) (deftest binding-root-clears-macro-metadata (alter-meta! #'example-var assoc :macro true) (is (contains? (meta #'example-var) :macro)) (.bindRoot #'example-var 0) (is (not (contains? (meta #'example-var) :macro)))) (deftest last-var-wins-for-core (testing "you can replace a core name, with warning" (let [ns (temp-ns) replacement (gensym)] (with-err-string-writer (intern ns 'prefers replacement)) (is (= replacement @('prefers (ns-publics ns)))))) (testing "you can replace a name you defined before" (let [ns (temp-ns) s (gensym) v1 (intern ns 'foo s) v2 (intern ns 'bar s)] (with-err-string-writer (.refer ns 'flatten v1)) (.refer ns 'flatten v2) (is (= v2 (ns-resolve ns 'flatten))))) (testing "you cannot intern over an existing non-core name" (let [ns (temp-ns 'clojure.set) replacement (gensym)] (is (thrown? InvalidOperationException ;;; IllegalStateException (intern ns 'subset? replacement))) (is (nil? ('subset? (ns-publics ns)))) (is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))) (testing "you cannot refer over an existing non-core name" (let [ns (temp-ns 'clojure.set) replacement (gensym)] (is (thrown? InvalidOperationException ;;; IllegalStateException (.refer ns 'subset? #'clojure.set/intersection))) (is (nil? ('subset? (ns-publics ns)))) (is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))))
64012
; 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. ; Author: <NAME> (ns clojure.test-clojure.rt (:require clojure.set) (:use clojure.test clojure.test-helper)) (defn bare-rt-print "Return string RT would print prior to print-initialize" [x] (with-out-str (try (push-thread-bindings {#'clojure.core/print-initialized false}) (clojure.lang.RT/print x *out*) (finally (pop-thread-bindings))))) (deftest rt-print-prior-to-print-initialize (testing "pattern literals" (is (= "#\"foo\"" (bare-rt-print #"foo"))))) (deftest error-messages (testing "binding a core var that already refers to something" (should-print-err-message #"WARNING: prefers already refers to: #'clojure.core/prefers in namespace: .*\r?\n" (defn prefers [] (throw (Exception. "rebound!"))))) ;;; RuntimeException (testing "reflection cannot resolve field" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - reference to field/property blah can't be resolved \(target class is unknown\).\r?\n" (defn foo [x] (.blah x)))) (testing "reflection cannot resolve instance method on known class" ;;; TODO: Figure out why the regexes don't match in these two tests. They look identical to me. (should-print-err-message #"Reflection warning, .*:\d+:\d+ - reference to field/property blah on System\.String can't be resolved\.\r?\n" (defn foo [^String x] (.blah x)))) (testing "reflection cannot resolve instance method because it is missing" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method zap on System\.String can't be resolved \(no such method\)\.\r?\n" (defn foo [^String x] (.zap x 1)))) (testing "reflection cannot resolve instance method because it has incompatible argument types" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System\.String can't be resolved \(argument types: System\.Double, clojure\.lang\.Symbol\)\.\r?\n" (defn foo [^String x] (.IndexOf x 12.1 'a)))) (testing "reflection cannot resolve instance method because it has unknown argument types" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System\.String can't be resolved \(argument types: unknown\)\.\r?\n" (defn foo [^String x y] (.IndexOf x y)))) (testing "reflection error prints correctly for nil arguments" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System.String can't be resolved \(argument types: unknown, unknown\)\.\r?\n" ;;; divide on java\.math\.BigDecimal (defn foo [a] (.IndexOf "abc" a nil)))) ;;; .(.Divide 1M a nil) -- we don't have an overload on this (testing "reflection cannot resolve instance method because target class is unknown" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method zap can't be resolved \(target class is unknown\)\.\r?\n" (defn foo [x] (.zap x 1)))) (testing "reflection cannot resolve static method" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to static method Format on System\.String can't be resolved \(argument types: System\.Text\.RegularExpressions\.Regex, System\.Int64\)\.\r?\n" (defn foo [] (String/Format #"boom" 12)))) ;;; (defn foo [] (Integer/valueOf #"boom")))) (testing "reflection cannot resolved constructor" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to System\.String ctor can't be resolved.\r?\n" ;;; java.lang.String (defn foo [] (String. 1 2 3))))) (def example-var) (deftest binding-root-clears-macro-metadata (alter-meta! #'example-var assoc :macro true) (is (contains? (meta #'example-var) :macro)) (.bindRoot #'example-var 0) (is (not (contains? (meta #'example-var) :macro)))) (deftest last-var-wins-for-core (testing "you can replace a core name, with warning" (let [ns (temp-ns) replacement (gensym)] (with-err-string-writer (intern ns 'prefers replacement)) (is (= replacement @('prefers (ns-publics ns)))))) (testing "you can replace a name you defined before" (let [ns (temp-ns) s (gensym) v1 (intern ns 'foo s) v2 (intern ns 'bar s)] (with-err-string-writer (.refer ns 'flatten v1)) (.refer ns 'flatten v2) (is (= v2 (ns-resolve ns 'flatten))))) (testing "you cannot intern over an existing non-core name" (let [ns (temp-ns 'clojure.set) replacement (gensym)] (is (thrown? InvalidOperationException ;;; IllegalStateException (intern ns 'subset? replacement))) (is (nil? ('subset? (ns-publics ns)))) (is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))) (testing "you cannot refer over an existing non-core name" (let [ns (temp-ns 'clojure.set) replacement (gensym)] (is (thrown? InvalidOperationException ;;; IllegalStateException (.refer ns 'subset? #'clojure.set/intersection))) (is (nil? ('subset? (ns-publics ns)))) (is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))))
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. ; Author: PI:NAME:<NAME>END_PI (ns clojure.test-clojure.rt (:require clojure.set) (:use clojure.test clojure.test-helper)) (defn bare-rt-print "Return string RT would print prior to print-initialize" [x] (with-out-str (try (push-thread-bindings {#'clojure.core/print-initialized false}) (clojure.lang.RT/print x *out*) (finally (pop-thread-bindings))))) (deftest rt-print-prior-to-print-initialize (testing "pattern literals" (is (= "#\"foo\"" (bare-rt-print #"foo"))))) (deftest error-messages (testing "binding a core var that already refers to something" (should-print-err-message #"WARNING: prefers already refers to: #'clojure.core/prefers in namespace: .*\r?\n" (defn prefers [] (throw (Exception. "rebound!"))))) ;;; RuntimeException (testing "reflection cannot resolve field" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - reference to field/property blah can't be resolved \(target class is unknown\).\r?\n" (defn foo [x] (.blah x)))) (testing "reflection cannot resolve instance method on known class" ;;; TODO: Figure out why the regexes don't match in these two tests. They look identical to me. (should-print-err-message #"Reflection warning, .*:\d+:\d+ - reference to field/property blah on System\.String can't be resolved\.\r?\n" (defn foo [^String x] (.blah x)))) (testing "reflection cannot resolve instance method because it is missing" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method zap on System\.String can't be resolved \(no such method\)\.\r?\n" (defn foo [^String x] (.zap x 1)))) (testing "reflection cannot resolve instance method because it has incompatible argument types" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System\.String can't be resolved \(argument types: System\.Double, clojure\.lang\.Symbol\)\.\r?\n" (defn foo [^String x] (.IndexOf x 12.1 'a)))) (testing "reflection cannot resolve instance method because it has unknown argument types" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System\.String can't be resolved \(argument types: unknown\)\.\r?\n" (defn foo [^String x y] (.IndexOf x y)))) (testing "reflection error prints correctly for nil arguments" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method IndexOf on System.String can't be resolved \(argument types: unknown, unknown\)\.\r?\n" ;;; divide on java\.math\.BigDecimal (defn foo [a] (.IndexOf "abc" a nil)))) ;;; .(.Divide 1M a nil) -- we don't have an overload on this (testing "reflection cannot resolve instance method because target class is unknown" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to method zap can't be resolved \(target class is unknown\)\.\r?\n" (defn foo [x] (.zap x 1)))) (testing "reflection cannot resolve static method" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to static method Format on System\.String can't be resolved \(argument types: System\.Text\.RegularExpressions\.Regex, System\.Int64\)\.\r?\n" (defn foo [] (String/Format #"boom" 12)))) ;;; (defn foo [] (Integer/valueOf #"boom")))) (testing "reflection cannot resolved constructor" (should-print-err-message #"Reflection warning, .*:\d+:\d+ - call to System\.String ctor can't be resolved.\r?\n" ;;; java.lang.String (defn foo [] (String. 1 2 3))))) (def example-var) (deftest binding-root-clears-macro-metadata (alter-meta! #'example-var assoc :macro true) (is (contains? (meta #'example-var) :macro)) (.bindRoot #'example-var 0) (is (not (contains? (meta #'example-var) :macro)))) (deftest last-var-wins-for-core (testing "you can replace a core name, with warning" (let [ns (temp-ns) replacement (gensym)] (with-err-string-writer (intern ns 'prefers replacement)) (is (= replacement @('prefers (ns-publics ns)))))) (testing "you can replace a name you defined before" (let [ns (temp-ns) s (gensym) v1 (intern ns 'foo s) v2 (intern ns 'bar s)] (with-err-string-writer (.refer ns 'flatten v1)) (.refer ns 'flatten v2) (is (= v2 (ns-resolve ns 'flatten))))) (testing "you cannot intern over an existing non-core name" (let [ns (temp-ns 'clojure.set) replacement (gensym)] (is (thrown? InvalidOperationException ;;; IllegalStateException (intern ns 'subset? replacement))) (is (nil? ('subset? (ns-publics ns)))) (is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))) (testing "you cannot refer over an existing non-core name" (let [ns (temp-ns 'clojure.set) replacement (gensym)] (is (thrown? InvalidOperationException ;;; IllegalStateException (.refer ns 'subset? #'clojure.set/intersection))) (is (nil? ('subset? (ns-publics ns)))) (is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))))
[ { "context": "graal-bin \"/home/user/Downloads/graalvm-ce-java11-19.3.0.2\"\n :opts [\"--verbose\"\n ", "end": 321, "score": 0.7913398742675781, "start": 313, "tag": "IP_ADDRESS", "value": "19.3.0.2" } ]
project.clj
victorb/cljfx-graalvm
1
(defproject cljfx-graalvm "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.10.1-patch_38bafca9_clj_1472_3"] [cljfx "1.6.1"]] :plugins [[io.taylorwood/lein-native-image "0.3.1"]] :native-image {:name "cljfx-graalvm" :graal-bin "/home/user/Downloads/graalvm-ce-java11-19.3.0.2" :opts ["--verbose" "--report-unsupported-elements-at-runtime" "--initialize-at-build-time" "-H:+ReportExceptionStackTraces" "-H:+TraceClassInitialization" "--no-server" "--no-fallback"]} :main ^:skip-aot cljfx-graalvm.core :target-path "target/%s" :profiles {:uberjar {:aot :all :injections [(javafx.application.Platform/exit)]}})
19592
(defproject cljfx-graalvm "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.10.1-patch_38bafca9_clj_1472_3"] [cljfx "1.6.1"]] :plugins [[io.taylorwood/lein-native-image "0.3.1"]] :native-image {:name "cljfx-graalvm" :graal-bin "/home/user/Downloads/graalvm-ce-java11-172.16.58.3" :opts ["--verbose" "--report-unsupported-elements-at-runtime" "--initialize-at-build-time" "-H:+ReportExceptionStackTraces" "-H:+TraceClassInitialization" "--no-server" "--no-fallback"]} :main ^:skip-aot cljfx-graalvm.core :target-path "target/%s" :profiles {:uberjar {:aot :all :injections [(javafx.application.Platform/exit)]}})
true
(defproject cljfx-graalvm "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.10.1-patch_38bafca9_clj_1472_3"] [cljfx "1.6.1"]] :plugins [[io.taylorwood/lein-native-image "0.3.1"]] :native-image {:name "cljfx-graalvm" :graal-bin "/home/user/Downloads/graalvm-ce-java11-PI:IP_ADDRESS:172.16.58.3END_PI" :opts ["--verbose" "--report-unsupported-elements-at-runtime" "--initialize-at-build-time" "-H:+ReportExceptionStackTraces" "-H:+TraceClassInitialization" "--no-server" "--no-fallback"]} :main ^:skip-aot cljfx-graalvm.core :target-path "target/%s" :profiles {:uberjar {:aot :all :injections [(javafx.application.Platform/exit)]}})
[ { "context": "-url \"https://redcap.example.com/api/\"\n :token \"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456\"})\n\n(defn init []\n (println \"Running sample init", "end": 225, "score": 0.9962389469146729, "start": 193, "tag": "KEY", "value": "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456" } ]
dev/user.clj
bmds-researchsoftware/clj-redcap
0
(ns user (:require [clojure.string :as str] [clojure.pprint :refer (pprint)] [mvt-clj.tools :refer [refresh]])) (def config {:api-url "https://redcap.example.com/api/" :token "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"}) (defn init [] (println "Running sample init")) (defn reset [] (refresh :after 'user/init))
22691
(ns user (:require [clojure.string :as str] [clojure.pprint :refer (pprint)] [mvt-clj.tools :refer [refresh]])) (def config {:api-url "https://redcap.example.com/api/" :token "<KEY>"}) (defn init [] (println "Running sample init")) (defn reset [] (refresh :after 'user/init))
true
(ns user (:require [clojure.string :as str] [clojure.pprint :refer (pprint)] [mvt-clj.tools :refer [refresh]])) (def config {:api-url "https://redcap.example.com/api/" :token "PI:KEY:<KEY>END_PI"}) (defn init [] (println "Running sample init")) (defn reset [] (refresh :after 'user/init))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998119473457336, "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.9998112916946411, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/dynamo/graph.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 dynamo.graph "Main api for graph and node" (:refer-clojure :exclude [deftype constantly]) (:require [clojure.tools.macro :as ctm] [cognitect.transit :as transit] [internal.cache :as c] [internal.graph :as ig] [internal.graph.types :as gt] [internal.low-memory :as low-memory] [internal.node :as in] [internal.system :as is] [internal.transaction :as it] [internal.util :as util] [potemkin.namespaces :as namespaces] [schema.core :as s]) (:import [internal.graph.error_values ErrorValue] [java.io ByteArrayInputStream ByteArrayOutputStream])) (set! *warn-on-reflection* true) (namespaces/import-vars [internal.graph.types node-id->graph-id node->graph-id sources targets connected? dependencies Node node-id node-id? produce-value node-by-id-at]) (namespaces/import-vars [internal.graph.error-values ->error error-aggregate error-fatal error-fatal? error-info error-info? error-message error-package? error-warning error-warning? error? flatten-errors map->error package-errors precluding-errors unpack-errors worse-than]) (namespaces/import-vars [internal.node value-type-schema value-type? isa-node-type? value-type-dispatch-value has-input? has-output? has-property? type-compatible? merge-display-order NodeType supertypes declared-properties declared-property-labels declared-inputs declared-outputs cached-outputs input-dependencies input-cardinality cascade-deletes substitute-for input-type output-type input-labels output-labels property-display-order]) (namespaces/import-vars [internal.graph arc node-ids pre-traverse]) (let [graph-id ^java.util.concurrent.atomic.AtomicInteger (java.util.concurrent.atomic.AtomicInteger. 0)] (defn next-graph-id [] (.getAndIncrement graph-id))) ;; --------------------------------------------------------------------------- ;; State handling ;; --------------------------------------------------------------------------- ;; Only marked dynamic so tests can rebind. Should never be rebound "for real". (defonce ^:dynamic *the-system* (atom nil)) (def ^:dynamic *tps-debug* nil) (defn now "The basis at the current point in time" [] (is/basis @*the-system*)) (defn clone-system ([] (clone-system @*the-system*)) ([sys] (is/clone-system sys))) (defn system= [s1 s2] (is/system= s1 s2)) (defmacro with-system [sys & body] `(binding [*the-system* (atom ~sys)] ~@body)) (defn node-by-id "Returns a node given its id. If the basis is provided, it returns the value of the node using that basis. Otherwise, it uses the current basis." ([node-id] (let [graph-id (node-id->graph-id node-id)] (ig/node-id->node (is/graph @*the-system* graph-id) node-id))) ([basis node-id] (gt/node-by-id-at basis node-id))) (defn node-type* "Return the node-type given a node-id. Uses the current basis if not provided." ([node-id] (node-type* (now) node-id)) ([basis node-id] (when-let [n (gt/node-by-id-at basis node-id)] (gt/node-type n basis)))) (defn node-type "Return the node-type given a node. Uses the current basis if not provided." ([node] (node-type (now) node)) ([basis node] (when node (gt/node-type node basis)))) (defn cache "The system cache of node values" [] (is/system-cache @*the-system*)) (defn clear-system-cache! "Clears a cache (default *the-system* cache), useful when debugging" ([] (clear-system-cache! *the-system*)) ([sys-atom] (swap! sys-atom assoc :cache (is/make-cache {})) nil) ([sys-atom node-id] (let [outputs (cached-outputs (node-type* node-id)) entries (map (partial vector node-id) outputs)] (swap! sys-atom update :cache c/cache-invalidate entries) nil))) (defn graph "Given a graph id, returns the particular graph in the system at the current point in time" [graph-id] (is/graph @*the-system* graph-id)) (when *tps-debug* (def tps-counter (agent (long-array 3 0))) (defn tick [^longs tps-counts now] (let [last-report-time (aget tps-counts 1) transaction-count (inc (aget tps-counts 0))] (aset-long tps-counts 0 transaction-count) (when (> now (+ last-report-time 1000000000)) (let [elapsed-time (/ (- now last-report-time) 1000000000.00)] (do (println "TPS" (/ transaction-count elapsed-time)))) (aset-long tps-counts 1 now) (aset-long tps-counts 0 0))) tps-counts)) (defn transact "Provides a way to run a transaction against the graph system. It takes a list of transaction steps. Example: (g/transact [(g/connect n1 output-name n :xs) (g/connect n2 output-name n :xs)]) It returns the transaction result, (tx-result), which is a map containing keys about the transaction. Transaction result-keys: `[:status :basis :graphs-modified :nodes-added :nodes-modified :nodes-deleted :outputs-modified :label :sequence-label]` " [txs] (when *tps-debug* (send-off tps-counter tick (System/nanoTime))) (let [basis (is/basis @*the-system*) id-generators (is/id-generators @*the-system*) override-id-generator (is/override-id-generator @*the-system*) tx-result (it/transact* (it/new-transaction-context basis id-generators override-id-generator) txs)] (when (= :ok (:status tx-result)) (swap! *the-system* is/merge-graphs (get-in tx-result [:basis :graphs]) (:graphs-modified tx-result) (:outputs-modified tx-result) (:nodes-deleted tx-result))) tx-result)) ;; --------------------------------------------------------------------------- ;; Using transaction data ;; --------------------------------------------------------------------------- (defn tx-data-nodes-added "Returns a list of the node-ids added given a list of transaction steps, (tx-data)." [txs] (keep (fn [tx-data] (case (:type tx-data) :create-node (-> tx-data :node :_node-id) nil)) (flatten txs))) ;; --------------------------------------------------------------------------- ;; Using transaction values ;; --------------------------------------------------------------------------- (defn tx-nodes-added "Returns a list of the node-ids added given a result from a transaction, (tx-result)." [transaction] (:nodes-added transaction)) (defn is-modified? "Returns a boolean if a node, or node and output, was modified as a result of a transaction given a tx-result." ([transaction node-id] (boolean (contains? (:outputs-modified transaction) node-id))) ([transaction node-id output] (boolean (get-in transaction [:outputs-modified node-id output])))) (defn is-added? "Returns a boolean if a node was added as a result of a transaction given a tx-result and node." [transaction node-id] (contains? (:nodes-added transaction) node-id)) (defn is-deleted? "Returns a boolean if a node was delete as a result of a transaction given a tx-result and node." [transaction node-id] (contains? (:nodes-deleted transaction) node-id)) (defn outputs-modified "Returns the pairs of node-id and label of the outputs that were modified for a node as the result of a transaction given a tx-result and node" [transaction node-id] (get-in transaction [:outputs-modified node-id])) (defn transaction-basis "Returns the final basis from the result of a transaction given a tx-result" [transaction] (:basis transaction)) (defn pre-transaction-basis "Returns the original, starting basis from the result of a transaction given a tx-result" [transaction] (:original-basis transaction)) ;; --------------------------------------------------------------------------- ;; Intrinsics ;; --------------------------------------------------------------------------- (defn strip-alias "If the list ends with :as _something_, return _something_ and the list without the last two elements" [argv] (if (and (<= 2 (count argv)) (= :as (nth argv (- (count argv) 2)))) [(last argv) (take (- (count argv) 2) argv)] [nil argv])) (defmacro fnk [argv & tail] (let [param (gensym "m") [alias argv] (strip-alias (vec argv)) kargv (mapv keyword argv) arglist (interleave argv (map #(list `get param %) kargv))] (if alias `(with-meta (fn [~param] (let [~alias (select-keys ~param ~kargv) ~@(vec arglist)] ~@tail)) {:arguments (quote ~kargv)}) `(with-meta (fn [~param] (let ~(vec arglist) ~@tail)) {:arguments (quote ~kargv)})))) (defmacro defnk [symb & body] (let [[name args] (ctm/name-with-attributes symb body)] (assert (symbol? name) (str "Name for defnk is not a symbol:" name)) `(def ~name (fnk ~@args)))) (defmacro constantly [v] `(let [ret# ~v] (dynamo.graph/fnk [] ret#))) (defmacro deftype [symb & body] (let [fully-qualified-node-type-symbol (symbol (str *ns*) (str symb)) key (keyword fully-qualified-node-type-symbol)] `(do (in/register-value-type '~fully-qualified-node-type-symbol ~key) (def ~symb (in/register-value-type ~key (in/make-value-type '~symb ~key ~@body)))))) (deftype Any s/Any) (deftype Bool s/Bool) (deftype Str String) (deftype Int s/Int) (deftype Num s/Num) (deftype NodeID s/Int) (deftype Keyword s/Keyword) (deftype KeywordMap {s/Keyword s/Any}) (deftype IdPair [(s/one s/Str "id") (s/one s/Int "node-id")]) (deftype Dict {s/Str s/Int}) (deftype Properties {:properties {s/Keyword {:node-id s/Int (s/optional-key :validation-problems) s/Any :value s/Any ; Can be property value or ErrorValue :type s/Any s/Keyword s/Any}} (s/optional-key :node-id) s/Int (s/optional-key :display-order) [(s/conditional vector? [(s/one String "category") s/Keyword] keyword? s/Keyword)]}) (deftype Err ErrorValue) ;; --------------------------------------------------------------------------- ;; Definition ;; --------------------------------------------------------------------------- (defn construct "Creates an instance of a node. The node type must have been previously defined via `defnode`. The node's properties will all have their default values. The caller may pass key/value pairs to override properties. A node that has been constructed is not connected to anything and it doesn't exist in any graph yet. Example: (defnode GravityModifier (property acceleration Int (default 32)) (construct GravityModifier :acceleration 16)" [node-type-ref & {:as args}] (in/construct node-type-ref args)) (defmacro defnode "Given a name and a specification of behaviors, creates a node, and attendant functions. Allowed clauses are: (inherits _symbol_) Compose the behavior from the named node type (input _symbol_ _schema_ [:array]?) Define an input with the name, whose values must match the schema. If the :array flag is present, then this input can have multiple outputs connected to it. Without the :array flag, this input can only have one incoming connection from an output. (property _symbol_ _property-type_ & _options_) Define a property with schema and, possibly, default value and constraints. Property options include the following: (default _value_) Set a default value for the property. If no default is set, then the property will be nil. (value _getter_) Define a custom getter. It must be an fnk. The fnk's arguments are magically wired the same as an output producer. (dynamic _label_ _evaluator_) Define a dynamic attribute of the property. The label is a symbol. The evaluator is an fnk like the getter. (set (fn [evaluation-context self old-value new-value])) Define a custom setter. This is _not_ an fnk, but a strict function of 4 arguments. (output _symbol_ _type_ (:cached)? _producer_) Define an output to produce values of type. The ':cached' flag is optional. _producer_ may be a var that names an fn, or fnk. It may also be a function tail as [arglist] + forms. Values produced on an output with the :cached flag will be cached in memory until the node is affected by some change in inputs or properties. At that time, the cached value will be sent for disposal. Example (from [[editors.atlas]]): (defnode TextureCompiler (input textureset TextureSet) (property texture-filename Str (default \"\")) (output texturec Any compile-texturec))) (defnode TextureSetCompiler (input textureset TextureSet) (property textureset-filename Str (default \"\")) (output texturesetc Any compile-texturesetc))) (defnode AtlasCompiler (inherit TextureCompiler) (inherit TextureSetCompiler)) This will produce a record `AtlasCompiler`. `defnode` merges the behaviors appropriately. A node may also implement protocols or interfaces, using a syntax identical to `deftype` or `defrecord`. A node may implement any number of such protocols. Every node always implements dynamo.graph/Node." [symb & body] (let [[symb forms] (ctm/name-with-attributes symb body) fully-qualified-node-type-symbol (symbol (str *ns*) (str symb)) node-type-def (in/process-node-type-forms fully-qualified-node-type-symbol forms) fn-paths (in/extract-def-fns node-type-def) fn-defs (for [[path func] fn-paths] (list `def (in/dollar-name symb path) func)) node-type-def (util/update-paths node-type-def fn-paths (fn [path func curr] (assoc curr :fn (list `var (in/dollar-name symb path))))) node-key (:key node-type-def) derivations (for [tref (:supertypes node-type-def)] `(when-not (contains? (descendants ~(:key (deref tref))) ~node-key) (derive ~node-key ~(:key (deref tref))))) node-type-def (update node-type-def :supertypes #(list `quote %)) runtime-definer (symbol (str symb "*")) ;; TODO - investigate if we even need to register these types ;; in release builds, since we don't do schema checking? type-regs (for [[key-form value-type-form] (:register-type-info node-type-def)] `(in/register-value-type ~key-form ~value-type-form)) node-type-def (dissoc node-type-def :register-type-info)] `(do ~@type-regs ~@fn-defs (defn ~runtime-definer [] ~node-type-def) (def ~symb (in/register-node-type ~node-key (in/map->NodeTypeImpl (~runtime-definer)))) ~@derivations))) ;; --------------------------------------------------------------------------- ;; Transactions ;; --------------------------------------------------------------------------- (defmacro make-nodes "Create a number of nodes in a graph, binding them to local names to wire up connections. The resulting code will return a collection of transaction steps, including the steps to construct nodes from the bindings. If the right side of the binding is a node type, it is used directly. If it is a vector, it is treated as a node type followed by initial property values. Example: (make-nodes view [render AtlasRender scene scene/SceneRenderer background background/Gradient camera [c/CameraController :camera (c/make-orthographic)]] (g/connect background :renderable scene :renderables) (g/connect atlas-render :renderable scene :renderables))" [graph-id binding-expr & body-exprs] (assert (vector? binding-expr) "make-nodes requires a vector for its binding") (assert (even? (count binding-expr)) "make-nodes requires an even number of forms in binding vector") (let [locals (take-nth 2 binding-expr) ctors (take-nth 2 (next binding-expr)) ids (repeat (count locals) `(internal.system/next-node-id @*the-system* ~graph-id))] `(let [~@(interleave locals ids)] (concat ~@(map (fn [ctor id] (list `it/new-node (if (sequential? ctor) (if (= 2 (count ctor)) `(apply construct ~(first ctor) :_node-id ~id (mapcat identity ~(second ctor))) `(construct ~@ctor :_node-id ~id)) `(construct ~ctor :_node-id ~id)))) ctors locals) ~@body-exprs)))) (defn operation-label "Set a human-readable label to describe the current transaction." [label] (it/label label)) (defn operation-sequence "Set a machine-readable label. Successive transactions with the same label will be coalesced into a single undo point." [label] (it/sequence-label label)) (defn prev-sequence-label [graph-id] (let [sys @*the-system*] (when-let [prev-step (some-> (is/graph-history sys graph-id) (is/undo-stack) (last))] (:sequence-label prev-step)))) (defn- construct-node-with-id [graph-id node-type args] (apply construct node-type :_node-id (is/next-node-id @*the-system* graph-id) (mapcat identity args))) (defn make-node "Returns the transaction step for creating a new node. Needs to be executed within a transact to actually create the node on a graph. Example: `(transact (make-node world SimpleTestNode))`" [graph-id node-type & args] (let [args (if (empty? args) {} (if (= 1 (count args)) (first args) (apply assoc {} args)))] (it/new-node (construct-node-with-id graph-id node-type args)))) (defn make-node! "Creates the transaction step and runs it in a transaction, returning the resulting node. Example: `(make-node! world SimpleTestNode)`" [graph-id node-type & args] (first (tx-nodes-added (transact (apply make-node graph-id node-type args))))) (defn delete-node "Returns the transaction step for deleting a node. Needs to be executed within a transact to actually create the node on a graph. Example: `(transact (delete-node node-id))`" [node-id] (assert node-id) (it/delete-node node-id)) (defn delete-node! "Creates the transaction step for deleting a node and runs it in a transaction. It returns the transaction results, tx-result Example: `(delete-node! node-id)`" [node-id] (assert node-id) (transact (delete-node node-id))) (defn callback "Call the specified function with args when reaching the transaction step" [f & args] (it/callback f args)) (defn connect "Make a connection from an output of the source node to an input on the target node. Takes effect when a transaction is applied. Example: `(transact (connect content-node :scalar view-node :first-name))`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (it/connect source-id source-label target-id target-label)) (defn connect! "Creates the transaction step to make a connection from an output of the source node to an input on the target node and applies it in a transaction Example: `(connect! content-node :scalar view-node :first-name)`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (transact (connect source-id source-label target-id target-label))) (defn disconnect "Creates the transaction step to remove a connection from an output of the source node to the input on the target node. Note that there might still be connections between the two nodes, from other outputs to other inputs. Takes effect when a transaction is applied with transact. Example: (`transact (disconnect aux-node :scalar view-node :last-name))`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (it/disconnect source-id source-label target-id target-label)) (defn disconnect! "Creates the transaction step to remove a connection from an output of the source node to the input on the target node. It also applies it in transaction, returning the transaction result, (tx-result). Note that there might still be connections between the two nodes, from other outputs to other inputs. Example: `(disconnect aux-node :scalar view-node :last-name)`" [source-id source-label target-id target-label] (transact (disconnect source-id source-label target-id target-label))) (defn disconnect-sources ([target-id target-label] (disconnect-sources (now) target-id target-label)) ([basis target-id target-label] (assert target-id) (it/disconnect-sources basis target-id target-label))) (defn set-property "Creates the transaction step to assign a value to a node's property (or properties) value(s). It will take effect when the transaction is applies in a transact. Example: `(transact (set-property root-id :touched 1))`" [node-id & kvs] (assert node-id) (mapcat (fn [[p v]] (it/update-property node-id p (clojure.core/constantly v) [])) (partition-all 2 kvs))) (defn set-property! "Creates the transaction step to assign a value to a node's property (or properties) value(s) and applies it in a transaction. It returns the result of the transaction, (tx-result). Example: `(set-property! root-id :touched 1)`" [node-id & kvs] (assert node-id) (transact (apply set-property node-id kvs))) (defn update-property "Create the transaction step to apply a function to a node's property in a transaction. The function f will be invoked as if by (apply f current-value args). It will take effect when the transaction is applied in a transact. Example: `(transact (g/update-property node-id :int-prop inc))`" [node-id p f & args] (assert node-id) (it/update-property node-id p f args)) (defn update-property! "Create the transaction step to apply a function to a node's property in a transaction. Then it applies the transaction. The function f will be invoked as if by (apply f current-value args). The transaction results, (tx-result), are returned. Example: `g/update-property! node-id :int-prop inc)`" [node-id p f & args] (assert node-id) (transact (apply update-property node-id p f args))) (defn clear-property [node-id p] (assert node-id) (it/clear-property node-id p)) (defn clear-property! [node-id p] (transact (clear-property node-id p))) (defn update-graph-value [graph-id k f & args] (it/update-graph-value graph-id update (into [k f] args))) (defn set-graph-value "Create the transaction step to attach a named value to a graph. It will take effect when the transaction is applied in a transact. Example: `(transact (set-graph-value 0 :string-value \"A String\"))`" [graph-id k v] (assert graph-id) (it/update-graph-value graph-id assoc [k v])) (defn set-graph-value! "Create the transaction step to attach a named value to a graph and applies the transaction. Returns the transaction result, (tx-result). Example: (set-graph-value! 0 :string-value \"A String\")" [graph-id k v] (assert graph-id) (transact (set-graph-value graph-id k v))) (defn user-data [node-id key] (is/user-data @*the-system* node-id key)) (defn user-data! [node-id key value] (swap! *the-system* is/assoc-user-data node-id key value) value) (defn user-data-swap! [node-id key f & args] (-> (swap! *the-system* (fn [sys] (apply is/update-user-data sys node-id key f args))) (is/user-data node-id key))) (defn invalidate "Creates the transaction step to invalidate all the outputs of the node. It will take effect when the transaction is applied in a transact. Example: `(transact (invalidate node-id))`" [node-id] (assert node-id) (it/invalidate node-id)) (defn mark-defective "Creates the transaction step to mark a node as _defective_. This means that all the outputs of the node will be replace by the defective value. It will take effect when the transaction is applied in a transact. Example: `(transact (mark-defective node-id (g/error-fatal \"Resource Not Found\")))`" ([node-id defective-value] (assert node-id) (mark-defective node-id (node-type* node-id) defective-value)) ([node-id node-type defective-value] (assert node-id) (let [jammable-outputs (in/jammable-output-labels node-type)] (list (set-property node-id :_output-jammers (zipmap jammable-outputs (repeat defective-value))) (invalidate node-id))))) (defn mark-defective! "Creates the transaction step to mark a node as _defective_. This means that all the outputs of the node will be replace by the defective value. It will take effect when the transaction is applied in a transact. Example: `(mark-defective! node-id (g/error-fatal \"Resource Not Found\"))`" [node-id defective-value] (assert node-id) (transact (mark-defective node-id defective-value))) ;; --------------------------------------------------------------------------- ;; Tracing ;; --------------------------------------------------------------------------- ;; ;; Run several tracers using (juxt (g/make-print-tracer) (g/make-tree-tracer result)) ;; (defn make-print-tracer "Prints an indented tree of all eval steps taken." [] (let [depth (atom 0)] (fn [state node output-type label] (when (or (= :end state) (= :fail state)) (swap! depth dec)) (println (str (apply str (take @depth (repeat " "))) state " " node " " output-type " " label)) (when (= :begin state) (swap! depth inc))))) (defn make-tree-tracer "Creates a tree trace of the evaluation of the form {:node-id ... :output-type ... :label ... :state ... :dependencies [{...} ...]} You can also pass in a function to decorate the steps. Timing: (defn timing-decorator [step state] (case state :begin (assoc step :start-time (System/currentTimeMillis)) (:end :fail) (-> step (assoc :elapsed (- (System/currentTimeMillis) (:start-time step))) (dissoc :start-time)))) Weight: (defn weight-decorator [step state] (case state :begin step :end (assoc step :weight (+ 1 (reduce + 0 (map :weight (:dependencies step))))) :fail (assoc step :weight 0))) Depth: (defn- depth-decorator [step state] (case state :begin step :end (assoc step :depth (+ 1 (or (:depth (first (:dependencies step))) 0))) :fail (assoc step :depth 0))) (g/node-value node :output (g/make-evaluation-context {:tracer (g/make-tree-tracer result-atom timing-decorator)}))" ([result-atom] (make-tree-tracer result-atom (fn [step _] step))) ([result-atom step-decorator] (let [stack (atom '())] (fn [state node output-type label] (case state :begin (swap! stack conj (step-decorator {:node-id node :output-type output-type :label label :dependencies []} state)) (:end :fail) (let [step (step-decorator (assoc (first @stack) :state state) state)] (swap! stack rest) (let [parent (first @stack)] (if parent (swap! stack #(conj (rest %) (update parent :dependencies conj step))) (reset! result-atom step))))))))) (defn tree-trace-seq [result] (tree-seq :dependencies :dependencies result)) ;; --------------------------------------------------------------------------- ;; Values ;; --------------------------------------------------------------------------- (defn make-evaluation-context ([] (is/default-evaluation-context @*the-system*)) ([options] (is/custom-evaluation-context @*the-system* options))) (defn pruned-evaluation-context "Selectively filters out cache entries from the supplied evaluation context. Returns a new evaluation context with only the cache entries that passed the cache-entry-pred predicate. The predicate function will be called with node-id, output-label, evaluation-context and should return true if the cache entry for the output-label should remain in the cache." [evaluation-context cache-entry-pred] (in/pruned-evaluation-context evaluation-context cache-entry-pred)) (defn update-cache-from-evaluation-context! [evaluation-context] (swap! *the-system* is/update-cache-from-evaluation-context evaluation-context) nil) (defmacro with-auto-evaluation-context [ec & body] `(let [~ec (make-evaluation-context) result# (do ~@body)] (update-cache-from-evaluation-context! ~ec) result#)) (def fake-system (is/make-system {:cache-size 0})) (defmacro with-auto-or-fake-evaluation-context [ec & body] `(let [real-system# @*the-system* ~ec (is/default-evaluation-context (or real-system# fake-system)) result# (do ~@body)] (when (some? real-system#) (update-cache-from-evaluation-context! ~ec)) result#)) (defn invalidate-counter ([node-id output] (get (:invalidate-counters @*the-system*) [node-id output])) ([node-id output evaluation-context] (get (:initial-invalidate-counters evaluation-context) [node-id output]))) (defn- do-node-value [node-id label evaluation-context] (is/node-value @*the-system* node-id label evaluation-context)) (defn node-value "Pull a value from a node's output, property or input, identified by `label`. The value may be cached or it may be computed on demand. This is transparent to the caller. This uses the value of the node and its output at the time the evaluation context was created. If the evaluation context is left out, a context will be created from the current state of the system and the caller will receive a value consistent with the most recently committed transaction. The system cache is only updated automatically if the context was left out. If passed explicitly, you will need to update the cache manually by calling update-cache-from-evaluation-context!. Example: `(node-value node-id :chained-output)`" ([node-id label] (with-auto-evaluation-context evaluation-context (do-node-value node-id label evaluation-context))) ([node-id label evaluation-context] (do-node-value node-id label evaluation-context))) (defn graph-value "Returns the graph from the system given a graph-id and key. It returns the graph at the point in time of the bais, if provided. If the basis is not provided, it will take it from the current point of time in the system. Example: `(graph-value (node->graph-id view) :renderer)`" ([graph-id k] (graph-value (now) graph-id k)) ([basis graph-id k] (get-in basis [:graphs graph-id :graph-values k]))) ;; --------------------------------------------------------------------------- ;; Interrogating the Graph ;; --------------------------------------------------------------------------- (defn arcs->tuples [arcs] (ig/arcs->tuples arcs)) (defn inputs "Return the inputs to this node. Returns a collection like [[source-id output target-id input] [source-id output target-id input]...]. If there are no inputs connected, returns an empty collection." ([node-id] (inputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/inputs basis node-id)))) (defn labelled-inputs ([node-id label] (labelled-inputs (now) node-id label)) ([basis node-id label] (arcs->tuples (ig/inputs basis node-id label)))) (defn outputs "Return the outputs from this node. Returns a collection like [[source-id output target-id input] [source-id output target-id input]...]. If there are no outputs connected, returns an empty collection." ([node-id] (outputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/outputs basis node-id)))) (defn labelled-outputs ([node-id label] (labelled-outputs (now) node-id label)) ([basis node-id label] (arcs->tuples (ig/outputs basis node-id label)))) (defn explicit-inputs ([node-id] (explicit-inputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/explicit-inputs basis node-id)))) (defn explicit-outputs ([node-id] (explicit-outputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/explicit-outputs basis node-id)))) (defn node-feeding-into "Find the one-and-only node ID that sources this input on this node. Should you use this on an input label with multiple connections, the result is undefined." ([node-id label] (node-feeding-into (now) node-id label)) ([basis node-id label] (ffirst (sources basis node-id label)))) (defn sources-of "Find the [node-id label] pairs for all connections into the given node's input label. The result is a sequence of pairs." ([node-id label] (sources-of (now) node-id label)) ([basis node-id label] (gt/sources basis node-id label))) (defn targets-of "Find the [node-id label] pairs for all connections out of the given node's output label. The result is a sequence of pairs." ([node-id label] (targets-of (now) node-id label)) ([basis node-id label] (gt/targets basis node-id label))) (defn find-node "Looks up nodes with a property that matches the given value. Exact equality is used. At present, this does a linear scan of all nodes. Future enhancements may offer indexing for faster access of some properties." [basis property-label expected-value] (gt/node-by-property basis property-label expected-value)) (defn invalidate-outputs! "Invalidate the given outputs and _everything_ that could be affected by them. Outputs are specified as pairs of [node-id label] for both the argument and return value." ([outputs] (swap! *the-system* is/invalidate-outputs outputs) nil)) (defn invalidate-node-outputs! [node-id] (let [labels (-> (node-type* node-id) (in/output-labels))] (invalidate-outputs! (map (partial vector node-id) labels)))) (defn node-instance*? "Returns true if the node is a member of a given type, including supertypes." ([type node] (node-instance*? (now) type node)) ([basis type node] (if-let [nt (and type (node-type basis node))] (isa? (:key @nt) (:key @type)) false))) (defn node-instance? "Returns true if the node is a member of a given type, including supertypes." ([type node-id] (node-instance? (now) type node-id)) ([basis type node-id] (node-instance*? basis type (gt/node-by-id-at basis node-id)))) ;; --------------------------------------------------------------------------- ;; Support for serialization, copy & paste, and drag & drop ;; --------------------------------------------------------------------------- (def ^:private write-handlers (transit/record-write-handlers internal.node.NodeTypeRef internal.node.ValueTypeRef)) (def ^:private read-handlers (transit/record-read-handlers internal.node.NodeTypeRef internal.node.ValueTypeRef)) (defn read-graph "Read a graph fragment from a string. Returns a fragment suitable for pasting." ([s] (read-graph s {})) ([^String s extra-handlers] (let [handlers (merge read-handlers extra-handlers) reader (transit/reader (ByteArrayInputStream. (.getBytes s "UTF-8")) :json {:handlers handlers})] (transit/read reader)))) (defn write-graph "Return a serialized string representation of the graph fragment." ([fragment] (write-graph fragment {})) ([fragment extra-handlers] (let [handlers (merge write-handlers extra-handlers) out (ByteArrayOutputStream. 4096) writer (transit/writer out :json {:handlers handlers})] (transit/write writer fragment) (.toString out "UTF-8")))) (defn- serialize-arc [id-dictionary arc] (let [[source-id source-label] (gt/source arc) [target-id target-label] (gt/target arc)] [(id-dictionary source-id) source-label (id-dictionary target-id) target-label])) (defn- in-same-graph? [_ arc] (apply = (map node-id->graph-id (take-nth 2 arc)))) (defn- every-arc-pred [& preds] (fn [basis arc] (reduce (fn [v pred] (and v (pred basis arc))) true preds))) (defn- predecessors [pred basis node-id] (into [] (comp (filter #(pred basis %)) (map first)) (inputs basis node-id))) (defn- input-traverse [basis pred root-ids] (ig/pre-traverse basis root-ids (partial predecessors (every-arc-pred in-same-graph? pred)))) (defn default-node-serializer [basis node] (let [node-id (gt/node-id node) all-node-properties (into {} (map (fn [[key value]] [key (:value value)]) (:properties (node-value node-id :_declared-properties)))) properties-without-fns (util/filterm (comp not fn? val) all-node-properties)] {:node-type (node-type basis node) :properties properties-without-fns})) (def opts-schema {(s/optional-key :traverse?) Runnable (s/optional-key :serializer) Runnable}) (defn override-originals "Given a node id, returns a sequence of node ids starting with the non-override node and proceeding with every override node leading up to and including the supplied node id." ([node-id] (override-originals (now) node-id)) ([basis node-id] (ig/override-originals basis node-id))) (defn- deep-arcs-by-source "Like arcs-by-source, but also includes connections from nodes earlier in the override chain. Note that arcs-by-target already does this." ([source-id] (deep-arcs-by-source (now) source-id)) ([basis source-id] (into [] (mapcat (partial gt/arcs-by-source basis)) (override-originals basis source-id)))) (defn copy "Given a vector of root ids, and an options map that can contain an `:traverse?` predicate and a `serializer` function, returns a copy graph fragment that can be serialized or pasted. Works on the current basis, if a basis is not provided. The `:traverse?` predicate determines whether the target node will be included at all. If it returns a falsey value, then traversal stops there. That node and all arcs to it will be left behind. If the predicate returns true, then that node --- or a stand-in for it --- will be included in the fragment. `:traverse?` will be called with the basis and arc data. The `:serializer` function determines _how_ to represent the node in the fragment. `dynamo.graph/default-node-serializer` adds a map with the original node's properties and node type. `paste` knows how to turn that map into a new (copied) node. You would use a `:serializer` function if you wanted to record a memo that could later be used to resolve and connect to an existing node rather than copy it. `:serializer` will be called with the node value. It must return an associative data structure (e.g., a map or a record). Note that connections to or from any nodes along the override chain will be flattened to source or target the serialized node instead of the nodes that it overrides. Example: `(g/copy root-ids {:traverse? (comp not resource? #(nth % 3)) :serializer (some-fn custom-serializer default-node-serializer %)})" ([root-ids opts] (copy (now) root-ids opts)) ([basis root-ids {:keys [traverse? serializer] :or {traverse? (clojure.core/constantly false) serializer default-node-serializer} :as opts}] (s/validate opts-schema opts) (let [arcs-by-source (partial deep-arcs-by-source basis) arcs-by-target (partial gt/arcs-by-target basis) serializer #(assoc (serializer basis (gt/node-by-id-at basis %2)) :serial-id %1) original-ids (input-traverse basis traverse? root-ids) replacements (zipmap original-ids (map-indexed serializer original-ids)) serial-ids (into {} (mapcat (fn [[original-id {serial-id :serial-id}]] (map #(vector % serial-id) (override-originals basis original-id)))) replacements) include-arc? (partial ig/arc-endpoints-p (partial contains? serial-ids)) serialize-arc (partial serialize-arc serial-ids) incoming-arcs (mapcat arcs-by-target original-ids) outgoing-arcs (mapcat arcs-by-source original-ids) fragment-arcs (into [] (comp (filter include-arc?) (map serialize-arc) (distinct)) (concat incoming-arcs outgoing-arcs))] {:roots (mapv serial-ids root-ids) :nodes (vec (vals replacements)) :arcs fragment-arcs :node-id->serial-id serial-ids}))) (defn- deserialize-arc [id-dictionary arc] (-> arc (update 0 id-dictionary) (update 2 id-dictionary) (->> (apply connect)))) (defn default-node-deserializer [basis graph-id {:keys [node-type properties]}] (construct-node-with-id graph-id node-type properties)) (defn paste "Given a `graph-id` and graph fragment from copying, provides the transaction data to create the nodes on the graph and connect all the new nodes together with the same arcs in the fragment. It will take effect when it is applied with a transact. Any nodes that were replaced during the copy must be resolved into real nodes here. That is the job of the `:deserializer` function. It receives the current basis, the graph-id being pasted into, and whatever data the :serializer function returned. `dynamo.graph/default-node-deserializer` creates new nodes (copies) from the fragment. Yours may look up nodes in the world, create new instances, or anything else. The deserializer _must_ return valid transaction data, even if that data is just an empty vector. Example: `(g/paste (graph project) fragment {:deserializer default-node-deserializer})" ([graph-id fragment opts] (paste (now) graph-id fragment opts)) ([basis graph-id fragment {:keys [deserializer] :or {deserializer default-node-deserializer} :as opts}] (let [deserializer (partial deserializer basis graph-id) nodes (map deserializer (:nodes fragment)) new-nodes (remove #(gt/node-by-id-at basis (gt/node-id %)) nodes) node-txs (vec (mapcat it/new-node new-nodes)) node-ids (map gt/node-id nodes) id-dictionary (zipmap (map :serial-id (:nodes fragment)) node-ids) connect-txs (mapcat #(deserialize-arc id-dictionary %) (:arcs fragment))] {:root-node-ids (map id-dictionary (:roots fragment)) :nodes node-ids :tx-data (into node-txs connect-txs) :serial-id->node-id id-dictionary}))) ;; --------------------------------------------------------------------------- ;; Sub-graph instancing ;; --------------------------------------------------------------------------- (defn- traverse-cascade-delete [basis [source-id source-label target-id target-label]] (get (cascade-deletes (node-type* basis target-id)) target-label)) (defn override ([root-id] (override root-id {})) ([root-id opts] (override root-id opts (clojure.core/constantly []))) ([root-id {:keys [traverse? properties-by-node-id] :or {traverse? (clojure.core/constantly true) properties-by-node-id (clojure.core/constantly {})}} init-fn] (let [traverse-fn (partial predecessors (every-arc-pred in-same-graph? traverse-cascade-delete traverse?))] (it/override root-id traverse-fn init-fn properties-by-node-id)))) (defn transfer-overrides [from-id->to-id] (it/transfer-overrides from-id->to-id)) (defn overrides ([root-id] (overrides (now) root-id)) ([basis root-id] (ig/get-overrides basis root-id))) (defn override-original ([node-id] (override-original (now) node-id)) ([basis node-id] (ig/override-original basis node-id))) (defn override-root ([node-id] (override-root (now) node-id)) ([basis node-id] (if-some [original (some->> node-id (override-original basis))] (recur basis original) node-id))) (defn override? ([node-id] (override? (now) node-id)) ([basis node-id] (not (nil? (override-original basis node-id))))) (defn override-id ([node-id] (override-id (now) node-id)) ([basis node-id] (when-some [node (node-by-id basis node-id)] (:override-id node)))) (defn property-overridden? ([node-id property] (property-overridden? (now) node-id property)) ([basis node-id property] (if-let [node (node-by-id basis node-id)] (gt/property-overridden? node property) false))) (defn property-value-origin? ([node-id prop-kw] (property-value-origin? (now) node-id prop-kw)) ([basis node-id prop-kw] (if (override? basis node-id) (property-overridden? basis node-id prop-kw) true))) (defn node-type-kw "Returns the fully-qualified keyword that corresponds to the node type of the specified node id, or nil if the node does not exist." ([node-id] (:k (node-type* node-id))) ([basis node-id] (:k (node-type* basis node-id)))) (defmulti node-key "Used to identify a node uniquely within a scope. This has various uses, among them is that we will restore overridden properties during resource sync for nodes that return a non-nil node-key. Usually this only happens for ResourceNodes, but this also enables us to restore overridden properties on nodes produced by the resource :load-fn." (fn [node-id {:keys [basis] :as _evaluation-context}] (if-some [node-type-kw (node-type-kw basis node-id)] node-type-kw (throw (ex-info (str "Unknown node id: " node-id) {:node-id node-id}))))) (defmethod node-key :default [_node-id _evaluation-context] nil) (defn overridden-properties "Returns a map of overridden prop-keywords to property values. Values will be produced by property value functions if possible." [node-id {:keys [basis] :as evaluation-context}] (let [node-type (node-type* basis node-id)] (into {} (map (fn [[prop-kw raw-prop-value]] [prop-kw (if (has-property? node-type prop-kw) (node-value node-id prop-kw evaluation-context) raw-prop-value)])) (node-value node-id :_overridden-properties evaluation-context)))) (defn collect-overridden-properties "Collects overridden property values from override nodes originating from the scope of the specified source-node-id. The idea is that one should be able to delete source-node-id, recreate it from disk, and re-apply the collected property values to the freshly created override nodes resulting from the resource :load-fn. Overridden properties will be collected from nodes whose node-key multi-method implementation returns a non-nil value. This will be used as a key along with the override-id to uniquely identify the node among the new set of nodes created by the :load-fn." ([source-node-id] (with-auto-evaluation-context evaluation-context (collect-overridden-properties source-node-id evaluation-context))) ([source-node-id {:keys [basis] :as evaluation-context}] (persistent! (reduce (fn [properties-by-override-node-key override-node-id] (or (when-some [override-id (override-id basis override-node-id)] (when-some [node-key (node-key override-node-id evaluation-context)] (let [override-node-key [override-id node-key] overridden-properties (overridden-properties override-node-id evaluation-context)] (if (contains? properties-by-override-node-key override-node-key) (let [node-type-kw (node-type-kw basis override-node-id)] (throw (ex-info (format "Duplicate node key `%s` from %s" node-key node-type-kw) {:node-key node-key :node-type node-type-kw}))) (when (seq overridden-properties) (assoc! properties-by-override-node-key override-node-key overridden-properties)))))) properties-by-override-node-key)) (transient {}) (ig/pre-traverse basis [source-node-id] ig/cascade-delete-sources))))) (defn restore-overridden-properties "Restores collected-properties obtained from the collect-overridden-properties function to override nodes originating from the scope of the specified target-node-id. Returns a sequence of transaction steps. Target nodes are identified by the value returned from their node-key multi-method implementation along with the override-id that produced them." ([target-node-id collected-properties] (with-auto-evaluation-context evaluation-context (restore-overridden-properties target-node-id collected-properties evaluation-context))) ([target-node-id collected-properties {:keys [basis] :as evaluation-context}] (for [node-id (ig/pre-traverse basis [target-node-id] ig/cascade-delete-sources)] (when-some [override-id (override-id basis node-id)] (when-some [node-key (node-key node-id evaluation-context)] (let [override-node-key [override-id node-key] overridden-properties (collected-properties override-node-key)] (for [[prop-kw prop-value] overridden-properties] (set-property node-id prop-kw prop-value)))))))) ;; --------------------------------------------------------------------------- ;; Boot, initialization, and facade ;; --------------------------------------------------------------------------- (defn initialize! "Set up the initial system including graphs, caches, and disposal queues" [config] (reset! *the-system* (is/make-system config)) (low-memory/add-callback! clear-system-cache!)) (defn make-graph! "Create a new graph in the system with optional values of `:history` and `:volatility`. If no options are provided, the history ability is false and the volatility is 0 Example: `(make-graph! :history true :volatility 1)`" [& {:keys [history volatility] :or {history false volatility 0}}] (let [g (assoc (ig/empty-graph) :_volatility volatility) s (swap! *the-system* (if history is/attach-graph-with-history is/attach-graph) g)] (:last-graph s))) (defn last-graph-added "Retuns the last graph added to the system" [] (is/last-graph @*the-system*)) (defn graph-version "Returns the latest version of a graph id" [graph-id] (is/graph-time @*the-system* graph-id)) (defn delete-graph! "Given a `graph-id`, deletes it from the system Example: ` (delete-graph! agraph-id)`" [graph-id] (when-let [graph (is/graph @*the-system* graph-id)] (transact (mapv it/delete-node (ig/node-ids graph))) (swap! *the-system* is/detach-graph graph-id) nil)) (defn undo! "Given a `graph-id` resets the graph back to the last _step_ in time. Example: (undo gid)" [graph-id] (swap! *the-system* is/undo-history graph-id) nil) (defn has-undo? "Returns true/false if a `graph-id` has an undo available" [graph-id] (let [undo-stack (is/undo-stack (is/graph-history @*the-system* graph-id))] (not (empty? undo-stack)))) (defn undo-stack-count "Returns the number of entries in the undo stack for `graph-id`" [graph-id] (let [undo-stack (is/undo-stack (is/graph-history @*the-system* graph-id))] (count undo-stack))) (defn redo! "Given a `graph-id` reverts an undo of the graph Example: `(redo gid)`" [graph-id] (swap! *the-system* is/redo-history graph-id) nil) (defn has-redo? "Returns true/false if a `graph-id` has an redo available" [graph-id] (let [redo-stack (is/redo-stack (is/graph-history @*the-system* graph-id))] (not (empty? redo-stack)))) (defn reset-undo! "Given a `graph-id`, clears all undo history for the graph Example: `(reset-undo! gid)`" [graph-id] (swap! *the-system* is/clear-history graph-id) nil) (defn cancel! "Given a `graph-id` and a `sequence-id` _cancels_ any sequence of undos on the graph as if they had never happened in the history. Example: `(cancel! gid :a)`" [graph-id sequence-id] (swap! *the-system* is/cancel graph-id sequence-id) nil)
270
;; 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 dynamo.graph "Main api for graph and node" (:refer-clojure :exclude [deftype constantly]) (:require [clojure.tools.macro :as ctm] [cognitect.transit :as transit] [internal.cache :as c] [internal.graph :as ig] [internal.graph.types :as gt] [internal.low-memory :as low-memory] [internal.node :as in] [internal.system :as is] [internal.transaction :as it] [internal.util :as util] [potemkin.namespaces :as namespaces] [schema.core :as s]) (:import [internal.graph.error_values ErrorValue] [java.io ByteArrayInputStream ByteArrayOutputStream])) (set! *warn-on-reflection* true) (namespaces/import-vars [internal.graph.types node-id->graph-id node->graph-id sources targets connected? dependencies Node node-id node-id? produce-value node-by-id-at]) (namespaces/import-vars [internal.graph.error-values ->error error-aggregate error-fatal error-fatal? error-info error-info? error-message error-package? error-warning error-warning? error? flatten-errors map->error package-errors precluding-errors unpack-errors worse-than]) (namespaces/import-vars [internal.node value-type-schema value-type? isa-node-type? value-type-dispatch-value has-input? has-output? has-property? type-compatible? merge-display-order NodeType supertypes declared-properties declared-property-labels declared-inputs declared-outputs cached-outputs input-dependencies input-cardinality cascade-deletes substitute-for input-type output-type input-labels output-labels property-display-order]) (namespaces/import-vars [internal.graph arc node-ids pre-traverse]) (let [graph-id ^java.util.concurrent.atomic.AtomicInteger (java.util.concurrent.atomic.AtomicInteger. 0)] (defn next-graph-id [] (.getAndIncrement graph-id))) ;; --------------------------------------------------------------------------- ;; State handling ;; --------------------------------------------------------------------------- ;; Only marked dynamic so tests can rebind. Should never be rebound "for real". (defonce ^:dynamic *the-system* (atom nil)) (def ^:dynamic *tps-debug* nil) (defn now "The basis at the current point in time" [] (is/basis @*the-system*)) (defn clone-system ([] (clone-system @*the-system*)) ([sys] (is/clone-system sys))) (defn system= [s1 s2] (is/system= s1 s2)) (defmacro with-system [sys & body] `(binding [*the-system* (atom ~sys)] ~@body)) (defn node-by-id "Returns a node given its id. If the basis is provided, it returns the value of the node using that basis. Otherwise, it uses the current basis." ([node-id] (let [graph-id (node-id->graph-id node-id)] (ig/node-id->node (is/graph @*the-system* graph-id) node-id))) ([basis node-id] (gt/node-by-id-at basis node-id))) (defn node-type* "Return the node-type given a node-id. Uses the current basis if not provided." ([node-id] (node-type* (now) node-id)) ([basis node-id] (when-let [n (gt/node-by-id-at basis node-id)] (gt/node-type n basis)))) (defn node-type "Return the node-type given a node. Uses the current basis if not provided." ([node] (node-type (now) node)) ([basis node] (when node (gt/node-type node basis)))) (defn cache "The system cache of node values" [] (is/system-cache @*the-system*)) (defn clear-system-cache! "Clears a cache (default *the-system* cache), useful when debugging" ([] (clear-system-cache! *the-system*)) ([sys-atom] (swap! sys-atom assoc :cache (is/make-cache {})) nil) ([sys-atom node-id] (let [outputs (cached-outputs (node-type* node-id)) entries (map (partial vector node-id) outputs)] (swap! sys-atom update :cache c/cache-invalidate entries) nil))) (defn graph "Given a graph id, returns the particular graph in the system at the current point in time" [graph-id] (is/graph @*the-system* graph-id)) (when *tps-debug* (def tps-counter (agent (long-array 3 0))) (defn tick [^longs tps-counts now] (let [last-report-time (aget tps-counts 1) transaction-count (inc (aget tps-counts 0))] (aset-long tps-counts 0 transaction-count) (when (> now (+ last-report-time 1000000000)) (let [elapsed-time (/ (- now last-report-time) 1000000000.00)] (do (println "TPS" (/ transaction-count elapsed-time)))) (aset-long tps-counts 1 now) (aset-long tps-counts 0 0))) tps-counts)) (defn transact "Provides a way to run a transaction against the graph system. It takes a list of transaction steps. Example: (g/transact [(g/connect n1 output-name n :xs) (g/connect n2 output-name n :xs)]) It returns the transaction result, (tx-result), which is a map containing keys about the transaction. Transaction result-keys: `[:status :basis :graphs-modified :nodes-added :nodes-modified :nodes-deleted :outputs-modified :label :sequence-label]` " [txs] (when *tps-debug* (send-off tps-counter tick (System/nanoTime))) (let [basis (is/basis @*the-system*) id-generators (is/id-generators @*the-system*) override-id-generator (is/override-id-generator @*the-system*) tx-result (it/transact* (it/new-transaction-context basis id-generators override-id-generator) txs)] (when (= :ok (:status tx-result)) (swap! *the-system* is/merge-graphs (get-in tx-result [:basis :graphs]) (:graphs-modified tx-result) (:outputs-modified tx-result) (:nodes-deleted tx-result))) tx-result)) ;; --------------------------------------------------------------------------- ;; Using transaction data ;; --------------------------------------------------------------------------- (defn tx-data-nodes-added "Returns a list of the node-ids added given a list of transaction steps, (tx-data)." [txs] (keep (fn [tx-data] (case (:type tx-data) :create-node (-> tx-data :node :_node-id) nil)) (flatten txs))) ;; --------------------------------------------------------------------------- ;; Using transaction values ;; --------------------------------------------------------------------------- (defn tx-nodes-added "Returns a list of the node-ids added given a result from a transaction, (tx-result)." [transaction] (:nodes-added transaction)) (defn is-modified? "Returns a boolean if a node, or node and output, was modified as a result of a transaction given a tx-result." ([transaction node-id] (boolean (contains? (:outputs-modified transaction) node-id))) ([transaction node-id output] (boolean (get-in transaction [:outputs-modified node-id output])))) (defn is-added? "Returns a boolean if a node was added as a result of a transaction given a tx-result and node." [transaction node-id] (contains? (:nodes-added transaction) node-id)) (defn is-deleted? "Returns a boolean if a node was delete as a result of a transaction given a tx-result and node." [transaction node-id] (contains? (:nodes-deleted transaction) node-id)) (defn outputs-modified "Returns the pairs of node-id and label of the outputs that were modified for a node as the result of a transaction given a tx-result and node" [transaction node-id] (get-in transaction [:outputs-modified node-id])) (defn transaction-basis "Returns the final basis from the result of a transaction given a tx-result" [transaction] (:basis transaction)) (defn pre-transaction-basis "Returns the original, starting basis from the result of a transaction given a tx-result" [transaction] (:original-basis transaction)) ;; --------------------------------------------------------------------------- ;; Intrinsics ;; --------------------------------------------------------------------------- (defn strip-alias "If the list ends with :as _something_, return _something_ and the list without the last two elements" [argv] (if (and (<= 2 (count argv)) (= :as (nth argv (- (count argv) 2)))) [(last argv) (take (- (count argv) 2) argv)] [nil argv])) (defmacro fnk [argv & tail] (let [param (gensym "m") [alias argv] (strip-alias (vec argv)) kargv (mapv keyword argv) arglist (interleave argv (map #(list `get param %) kargv))] (if alias `(with-meta (fn [~param] (let [~alias (select-keys ~param ~kargv) ~@(vec arglist)] ~@tail)) {:arguments (quote ~kargv)}) `(with-meta (fn [~param] (let ~(vec arglist) ~@tail)) {:arguments (quote ~kargv)})))) (defmacro defnk [symb & body] (let [[name args] (ctm/name-with-attributes symb body)] (assert (symbol? name) (str "Name for defnk is not a symbol:" name)) `(def ~name (fnk ~@args)))) (defmacro constantly [v] `(let [ret# ~v] (dynamo.graph/fnk [] ret#))) (defmacro deftype [symb & body] (let [fully-qualified-node-type-symbol (symbol (str *ns*) (str symb)) key (keyword fully-qualified-node-type-symbol)] `(do (in/register-value-type '~fully-qualified-node-type-symbol ~key) (def ~symb (in/register-value-type ~key (in/make-value-type '~symb ~key ~@body)))))) (deftype Any s/Any) (deftype Bool s/Bool) (deftype Str String) (deftype Int s/Int) (deftype Num s/Num) (deftype NodeID s/Int) (deftype Keyword s/Keyword) (deftype KeywordMap {s/Keyword s/Any}) (deftype IdPair [(s/one s/Str "id") (s/one s/Int "node-id")]) (deftype Dict {s/Str s/Int}) (deftype Properties {:properties {s/Keyword {:node-id s/Int (s/optional-key :validation-problems) s/Any :value s/Any ; Can be property value or ErrorValue :type s/Any s/Keyword s/Any}} (s/optional-key :node-id) s/Int (s/optional-key :display-order) [(s/conditional vector? [(s/one String "category") s/Keyword] keyword? s/Keyword)]}) (deftype Err ErrorValue) ;; --------------------------------------------------------------------------- ;; Definition ;; --------------------------------------------------------------------------- (defn construct "Creates an instance of a node. The node type must have been previously defined via `defnode`. The node's properties will all have their default values. The caller may pass key/value pairs to override properties. A node that has been constructed is not connected to anything and it doesn't exist in any graph yet. Example: (defnode GravityModifier (property acceleration Int (default 32)) (construct GravityModifier :acceleration 16)" [node-type-ref & {:as args}] (in/construct node-type-ref args)) (defmacro defnode "Given a name and a specification of behaviors, creates a node, and attendant functions. Allowed clauses are: (inherits _symbol_) Compose the behavior from the named node type (input _symbol_ _schema_ [:array]?) Define an input with the name, whose values must match the schema. If the :array flag is present, then this input can have multiple outputs connected to it. Without the :array flag, this input can only have one incoming connection from an output. (property _symbol_ _property-type_ & _options_) Define a property with schema and, possibly, default value and constraints. Property options include the following: (default _value_) Set a default value for the property. If no default is set, then the property will be nil. (value _getter_) Define a custom getter. It must be an fnk. The fnk's arguments are magically wired the same as an output producer. (dynamic _label_ _evaluator_) Define a dynamic attribute of the property. The label is a symbol. The evaluator is an fnk like the getter. (set (fn [evaluation-context self old-value new-value])) Define a custom setter. This is _not_ an fnk, but a strict function of 4 arguments. (output _symbol_ _type_ (:cached)? _producer_) Define an output to produce values of type. The ':cached' flag is optional. _producer_ may be a var that names an fn, or fnk. It may also be a function tail as [arglist] + forms. Values produced on an output with the :cached flag will be cached in memory until the node is affected by some change in inputs or properties. At that time, the cached value will be sent for disposal. Example (from [[editors.atlas]]): (defnode TextureCompiler (input textureset TextureSet) (property texture-filename Str (default \"\")) (output texturec Any compile-texturec))) (defnode TextureSetCompiler (input textureset TextureSet) (property textureset-filename Str (default \"\")) (output texturesetc Any compile-texturesetc))) (defnode AtlasCompiler (inherit TextureCompiler) (inherit TextureSetCompiler)) This will produce a record `AtlasCompiler`. `defnode` merges the behaviors appropriately. A node may also implement protocols or interfaces, using a syntax identical to `deftype` or `defrecord`. A node may implement any number of such protocols. Every node always implements dynamo.graph/Node." [symb & body] (let [[symb forms] (ctm/name-with-attributes symb body) fully-qualified-node-type-symbol (symbol (str *ns*) (str symb)) node-type-def (in/process-node-type-forms fully-qualified-node-type-symbol forms) fn-paths (in/extract-def-fns node-type-def) fn-defs (for [[path func] fn-paths] (list `def (in/dollar-name symb path) func)) node-type-def (util/update-paths node-type-def fn-paths (fn [path func curr] (assoc curr :fn (list `var (in/dollar-name symb path))))) node-key (:key node-type-def) derivations (for [tref (:supertypes node-type-def)] `(when-not (contains? (descendants ~(:key (deref tref))) ~node-key) (derive ~node-key ~(:key (deref tref))))) node-type-def (update node-type-def :supertypes #(list `quote %)) runtime-definer (symbol (str symb "*")) ;; TODO - investigate if we even need to register these types ;; in release builds, since we don't do schema checking? type-regs (for [[key-form value-type-form] (:register-type-info node-type-def)] `(in/register-value-type ~key-form ~value-type-form)) node-type-def (dissoc node-type-def :register-type-info)] `(do ~@type-regs ~@fn-defs (defn ~runtime-definer [] ~node-type-def) (def ~symb (in/register-node-type ~node-key (in/map->NodeTypeImpl (~runtime-definer)))) ~@derivations))) ;; --------------------------------------------------------------------------- ;; Transactions ;; --------------------------------------------------------------------------- (defmacro make-nodes "Create a number of nodes in a graph, binding them to local names to wire up connections. The resulting code will return a collection of transaction steps, including the steps to construct nodes from the bindings. If the right side of the binding is a node type, it is used directly. If it is a vector, it is treated as a node type followed by initial property values. Example: (make-nodes view [render AtlasRender scene scene/SceneRenderer background background/Gradient camera [c/CameraController :camera (c/make-orthographic)]] (g/connect background :renderable scene :renderables) (g/connect atlas-render :renderable scene :renderables))" [graph-id binding-expr & body-exprs] (assert (vector? binding-expr) "make-nodes requires a vector for its binding") (assert (even? (count binding-expr)) "make-nodes requires an even number of forms in binding vector") (let [locals (take-nth 2 binding-expr) ctors (take-nth 2 (next binding-expr)) ids (repeat (count locals) `(internal.system/next-node-id @*the-system* ~graph-id))] `(let [~@(interleave locals ids)] (concat ~@(map (fn [ctor id] (list `it/new-node (if (sequential? ctor) (if (= 2 (count ctor)) `(apply construct ~(first ctor) :_node-id ~id (mapcat identity ~(second ctor))) `(construct ~@ctor :_node-id ~id)) `(construct ~ctor :_node-id ~id)))) ctors locals) ~@body-exprs)))) (defn operation-label "Set a human-readable label to describe the current transaction." [label] (it/label label)) (defn operation-sequence "Set a machine-readable label. Successive transactions with the same label will be coalesced into a single undo point." [label] (it/sequence-label label)) (defn prev-sequence-label [graph-id] (let [sys @*the-system*] (when-let [prev-step (some-> (is/graph-history sys graph-id) (is/undo-stack) (last))] (:sequence-label prev-step)))) (defn- construct-node-with-id [graph-id node-type args] (apply construct node-type :_node-id (is/next-node-id @*the-system* graph-id) (mapcat identity args))) (defn make-node "Returns the transaction step for creating a new node. Needs to be executed within a transact to actually create the node on a graph. Example: `(transact (make-node world SimpleTestNode))`" [graph-id node-type & args] (let [args (if (empty? args) {} (if (= 1 (count args)) (first args) (apply assoc {} args)))] (it/new-node (construct-node-with-id graph-id node-type args)))) (defn make-node! "Creates the transaction step and runs it in a transaction, returning the resulting node. Example: `(make-node! world SimpleTestNode)`" [graph-id node-type & args] (first (tx-nodes-added (transact (apply make-node graph-id node-type args))))) (defn delete-node "Returns the transaction step for deleting a node. Needs to be executed within a transact to actually create the node on a graph. Example: `(transact (delete-node node-id))`" [node-id] (assert node-id) (it/delete-node node-id)) (defn delete-node! "Creates the transaction step for deleting a node and runs it in a transaction. It returns the transaction results, tx-result Example: `(delete-node! node-id)`" [node-id] (assert node-id) (transact (delete-node node-id))) (defn callback "Call the specified function with args when reaching the transaction step" [f & args] (it/callback f args)) (defn connect "Make a connection from an output of the source node to an input on the target node. Takes effect when a transaction is applied. Example: `(transact (connect content-node :scalar view-node :first-name))`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (it/connect source-id source-label target-id target-label)) (defn connect! "Creates the transaction step to make a connection from an output of the source node to an input on the target node and applies it in a transaction Example: `(connect! content-node :scalar view-node :first-name)`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (transact (connect source-id source-label target-id target-label))) (defn disconnect "Creates the transaction step to remove a connection from an output of the source node to the input on the target node. Note that there might still be connections between the two nodes, from other outputs to other inputs. Takes effect when a transaction is applied with transact. Example: (`transact (disconnect aux-node :scalar view-node :last-name))`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (it/disconnect source-id source-label target-id target-label)) (defn disconnect! "Creates the transaction step to remove a connection from an output of the source node to the input on the target node. It also applies it in transaction, returning the transaction result, (tx-result). Note that there might still be connections between the two nodes, from other outputs to other inputs. Example: `(disconnect aux-node :scalar view-node :last-name)`" [source-id source-label target-id target-label] (transact (disconnect source-id source-label target-id target-label))) (defn disconnect-sources ([target-id target-label] (disconnect-sources (now) target-id target-label)) ([basis target-id target-label] (assert target-id) (it/disconnect-sources basis target-id target-label))) (defn set-property "Creates the transaction step to assign a value to a node's property (or properties) value(s). It will take effect when the transaction is applies in a transact. Example: `(transact (set-property root-id :touched 1))`" [node-id & kvs] (assert node-id) (mapcat (fn [[p v]] (it/update-property node-id p (clojure.core/constantly v) [])) (partition-all 2 kvs))) (defn set-property! "Creates the transaction step to assign a value to a node's property (or properties) value(s) and applies it in a transaction. It returns the result of the transaction, (tx-result). Example: `(set-property! root-id :touched 1)`" [node-id & kvs] (assert node-id) (transact (apply set-property node-id kvs))) (defn update-property "Create the transaction step to apply a function to a node's property in a transaction. The function f will be invoked as if by (apply f current-value args). It will take effect when the transaction is applied in a transact. Example: `(transact (g/update-property node-id :int-prop inc))`" [node-id p f & args] (assert node-id) (it/update-property node-id p f args)) (defn update-property! "Create the transaction step to apply a function to a node's property in a transaction. Then it applies the transaction. The function f will be invoked as if by (apply f current-value args). The transaction results, (tx-result), are returned. Example: `g/update-property! node-id :int-prop inc)`" [node-id p f & args] (assert node-id) (transact (apply update-property node-id p f args))) (defn clear-property [node-id p] (assert node-id) (it/clear-property node-id p)) (defn clear-property! [node-id p] (transact (clear-property node-id p))) (defn update-graph-value [graph-id k f & args] (it/update-graph-value graph-id update (into [k f] args))) (defn set-graph-value "Create the transaction step to attach a named value to a graph. It will take effect when the transaction is applied in a transact. Example: `(transact (set-graph-value 0 :string-value \"A String\"))`" [graph-id k v] (assert graph-id) (it/update-graph-value graph-id assoc [k v])) (defn set-graph-value! "Create the transaction step to attach a named value to a graph and applies the transaction. Returns the transaction result, (tx-result). Example: (set-graph-value! 0 :string-value \"A String\")" [graph-id k v] (assert graph-id) (transact (set-graph-value graph-id k v))) (defn user-data [node-id key] (is/user-data @*the-system* node-id key)) (defn user-data! [node-id key value] (swap! *the-system* is/assoc-user-data node-id key value) value) (defn user-data-swap! [node-id key f & args] (-> (swap! *the-system* (fn [sys] (apply is/update-user-data sys node-id key f args))) (is/user-data node-id key))) (defn invalidate "Creates the transaction step to invalidate all the outputs of the node. It will take effect when the transaction is applied in a transact. Example: `(transact (invalidate node-id))`" [node-id] (assert node-id) (it/invalidate node-id)) (defn mark-defective "Creates the transaction step to mark a node as _defective_. This means that all the outputs of the node will be replace by the defective value. It will take effect when the transaction is applied in a transact. Example: `(transact (mark-defective node-id (g/error-fatal \"Resource Not Found\")))`" ([node-id defective-value] (assert node-id) (mark-defective node-id (node-type* node-id) defective-value)) ([node-id node-type defective-value] (assert node-id) (let [jammable-outputs (in/jammable-output-labels node-type)] (list (set-property node-id :_output-jammers (zipmap jammable-outputs (repeat defective-value))) (invalidate node-id))))) (defn mark-defective! "Creates the transaction step to mark a node as _defective_. This means that all the outputs of the node will be replace by the defective value. It will take effect when the transaction is applied in a transact. Example: `(mark-defective! node-id (g/error-fatal \"Resource Not Found\"))`" [node-id defective-value] (assert node-id) (transact (mark-defective node-id defective-value))) ;; --------------------------------------------------------------------------- ;; Tracing ;; --------------------------------------------------------------------------- ;; ;; Run several tracers using (juxt (g/make-print-tracer) (g/make-tree-tracer result)) ;; (defn make-print-tracer "Prints an indented tree of all eval steps taken." [] (let [depth (atom 0)] (fn [state node output-type label] (when (or (= :end state) (= :fail state)) (swap! depth dec)) (println (str (apply str (take @depth (repeat " "))) state " " node " " output-type " " label)) (when (= :begin state) (swap! depth inc))))) (defn make-tree-tracer "Creates a tree trace of the evaluation of the form {:node-id ... :output-type ... :label ... :state ... :dependencies [{...} ...]} You can also pass in a function to decorate the steps. Timing: (defn timing-decorator [step state] (case state :begin (assoc step :start-time (System/currentTimeMillis)) (:end :fail) (-> step (assoc :elapsed (- (System/currentTimeMillis) (:start-time step))) (dissoc :start-time)))) Weight: (defn weight-decorator [step state] (case state :begin step :end (assoc step :weight (+ 1 (reduce + 0 (map :weight (:dependencies step))))) :fail (assoc step :weight 0))) Depth: (defn- depth-decorator [step state] (case state :begin step :end (assoc step :depth (+ 1 (or (:depth (first (:dependencies step))) 0))) :fail (assoc step :depth 0))) (g/node-value node :output (g/make-evaluation-context {:tracer (g/make-tree-tracer result-atom timing-decorator)}))" ([result-atom] (make-tree-tracer result-atom (fn [step _] step))) ([result-atom step-decorator] (let [stack (atom '())] (fn [state node output-type label] (case state :begin (swap! stack conj (step-decorator {:node-id node :output-type output-type :label label :dependencies []} state)) (:end :fail) (let [step (step-decorator (assoc (first @stack) :state state) state)] (swap! stack rest) (let [parent (first @stack)] (if parent (swap! stack #(conj (rest %) (update parent :dependencies conj step))) (reset! result-atom step))))))))) (defn tree-trace-seq [result] (tree-seq :dependencies :dependencies result)) ;; --------------------------------------------------------------------------- ;; Values ;; --------------------------------------------------------------------------- (defn make-evaluation-context ([] (is/default-evaluation-context @*the-system*)) ([options] (is/custom-evaluation-context @*the-system* options))) (defn pruned-evaluation-context "Selectively filters out cache entries from the supplied evaluation context. Returns a new evaluation context with only the cache entries that passed the cache-entry-pred predicate. The predicate function will be called with node-id, output-label, evaluation-context and should return true if the cache entry for the output-label should remain in the cache." [evaluation-context cache-entry-pred] (in/pruned-evaluation-context evaluation-context cache-entry-pred)) (defn update-cache-from-evaluation-context! [evaluation-context] (swap! *the-system* is/update-cache-from-evaluation-context evaluation-context) nil) (defmacro with-auto-evaluation-context [ec & body] `(let [~ec (make-evaluation-context) result# (do ~@body)] (update-cache-from-evaluation-context! ~ec) result#)) (def fake-system (is/make-system {:cache-size 0})) (defmacro with-auto-or-fake-evaluation-context [ec & body] `(let [real-system# @*the-system* ~ec (is/default-evaluation-context (or real-system# fake-system)) result# (do ~@body)] (when (some? real-system#) (update-cache-from-evaluation-context! ~ec)) result#)) (defn invalidate-counter ([node-id output] (get (:invalidate-counters @*the-system*) [node-id output])) ([node-id output evaluation-context] (get (:initial-invalidate-counters evaluation-context) [node-id output]))) (defn- do-node-value [node-id label evaluation-context] (is/node-value @*the-system* node-id label evaluation-context)) (defn node-value "Pull a value from a node's output, property or input, identified by `label`. The value may be cached or it may be computed on demand. This is transparent to the caller. This uses the value of the node and its output at the time the evaluation context was created. If the evaluation context is left out, a context will be created from the current state of the system and the caller will receive a value consistent with the most recently committed transaction. The system cache is only updated automatically if the context was left out. If passed explicitly, you will need to update the cache manually by calling update-cache-from-evaluation-context!. Example: `(node-value node-id :chained-output)`" ([node-id label] (with-auto-evaluation-context evaluation-context (do-node-value node-id label evaluation-context))) ([node-id label evaluation-context] (do-node-value node-id label evaluation-context))) (defn graph-value "Returns the graph from the system given a graph-id and key. It returns the graph at the point in time of the bais, if provided. If the basis is not provided, it will take it from the current point of time in the system. Example: `(graph-value (node->graph-id view) :renderer)`" ([graph-id k] (graph-value (now) graph-id k)) ([basis graph-id k] (get-in basis [:graphs graph-id :graph-values k]))) ;; --------------------------------------------------------------------------- ;; Interrogating the Graph ;; --------------------------------------------------------------------------- (defn arcs->tuples [arcs] (ig/arcs->tuples arcs)) (defn inputs "Return the inputs to this node. Returns a collection like [[source-id output target-id input] [source-id output target-id input]...]. If there are no inputs connected, returns an empty collection." ([node-id] (inputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/inputs basis node-id)))) (defn labelled-inputs ([node-id label] (labelled-inputs (now) node-id label)) ([basis node-id label] (arcs->tuples (ig/inputs basis node-id label)))) (defn outputs "Return the outputs from this node. Returns a collection like [[source-id output target-id input] [source-id output target-id input]...]. If there are no outputs connected, returns an empty collection." ([node-id] (outputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/outputs basis node-id)))) (defn labelled-outputs ([node-id label] (labelled-outputs (now) node-id label)) ([basis node-id label] (arcs->tuples (ig/outputs basis node-id label)))) (defn explicit-inputs ([node-id] (explicit-inputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/explicit-inputs basis node-id)))) (defn explicit-outputs ([node-id] (explicit-outputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/explicit-outputs basis node-id)))) (defn node-feeding-into "Find the one-and-only node ID that sources this input on this node. Should you use this on an input label with multiple connections, the result is undefined." ([node-id label] (node-feeding-into (now) node-id label)) ([basis node-id label] (ffirst (sources basis node-id label)))) (defn sources-of "Find the [node-id label] pairs for all connections into the given node's input label. The result is a sequence of pairs." ([node-id label] (sources-of (now) node-id label)) ([basis node-id label] (gt/sources basis node-id label))) (defn targets-of "Find the [node-id label] pairs for all connections out of the given node's output label. The result is a sequence of pairs." ([node-id label] (targets-of (now) node-id label)) ([basis node-id label] (gt/targets basis node-id label))) (defn find-node "Looks up nodes with a property that matches the given value. Exact equality is used. At present, this does a linear scan of all nodes. Future enhancements may offer indexing for faster access of some properties." [basis property-label expected-value] (gt/node-by-property basis property-label expected-value)) (defn invalidate-outputs! "Invalidate the given outputs and _everything_ that could be affected by them. Outputs are specified as pairs of [node-id label] for both the argument and return value." ([outputs] (swap! *the-system* is/invalidate-outputs outputs) nil)) (defn invalidate-node-outputs! [node-id] (let [labels (-> (node-type* node-id) (in/output-labels))] (invalidate-outputs! (map (partial vector node-id) labels)))) (defn node-instance*? "Returns true if the node is a member of a given type, including supertypes." ([type node] (node-instance*? (now) type node)) ([basis type node] (if-let [nt (and type (node-type basis node))] (isa? (:key @nt) (:key @type)) false))) (defn node-instance? "Returns true if the node is a member of a given type, including supertypes." ([type node-id] (node-instance? (now) type node-id)) ([basis type node-id] (node-instance*? basis type (gt/node-by-id-at basis node-id)))) ;; --------------------------------------------------------------------------- ;; Support for serialization, copy & paste, and drag & drop ;; --------------------------------------------------------------------------- (def ^:private write-handlers (transit/record-write-handlers internal.node.NodeTypeRef internal.node.ValueTypeRef)) (def ^:private read-handlers (transit/record-read-handlers internal.node.NodeTypeRef internal.node.ValueTypeRef)) (defn read-graph "Read a graph fragment from a string. Returns a fragment suitable for pasting." ([s] (read-graph s {})) ([^String s extra-handlers] (let [handlers (merge read-handlers extra-handlers) reader (transit/reader (ByteArrayInputStream. (.getBytes s "UTF-8")) :json {:handlers handlers})] (transit/read reader)))) (defn write-graph "Return a serialized string representation of the graph fragment." ([fragment] (write-graph fragment {})) ([fragment extra-handlers] (let [handlers (merge write-handlers extra-handlers) out (ByteArrayOutputStream. 4096) writer (transit/writer out :json {:handlers handlers})] (transit/write writer fragment) (.toString out "UTF-8")))) (defn- serialize-arc [id-dictionary arc] (let [[source-id source-label] (gt/source arc) [target-id target-label] (gt/target arc)] [(id-dictionary source-id) source-label (id-dictionary target-id) target-label])) (defn- in-same-graph? [_ arc] (apply = (map node-id->graph-id (take-nth 2 arc)))) (defn- every-arc-pred [& preds] (fn [basis arc] (reduce (fn [v pred] (and v (pred basis arc))) true preds))) (defn- predecessors [pred basis node-id] (into [] (comp (filter #(pred basis %)) (map first)) (inputs basis node-id))) (defn- input-traverse [basis pred root-ids] (ig/pre-traverse basis root-ids (partial predecessors (every-arc-pred in-same-graph? pred)))) (defn default-node-serializer [basis node] (let [node-id (gt/node-id node) all-node-properties (into {} (map (fn [[key value]] [key (:value value)]) (:properties (node-value node-id :_declared-properties)))) properties-without-fns (util/filterm (comp not fn? val) all-node-properties)] {:node-type (node-type basis node) :properties properties-without-fns})) (def opts-schema {(s/optional-key :traverse?) Runnable (s/optional-key :serializer) Runnable}) (defn override-originals "Given a node id, returns a sequence of node ids starting with the non-override node and proceeding with every override node leading up to and including the supplied node id." ([node-id] (override-originals (now) node-id)) ([basis node-id] (ig/override-originals basis node-id))) (defn- deep-arcs-by-source "Like arcs-by-source, but also includes connections from nodes earlier in the override chain. Note that arcs-by-target already does this." ([source-id] (deep-arcs-by-source (now) source-id)) ([basis source-id] (into [] (mapcat (partial gt/arcs-by-source basis)) (override-originals basis source-id)))) (defn copy "Given a vector of root ids, and an options map that can contain an `:traverse?` predicate and a `serializer` function, returns a copy graph fragment that can be serialized or pasted. Works on the current basis, if a basis is not provided. The `:traverse?` predicate determines whether the target node will be included at all. If it returns a falsey value, then traversal stops there. That node and all arcs to it will be left behind. If the predicate returns true, then that node --- or a stand-in for it --- will be included in the fragment. `:traverse?` will be called with the basis and arc data. The `:serializer` function determines _how_ to represent the node in the fragment. `dynamo.graph/default-node-serializer` adds a map with the original node's properties and node type. `paste` knows how to turn that map into a new (copied) node. You would use a `:serializer` function if you wanted to record a memo that could later be used to resolve and connect to an existing node rather than copy it. `:serializer` will be called with the node value. It must return an associative data structure (e.g., a map or a record). Note that connections to or from any nodes along the override chain will be flattened to source or target the serialized node instead of the nodes that it overrides. Example: `(g/copy root-ids {:traverse? (comp not resource? #(nth % 3)) :serializer (some-fn custom-serializer default-node-serializer %)})" ([root-ids opts] (copy (now) root-ids opts)) ([basis root-ids {:keys [traverse? serializer] :or {traverse? (clojure.core/constantly false) serializer default-node-serializer} :as opts}] (s/validate opts-schema opts) (let [arcs-by-source (partial deep-arcs-by-source basis) arcs-by-target (partial gt/arcs-by-target basis) serializer #(assoc (serializer basis (gt/node-by-id-at basis %2)) :serial-id %1) original-ids (input-traverse basis traverse? root-ids) replacements (zipmap original-ids (map-indexed serializer original-ids)) serial-ids (into {} (mapcat (fn [[original-id {serial-id :serial-id}]] (map #(vector % serial-id) (override-originals basis original-id)))) replacements) include-arc? (partial ig/arc-endpoints-p (partial contains? serial-ids)) serialize-arc (partial serialize-arc serial-ids) incoming-arcs (mapcat arcs-by-target original-ids) outgoing-arcs (mapcat arcs-by-source original-ids) fragment-arcs (into [] (comp (filter include-arc?) (map serialize-arc) (distinct)) (concat incoming-arcs outgoing-arcs))] {:roots (mapv serial-ids root-ids) :nodes (vec (vals replacements)) :arcs fragment-arcs :node-id->serial-id serial-ids}))) (defn- deserialize-arc [id-dictionary arc] (-> arc (update 0 id-dictionary) (update 2 id-dictionary) (->> (apply connect)))) (defn default-node-deserializer [basis graph-id {:keys [node-type properties]}] (construct-node-with-id graph-id node-type properties)) (defn paste "Given a `graph-id` and graph fragment from copying, provides the transaction data to create the nodes on the graph and connect all the new nodes together with the same arcs in the fragment. It will take effect when it is applied with a transact. Any nodes that were replaced during the copy must be resolved into real nodes here. That is the job of the `:deserializer` function. It receives the current basis, the graph-id being pasted into, and whatever data the :serializer function returned. `dynamo.graph/default-node-deserializer` creates new nodes (copies) from the fragment. Yours may look up nodes in the world, create new instances, or anything else. The deserializer _must_ return valid transaction data, even if that data is just an empty vector. Example: `(g/paste (graph project) fragment {:deserializer default-node-deserializer})" ([graph-id fragment opts] (paste (now) graph-id fragment opts)) ([basis graph-id fragment {:keys [deserializer] :or {deserializer default-node-deserializer} :as opts}] (let [deserializer (partial deserializer basis graph-id) nodes (map deserializer (:nodes fragment)) new-nodes (remove #(gt/node-by-id-at basis (gt/node-id %)) nodes) node-txs (vec (mapcat it/new-node new-nodes)) node-ids (map gt/node-id nodes) id-dictionary (zipmap (map :serial-id (:nodes fragment)) node-ids) connect-txs (mapcat #(deserialize-arc id-dictionary %) (:arcs fragment))] {:root-node-ids (map id-dictionary (:roots fragment)) :nodes node-ids :tx-data (into node-txs connect-txs) :serial-id->node-id id-dictionary}))) ;; --------------------------------------------------------------------------- ;; Sub-graph instancing ;; --------------------------------------------------------------------------- (defn- traverse-cascade-delete [basis [source-id source-label target-id target-label]] (get (cascade-deletes (node-type* basis target-id)) target-label)) (defn override ([root-id] (override root-id {})) ([root-id opts] (override root-id opts (clojure.core/constantly []))) ([root-id {:keys [traverse? properties-by-node-id] :or {traverse? (clojure.core/constantly true) properties-by-node-id (clojure.core/constantly {})}} init-fn] (let [traverse-fn (partial predecessors (every-arc-pred in-same-graph? traverse-cascade-delete traverse?))] (it/override root-id traverse-fn init-fn properties-by-node-id)))) (defn transfer-overrides [from-id->to-id] (it/transfer-overrides from-id->to-id)) (defn overrides ([root-id] (overrides (now) root-id)) ([basis root-id] (ig/get-overrides basis root-id))) (defn override-original ([node-id] (override-original (now) node-id)) ([basis node-id] (ig/override-original basis node-id))) (defn override-root ([node-id] (override-root (now) node-id)) ([basis node-id] (if-some [original (some->> node-id (override-original basis))] (recur basis original) node-id))) (defn override? ([node-id] (override? (now) node-id)) ([basis node-id] (not (nil? (override-original basis node-id))))) (defn override-id ([node-id] (override-id (now) node-id)) ([basis node-id] (when-some [node (node-by-id basis node-id)] (:override-id node)))) (defn property-overridden? ([node-id property] (property-overridden? (now) node-id property)) ([basis node-id property] (if-let [node (node-by-id basis node-id)] (gt/property-overridden? node property) false))) (defn property-value-origin? ([node-id prop-kw] (property-value-origin? (now) node-id prop-kw)) ([basis node-id prop-kw] (if (override? basis node-id) (property-overridden? basis node-id prop-kw) true))) (defn node-type-kw "Returns the fully-qualified keyword that corresponds to the node type of the specified node id, or nil if the node does not exist." ([node-id] (:k (node-type* node-id))) ([basis node-id] (:k (node-type* basis node-id)))) (defmulti node-key "Used to identify a node uniquely within a scope. This has various uses, among them is that we will restore overridden properties during resource sync for nodes that return a non-nil node-key. Usually this only happens for ResourceNodes, but this also enables us to restore overridden properties on nodes produced by the resource :load-fn." (fn [node-id {:keys [basis] :as _evaluation-context}] (if-some [node-type-kw (node-type-kw basis node-id)] node-type-kw (throw (ex-info (str "Unknown node id: " node-id) {:node-id node-id}))))) (defmethod node-key :default [_node-id _evaluation-context] nil) (defn overridden-properties "Returns a map of overridden prop-keywords to property values. Values will be produced by property value functions if possible." [node-id {:keys [basis] :as evaluation-context}] (let [node-type (node-type* basis node-id)] (into {} (map (fn [[prop-kw raw-prop-value]] [prop-kw (if (has-property? node-type prop-kw) (node-value node-id prop-kw evaluation-context) raw-prop-value)])) (node-value node-id :_overridden-properties evaluation-context)))) (defn collect-overridden-properties "Collects overridden property values from override nodes originating from the scope of the specified source-node-id. The idea is that one should be able to delete source-node-id, recreate it from disk, and re-apply the collected property values to the freshly created override nodes resulting from the resource :load-fn. Overridden properties will be collected from nodes whose node-key multi-method implementation returns a non-nil value. This will be used as a key along with the override-id to uniquely identify the node among the new set of nodes created by the :load-fn." ([source-node-id] (with-auto-evaluation-context evaluation-context (collect-overridden-properties source-node-id evaluation-context))) ([source-node-id {:keys [basis] :as evaluation-context}] (persistent! (reduce (fn [properties-by-override-node-key override-node-id] (or (when-some [override-id (override-id basis override-node-id)] (when-some [node-key (node-key override-node-id evaluation-context)] (let [override-node-key [override-id node-key] overridden-properties (overridden-properties override-node-id evaluation-context)] (if (contains? properties-by-override-node-key override-node-key) (let [node-type-kw (node-type-kw basis override-node-id)] (throw (ex-info (format "Duplicate node key `%s` from %s" node-key node-type-kw) {:node-key node-key :node-type node-type-kw}))) (when (seq overridden-properties) (assoc! properties-by-override-node-key override-node-key overridden-properties)))))) properties-by-override-node-key)) (transient {}) (ig/pre-traverse basis [source-node-id] ig/cascade-delete-sources))))) (defn restore-overridden-properties "Restores collected-properties obtained from the collect-overridden-properties function to override nodes originating from the scope of the specified target-node-id. Returns a sequence of transaction steps. Target nodes are identified by the value returned from their node-key multi-method implementation along with the override-id that produced them." ([target-node-id collected-properties] (with-auto-evaluation-context evaluation-context (restore-overridden-properties target-node-id collected-properties evaluation-context))) ([target-node-id collected-properties {:keys [basis] :as evaluation-context}] (for [node-id (ig/pre-traverse basis [target-node-id] ig/cascade-delete-sources)] (when-some [override-id (override-id basis node-id)] (when-some [node-key (node-key node-id evaluation-context)] (let [override-node-key [override-id node-key] overridden-properties (collected-properties override-node-key)] (for [[prop-kw prop-value] overridden-properties] (set-property node-id prop-kw prop-value)))))))) ;; --------------------------------------------------------------------------- ;; Boot, initialization, and facade ;; --------------------------------------------------------------------------- (defn initialize! "Set up the initial system including graphs, caches, and disposal queues" [config] (reset! *the-system* (is/make-system config)) (low-memory/add-callback! clear-system-cache!)) (defn make-graph! "Create a new graph in the system with optional values of `:history` and `:volatility`. If no options are provided, the history ability is false and the volatility is 0 Example: `(make-graph! :history true :volatility 1)`" [& {:keys [history volatility] :or {history false volatility 0}}] (let [g (assoc (ig/empty-graph) :_volatility volatility) s (swap! *the-system* (if history is/attach-graph-with-history is/attach-graph) g)] (:last-graph s))) (defn last-graph-added "Retuns the last graph added to the system" [] (is/last-graph @*the-system*)) (defn graph-version "Returns the latest version of a graph id" [graph-id] (is/graph-time @*the-system* graph-id)) (defn delete-graph! "Given a `graph-id`, deletes it from the system Example: ` (delete-graph! agraph-id)`" [graph-id] (when-let [graph (is/graph @*the-system* graph-id)] (transact (mapv it/delete-node (ig/node-ids graph))) (swap! *the-system* is/detach-graph graph-id) nil)) (defn undo! "Given a `graph-id` resets the graph back to the last _step_ in time. Example: (undo gid)" [graph-id] (swap! *the-system* is/undo-history graph-id) nil) (defn has-undo? "Returns true/false if a `graph-id` has an undo available" [graph-id] (let [undo-stack (is/undo-stack (is/graph-history @*the-system* graph-id))] (not (empty? undo-stack)))) (defn undo-stack-count "Returns the number of entries in the undo stack for `graph-id`" [graph-id] (let [undo-stack (is/undo-stack (is/graph-history @*the-system* graph-id))] (count undo-stack))) (defn redo! "Given a `graph-id` reverts an undo of the graph Example: `(redo gid)`" [graph-id] (swap! *the-system* is/redo-history graph-id) nil) (defn has-redo? "Returns true/false if a `graph-id` has an redo available" [graph-id] (let [redo-stack (is/redo-stack (is/graph-history @*the-system* graph-id))] (not (empty? redo-stack)))) (defn reset-undo! "Given a `graph-id`, clears all undo history for the graph Example: `(reset-undo! gid)`" [graph-id] (swap! *the-system* is/clear-history graph-id) nil) (defn cancel! "Given a `graph-id` and a `sequence-id` _cancels_ any sequence of undos on the graph as if they had never happened in the history. Example: `(cancel! gid :a)`" [graph-id sequence-id] (swap! *the-system* is/cancel graph-id sequence-id) nil)
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 dynamo.graph "Main api for graph and node" (:refer-clojure :exclude [deftype constantly]) (:require [clojure.tools.macro :as ctm] [cognitect.transit :as transit] [internal.cache :as c] [internal.graph :as ig] [internal.graph.types :as gt] [internal.low-memory :as low-memory] [internal.node :as in] [internal.system :as is] [internal.transaction :as it] [internal.util :as util] [potemkin.namespaces :as namespaces] [schema.core :as s]) (:import [internal.graph.error_values ErrorValue] [java.io ByteArrayInputStream ByteArrayOutputStream])) (set! *warn-on-reflection* true) (namespaces/import-vars [internal.graph.types node-id->graph-id node->graph-id sources targets connected? dependencies Node node-id node-id? produce-value node-by-id-at]) (namespaces/import-vars [internal.graph.error-values ->error error-aggregate error-fatal error-fatal? error-info error-info? error-message error-package? error-warning error-warning? error? flatten-errors map->error package-errors precluding-errors unpack-errors worse-than]) (namespaces/import-vars [internal.node value-type-schema value-type? isa-node-type? value-type-dispatch-value has-input? has-output? has-property? type-compatible? merge-display-order NodeType supertypes declared-properties declared-property-labels declared-inputs declared-outputs cached-outputs input-dependencies input-cardinality cascade-deletes substitute-for input-type output-type input-labels output-labels property-display-order]) (namespaces/import-vars [internal.graph arc node-ids pre-traverse]) (let [graph-id ^java.util.concurrent.atomic.AtomicInteger (java.util.concurrent.atomic.AtomicInteger. 0)] (defn next-graph-id [] (.getAndIncrement graph-id))) ;; --------------------------------------------------------------------------- ;; State handling ;; --------------------------------------------------------------------------- ;; Only marked dynamic so tests can rebind. Should never be rebound "for real". (defonce ^:dynamic *the-system* (atom nil)) (def ^:dynamic *tps-debug* nil) (defn now "The basis at the current point in time" [] (is/basis @*the-system*)) (defn clone-system ([] (clone-system @*the-system*)) ([sys] (is/clone-system sys))) (defn system= [s1 s2] (is/system= s1 s2)) (defmacro with-system [sys & body] `(binding [*the-system* (atom ~sys)] ~@body)) (defn node-by-id "Returns a node given its id. If the basis is provided, it returns the value of the node using that basis. Otherwise, it uses the current basis." ([node-id] (let [graph-id (node-id->graph-id node-id)] (ig/node-id->node (is/graph @*the-system* graph-id) node-id))) ([basis node-id] (gt/node-by-id-at basis node-id))) (defn node-type* "Return the node-type given a node-id. Uses the current basis if not provided." ([node-id] (node-type* (now) node-id)) ([basis node-id] (when-let [n (gt/node-by-id-at basis node-id)] (gt/node-type n basis)))) (defn node-type "Return the node-type given a node. Uses the current basis if not provided." ([node] (node-type (now) node)) ([basis node] (when node (gt/node-type node basis)))) (defn cache "The system cache of node values" [] (is/system-cache @*the-system*)) (defn clear-system-cache! "Clears a cache (default *the-system* cache), useful when debugging" ([] (clear-system-cache! *the-system*)) ([sys-atom] (swap! sys-atom assoc :cache (is/make-cache {})) nil) ([sys-atom node-id] (let [outputs (cached-outputs (node-type* node-id)) entries (map (partial vector node-id) outputs)] (swap! sys-atom update :cache c/cache-invalidate entries) nil))) (defn graph "Given a graph id, returns the particular graph in the system at the current point in time" [graph-id] (is/graph @*the-system* graph-id)) (when *tps-debug* (def tps-counter (agent (long-array 3 0))) (defn tick [^longs tps-counts now] (let [last-report-time (aget tps-counts 1) transaction-count (inc (aget tps-counts 0))] (aset-long tps-counts 0 transaction-count) (when (> now (+ last-report-time 1000000000)) (let [elapsed-time (/ (- now last-report-time) 1000000000.00)] (do (println "TPS" (/ transaction-count elapsed-time)))) (aset-long tps-counts 1 now) (aset-long tps-counts 0 0))) tps-counts)) (defn transact "Provides a way to run a transaction against the graph system. It takes a list of transaction steps. Example: (g/transact [(g/connect n1 output-name n :xs) (g/connect n2 output-name n :xs)]) It returns the transaction result, (tx-result), which is a map containing keys about the transaction. Transaction result-keys: `[:status :basis :graphs-modified :nodes-added :nodes-modified :nodes-deleted :outputs-modified :label :sequence-label]` " [txs] (when *tps-debug* (send-off tps-counter tick (System/nanoTime))) (let [basis (is/basis @*the-system*) id-generators (is/id-generators @*the-system*) override-id-generator (is/override-id-generator @*the-system*) tx-result (it/transact* (it/new-transaction-context basis id-generators override-id-generator) txs)] (when (= :ok (:status tx-result)) (swap! *the-system* is/merge-graphs (get-in tx-result [:basis :graphs]) (:graphs-modified tx-result) (:outputs-modified tx-result) (:nodes-deleted tx-result))) tx-result)) ;; --------------------------------------------------------------------------- ;; Using transaction data ;; --------------------------------------------------------------------------- (defn tx-data-nodes-added "Returns a list of the node-ids added given a list of transaction steps, (tx-data)." [txs] (keep (fn [tx-data] (case (:type tx-data) :create-node (-> tx-data :node :_node-id) nil)) (flatten txs))) ;; --------------------------------------------------------------------------- ;; Using transaction values ;; --------------------------------------------------------------------------- (defn tx-nodes-added "Returns a list of the node-ids added given a result from a transaction, (tx-result)." [transaction] (:nodes-added transaction)) (defn is-modified? "Returns a boolean if a node, or node and output, was modified as a result of a transaction given a tx-result." ([transaction node-id] (boolean (contains? (:outputs-modified transaction) node-id))) ([transaction node-id output] (boolean (get-in transaction [:outputs-modified node-id output])))) (defn is-added? "Returns a boolean if a node was added as a result of a transaction given a tx-result and node." [transaction node-id] (contains? (:nodes-added transaction) node-id)) (defn is-deleted? "Returns a boolean if a node was delete as a result of a transaction given a tx-result and node." [transaction node-id] (contains? (:nodes-deleted transaction) node-id)) (defn outputs-modified "Returns the pairs of node-id and label of the outputs that were modified for a node as the result of a transaction given a tx-result and node" [transaction node-id] (get-in transaction [:outputs-modified node-id])) (defn transaction-basis "Returns the final basis from the result of a transaction given a tx-result" [transaction] (:basis transaction)) (defn pre-transaction-basis "Returns the original, starting basis from the result of a transaction given a tx-result" [transaction] (:original-basis transaction)) ;; --------------------------------------------------------------------------- ;; Intrinsics ;; --------------------------------------------------------------------------- (defn strip-alias "If the list ends with :as _something_, return _something_ and the list without the last two elements" [argv] (if (and (<= 2 (count argv)) (= :as (nth argv (- (count argv) 2)))) [(last argv) (take (- (count argv) 2) argv)] [nil argv])) (defmacro fnk [argv & tail] (let [param (gensym "m") [alias argv] (strip-alias (vec argv)) kargv (mapv keyword argv) arglist (interleave argv (map #(list `get param %) kargv))] (if alias `(with-meta (fn [~param] (let [~alias (select-keys ~param ~kargv) ~@(vec arglist)] ~@tail)) {:arguments (quote ~kargv)}) `(with-meta (fn [~param] (let ~(vec arglist) ~@tail)) {:arguments (quote ~kargv)})))) (defmacro defnk [symb & body] (let [[name args] (ctm/name-with-attributes symb body)] (assert (symbol? name) (str "Name for defnk is not a symbol:" name)) `(def ~name (fnk ~@args)))) (defmacro constantly [v] `(let [ret# ~v] (dynamo.graph/fnk [] ret#))) (defmacro deftype [symb & body] (let [fully-qualified-node-type-symbol (symbol (str *ns*) (str symb)) key (keyword fully-qualified-node-type-symbol)] `(do (in/register-value-type '~fully-qualified-node-type-symbol ~key) (def ~symb (in/register-value-type ~key (in/make-value-type '~symb ~key ~@body)))))) (deftype Any s/Any) (deftype Bool s/Bool) (deftype Str String) (deftype Int s/Int) (deftype Num s/Num) (deftype NodeID s/Int) (deftype Keyword s/Keyword) (deftype KeywordMap {s/Keyword s/Any}) (deftype IdPair [(s/one s/Str "id") (s/one s/Int "node-id")]) (deftype Dict {s/Str s/Int}) (deftype Properties {:properties {s/Keyword {:node-id s/Int (s/optional-key :validation-problems) s/Any :value s/Any ; Can be property value or ErrorValue :type s/Any s/Keyword s/Any}} (s/optional-key :node-id) s/Int (s/optional-key :display-order) [(s/conditional vector? [(s/one String "category") s/Keyword] keyword? s/Keyword)]}) (deftype Err ErrorValue) ;; --------------------------------------------------------------------------- ;; Definition ;; --------------------------------------------------------------------------- (defn construct "Creates an instance of a node. The node type must have been previously defined via `defnode`. The node's properties will all have their default values. The caller may pass key/value pairs to override properties. A node that has been constructed is not connected to anything and it doesn't exist in any graph yet. Example: (defnode GravityModifier (property acceleration Int (default 32)) (construct GravityModifier :acceleration 16)" [node-type-ref & {:as args}] (in/construct node-type-ref args)) (defmacro defnode "Given a name and a specification of behaviors, creates a node, and attendant functions. Allowed clauses are: (inherits _symbol_) Compose the behavior from the named node type (input _symbol_ _schema_ [:array]?) Define an input with the name, whose values must match the schema. If the :array flag is present, then this input can have multiple outputs connected to it. Without the :array flag, this input can only have one incoming connection from an output. (property _symbol_ _property-type_ & _options_) Define a property with schema and, possibly, default value and constraints. Property options include the following: (default _value_) Set a default value for the property. If no default is set, then the property will be nil. (value _getter_) Define a custom getter. It must be an fnk. The fnk's arguments are magically wired the same as an output producer. (dynamic _label_ _evaluator_) Define a dynamic attribute of the property. The label is a symbol. The evaluator is an fnk like the getter. (set (fn [evaluation-context self old-value new-value])) Define a custom setter. This is _not_ an fnk, but a strict function of 4 arguments. (output _symbol_ _type_ (:cached)? _producer_) Define an output to produce values of type. The ':cached' flag is optional. _producer_ may be a var that names an fn, or fnk. It may also be a function tail as [arglist] + forms. Values produced on an output with the :cached flag will be cached in memory until the node is affected by some change in inputs or properties. At that time, the cached value will be sent for disposal. Example (from [[editors.atlas]]): (defnode TextureCompiler (input textureset TextureSet) (property texture-filename Str (default \"\")) (output texturec Any compile-texturec))) (defnode TextureSetCompiler (input textureset TextureSet) (property textureset-filename Str (default \"\")) (output texturesetc Any compile-texturesetc))) (defnode AtlasCompiler (inherit TextureCompiler) (inherit TextureSetCompiler)) This will produce a record `AtlasCompiler`. `defnode` merges the behaviors appropriately. A node may also implement protocols or interfaces, using a syntax identical to `deftype` or `defrecord`. A node may implement any number of such protocols. Every node always implements dynamo.graph/Node." [symb & body] (let [[symb forms] (ctm/name-with-attributes symb body) fully-qualified-node-type-symbol (symbol (str *ns*) (str symb)) node-type-def (in/process-node-type-forms fully-qualified-node-type-symbol forms) fn-paths (in/extract-def-fns node-type-def) fn-defs (for [[path func] fn-paths] (list `def (in/dollar-name symb path) func)) node-type-def (util/update-paths node-type-def fn-paths (fn [path func curr] (assoc curr :fn (list `var (in/dollar-name symb path))))) node-key (:key node-type-def) derivations (for [tref (:supertypes node-type-def)] `(when-not (contains? (descendants ~(:key (deref tref))) ~node-key) (derive ~node-key ~(:key (deref tref))))) node-type-def (update node-type-def :supertypes #(list `quote %)) runtime-definer (symbol (str symb "*")) ;; TODO - investigate if we even need to register these types ;; in release builds, since we don't do schema checking? type-regs (for [[key-form value-type-form] (:register-type-info node-type-def)] `(in/register-value-type ~key-form ~value-type-form)) node-type-def (dissoc node-type-def :register-type-info)] `(do ~@type-regs ~@fn-defs (defn ~runtime-definer [] ~node-type-def) (def ~symb (in/register-node-type ~node-key (in/map->NodeTypeImpl (~runtime-definer)))) ~@derivations))) ;; --------------------------------------------------------------------------- ;; Transactions ;; --------------------------------------------------------------------------- (defmacro make-nodes "Create a number of nodes in a graph, binding them to local names to wire up connections. The resulting code will return a collection of transaction steps, including the steps to construct nodes from the bindings. If the right side of the binding is a node type, it is used directly. If it is a vector, it is treated as a node type followed by initial property values. Example: (make-nodes view [render AtlasRender scene scene/SceneRenderer background background/Gradient camera [c/CameraController :camera (c/make-orthographic)]] (g/connect background :renderable scene :renderables) (g/connect atlas-render :renderable scene :renderables))" [graph-id binding-expr & body-exprs] (assert (vector? binding-expr) "make-nodes requires a vector for its binding") (assert (even? (count binding-expr)) "make-nodes requires an even number of forms in binding vector") (let [locals (take-nth 2 binding-expr) ctors (take-nth 2 (next binding-expr)) ids (repeat (count locals) `(internal.system/next-node-id @*the-system* ~graph-id))] `(let [~@(interleave locals ids)] (concat ~@(map (fn [ctor id] (list `it/new-node (if (sequential? ctor) (if (= 2 (count ctor)) `(apply construct ~(first ctor) :_node-id ~id (mapcat identity ~(second ctor))) `(construct ~@ctor :_node-id ~id)) `(construct ~ctor :_node-id ~id)))) ctors locals) ~@body-exprs)))) (defn operation-label "Set a human-readable label to describe the current transaction." [label] (it/label label)) (defn operation-sequence "Set a machine-readable label. Successive transactions with the same label will be coalesced into a single undo point." [label] (it/sequence-label label)) (defn prev-sequence-label [graph-id] (let [sys @*the-system*] (when-let [prev-step (some-> (is/graph-history sys graph-id) (is/undo-stack) (last))] (:sequence-label prev-step)))) (defn- construct-node-with-id [graph-id node-type args] (apply construct node-type :_node-id (is/next-node-id @*the-system* graph-id) (mapcat identity args))) (defn make-node "Returns the transaction step for creating a new node. Needs to be executed within a transact to actually create the node on a graph. Example: `(transact (make-node world SimpleTestNode))`" [graph-id node-type & args] (let [args (if (empty? args) {} (if (= 1 (count args)) (first args) (apply assoc {} args)))] (it/new-node (construct-node-with-id graph-id node-type args)))) (defn make-node! "Creates the transaction step and runs it in a transaction, returning the resulting node. Example: `(make-node! world SimpleTestNode)`" [graph-id node-type & args] (first (tx-nodes-added (transact (apply make-node graph-id node-type args))))) (defn delete-node "Returns the transaction step for deleting a node. Needs to be executed within a transact to actually create the node on a graph. Example: `(transact (delete-node node-id))`" [node-id] (assert node-id) (it/delete-node node-id)) (defn delete-node! "Creates the transaction step for deleting a node and runs it in a transaction. It returns the transaction results, tx-result Example: `(delete-node! node-id)`" [node-id] (assert node-id) (transact (delete-node node-id))) (defn callback "Call the specified function with args when reaching the transaction step" [f & args] (it/callback f args)) (defn connect "Make a connection from an output of the source node to an input on the target node. Takes effect when a transaction is applied. Example: `(transact (connect content-node :scalar view-node :first-name))`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (it/connect source-id source-label target-id target-label)) (defn connect! "Creates the transaction step to make a connection from an output of the source node to an input on the target node and applies it in a transaction Example: `(connect! content-node :scalar view-node :first-name)`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (transact (connect source-id source-label target-id target-label))) (defn disconnect "Creates the transaction step to remove a connection from an output of the source node to the input on the target node. Note that there might still be connections between the two nodes, from other outputs to other inputs. Takes effect when a transaction is applied with transact. Example: (`transact (disconnect aux-node :scalar view-node :last-name))`" [source-id source-label target-id target-label] (assert source-id) (assert target-id) (it/disconnect source-id source-label target-id target-label)) (defn disconnect! "Creates the transaction step to remove a connection from an output of the source node to the input on the target node. It also applies it in transaction, returning the transaction result, (tx-result). Note that there might still be connections between the two nodes, from other outputs to other inputs. Example: `(disconnect aux-node :scalar view-node :last-name)`" [source-id source-label target-id target-label] (transact (disconnect source-id source-label target-id target-label))) (defn disconnect-sources ([target-id target-label] (disconnect-sources (now) target-id target-label)) ([basis target-id target-label] (assert target-id) (it/disconnect-sources basis target-id target-label))) (defn set-property "Creates the transaction step to assign a value to a node's property (or properties) value(s). It will take effect when the transaction is applies in a transact. Example: `(transact (set-property root-id :touched 1))`" [node-id & kvs] (assert node-id) (mapcat (fn [[p v]] (it/update-property node-id p (clojure.core/constantly v) [])) (partition-all 2 kvs))) (defn set-property! "Creates the transaction step to assign a value to a node's property (or properties) value(s) and applies it in a transaction. It returns the result of the transaction, (tx-result). Example: `(set-property! root-id :touched 1)`" [node-id & kvs] (assert node-id) (transact (apply set-property node-id kvs))) (defn update-property "Create the transaction step to apply a function to a node's property in a transaction. The function f will be invoked as if by (apply f current-value args). It will take effect when the transaction is applied in a transact. Example: `(transact (g/update-property node-id :int-prop inc))`" [node-id p f & args] (assert node-id) (it/update-property node-id p f args)) (defn update-property! "Create the transaction step to apply a function to a node's property in a transaction. Then it applies the transaction. The function f will be invoked as if by (apply f current-value args). The transaction results, (tx-result), are returned. Example: `g/update-property! node-id :int-prop inc)`" [node-id p f & args] (assert node-id) (transact (apply update-property node-id p f args))) (defn clear-property [node-id p] (assert node-id) (it/clear-property node-id p)) (defn clear-property! [node-id p] (transact (clear-property node-id p))) (defn update-graph-value [graph-id k f & args] (it/update-graph-value graph-id update (into [k f] args))) (defn set-graph-value "Create the transaction step to attach a named value to a graph. It will take effect when the transaction is applied in a transact. Example: `(transact (set-graph-value 0 :string-value \"A String\"))`" [graph-id k v] (assert graph-id) (it/update-graph-value graph-id assoc [k v])) (defn set-graph-value! "Create the transaction step to attach a named value to a graph and applies the transaction. Returns the transaction result, (tx-result). Example: (set-graph-value! 0 :string-value \"A String\")" [graph-id k v] (assert graph-id) (transact (set-graph-value graph-id k v))) (defn user-data [node-id key] (is/user-data @*the-system* node-id key)) (defn user-data! [node-id key value] (swap! *the-system* is/assoc-user-data node-id key value) value) (defn user-data-swap! [node-id key f & args] (-> (swap! *the-system* (fn [sys] (apply is/update-user-data sys node-id key f args))) (is/user-data node-id key))) (defn invalidate "Creates the transaction step to invalidate all the outputs of the node. It will take effect when the transaction is applied in a transact. Example: `(transact (invalidate node-id))`" [node-id] (assert node-id) (it/invalidate node-id)) (defn mark-defective "Creates the transaction step to mark a node as _defective_. This means that all the outputs of the node will be replace by the defective value. It will take effect when the transaction is applied in a transact. Example: `(transact (mark-defective node-id (g/error-fatal \"Resource Not Found\")))`" ([node-id defective-value] (assert node-id) (mark-defective node-id (node-type* node-id) defective-value)) ([node-id node-type defective-value] (assert node-id) (let [jammable-outputs (in/jammable-output-labels node-type)] (list (set-property node-id :_output-jammers (zipmap jammable-outputs (repeat defective-value))) (invalidate node-id))))) (defn mark-defective! "Creates the transaction step to mark a node as _defective_. This means that all the outputs of the node will be replace by the defective value. It will take effect when the transaction is applied in a transact. Example: `(mark-defective! node-id (g/error-fatal \"Resource Not Found\"))`" [node-id defective-value] (assert node-id) (transact (mark-defective node-id defective-value))) ;; --------------------------------------------------------------------------- ;; Tracing ;; --------------------------------------------------------------------------- ;; ;; Run several tracers using (juxt (g/make-print-tracer) (g/make-tree-tracer result)) ;; (defn make-print-tracer "Prints an indented tree of all eval steps taken." [] (let [depth (atom 0)] (fn [state node output-type label] (when (or (= :end state) (= :fail state)) (swap! depth dec)) (println (str (apply str (take @depth (repeat " "))) state " " node " " output-type " " label)) (when (= :begin state) (swap! depth inc))))) (defn make-tree-tracer "Creates a tree trace of the evaluation of the form {:node-id ... :output-type ... :label ... :state ... :dependencies [{...} ...]} You can also pass in a function to decorate the steps. Timing: (defn timing-decorator [step state] (case state :begin (assoc step :start-time (System/currentTimeMillis)) (:end :fail) (-> step (assoc :elapsed (- (System/currentTimeMillis) (:start-time step))) (dissoc :start-time)))) Weight: (defn weight-decorator [step state] (case state :begin step :end (assoc step :weight (+ 1 (reduce + 0 (map :weight (:dependencies step))))) :fail (assoc step :weight 0))) Depth: (defn- depth-decorator [step state] (case state :begin step :end (assoc step :depth (+ 1 (or (:depth (first (:dependencies step))) 0))) :fail (assoc step :depth 0))) (g/node-value node :output (g/make-evaluation-context {:tracer (g/make-tree-tracer result-atom timing-decorator)}))" ([result-atom] (make-tree-tracer result-atom (fn [step _] step))) ([result-atom step-decorator] (let [stack (atom '())] (fn [state node output-type label] (case state :begin (swap! stack conj (step-decorator {:node-id node :output-type output-type :label label :dependencies []} state)) (:end :fail) (let [step (step-decorator (assoc (first @stack) :state state) state)] (swap! stack rest) (let [parent (first @stack)] (if parent (swap! stack #(conj (rest %) (update parent :dependencies conj step))) (reset! result-atom step))))))))) (defn tree-trace-seq [result] (tree-seq :dependencies :dependencies result)) ;; --------------------------------------------------------------------------- ;; Values ;; --------------------------------------------------------------------------- (defn make-evaluation-context ([] (is/default-evaluation-context @*the-system*)) ([options] (is/custom-evaluation-context @*the-system* options))) (defn pruned-evaluation-context "Selectively filters out cache entries from the supplied evaluation context. Returns a new evaluation context with only the cache entries that passed the cache-entry-pred predicate. The predicate function will be called with node-id, output-label, evaluation-context and should return true if the cache entry for the output-label should remain in the cache." [evaluation-context cache-entry-pred] (in/pruned-evaluation-context evaluation-context cache-entry-pred)) (defn update-cache-from-evaluation-context! [evaluation-context] (swap! *the-system* is/update-cache-from-evaluation-context evaluation-context) nil) (defmacro with-auto-evaluation-context [ec & body] `(let [~ec (make-evaluation-context) result# (do ~@body)] (update-cache-from-evaluation-context! ~ec) result#)) (def fake-system (is/make-system {:cache-size 0})) (defmacro with-auto-or-fake-evaluation-context [ec & body] `(let [real-system# @*the-system* ~ec (is/default-evaluation-context (or real-system# fake-system)) result# (do ~@body)] (when (some? real-system#) (update-cache-from-evaluation-context! ~ec)) result#)) (defn invalidate-counter ([node-id output] (get (:invalidate-counters @*the-system*) [node-id output])) ([node-id output evaluation-context] (get (:initial-invalidate-counters evaluation-context) [node-id output]))) (defn- do-node-value [node-id label evaluation-context] (is/node-value @*the-system* node-id label evaluation-context)) (defn node-value "Pull a value from a node's output, property or input, identified by `label`. The value may be cached or it may be computed on demand. This is transparent to the caller. This uses the value of the node and its output at the time the evaluation context was created. If the evaluation context is left out, a context will be created from the current state of the system and the caller will receive a value consistent with the most recently committed transaction. The system cache is only updated automatically if the context was left out. If passed explicitly, you will need to update the cache manually by calling update-cache-from-evaluation-context!. Example: `(node-value node-id :chained-output)`" ([node-id label] (with-auto-evaluation-context evaluation-context (do-node-value node-id label evaluation-context))) ([node-id label evaluation-context] (do-node-value node-id label evaluation-context))) (defn graph-value "Returns the graph from the system given a graph-id and key. It returns the graph at the point in time of the bais, if provided. If the basis is not provided, it will take it from the current point of time in the system. Example: `(graph-value (node->graph-id view) :renderer)`" ([graph-id k] (graph-value (now) graph-id k)) ([basis graph-id k] (get-in basis [:graphs graph-id :graph-values k]))) ;; --------------------------------------------------------------------------- ;; Interrogating the Graph ;; --------------------------------------------------------------------------- (defn arcs->tuples [arcs] (ig/arcs->tuples arcs)) (defn inputs "Return the inputs to this node. Returns a collection like [[source-id output target-id input] [source-id output target-id input]...]. If there are no inputs connected, returns an empty collection." ([node-id] (inputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/inputs basis node-id)))) (defn labelled-inputs ([node-id label] (labelled-inputs (now) node-id label)) ([basis node-id label] (arcs->tuples (ig/inputs basis node-id label)))) (defn outputs "Return the outputs from this node. Returns a collection like [[source-id output target-id input] [source-id output target-id input]...]. If there are no outputs connected, returns an empty collection." ([node-id] (outputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/outputs basis node-id)))) (defn labelled-outputs ([node-id label] (labelled-outputs (now) node-id label)) ([basis node-id label] (arcs->tuples (ig/outputs basis node-id label)))) (defn explicit-inputs ([node-id] (explicit-inputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/explicit-inputs basis node-id)))) (defn explicit-outputs ([node-id] (explicit-outputs (now) node-id)) ([basis node-id] (arcs->tuples (ig/explicit-outputs basis node-id)))) (defn node-feeding-into "Find the one-and-only node ID that sources this input on this node. Should you use this on an input label with multiple connections, the result is undefined." ([node-id label] (node-feeding-into (now) node-id label)) ([basis node-id label] (ffirst (sources basis node-id label)))) (defn sources-of "Find the [node-id label] pairs for all connections into the given node's input label. The result is a sequence of pairs." ([node-id label] (sources-of (now) node-id label)) ([basis node-id label] (gt/sources basis node-id label))) (defn targets-of "Find the [node-id label] pairs for all connections out of the given node's output label. The result is a sequence of pairs." ([node-id label] (targets-of (now) node-id label)) ([basis node-id label] (gt/targets basis node-id label))) (defn find-node "Looks up nodes with a property that matches the given value. Exact equality is used. At present, this does a linear scan of all nodes. Future enhancements may offer indexing for faster access of some properties." [basis property-label expected-value] (gt/node-by-property basis property-label expected-value)) (defn invalidate-outputs! "Invalidate the given outputs and _everything_ that could be affected by them. Outputs are specified as pairs of [node-id label] for both the argument and return value." ([outputs] (swap! *the-system* is/invalidate-outputs outputs) nil)) (defn invalidate-node-outputs! [node-id] (let [labels (-> (node-type* node-id) (in/output-labels))] (invalidate-outputs! (map (partial vector node-id) labels)))) (defn node-instance*? "Returns true if the node is a member of a given type, including supertypes." ([type node] (node-instance*? (now) type node)) ([basis type node] (if-let [nt (and type (node-type basis node))] (isa? (:key @nt) (:key @type)) false))) (defn node-instance? "Returns true if the node is a member of a given type, including supertypes." ([type node-id] (node-instance? (now) type node-id)) ([basis type node-id] (node-instance*? basis type (gt/node-by-id-at basis node-id)))) ;; --------------------------------------------------------------------------- ;; Support for serialization, copy & paste, and drag & drop ;; --------------------------------------------------------------------------- (def ^:private write-handlers (transit/record-write-handlers internal.node.NodeTypeRef internal.node.ValueTypeRef)) (def ^:private read-handlers (transit/record-read-handlers internal.node.NodeTypeRef internal.node.ValueTypeRef)) (defn read-graph "Read a graph fragment from a string. Returns a fragment suitable for pasting." ([s] (read-graph s {})) ([^String s extra-handlers] (let [handlers (merge read-handlers extra-handlers) reader (transit/reader (ByteArrayInputStream. (.getBytes s "UTF-8")) :json {:handlers handlers})] (transit/read reader)))) (defn write-graph "Return a serialized string representation of the graph fragment." ([fragment] (write-graph fragment {})) ([fragment extra-handlers] (let [handlers (merge write-handlers extra-handlers) out (ByteArrayOutputStream. 4096) writer (transit/writer out :json {:handlers handlers})] (transit/write writer fragment) (.toString out "UTF-8")))) (defn- serialize-arc [id-dictionary arc] (let [[source-id source-label] (gt/source arc) [target-id target-label] (gt/target arc)] [(id-dictionary source-id) source-label (id-dictionary target-id) target-label])) (defn- in-same-graph? [_ arc] (apply = (map node-id->graph-id (take-nth 2 arc)))) (defn- every-arc-pred [& preds] (fn [basis arc] (reduce (fn [v pred] (and v (pred basis arc))) true preds))) (defn- predecessors [pred basis node-id] (into [] (comp (filter #(pred basis %)) (map first)) (inputs basis node-id))) (defn- input-traverse [basis pred root-ids] (ig/pre-traverse basis root-ids (partial predecessors (every-arc-pred in-same-graph? pred)))) (defn default-node-serializer [basis node] (let [node-id (gt/node-id node) all-node-properties (into {} (map (fn [[key value]] [key (:value value)]) (:properties (node-value node-id :_declared-properties)))) properties-without-fns (util/filterm (comp not fn? val) all-node-properties)] {:node-type (node-type basis node) :properties properties-without-fns})) (def opts-schema {(s/optional-key :traverse?) Runnable (s/optional-key :serializer) Runnable}) (defn override-originals "Given a node id, returns a sequence of node ids starting with the non-override node and proceeding with every override node leading up to and including the supplied node id." ([node-id] (override-originals (now) node-id)) ([basis node-id] (ig/override-originals basis node-id))) (defn- deep-arcs-by-source "Like arcs-by-source, but also includes connections from nodes earlier in the override chain. Note that arcs-by-target already does this." ([source-id] (deep-arcs-by-source (now) source-id)) ([basis source-id] (into [] (mapcat (partial gt/arcs-by-source basis)) (override-originals basis source-id)))) (defn copy "Given a vector of root ids, and an options map that can contain an `:traverse?` predicate and a `serializer` function, returns a copy graph fragment that can be serialized or pasted. Works on the current basis, if a basis is not provided. The `:traverse?` predicate determines whether the target node will be included at all. If it returns a falsey value, then traversal stops there. That node and all arcs to it will be left behind. If the predicate returns true, then that node --- or a stand-in for it --- will be included in the fragment. `:traverse?` will be called with the basis and arc data. The `:serializer` function determines _how_ to represent the node in the fragment. `dynamo.graph/default-node-serializer` adds a map with the original node's properties and node type. `paste` knows how to turn that map into a new (copied) node. You would use a `:serializer` function if you wanted to record a memo that could later be used to resolve and connect to an existing node rather than copy it. `:serializer` will be called with the node value. It must return an associative data structure (e.g., a map or a record). Note that connections to or from any nodes along the override chain will be flattened to source or target the serialized node instead of the nodes that it overrides. Example: `(g/copy root-ids {:traverse? (comp not resource? #(nth % 3)) :serializer (some-fn custom-serializer default-node-serializer %)})" ([root-ids opts] (copy (now) root-ids opts)) ([basis root-ids {:keys [traverse? serializer] :or {traverse? (clojure.core/constantly false) serializer default-node-serializer} :as opts}] (s/validate opts-schema opts) (let [arcs-by-source (partial deep-arcs-by-source basis) arcs-by-target (partial gt/arcs-by-target basis) serializer #(assoc (serializer basis (gt/node-by-id-at basis %2)) :serial-id %1) original-ids (input-traverse basis traverse? root-ids) replacements (zipmap original-ids (map-indexed serializer original-ids)) serial-ids (into {} (mapcat (fn [[original-id {serial-id :serial-id}]] (map #(vector % serial-id) (override-originals basis original-id)))) replacements) include-arc? (partial ig/arc-endpoints-p (partial contains? serial-ids)) serialize-arc (partial serialize-arc serial-ids) incoming-arcs (mapcat arcs-by-target original-ids) outgoing-arcs (mapcat arcs-by-source original-ids) fragment-arcs (into [] (comp (filter include-arc?) (map serialize-arc) (distinct)) (concat incoming-arcs outgoing-arcs))] {:roots (mapv serial-ids root-ids) :nodes (vec (vals replacements)) :arcs fragment-arcs :node-id->serial-id serial-ids}))) (defn- deserialize-arc [id-dictionary arc] (-> arc (update 0 id-dictionary) (update 2 id-dictionary) (->> (apply connect)))) (defn default-node-deserializer [basis graph-id {:keys [node-type properties]}] (construct-node-with-id graph-id node-type properties)) (defn paste "Given a `graph-id` and graph fragment from copying, provides the transaction data to create the nodes on the graph and connect all the new nodes together with the same arcs in the fragment. It will take effect when it is applied with a transact. Any nodes that were replaced during the copy must be resolved into real nodes here. That is the job of the `:deserializer` function. It receives the current basis, the graph-id being pasted into, and whatever data the :serializer function returned. `dynamo.graph/default-node-deserializer` creates new nodes (copies) from the fragment. Yours may look up nodes in the world, create new instances, or anything else. The deserializer _must_ return valid transaction data, even if that data is just an empty vector. Example: `(g/paste (graph project) fragment {:deserializer default-node-deserializer})" ([graph-id fragment opts] (paste (now) graph-id fragment opts)) ([basis graph-id fragment {:keys [deserializer] :or {deserializer default-node-deserializer} :as opts}] (let [deserializer (partial deserializer basis graph-id) nodes (map deserializer (:nodes fragment)) new-nodes (remove #(gt/node-by-id-at basis (gt/node-id %)) nodes) node-txs (vec (mapcat it/new-node new-nodes)) node-ids (map gt/node-id nodes) id-dictionary (zipmap (map :serial-id (:nodes fragment)) node-ids) connect-txs (mapcat #(deserialize-arc id-dictionary %) (:arcs fragment))] {:root-node-ids (map id-dictionary (:roots fragment)) :nodes node-ids :tx-data (into node-txs connect-txs) :serial-id->node-id id-dictionary}))) ;; --------------------------------------------------------------------------- ;; Sub-graph instancing ;; --------------------------------------------------------------------------- (defn- traverse-cascade-delete [basis [source-id source-label target-id target-label]] (get (cascade-deletes (node-type* basis target-id)) target-label)) (defn override ([root-id] (override root-id {})) ([root-id opts] (override root-id opts (clojure.core/constantly []))) ([root-id {:keys [traverse? properties-by-node-id] :or {traverse? (clojure.core/constantly true) properties-by-node-id (clojure.core/constantly {})}} init-fn] (let [traverse-fn (partial predecessors (every-arc-pred in-same-graph? traverse-cascade-delete traverse?))] (it/override root-id traverse-fn init-fn properties-by-node-id)))) (defn transfer-overrides [from-id->to-id] (it/transfer-overrides from-id->to-id)) (defn overrides ([root-id] (overrides (now) root-id)) ([basis root-id] (ig/get-overrides basis root-id))) (defn override-original ([node-id] (override-original (now) node-id)) ([basis node-id] (ig/override-original basis node-id))) (defn override-root ([node-id] (override-root (now) node-id)) ([basis node-id] (if-some [original (some->> node-id (override-original basis))] (recur basis original) node-id))) (defn override? ([node-id] (override? (now) node-id)) ([basis node-id] (not (nil? (override-original basis node-id))))) (defn override-id ([node-id] (override-id (now) node-id)) ([basis node-id] (when-some [node (node-by-id basis node-id)] (:override-id node)))) (defn property-overridden? ([node-id property] (property-overridden? (now) node-id property)) ([basis node-id property] (if-let [node (node-by-id basis node-id)] (gt/property-overridden? node property) false))) (defn property-value-origin? ([node-id prop-kw] (property-value-origin? (now) node-id prop-kw)) ([basis node-id prop-kw] (if (override? basis node-id) (property-overridden? basis node-id prop-kw) true))) (defn node-type-kw "Returns the fully-qualified keyword that corresponds to the node type of the specified node id, or nil if the node does not exist." ([node-id] (:k (node-type* node-id))) ([basis node-id] (:k (node-type* basis node-id)))) (defmulti node-key "Used to identify a node uniquely within a scope. This has various uses, among them is that we will restore overridden properties during resource sync for nodes that return a non-nil node-key. Usually this only happens for ResourceNodes, but this also enables us to restore overridden properties on nodes produced by the resource :load-fn." (fn [node-id {:keys [basis] :as _evaluation-context}] (if-some [node-type-kw (node-type-kw basis node-id)] node-type-kw (throw (ex-info (str "Unknown node id: " node-id) {:node-id node-id}))))) (defmethod node-key :default [_node-id _evaluation-context] nil) (defn overridden-properties "Returns a map of overridden prop-keywords to property values. Values will be produced by property value functions if possible." [node-id {:keys [basis] :as evaluation-context}] (let [node-type (node-type* basis node-id)] (into {} (map (fn [[prop-kw raw-prop-value]] [prop-kw (if (has-property? node-type prop-kw) (node-value node-id prop-kw evaluation-context) raw-prop-value)])) (node-value node-id :_overridden-properties evaluation-context)))) (defn collect-overridden-properties "Collects overridden property values from override nodes originating from the scope of the specified source-node-id. The idea is that one should be able to delete source-node-id, recreate it from disk, and re-apply the collected property values to the freshly created override nodes resulting from the resource :load-fn. Overridden properties will be collected from nodes whose node-key multi-method implementation returns a non-nil value. This will be used as a key along with the override-id to uniquely identify the node among the new set of nodes created by the :load-fn." ([source-node-id] (with-auto-evaluation-context evaluation-context (collect-overridden-properties source-node-id evaluation-context))) ([source-node-id {:keys [basis] :as evaluation-context}] (persistent! (reduce (fn [properties-by-override-node-key override-node-id] (or (when-some [override-id (override-id basis override-node-id)] (when-some [node-key (node-key override-node-id evaluation-context)] (let [override-node-key [override-id node-key] overridden-properties (overridden-properties override-node-id evaluation-context)] (if (contains? properties-by-override-node-key override-node-key) (let [node-type-kw (node-type-kw basis override-node-id)] (throw (ex-info (format "Duplicate node key `%s` from %s" node-key node-type-kw) {:node-key node-key :node-type node-type-kw}))) (when (seq overridden-properties) (assoc! properties-by-override-node-key override-node-key overridden-properties)))))) properties-by-override-node-key)) (transient {}) (ig/pre-traverse basis [source-node-id] ig/cascade-delete-sources))))) (defn restore-overridden-properties "Restores collected-properties obtained from the collect-overridden-properties function to override nodes originating from the scope of the specified target-node-id. Returns a sequence of transaction steps. Target nodes are identified by the value returned from their node-key multi-method implementation along with the override-id that produced them." ([target-node-id collected-properties] (with-auto-evaluation-context evaluation-context (restore-overridden-properties target-node-id collected-properties evaluation-context))) ([target-node-id collected-properties {:keys [basis] :as evaluation-context}] (for [node-id (ig/pre-traverse basis [target-node-id] ig/cascade-delete-sources)] (when-some [override-id (override-id basis node-id)] (when-some [node-key (node-key node-id evaluation-context)] (let [override-node-key [override-id node-key] overridden-properties (collected-properties override-node-key)] (for [[prop-kw prop-value] overridden-properties] (set-property node-id prop-kw prop-value)))))))) ;; --------------------------------------------------------------------------- ;; Boot, initialization, and facade ;; --------------------------------------------------------------------------- (defn initialize! "Set up the initial system including graphs, caches, and disposal queues" [config] (reset! *the-system* (is/make-system config)) (low-memory/add-callback! clear-system-cache!)) (defn make-graph! "Create a new graph in the system with optional values of `:history` and `:volatility`. If no options are provided, the history ability is false and the volatility is 0 Example: `(make-graph! :history true :volatility 1)`" [& {:keys [history volatility] :or {history false volatility 0}}] (let [g (assoc (ig/empty-graph) :_volatility volatility) s (swap! *the-system* (if history is/attach-graph-with-history is/attach-graph) g)] (:last-graph s))) (defn last-graph-added "Retuns the last graph added to the system" [] (is/last-graph @*the-system*)) (defn graph-version "Returns the latest version of a graph id" [graph-id] (is/graph-time @*the-system* graph-id)) (defn delete-graph! "Given a `graph-id`, deletes it from the system Example: ` (delete-graph! agraph-id)`" [graph-id] (when-let [graph (is/graph @*the-system* graph-id)] (transact (mapv it/delete-node (ig/node-ids graph))) (swap! *the-system* is/detach-graph graph-id) nil)) (defn undo! "Given a `graph-id` resets the graph back to the last _step_ in time. Example: (undo gid)" [graph-id] (swap! *the-system* is/undo-history graph-id) nil) (defn has-undo? "Returns true/false if a `graph-id` has an undo available" [graph-id] (let [undo-stack (is/undo-stack (is/graph-history @*the-system* graph-id))] (not (empty? undo-stack)))) (defn undo-stack-count "Returns the number of entries in the undo stack for `graph-id`" [graph-id] (let [undo-stack (is/undo-stack (is/graph-history @*the-system* graph-id))] (count undo-stack))) (defn redo! "Given a `graph-id` reverts an undo of the graph Example: `(redo gid)`" [graph-id] (swap! *the-system* is/redo-history graph-id) nil) (defn has-redo? "Returns true/false if a `graph-id` has an redo available" [graph-id] (let [redo-stack (is/redo-stack (is/graph-history @*the-system* graph-id))] (not (empty? redo-stack)))) (defn reset-undo! "Given a `graph-id`, clears all undo history for the graph Example: `(reset-undo! gid)`" [graph-id] (swap! *the-system* is/clear-history graph-id) nil) (defn cancel! "Given a `graph-id` and a `sequence-id` _cancels_ any sequence of undos on the graph as if they had never happened in the history. Example: `(cancel! gid :a)`" [graph-id sequence-id] (swap! *the-system* is/cancel graph-id sequence-id) nil)
[ { "context": " ])})))\n\n;; [\n;; \"v=0\n;; o=william 0 0 IN IP4 139.19.186.120\n;; s=-\n;; c=IN IP4 139.19.186.120\n;; t=0 0\n;; ", "end": 6811, "score": 0.9997488856315613, "start": 6797, "tag": "IP_ADDRESS", "value": "139.19.186.120" }, { "context": "am 0 0 IN IP4 139.19.186.120\n;; s=-\n;; c=IN IP4 139.19.186.120\n;; t=0 0\n;; m=audio 5024 RTP/AVP 96 97 98 9 100", "end": 6847, "score": 0.9997485280036926, "start": 6833, "tag": "IP_ADDRESS", "value": "139.19.186.120" }, { "context": " (go (>! rtcp-dest {:host \"127.0.0.1\" :port 1234}))\n (go (>", "end": 38619, "score": 0.99968421459198, "start": 38610, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " (go (>! sdp-dest {:host \"127.0.0.1\" :port 1234}))\n (log/i", "end": 38697, "score": 0.999688446521759, "start": 38688, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "e{acodec=ulaw,channels=1,samplerate=8000}:rtp{dst=127.0.0.1,port-audio=\" (:port local-dest) \"}'\") nil #(do (l", "end": 41546, "score": 0.9996821880340576, "start": 41537, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " {:name caller\n ", "end": 47775, "score": 0.6835638880729675, "start": 47769, "tag": "NAME", "value": "caller" }, { "context": " URI\n;; version 2.0\n;; headers {contact [{name \"herd\"\n;; uri sip:herd@127.0.0.1:18", "end": 50013, "score": 0.9903485774993896, "start": 50009, "tag": "USERNAME", "value": "herd" }, { "context": "[{name \"herd\"\n;; uri sip:herd@127.0.0.1:18750;transport=udp;registering_acc=localhost ", "end": 50060, "score": 0.9997729063034058, "start": 50051, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " call-id 659987c14fca0876dc89d5fa4ec715e5@0:0:0:0:0:0:0:0 ; this changes.\n", "end": 50366, "score": 0.983644425868988, "start": 50351, "tag": "IP_ADDRESS", "value": "0:0:0:0:0:0:0:0" }, { "context": " ; this changes.\n;; from {name \"herd\"\n;; uri sip:herd@localhost ", "end": 50445, "score": 0.9940652847290039, "start": 50441, "tag": "USERNAME", "value": "herd" }, { "context": " protocol UDP\n;; host 127.0.0.1 ", "end": 50762, "score": 0.9997774958610535, "start": 50753, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "fa6deeabaab8f\n;; received 127.0.0.1}}] ", "end": 51025, "score": 0.9997715353965759, "start": 51016, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " content-length 0\n;; to {name \"herd\"\n;; uri sip:herd@localhost\n;; ", "end": 51205, "score": 0.9931581020355225, "start": 51201, "tag": "USERNAME", "value": "herd" }, { "context": "\n;; Ann Server Bob\n;; | | | ", "end": 51456, "score": 0.5057275891304016, "start": 51453, "tag": "NAME", "value": "Bob" }, { "context": ":headers {:via [{:version 2.0 :protocol UDP :host 127.0.0.1 :port 9669\n;; :params {:branch ", "end": 52888, "score": 0.9997437596321106, "start": 52879, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "09af2cc53\n;; :received 127.0.0.1}}]\n;; :content-type application/pidf+x", "end": 53035, "score": 0.9997534155845642, "start": 53026, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " :content-length 401\n;; :to {:name \"me\"\n;; :uri sip:me@localhost\n;; ", "end": 53239, "score": 0.9753139615058899, "start": 53237, "tag": "USERNAME", "value": "me" }, { "context": " :method PUBLISH}\n;; :contact [{:name \"me\"\n;; :uri sip:me@127.0.0.1:9", "end": 53413, "score": 0.9862940907478333, "start": 53411, "tag": "USERNAME", "value": "me" }, { "context": "[{:name \"me\"\n;; :uri sip:me@127.0.0.1:9669;transport=udp;registering_acc=localhost\n;; ", "end": 53461, "score": 0.999762237071991, "start": 53452, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " :call-id a091313efa9d8c5f2c7471c2952d21de@0:0:0:0:0:0:0:0\n;; :from {:name \"me\"\n;; ", "end": 53661, "score": 0.9475474953651428, "start": 53646, "tag": "IP_ADDRESS", "value": "0:0:0:0:0:0:0:0" }, { "context": "d21de@0:0:0:0:0:0:0:0\n;; :from {:name \"me\"\n;; :uri sip:me@localhost\n;; ", "end": 53692, "score": 0.9987833499908447, "start": 53690, "tag": "USERNAME", "value": "me" }, { "context": " :protocol UDP\n;; :host 127.0.0.1\n;; :port 55590\n;; ", "end": 54400, "score": 0.9996914267539978, "start": 54391, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "c2c8c93\n;; :received 127.0.0.1}}]\n;; :expires 3600\n;; ", "end": 54575, "score": 0.9997565150260925, "start": 54566, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " :content-length 0\n;; :to {:name \"me\"\n;; :uri sip:me@localhost\n;; ", "end": 54745, "score": 0.9936539530754089, "start": 54743, "tag": "USERNAME", "value": "me" }, { "context": "thod SUBSCRIBE}\n;; :contact [{:name \"me\"\n;; :uri sip:me@127.0.0.1", "end": 54931, "score": 0.9877322316169739, "start": 54929, "tag": "USERNAME", "value": "me" }, { "context": ":name \"me\"\n;; :uri sip:me@127.0.0.1:55590;transport=udp;registering_acc=localhost\n;; ", "end": 54981, "score": 0.9960418343544006, "start": 54972, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " :call-id 9fe891081a73da36fd0d1984409fedb5@0:0:0:0:0:0:0:0\n;; :from {:name \"me\"\n;; ", "end": 55247, "score": 0.9958937764167786, "start": 55232, "tag": "IP_ADDRESS", "value": "0:0:0:0:0:0:0:0" }, { "context": "db5@0:0:0:0:0:0:0:0\n;; :from {:name \"me\"\n;; :uri sip:me@localhost\n;; ", "end": 55280, "score": 0.9740056395530701, "start": 55278, "tag": "USERNAME", "value": "me" }, { "context": "13e9ef}}}\n;;\n\n;; {:method INVITE\n;; :uri sip:lol@172.17.0.7\n;; :version 2.0\n;; :headers {:supported \" repla", "end": 55426, "score": 0.9997605085372925, "start": 55416, "tag": "IP_ADDRESS", "value": "172.17.0.7" }, { "context": " :protocol UDP\n;; :host 172.17.42.1\n;; :port 5555\n;; ", "end": 55616, "score": 0.9997917413711548, "start": 55605, "tag": "IP_ADDRESS", "value": "172.17.42.1" }, { "context": "d7bad0c60\n;; :received 172.17.42.1}}]\n;; :content-type \"application/sdp\"\n", "end": 55826, "score": 0.9997842311859131, "start": 55815, "tag": "IP_ADDRESS", "value": "172.17.42.1" }, { "context": " :to {:name nil\n;; :uri \"sip:lol@172.17.0.7\"\n;; :params {}}\n;; :cs", "end": 56013, "score": 0.9997607469558716, "start": 56003, "tag": "IP_ADDRESS", "value": "172.17.0.7" }, { "context": "name nil\n;; :uri \"sip:aoeu1@172.17.42.1:5555;transport=UDP;ob\"\n;; :", "end": 56237, "score": 0.9997823238372803, "start": 56226, "tag": "IP_ADDRESS", "value": "172.17.42.1" }, { "context": "r-agent \"PJSUA v1.14.0 Linux-3.13.5/x86_64/glibc-2.17 \"\n;; :allow \" PRACK, INVITE, ACK, BYE,", "end": 56370, "score": 0.9994502067565918, "start": 56368, "tag": "IP_ADDRESS", "value": "17" }, { "context": "m {:name nil\n;; :uri \"sip:aoeu1@172.17.0.7\"\n;; :params {:tag 676d64bf-a738", "end": 56622, "score": 0.9997386932373047, "start": 56612, "tag": "IP_ADDRESS", "value": "172.17.0.7" }, { "context": "v=0\n;; o=- 3606712585 3606712585 IN IP4 139.19.186.120\n;; s=pjmedia\n;; c=IN IP4 139.", "end": 56802, "score": 0.9997750520706177, "start": 56788, "tag": "IP_ADDRESS", "value": "139.19.186.120" }, { "context": ".120\n;; s=pjmedia\n;; c=IN IP4 139.19.186.120\n;; t=0 0\n;; a=X-nat:0\n;; ", "end": 56862, "score": 0.9997771382331848, "start": 56848, "tag": "IP_ADDRESS", "value": "139.19.186.120" }, { "context": "o 4000 RTP/AVP 96\n;; a=rtcp:4001 IN IP4 139.19.186.120\n;; a=sendrecv\n;; a=rtpmap:96 ", "end": 56988, "score": 0.9997711777687073, "start": 56974, "tag": "IP_ADDRESS", "value": "139.19.186.120" } ]
src/herd_node/sip.cljs
herd1/herd
0
(ns herd-node.sip (:require [cljs.core :as cljs] [cljs.nodejs :as node] [cljs.core.async :refer [chan <! >!]] [clojure.string :as str] [clojure.walk :as walk] [herd-node.log :as log] [herd-node.buf :as b] [herd-node.parse :as conv] [herd-node.conns :as c] [herd-node.conn-mgr :as conn] [herd-node.circ :as circ] [herd-node.path :as path] [herd-node.dir :as dir] [herd-node.dtls-comm :as dtls] [herd-node.sip-dir :as sd] [herd-node.sip-helpers :as s]) (:require-macros [cljs.core.async.macros :as m :refer [go-loop go]])) ;; Call management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; call data: ;; {:sip-ctrl sip channel dedicated to that call ;; :sip-call-id sip id we're feeding to our SIP client ;; :state state of the call} (def calls (atom {})) (def sip-to-call-id (atom {})) (defn add-sip-call [sip-id call-id] (swap! sip-to-call-id merge {sip-id call-id})) (defn add-call [call-id data] (when (:sip-call-id data) (add-sip-call (:sip-call-id data) call-id)) (swap! calls merge {call-id data})) (defn update-data [call-id keys data] (swap! calls assoc-in (cons call-id keys) data)) (defn rm-call [call-id] (when-let [sip-id (-> call-id (@calls) :sip-call-id)] (swap! sip-to-call-id dissoc sip-id)) (swap! calls dissoc call-id)) (defn kill-call [config call-id] (let [call (@calls call-id) flat-sel #(map second (select-keys %1 %2)) vlc (:vlc-child call)] (log/info "SIP killing call:" call-id) (doseq [r [:rt :rtcp] i [:in :out]] (->> call r i (circ/destroy config))) (when vlc (try (.kill js/process (.-pid vlc) "SIGKILL") (catch js/Object e (log/c-info e "VLC already exited.")))) (rm-call call-id))) (defn mk-call-id [] (-> (node/require "crypto") (.randomBytes 16) (.toString "hex"))) ;; SIP sdp creation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mk-ack [ok-200 call-id] "Creates an ACK based on the 200 ok headers." (let [h (:headers ok-200)] {:method "ACK" :uri (-> ok-200 :headers :contact first :uri) :headers {:to (-> h :to) :from (-> h :from) :call-id call-id :cseq {:method "ACK" :seq (-> h :cseq :seq)} :via []}})) (defn mk-headers [method call-id caller headers uri-to {ip :host}] "create headers for generating an invite. Uses the headers that we saved during register." {:uri uri-to :method method :headers (merge {:to {:uri uri-to} :from {:uri (str/replace (-> headers :from :uri) #"sip:\w+@" (str "sip:" caller "@")) :name caller} :call-id call-id ;:via ; thankfully, sip.js takes care of this one. :contact [{:name nil :uri (str "sip:" caller "@" ip ":5060;transport=UDP;ob") :params {}}] :cseq {:seq 1 ;(rand-int 888888) :method method}} ;; FIXME (rand-int 0xFFFFFFFF) is what we'd want. (when (= "INVITE" method) {:content-type "application/sdp"}))}) (defn mk-sdp [codec {ip :host port :port} {rtcp-port :port} method & [sdp]] ;; FIXME: Codec is temporary "generates SDP for invite or 200/ok. codec choice is hardcoded for now." (let [to-string #(apply str (interleave % (repeat "\r\n")))] (if sdp (let [[owner-sess-id owner-sess-version] (next (re-find #"o=.*\b(\d+) (\d+) IN IP" sdp)) sdp (str/replace sdp #"o=.*" (str "o=- " owner-sess-id " " (inc (js/parseInt owner-sess-version)) " IN IP4 " ip)) ;; should completely generate these, inc of that thing is only needed on re-offer/re-negotiation. sdp (str/replace sdp #"c=.*" (str "c=IN IP4 " ip)) sdp (str/replace sdp #"(m=video).*" (str "$1 " rtcp-port " RTP/AVP 105 99")) sdp (str/replace sdp #"m=audio \d+ .*" (str "m=audio " port " RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101")) ;sdp (->> sdp str/split-lines (filter #(or (not= "a" (first %)) ; (re-find #"X-nat|sendrecv|rtpmap:9 |rtcp" %)))) ] {:content sdp}) {:content (to-string ["v=0" (str "o=- 3607434973 3607434973 IN IP4 " ip) "s=-" (str "c=IN IP4 " ip) "t=0 0" "a=X-nat:0" (condp = codec :pcma (str "m=audio " port " RTP/AVP 8 96 97 98 9 100 102 0 103 3 104 101") :pcmu (str "m=audio " port " RTP/AVP 0 96 97 98 9 100 102 8 103 3 104 101") :opus (str "m=audio " port " RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101") :g722 (str "m=audio " port " RTP/AVP 9 96 97 98 100 102 0 8 103 3 104 101")) ;(str "a=rtcp:" rtcp-port " IN IP4 " ip) ;; FIXME nothing open for that yet. "a=rtpmap:96 opus/48000/2" "a=fmtp:96 usedtx=1" "a=rtpmap:97 SILK/24000" "a=rtpmap:98 SILK/16000" "a=rtpmap:9 G722/8000" "a=rtpmap:100 speex/32000" "a=rtpmap:102 speex/16000" "a=rtpmap:0 PCMU/8000" "a=rtpmap:8 PCMA/8000" "a=rtpmap:103 iLBC/8000" "a=rtpmap:3 GSM/8000" "a=rtpmap:104 speex/8000" "a=rtpmap:101 telephone-event/8000" "a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level" (str "m=video " rtcp-port " RTP/AVP 105 99") "a=recvonly" "a=rtpmap:105 H264/90000" "a=fmtp:105 profile-level-id=4DE01f;packetization-mode=1" "a=imageattr:105 send * recv [x=[0-1366],y=[0-768]]" "a=rtpmap:99 H264/90000" "a=fmtp:99 profile-level-id=4DE01f" "a=imageattr:99 send * recv [x=[0-1366],y=[0-768]]" ])}))) ;; [ ;; "v=0 ;; o=william 0 0 IN IP4 139.19.186.120 ;; s=- ;; c=IN IP4 139.19.186.120 ;; t=0 0 ;; m=audio 5024 RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101 ;; a=rtpmap:96 opus/48000/2 ;; a=fmtp:96 usedtx=1 ;; a=rtpmap:97 SILK/24000 ;; a=rtpmap:98 SILK/16000 ;; a=rtpmap:9 G722/8000 ;; a=rtpmap:100 speex/32000 ;; a=rtpmap:102 speex/16000 ;; a=rtpmap:0 PCMU/8000 ;; a=rtpmap:8 PCMA/8000 ;; a=rtpmap:103 iLBC/8000 ;; a=rtpmap:3 GSM/8000 ;; a=rtpmap:104 speex/8000 ;; a=rtpmap:101 telephone-event/8000 ;; a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level ;; m=video 5026 RTP/AVP 105 99 ;; a=recvonly ;; a=rtpmap:105 H264/90000 ;; a=fmtp:105 profile-level-id=4DE01f;packetization-mode=1 ;; a=imageattr:105 send * recv [x=[0-1366],y=[0-768]] ;; a=rtpmap:99 H264/90000 ;; a=fmtp:99 profile-level-id=4DE01f ;; a=imageattr:99 send * recv [x=[0-1366],y=[0-768]] ;; " ;; ] ;; Manage local SIP client requests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-server [config] "Creates the listening service that will process the connected SIP client's requests. Application Proxies start this service." (let [incoming-sip (chan) node-id-len (-> config :ntor-values :node-id-len)] ;; Constant we'll be using often. (go (let [sip (node/require "sip") headers (atom {}) uri-to (atom "") my-name (atom "") answering-machine (some #(= % :answering-machine) (:roles config)) ;; Prepare RDV: rdv-id (<! (path/get-path :single)) ;; FIXME we should specify what zone we want our rdv in. rdv-data (circ/get-data rdv-id) rdv-ctrl (:dest-ctrl rdv-data) rdv-notify (:notify rdv-data) ;; Outgoinp RDV: out-rdv-id (<! (path/get-path :single)) ;; FIXME we should specify what zone we want our rdv in. out-rdv-data (circ/get-data out-rdv-id) out-rdv-ctrl (:dest-ctrl out-rdv-data) out-rdv-notify (:notify out-rdv-data) ;; Prepare MIX SIG: mix-id (<! (path/get-path :one-hop)) ;; SDP parsing: get-sdp-dest (fn [rq] {:port (->> (:content rq) (re-seq #"(?m)m\=(audio)\s+(\d+)") first last) :host (second (re-find #"(?m)c\=IN IP4 ((\d+\.){3}\d+)" (:content rq)))}) get-sdp-rtcp (fn [rq] {:port (->> (:content rq) (re-seq #"(?m)m\=(video)\s*(\d+)") first last) :host (second (re-find #"(?m)c\=IN IP4 ((\d+\.){3}\d+)" (:content rq)))}) ;; temp helper select #(->> (dir/get-net-info) seq (map second) (filter %) shuffle) ;; FIXME -> this should be shared by path. distinct-hops (fn [[m1 r1 r2 m2 c]] "We are already connected to m1. Remove duplicate hops (only happens on same zone calls)." (let [id= #(= (-> %1 :auth :srv-id b/hx) (-> %2 :auth :srv-id b/hx))] (cond (id= m1 m2) [c] (or (id= r1 r2) (id= m1 r2)) [r1 m2 c] (id= r2 m2) [r2 m2 c] :else [r1 r2 m2 c]))) ;;print-hops (fn [path] ;; used for testing distinct-hops ;; (doseq [h path] ;; (println :path (-> h :auth :srv-id b/hx)))) ;; sip channel processing: skip-until (fn [found-it? from] (go-loop [r (<! from)] (if (found-it? r) r (recur (<! from))))) wait-for-bye (fn [call-id sip-ctrl {name :name local-dest :dest}] (let [{bye :bye sip-call-id :sip-call-id headers :headers uri-to :uri-to} (@calls call-id)] (skip-until #(when (or (= "BYE" (-> % :nrq :method)) (< 200 (-> % :nrq :status)) (= :bye %)) ;(.send sip bye) ;(->> (mk-headers "BYE" sip-call-id name headers uri-to local-dest) ; (merge {:content ""}) ; conv/to-js ; (.send sip)) (kill-call config call-id)) sip-ctrl))) add-sip-ctrl-to-rt-circs (fn [call-id sip-ctrl] (doseq [r [:rt :rtcp] i [:in :out] :let [circ-id (->> call-id (@calls) r i)]] (circ/update-data circ-id [:sip-ctrl] sip-ctrl))) ;; Process SIP logic: process (fn process [rq] (let [nrq (-> rq cljs/js->clj walk/keywordize-keys) contact (-> nrq :headers :contact first) name (str/replace (or (-> contact :name) ;; get name and remove surrounding "". (->> contact :uri (re-find #"sip:(.*)@") second)) #"\"" "")] ;; debug <-- ;; (println) ;; (println :nrq nrq) ;; (println :cid (-> nrq :headers :call-id (@sip-to-call-id) (@calls))) ;; (println :cid @sip-to-call-id (-> nrq :headers :call-id )) ;; debug --> (cond ;; if call is recognised: (-> nrq :headers :call-id (@sip-to-call-id)) (go (>! (-> nrq :headers :call-id (@sip-to-call-id) (@calls) :sip-ctrl) {:nrq nrq :rq rq})) (= (:method nrq) "REGISTER") (let [rdv-data (circ/get-data out-rdv-id) sip-dir-dest (first (select #(= (:role %) :sip-dir))) ack (.makeResponse sip rq 200 "OK")] ;; prepare sip successful answer (println :l (doall (map :role (select identity)))) (if (:auth sip-dir-dest) (go (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/register config name out-rdv-id rdv-id (-> rdv-data :rdv :auth :srv-id)) ;; send register to dir, ack to sip client: (sd/register-to-mix config name mix-id) ;; register our sip user name (needed for last step of incoming rt circs, without giving our ip to caller) (.send sip ack) ;; --- SIP: answer sip client, successfully registered. (reset! my-name name) (reset! uri-to (-> contact :uri)) ;; save uri & headers for building invite later: (reset! headers (-> ack cljs/js->clj walk/keywordize-keys :headers))) (do (log/error "Could not find SIP DIR in herd network") ;; debug <-- (doall (->> (dir/get-net-info) seq (map second) (map #(dissoc % :auth)) (map println))) ;; debug --> (.send sip (.makeResponse sip rq "404" "NOT FOUND"))))) (= (:method nrq) "BYE") (.send sip (.makeResponse sip rq "200" "OK")) (= (:method nrq) "SUBSCRIBE") (condp = (-> nrq :headers :event) "presence.winfo" (do (println (:event nrq)) ;; and register the gringo. (.send sip (.makeResponse sip rq 200 "OK"))) "message-summary" (do (println :200 :OK) (.send sip (.makeResponse sip rq 200 "OK"))) (.send sip (.makeResponse sip rq 501 "Not Implemented"))) (= (:method nrq) "PUBLISH") (when false (go (if (= "presence" (-> nrq :headers :event)) (let [parse-xml (-> (node/require "xml2js") .-parseString) xml (chan)] ;; debug <-- (parse-xml (:content nrq) #(go (println %2) (>! xml %2))) (println (-> (<! xml) cljs/js->clj walk/keywordize-keys)) ;; debug --> (.send sip (.makeResponse sip rq 200 "OK"))) (do (log/error "SIP: Unsupported PUBLISH event:" (-> nrq :headers :event)) (.send sip (.makeResponse sip rq 501 "Not Implemented")))))) (= (:method nrq) "OPTIONS") (.send sip (.makeResponse sip rq 200 "OK")) ;; Take care of invite: SIP client sent an invite. ;; this means we are the caller. The following will find the callee & initiate call: (= (:method nrq) "INVITE") (go (let [sip-call-id (-> nrq :headers :call-id) call-id (mk-call-id) sip-ctrl (chan) callee-name (second (re-find #"sip:(.*)@" (:uri nrq))) ;; get callee name sdp (:content nrq) sip-dir-dest (first (select #(= (:role %) :sip-dir)))] (add-call call-id {:sip-ctrl sip-ctrl :sip-call-id sip-call-id :state :ringing :headers (-> (.makeResponse sip rq 200 "OK") cljs/js->clj walk/keywordize-keys :headers) :uri-to (-> contact :uri)}) (assert (:auth sip-dir-dest) "Could not find SIP DIR in herd network") (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/query config callee-name out-rdv-id call-id) ;; query for callee's rdv (log/info "SIP:" "initiating call" call-id "to" callee-name) (let [query-reply-rdv (<! sip-ctrl) ;; get query reply rdv-data (circ/get-data rdv-id)] (if (= :error (-> query-reply-rdv :sip-rq (.readUInt8 0) s/to-cmd)) ;; FIXME: assert this instead. (do (log/error "Query for" callee-name "failed.") (.send sip (.makeResponse sip rq 404 "NOT FOUND"))) (let [callee-rdv (:data query-reply-rdv) callee-rdv-cid (.readUInt32BE callee-rdv 0) callee-rdv-id (.slice callee-rdv 4 (+ 4 node-id-len)) sdp-dest (get-sdp-dest nrq) rtcp-dest (get-sdp-rtcp nrq)] ;; parse sdp to find where the SIP client expects to receive incoming RTP. (println sdp-dest) (println rtcp-dest) (assert callee-rdv-id (str "SIP: Could not find callee's mix:" name)) (update-data call-id [:peer-rdv] callee-rdv-cid) (.send sip (.makeResponse sip rq 100 "TRYING")) ;; inform the SIP client we have initiated the call. (if (not (b/b= callee-rdv-id (-> out-rdv-id circ/get-data :rdv :auth :srv-id))) (do (>! out-rdv-ctrl (dir/find-by-id callee-rdv-id)) (<! out-rdv-notify) (log/debug "Extended to callee's RDV")) (do (>! out-rdv-ctrl :drop-last) (<! out-rdv-notify) (log/debug "We already are on callee's RDV"))) ;; FIXME: once this works we'll add relay-sip extend to callee so rdv can't read demand, ;; and client can match our HS against the keys he has for his contacts. (circ/relay-sip config out-rdv-id :f-enc (b/cat (-> :invite s/from-cmd b/new1) ;; Send invite to callee. include our rdv-id so callee can send sig to us. (b/new call-id) b/zero (b/new4 callee-rdv-cid) (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (b/new name) b/zero (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (let [reply1 (<! sip-ctrl) reply2 (<! sip-ctrl) [rtp-rep rtcp-rep] (if (= (:cmd reply1) :ack-rtcp) [reply2 reply1] [reply1 reply2])] ;; and now we wait for ack (assert (= (:cmd rtp-rep) :ack) (str "Something went wrong with call" call-id)) (.send sip (.makeResponse sip rq 180 "RINGING")) ;; we received an answer (non error) from callee, inform our SIP client that callee's phone is ringing (let [[rdv-callee-id mix-id id pub] (b/cut (:data rtp-rep) node-id-len (* 2 node-id-len) (* 3 node-id-len)) rtp-circ (<! (path/get-path :rt)) rtp-data (circ/get-data rtp-circ) rtp-ctrl (:dest-ctrl rtp-data) rtp-notify (:notify rtp-data) rtp-done (chan) [_ local-port] (<! (path/attach-circs-to-new-udp config ;; create local udp socket. in-circ will be sent to sdp-dest, the SIP client's RTP media. out-circ is where data from the sip client will be sent through to callee. (go (:circ-id rtp-rep)) rtp-done (go sdp-dest))) rtcp-circ (<! (path/get-path :rt)) rtcp-data (circ/get-data rtcp-circ) rtcp-ctrl (:dest-ctrl rtcp-data) rtcp-notify (:notify rtcp-data) rtcp-done (chan) [_ loc-rtcp-port] (<! (path/attach-circs-to-new-udp config ;; create local udp socket. in-circ will be sent to sdp-dest, the SIP client's RTP media. out-circ is where data from the sip client will be sent through to callee. (go (:circ-id rtcp-rep)) rtcp-done (go rtcp-dest))) circuit-path (distinct-hops [(:chosen-mix rdv-data) ;; our mix (:rdv rdv-data) ;; our rdv (dir/find-by-id rdv-callee-id) ;; callee's rdv (dir/find-by-id mix-id) ;; callee's mix {:auth {:pub-B pub :srv-id id}}])] ;; callee. (>! rtp-ctrl circuit-path) ;; connect to callee using given path. (>! rtcp-ctrl circuit-path) ;; connect to callee using given path. (<! rtp-notify) ;; wait until ready. (<! rtcp-notify) ;; wait until ready. (>! rtcp-done rtcp-circ) (>! rtp-done rtp-circ) (log/info "SIP: RT circuits ready for outgoing data on:" call-id) (update-data call-id [:rt] {:in (:circ-id rtp-rep) :out rtp-circ}) ;; FIXME if needed add chans. (update-data call-id [:rtcp] {:in (:circ-id rtcp-rep) :out rtcp-circ}) ;; FIXME if needed add chans. (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ackack s/from-cmd b/new1) ;; send final ack to callee, with call-id so it knows that this circuit will be used for our outgoing (its incoming) RTP. (b/new call-id) b/zero)) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ackack-rtcp s/from-cmd b/new1) ;; send final ack to callee, with call-id so it knows that this circuit will be used for our outgoing (its incoming) RTP. (b/new call-id) b/zero)) (log/info "SIP: sent ackack, ready for relay on" call-id) (let [ok (merge (assoc-in (assoc-in (conv/to-clj (.makeResponse sip rq 200 "OK")) ;; Send our client a 200 OK, with out-circ's listening udp as "callee's" dest (what caller thinks is the callee actually is herd). [:headers :content-type] "application/sdp") ;; inelegant, testing. [:headers :contact] [{:name nil :uri (str "sip:" callee-name "@" (:local-ip config) ":5060;transport=UDP;ob") :params {}}]) (mk-sdp (:codec config) {:host (:local-ip config) :port local-port} {:port loc-rtcp-port} :ack sdp))] (update-data call-id [:uri-to] (-> ok :headers :contact first :uri)) (update-data call-id [:headers] (-> ok :headers)) ;(update-data call-id [:bye] (.makeResponse sip rq)) (.send sip (conv/to-js ok))) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 500) (wait-for-bye call-id sip-ctrl {:name callee-name :dest {:host (:local-ip config)}})))))))) :else (log/error "Unsupported sip method" (:method nrq)))))] ;; Initialisation of create-server: prepare RDV, sip signalisation incoming channel. (log/debug :lol1) (>! rdv-ctrl :rdv) (log/debug :lol0.5) (>! out-rdv-ctrl :rdv) (circ/update-data rdv-id [:sip-chan] incoming-sip) (circ/update-data out-rdv-id [:sip-chan] incoming-sip) (.start sip (cljs/clj->js {:protocol "UDP"}) process) (log/debug :lol2) ;; FIXME: sip-ch is general and dispatches according to call-id to sub channels. (go-loop [query (<! incoming-sip)] (if (= query :destroy) (do (log/info "SIP lost connectivity, stopping.") (.stop sip) (doseq [call-id @calls] (kill-call config call-id))) (let [cmd (-> query :sip-rq (.readUInt8 0) s/to-cmd) [call-id msg] (-> query :sip-rq s/get-call-id) call-chan (-> call-id (@calls) :sip-ctrl)] (log/info "SIP: call-id:" call-id "-" cmd) (cond ;; try to dispatch to an existing call. Right now, sig messages from SIP client to us, and from herd nw to us are put in the same chan. We might want one for each, and avoid doing things like skip-until. call-chan (go (>! call-chan (merge query {:data msg :call-id call-id :cmd cmd}))) ;; if it's an invite, initiate call. We are the callee. (= cmd :invite) (go (let [caller-rdv-id (.readUInt32BE msg 0) [_ rdv-caller-id mix-id msg] (b/cut msg 4 (+ 4 node-id-len) (+ 4 (* 2 node-id-len))) [caller msg] (b/cut-at-null-byte msg) [id pub] (b/cut msg node-id-len) rdv-data (circ/get-data rdv-id) caller (.toString caller) sip-ctrl (chan) mix-dest (dir/find-by-id mix-id) circuit-path (distinct-hops [(:chosen-mix rdv-data) ;; our mix (:rdv rdv-data) ;; our rdv (dir/find-by-id rdv-caller-id) ;; caller's rdv (dir/find-by-id mix-id) ;; caller's mix {:auth {:pub-B pub :srv-id id}}]) ;; caller ;; rtp rtp-circ (<! (path/get-path :rt)) rtp-data (circ/get-data rtp-circ) rtp-ctrl (:dest-ctrl rtp-data) rtp-notify (:notify rtp-data) rtp-done (chan) rtp-incoming (chan) sdp-dest (chan) [_ local-port] (<! (path/attach-circs-to-new-udp config ;; our local udp socket for exchanging RTP with local sip client. rtp-incoming is caller's RTP which we'll route to the @/port which will be given in 200/OK after sending invite to it. rtp-incoming rtp-done ;; The invite we'll send will have our local sockets @/port as media, so sip client sends us RTP, we'll route it through rtp-circ. sdp-dest)) local-dest {:host (:local-ip config) :port local-port} ;; rtcp rtcp-circ (<! (path/get-path :rt)) rtcp-data (circ/get-data rtcp-circ) rtcp-ctrl (:dest-ctrl rtcp-data) rtcp-notify (:notify rtcp-data) rtcp-done (chan) rtcp-incoming (chan) rtcp-dest (chan) [_ loc-rtcp-port] (<! (path/attach-circs-to-new-udp config ;; our local udp socket for exchanging RTP with local sip client. rtp-incoming is caller's RTP which we'll route to the @/port which will be given in 200/OK after sending invite to it. rtcp-incoming rtcp-done ;; The invite we'll send will have our local sockets @/port as media, so sip client sends us RTP, we'll route it through rtp-circ. rtcp-dest)) ok-200 (atom {})] (log/info "SIP: invited by" caller "- Call-ID:" call-id "Rdv" caller-rdv-id) (add-call call-id {:sip-ctrl sip-ctrl, :sip-call-id call-id, :state :ringing, :peer-rdv caller-rdv-id :rtcp {:out rtcp-circ} :rt {:out rtp-circ} :headers @headers :uri-to @uri-to}) (if answering-machine (let [exec (.-exec (node/require "child_process"))] ; (.writeFile fs file sdp) (>! rtp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (>! rtcp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (<! rtcp-notify) ;; wait for answer. (<! rtp-notify) ;; wait for answer. (>! rtcp-done rtcp-circ) (>! rtp-done rtp-circ) (go (>! rtcp-dest {:host "127.0.0.1" :port 1234})) (go (>! sdp-dest {:host "127.0.0.1" :port 1234})) (log/info "SIP: RT circuit ready for call" call-id) (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ack s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ack-rtcp s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero)) (let [reply1 (<! (skip-until #(:circ-id %) sip-ctrl)) reply2 (<! (skip-until #(:circ-id %) sip-ctrl)) [rtp-id rtcp-id] (map :circ-id (if (= (:cmd reply1) :ackack-rtcp) [reply2 reply1] [reply1 reply2]))] ;; Wait for caller's rt path's first message. (>! rtp-incoming rtp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (>! rtcp-incoming rtcp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (update-data call-id [:rt :in] rtp-id) (update-data call-id [:rtcp :in] rtcp-id)) (log/info "SIP: got ackack, ready for relay on" call-id) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 100) (log/info "SIP: launching vlc for answering-machine playback") (update-data call-id [:vlc-child] (exec (str "cvlc '" (:answering-machine-file config) "' --play-and-exit --sout '#transcode{acodec=ulaw,channels=1,samplerate=8000}:rtp{dst=127.0.0.1,port-audio=" (:port local-dest) "}'") nil #(do (log/debug "VLC exited with:" %1) (log/debug "VLC stdout:" %2) (log/debug "VLC stdout:" %3) (kill-call config call-id)))) (wait-for-bye call-id sip-ctrl nil)) (do (.send sip (conv/to-js (merge (mk-headers "INVITE" call-id caller @headers @uri-to local-dest) ;; Send our crafted invite with local udp port as "caller's" media session (mk-sdp (:codec config) local-dest {:port loc-rtcp-port} :invite)))) (let [user-answer (<! (skip-until #(let [status (-> % :nrq :status) {user-answer :nrq} %] (cond (> 200 status) false (< 200 status) true :else (do (go (>! sdp-dest (get-sdp-dest user-answer))) ;; FIXME one go should do, test (go (>! rtcp-dest (get-sdp-rtcp user-answer))) (reset! ok-200 user-answer)))) sip-ctrl))] (if (not= 200 (-> user-answer :nrq :status)) (kill-call config call-id) (do (>! rtp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (>! rtcp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (<! rtcp-notify) ;; wait for answer. (<! rtp-notify) ;; wait for answer. (log/info "SIP: RT circuit ready for call" call-id) (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ack s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ack-rtcp s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero)) (let [reply1 (<! (skip-until #(:circ-id %) sip-ctrl)) reply2 (<! (skip-until #(:circ-id %) sip-ctrl)) [rtp-id rtcp-id] (map :circ-id (if (= (:cmd reply1) :ackack-rtcp) [reply2 reply1] [reply1 reply2]))] ;; Wait for caller's rt path's first message. (>! rtp-incoming rtp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (>! rtcp-incoming rtcp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (update-data call-id [:rt :in] rtp-id) (update-data call-id [:rtcp :in] rtcp-id)) (let [ok (mk-ack @ok-200 call-id)] (update-data call-id [:uri-to] (-> ok :uri)) (update-data call-id [:headers] (-> ok :headers)) (.send sip (conv/to-js ok))) (log/info "SIP: got ackack, ready for relay on" call-id) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 100) (wait-for-bye call-id sip-ctrl {:name caller :dest {:host (:local-ip config)}})))))))) ;; loop waiting for bye. :else (log/info "SIP: incoming message with unknown call id:" call-id "-- dropping.")) (recur (<! incoming-sip))))) (log/info "SIP proxy listening on default UDP SIP port") (when answering-machine (let [name (:answering-machine-name config) sip-dir-dest (first (select #(= (:role %) :sip-dir))) rdv-data (circ/get-data rdv-id) register #(go (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/register config name out-rdv-id rdv-id (-> rdv-data :rdv :auth :srv-id)) ;; send register to dir, ack to sip client: (sd/register-to-mix config name mix-id) ;; register our sip user name (needed for last step of incoming rt circs, without giving our ip to caller) (reset! my-name name))] (register) (js/setInterval register (/ (:sip-register-interval config) 2))))) (when (:debug config) (js/setInterval (fn [] (let [rtp-conns (filter #(-> % second :rtp-stats) (c/get-all))] (doseq [[socket {[total rtp-seq] :rtp-stats circ-id :circuit}] rtp-conns] (c/update-data socket [:rtp-stats] [0 rtp-seq]) (log/debug "RTP Status:" total "drops on circuit" circ-id "in the last 5 seconds")))) 5000))) incoming-sip)) ;; replace all uris, tags, ports by hc defaults. ;; {method REGISTER ;; uri sip:localhost ; URI ;; version 2.0 ;; headers {contact [{name "herd" ;; uri sip:herd@127.0.0.1:18750;transport=udp;registering_acc=localhost ; URI ;; params {expires 600}}] ;; user-agent Jitsi2.5.5104Linux ; becomes herd-version. ;; call-id 659987c14fca0876dc89d5fa4ec715e5@0:0:0:0:0:0:0:0 ; this changes. ;; from {name "herd" ;; uri sip:herd@localhost ; URI ;; params {tag 81429e45}} ; tag. ;; via [{version 2.0 ;; protocol UDP ;; host 127.0.0.1 ; remove this. remove via entirely? ;; port 18750 ;; params {branch z9hG4bK-313432-de5cc56153489d6de96fa6deeabaab8f ;; received 127.0.0.1}}] ; and this ;; expires 600 ;; max-forwards 70 ;; content-length 0 ;; to {name "herd" ;; uri sip:herd@localhost ;; params {}} ;; cseq {seq 1 ;; method REGISTER}} ;; content } ;; media session. ;; B2BUA ;; Ann Server Bob ;; | | | | ;; | INVITE F1 | | | ;; |------------------->| | | ;; | 100 Trying F2 | | | ;; |<-------------------| | INVITE F3 | ;; | | |------------------->| ;; | | | 100 Trying F4 | ;; | | |<-------------------| ;; | | | 180 Ringing F5 | ;; | 180 Ringing F6 | |<-------------------| ;; |<-------------------| | | ;; | | | 200 OK F7 | ;; | 200 OK F8 | |<-------------------| ;; |<-------------------| | ACK F9 | ;; | ACK F10 | |------------------->| ;; |------------------->| | | ;; | RTP Media | | RTP Media | ;; |<==================>| |<==================>| ;; | BYE F11 | | | ;; |------------------->| | BYE F12 | ;; | 200 OK F13 | |------------------->| ;; |<-------------------| | 200 OK F14 | ;; | | |<-------------------| ;; | | | | ;; presence stuff ;; (comment ;; {:method PUBLISH ;; :uri sip:me@localhost ;; :version 2.0 ;; :headers {:via [{:version 2.0 :protocol UDP :host 127.0.0.1 :port 9669 ;; :params {:branch z9hG4bK-373037-96f223ef93a23586ffc02df09af2cc53 ;; :received 127.0.0.1}}] ;; :content-type application/pidf+xml ;; :expires 3600 ;; :max-forwards 70 ;; :event presence ;; :content-length 401 ;; :to {:name "me" ;; :uri sip:me@localhost ;; :params {}} ;; :cseq {:seq 2 ;; :method PUBLISH} ;; :contact [{:name "me" ;; :uri sip:me@127.0.0.1:9669;transport=udp;registering_acc=localhost ;; :params {}}] ;; :user-agent Jitsi2.5.5104Linux ;; :call-id a091313efa9d8c5f2c7471c2952d21de@0:0:0:0:0:0:0:0 ;; :from {:name "me" ;; :uri sip:me@localhost ;; :params {:tag c4c41a24}}} ;; :content <?xml version="1.0" encoding="UTF-8" standalone="no"?><presence xmlns="urn:ietf:params:xml:ns:pidf" xmlns:dm="urn:ietf:params:xml:ns:pidf:data-model" xmlns:rpid="urn:ietf:params:xml:ns:pidf:rpid" entity="sip:me@localhost"><dm:personid="p2856"><rpid:activities/></dm:person><tuple id="t5430"><status><basic>open</basic></status><contact>sip:me@localhost</contact><note>Online</note></tuple></presence>}) ;; ;; ;; (comment ;; {:method SUBSCRIBE ;; :uri sip:me@localhost ;; :version 2.0 ;; :headers {:via [{:version 2.0 ;; :protocol UDP ;; :host 127.0.0.1 ;; :port 55590 ;; :params {:branch z9hG4bK-373037-cae0467c2ff1881dad572e4d6c2c8c93 ;; :received 127.0.0.1}}] ;; :expires 3600 ;; :max-forwards 70 ;; :event message-summary ;; :content-length 0 ;; :to {:name "me" ;; :uri sip:me@localhost ;; :params {}} ;; :cseq {:seq 1 ;; :method SUBSCRIBE} ;; :contact [{:name "me" ;; :uri sip:me@127.0.0.1:55590;transport=udp;registering_acc=localhost ;; :params {}}] ;; :user-agent Jitsi2.5.5104Linux ;; :accept application/simple-message-summary ;; :call-id 9fe891081a73da36fd0d1984409fedb5@0:0:0:0:0:0:0:0 ;; :from {:name "me" ;; :uri sip:me@localhost ;; :params {:tag ba13e9ef}}} ;; ;; {:method INVITE ;; :uri sip:lol@172.17.0.7 ;; :version 2.0 ;; :headers {:supported " replaces, 100rel, timer, norefersub," ;; :via [{:version 2.0 ;; :protocol UDP ;; :host 172.17.42.1 ;; :port 5555 ;; :params {:rport 5555 ;; :branch z9hG4bKPjb3bfc8f5-ced1-42ce-ade2-495d7bad0c60 ;; :received 172.17.42.1}}] ;; :content-type "application/sdp" ;; :max-forwards 70 ;; :content-length 230 ;; :to {:name nil ;; :uri "sip:lol@172.17.0.7" ;; :params {}} ;; :cseq {:seq 9058 ;; :method INVITE} ;; :session-expires 1800 ;; :contact [{:name nil ;; :uri "sip:aoeu1@172.17.42.1:5555;transport=UDP;ob" ;; :params {}}] ;; :user-agent "PJSUA v1.14.0 Linux-3.13.5/x86_64/glibc-2.17 " ;; :allow " PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS," ;; :call-id "4e6eb96d-c8e5-482b-ac12-f0cb9076655b" ;; :from {:name nil ;; :uri "sip:aoeu1@172.17.0.7" ;; :params {:tag 676d64bf-a738-48fe-9b6b-6c108f484edd}} ;; :min-se 90} ;; :content "v=0 ;; o=- 3606712585 3606712585 IN IP4 139.19.186.120 ;; s=pjmedia ;; c=IN IP4 139.19.186.120 ;; t=0 0 ;; a=X-nat:0 ;; m=audio 4000 RTP/AVP 96 ;; a=rtcp:4001 IN IP4 139.19.186.120 ;; a=sendrecv ;; a=rtpmap:96 telephone-event/8000 ;; a=fmtp:96 0-15" }
55722
(ns herd-node.sip (:require [cljs.core :as cljs] [cljs.nodejs :as node] [cljs.core.async :refer [chan <! >!]] [clojure.string :as str] [clojure.walk :as walk] [herd-node.log :as log] [herd-node.buf :as b] [herd-node.parse :as conv] [herd-node.conns :as c] [herd-node.conn-mgr :as conn] [herd-node.circ :as circ] [herd-node.path :as path] [herd-node.dir :as dir] [herd-node.dtls-comm :as dtls] [herd-node.sip-dir :as sd] [herd-node.sip-helpers :as s]) (:require-macros [cljs.core.async.macros :as m :refer [go-loop go]])) ;; Call management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; call data: ;; {:sip-ctrl sip channel dedicated to that call ;; :sip-call-id sip id we're feeding to our SIP client ;; :state state of the call} (def calls (atom {})) (def sip-to-call-id (atom {})) (defn add-sip-call [sip-id call-id] (swap! sip-to-call-id merge {sip-id call-id})) (defn add-call [call-id data] (when (:sip-call-id data) (add-sip-call (:sip-call-id data) call-id)) (swap! calls merge {call-id data})) (defn update-data [call-id keys data] (swap! calls assoc-in (cons call-id keys) data)) (defn rm-call [call-id] (when-let [sip-id (-> call-id (@calls) :sip-call-id)] (swap! sip-to-call-id dissoc sip-id)) (swap! calls dissoc call-id)) (defn kill-call [config call-id] (let [call (@calls call-id) flat-sel #(map second (select-keys %1 %2)) vlc (:vlc-child call)] (log/info "SIP killing call:" call-id) (doseq [r [:rt :rtcp] i [:in :out]] (->> call r i (circ/destroy config))) (when vlc (try (.kill js/process (.-pid vlc) "SIGKILL") (catch js/Object e (log/c-info e "VLC already exited.")))) (rm-call call-id))) (defn mk-call-id [] (-> (node/require "crypto") (.randomBytes 16) (.toString "hex"))) ;; SIP sdp creation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mk-ack [ok-200 call-id] "Creates an ACK based on the 200 ok headers." (let [h (:headers ok-200)] {:method "ACK" :uri (-> ok-200 :headers :contact first :uri) :headers {:to (-> h :to) :from (-> h :from) :call-id call-id :cseq {:method "ACK" :seq (-> h :cseq :seq)} :via []}})) (defn mk-headers [method call-id caller headers uri-to {ip :host}] "create headers for generating an invite. Uses the headers that we saved during register." {:uri uri-to :method method :headers (merge {:to {:uri uri-to} :from {:uri (str/replace (-> headers :from :uri) #"sip:\w+@" (str "sip:" caller "@")) :name caller} :call-id call-id ;:via ; thankfully, sip.js takes care of this one. :contact [{:name nil :uri (str "sip:" caller "@" ip ":5060;transport=UDP;ob") :params {}}] :cseq {:seq 1 ;(rand-int 888888) :method method}} ;; FIXME (rand-int 0xFFFFFFFF) is what we'd want. (when (= "INVITE" method) {:content-type "application/sdp"}))}) (defn mk-sdp [codec {ip :host port :port} {rtcp-port :port} method & [sdp]] ;; FIXME: Codec is temporary "generates SDP for invite or 200/ok. codec choice is hardcoded for now." (let [to-string #(apply str (interleave % (repeat "\r\n")))] (if sdp (let [[owner-sess-id owner-sess-version] (next (re-find #"o=.*\b(\d+) (\d+) IN IP" sdp)) sdp (str/replace sdp #"o=.*" (str "o=- " owner-sess-id " " (inc (js/parseInt owner-sess-version)) " IN IP4 " ip)) ;; should completely generate these, inc of that thing is only needed on re-offer/re-negotiation. sdp (str/replace sdp #"c=.*" (str "c=IN IP4 " ip)) sdp (str/replace sdp #"(m=video).*" (str "$1 " rtcp-port " RTP/AVP 105 99")) sdp (str/replace sdp #"m=audio \d+ .*" (str "m=audio " port " RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101")) ;sdp (->> sdp str/split-lines (filter #(or (not= "a" (first %)) ; (re-find #"X-nat|sendrecv|rtpmap:9 |rtcp" %)))) ] {:content sdp}) {:content (to-string ["v=0" (str "o=- 3607434973 3607434973 IN IP4 " ip) "s=-" (str "c=IN IP4 " ip) "t=0 0" "a=X-nat:0" (condp = codec :pcma (str "m=audio " port " RTP/AVP 8 96 97 98 9 100 102 0 103 3 104 101") :pcmu (str "m=audio " port " RTP/AVP 0 96 97 98 9 100 102 8 103 3 104 101") :opus (str "m=audio " port " RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101") :g722 (str "m=audio " port " RTP/AVP 9 96 97 98 100 102 0 8 103 3 104 101")) ;(str "a=rtcp:" rtcp-port " IN IP4 " ip) ;; FIXME nothing open for that yet. "a=rtpmap:96 opus/48000/2" "a=fmtp:96 usedtx=1" "a=rtpmap:97 SILK/24000" "a=rtpmap:98 SILK/16000" "a=rtpmap:9 G722/8000" "a=rtpmap:100 speex/32000" "a=rtpmap:102 speex/16000" "a=rtpmap:0 PCMU/8000" "a=rtpmap:8 PCMA/8000" "a=rtpmap:103 iLBC/8000" "a=rtpmap:3 GSM/8000" "a=rtpmap:104 speex/8000" "a=rtpmap:101 telephone-event/8000" "a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level" (str "m=video " rtcp-port " RTP/AVP 105 99") "a=recvonly" "a=rtpmap:105 H264/90000" "a=fmtp:105 profile-level-id=4DE01f;packetization-mode=1" "a=imageattr:105 send * recv [x=[0-1366],y=[0-768]]" "a=rtpmap:99 H264/90000" "a=fmtp:99 profile-level-id=4DE01f" "a=imageattr:99 send * recv [x=[0-1366],y=[0-768]]" ])}))) ;; [ ;; "v=0 ;; o=william 0 0 IN IP4 192.168.127.12 ;; s=- ;; c=IN IP4 192.168.127.12 ;; t=0 0 ;; m=audio 5024 RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101 ;; a=rtpmap:96 opus/48000/2 ;; a=fmtp:96 usedtx=1 ;; a=rtpmap:97 SILK/24000 ;; a=rtpmap:98 SILK/16000 ;; a=rtpmap:9 G722/8000 ;; a=rtpmap:100 speex/32000 ;; a=rtpmap:102 speex/16000 ;; a=rtpmap:0 PCMU/8000 ;; a=rtpmap:8 PCMA/8000 ;; a=rtpmap:103 iLBC/8000 ;; a=rtpmap:3 GSM/8000 ;; a=rtpmap:104 speex/8000 ;; a=rtpmap:101 telephone-event/8000 ;; a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level ;; m=video 5026 RTP/AVP 105 99 ;; a=recvonly ;; a=rtpmap:105 H264/90000 ;; a=fmtp:105 profile-level-id=4DE01f;packetization-mode=1 ;; a=imageattr:105 send * recv [x=[0-1366],y=[0-768]] ;; a=rtpmap:99 H264/90000 ;; a=fmtp:99 profile-level-id=4DE01f ;; a=imageattr:99 send * recv [x=[0-1366],y=[0-768]] ;; " ;; ] ;; Manage local SIP client requests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-server [config] "Creates the listening service that will process the connected SIP client's requests. Application Proxies start this service." (let [incoming-sip (chan) node-id-len (-> config :ntor-values :node-id-len)] ;; Constant we'll be using often. (go (let [sip (node/require "sip") headers (atom {}) uri-to (atom "") my-name (atom "") answering-machine (some #(= % :answering-machine) (:roles config)) ;; Prepare RDV: rdv-id (<! (path/get-path :single)) ;; FIXME we should specify what zone we want our rdv in. rdv-data (circ/get-data rdv-id) rdv-ctrl (:dest-ctrl rdv-data) rdv-notify (:notify rdv-data) ;; Outgoinp RDV: out-rdv-id (<! (path/get-path :single)) ;; FIXME we should specify what zone we want our rdv in. out-rdv-data (circ/get-data out-rdv-id) out-rdv-ctrl (:dest-ctrl out-rdv-data) out-rdv-notify (:notify out-rdv-data) ;; Prepare MIX SIG: mix-id (<! (path/get-path :one-hop)) ;; SDP parsing: get-sdp-dest (fn [rq] {:port (->> (:content rq) (re-seq #"(?m)m\=(audio)\s+(\d+)") first last) :host (second (re-find #"(?m)c\=IN IP4 ((\d+\.){3}\d+)" (:content rq)))}) get-sdp-rtcp (fn [rq] {:port (->> (:content rq) (re-seq #"(?m)m\=(video)\s*(\d+)") first last) :host (second (re-find #"(?m)c\=IN IP4 ((\d+\.){3}\d+)" (:content rq)))}) ;; temp helper select #(->> (dir/get-net-info) seq (map second) (filter %) shuffle) ;; FIXME -> this should be shared by path. distinct-hops (fn [[m1 r1 r2 m2 c]] "We are already connected to m1. Remove duplicate hops (only happens on same zone calls)." (let [id= #(= (-> %1 :auth :srv-id b/hx) (-> %2 :auth :srv-id b/hx))] (cond (id= m1 m2) [c] (or (id= r1 r2) (id= m1 r2)) [r1 m2 c] (id= r2 m2) [r2 m2 c] :else [r1 r2 m2 c]))) ;;print-hops (fn [path] ;; used for testing distinct-hops ;; (doseq [h path] ;; (println :path (-> h :auth :srv-id b/hx)))) ;; sip channel processing: skip-until (fn [found-it? from] (go-loop [r (<! from)] (if (found-it? r) r (recur (<! from))))) wait-for-bye (fn [call-id sip-ctrl {name :name local-dest :dest}] (let [{bye :bye sip-call-id :sip-call-id headers :headers uri-to :uri-to} (@calls call-id)] (skip-until #(when (or (= "BYE" (-> % :nrq :method)) (< 200 (-> % :nrq :status)) (= :bye %)) ;(.send sip bye) ;(->> (mk-headers "BYE" sip-call-id name headers uri-to local-dest) ; (merge {:content ""}) ; conv/to-js ; (.send sip)) (kill-call config call-id)) sip-ctrl))) add-sip-ctrl-to-rt-circs (fn [call-id sip-ctrl] (doseq [r [:rt :rtcp] i [:in :out] :let [circ-id (->> call-id (@calls) r i)]] (circ/update-data circ-id [:sip-ctrl] sip-ctrl))) ;; Process SIP logic: process (fn process [rq] (let [nrq (-> rq cljs/js->clj walk/keywordize-keys) contact (-> nrq :headers :contact first) name (str/replace (or (-> contact :name) ;; get name and remove surrounding "". (->> contact :uri (re-find #"sip:(.*)@") second)) #"\"" "")] ;; debug <-- ;; (println) ;; (println :nrq nrq) ;; (println :cid (-> nrq :headers :call-id (@sip-to-call-id) (@calls))) ;; (println :cid @sip-to-call-id (-> nrq :headers :call-id )) ;; debug --> (cond ;; if call is recognised: (-> nrq :headers :call-id (@sip-to-call-id)) (go (>! (-> nrq :headers :call-id (@sip-to-call-id) (@calls) :sip-ctrl) {:nrq nrq :rq rq})) (= (:method nrq) "REGISTER") (let [rdv-data (circ/get-data out-rdv-id) sip-dir-dest (first (select #(= (:role %) :sip-dir))) ack (.makeResponse sip rq 200 "OK")] ;; prepare sip successful answer (println :l (doall (map :role (select identity)))) (if (:auth sip-dir-dest) (go (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/register config name out-rdv-id rdv-id (-> rdv-data :rdv :auth :srv-id)) ;; send register to dir, ack to sip client: (sd/register-to-mix config name mix-id) ;; register our sip user name (needed for last step of incoming rt circs, without giving our ip to caller) (.send sip ack) ;; --- SIP: answer sip client, successfully registered. (reset! my-name name) (reset! uri-to (-> contact :uri)) ;; save uri & headers for building invite later: (reset! headers (-> ack cljs/js->clj walk/keywordize-keys :headers))) (do (log/error "Could not find SIP DIR in herd network") ;; debug <-- (doall (->> (dir/get-net-info) seq (map second) (map #(dissoc % :auth)) (map println))) ;; debug --> (.send sip (.makeResponse sip rq "404" "NOT FOUND"))))) (= (:method nrq) "BYE") (.send sip (.makeResponse sip rq "200" "OK")) (= (:method nrq) "SUBSCRIBE") (condp = (-> nrq :headers :event) "presence.winfo" (do (println (:event nrq)) ;; and register the gringo. (.send sip (.makeResponse sip rq 200 "OK"))) "message-summary" (do (println :200 :OK) (.send sip (.makeResponse sip rq 200 "OK"))) (.send sip (.makeResponse sip rq 501 "Not Implemented"))) (= (:method nrq) "PUBLISH") (when false (go (if (= "presence" (-> nrq :headers :event)) (let [parse-xml (-> (node/require "xml2js") .-parseString) xml (chan)] ;; debug <-- (parse-xml (:content nrq) #(go (println %2) (>! xml %2))) (println (-> (<! xml) cljs/js->clj walk/keywordize-keys)) ;; debug --> (.send sip (.makeResponse sip rq 200 "OK"))) (do (log/error "SIP: Unsupported PUBLISH event:" (-> nrq :headers :event)) (.send sip (.makeResponse sip rq 501 "Not Implemented")))))) (= (:method nrq) "OPTIONS") (.send sip (.makeResponse sip rq 200 "OK")) ;; Take care of invite: SIP client sent an invite. ;; this means we are the caller. The following will find the callee & initiate call: (= (:method nrq) "INVITE") (go (let [sip-call-id (-> nrq :headers :call-id) call-id (mk-call-id) sip-ctrl (chan) callee-name (second (re-find #"sip:(.*)@" (:uri nrq))) ;; get callee name sdp (:content nrq) sip-dir-dest (first (select #(= (:role %) :sip-dir)))] (add-call call-id {:sip-ctrl sip-ctrl :sip-call-id sip-call-id :state :ringing :headers (-> (.makeResponse sip rq 200 "OK") cljs/js->clj walk/keywordize-keys :headers) :uri-to (-> contact :uri)}) (assert (:auth sip-dir-dest) "Could not find SIP DIR in herd network") (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/query config callee-name out-rdv-id call-id) ;; query for callee's rdv (log/info "SIP:" "initiating call" call-id "to" callee-name) (let [query-reply-rdv (<! sip-ctrl) ;; get query reply rdv-data (circ/get-data rdv-id)] (if (= :error (-> query-reply-rdv :sip-rq (.readUInt8 0) s/to-cmd)) ;; FIXME: assert this instead. (do (log/error "Query for" callee-name "failed.") (.send sip (.makeResponse sip rq 404 "NOT FOUND"))) (let [callee-rdv (:data query-reply-rdv) callee-rdv-cid (.readUInt32BE callee-rdv 0) callee-rdv-id (.slice callee-rdv 4 (+ 4 node-id-len)) sdp-dest (get-sdp-dest nrq) rtcp-dest (get-sdp-rtcp nrq)] ;; parse sdp to find where the SIP client expects to receive incoming RTP. (println sdp-dest) (println rtcp-dest) (assert callee-rdv-id (str "SIP: Could not find callee's mix:" name)) (update-data call-id [:peer-rdv] callee-rdv-cid) (.send sip (.makeResponse sip rq 100 "TRYING")) ;; inform the SIP client we have initiated the call. (if (not (b/b= callee-rdv-id (-> out-rdv-id circ/get-data :rdv :auth :srv-id))) (do (>! out-rdv-ctrl (dir/find-by-id callee-rdv-id)) (<! out-rdv-notify) (log/debug "Extended to callee's RDV")) (do (>! out-rdv-ctrl :drop-last) (<! out-rdv-notify) (log/debug "We already are on callee's RDV"))) ;; FIXME: once this works we'll add relay-sip extend to callee so rdv can't read demand, ;; and client can match our HS against the keys he has for his contacts. (circ/relay-sip config out-rdv-id :f-enc (b/cat (-> :invite s/from-cmd b/new1) ;; Send invite to callee. include our rdv-id so callee can send sig to us. (b/new call-id) b/zero (b/new4 callee-rdv-cid) (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (b/new name) b/zero (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (let [reply1 (<! sip-ctrl) reply2 (<! sip-ctrl) [rtp-rep rtcp-rep] (if (= (:cmd reply1) :ack-rtcp) [reply2 reply1] [reply1 reply2])] ;; and now we wait for ack (assert (= (:cmd rtp-rep) :ack) (str "Something went wrong with call" call-id)) (.send sip (.makeResponse sip rq 180 "RINGING")) ;; we received an answer (non error) from callee, inform our SIP client that callee's phone is ringing (let [[rdv-callee-id mix-id id pub] (b/cut (:data rtp-rep) node-id-len (* 2 node-id-len) (* 3 node-id-len)) rtp-circ (<! (path/get-path :rt)) rtp-data (circ/get-data rtp-circ) rtp-ctrl (:dest-ctrl rtp-data) rtp-notify (:notify rtp-data) rtp-done (chan) [_ local-port] (<! (path/attach-circs-to-new-udp config ;; create local udp socket. in-circ will be sent to sdp-dest, the SIP client's RTP media. out-circ is where data from the sip client will be sent through to callee. (go (:circ-id rtp-rep)) rtp-done (go sdp-dest))) rtcp-circ (<! (path/get-path :rt)) rtcp-data (circ/get-data rtcp-circ) rtcp-ctrl (:dest-ctrl rtcp-data) rtcp-notify (:notify rtcp-data) rtcp-done (chan) [_ loc-rtcp-port] (<! (path/attach-circs-to-new-udp config ;; create local udp socket. in-circ will be sent to sdp-dest, the SIP client's RTP media. out-circ is where data from the sip client will be sent through to callee. (go (:circ-id rtcp-rep)) rtcp-done (go rtcp-dest))) circuit-path (distinct-hops [(:chosen-mix rdv-data) ;; our mix (:rdv rdv-data) ;; our rdv (dir/find-by-id rdv-callee-id) ;; callee's rdv (dir/find-by-id mix-id) ;; callee's mix {:auth {:pub-B pub :srv-id id}}])] ;; callee. (>! rtp-ctrl circuit-path) ;; connect to callee using given path. (>! rtcp-ctrl circuit-path) ;; connect to callee using given path. (<! rtp-notify) ;; wait until ready. (<! rtcp-notify) ;; wait until ready. (>! rtcp-done rtcp-circ) (>! rtp-done rtp-circ) (log/info "SIP: RT circuits ready for outgoing data on:" call-id) (update-data call-id [:rt] {:in (:circ-id rtp-rep) :out rtp-circ}) ;; FIXME if needed add chans. (update-data call-id [:rtcp] {:in (:circ-id rtcp-rep) :out rtcp-circ}) ;; FIXME if needed add chans. (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ackack s/from-cmd b/new1) ;; send final ack to callee, with call-id so it knows that this circuit will be used for our outgoing (its incoming) RTP. (b/new call-id) b/zero)) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ackack-rtcp s/from-cmd b/new1) ;; send final ack to callee, with call-id so it knows that this circuit will be used for our outgoing (its incoming) RTP. (b/new call-id) b/zero)) (log/info "SIP: sent ackack, ready for relay on" call-id) (let [ok (merge (assoc-in (assoc-in (conv/to-clj (.makeResponse sip rq 200 "OK")) ;; Send our client a 200 OK, with out-circ's listening udp as "callee's" dest (what caller thinks is the callee actually is herd). [:headers :content-type] "application/sdp") ;; inelegant, testing. [:headers :contact] [{:name nil :uri (str "sip:" callee-name "@" (:local-ip config) ":5060;transport=UDP;ob") :params {}}]) (mk-sdp (:codec config) {:host (:local-ip config) :port local-port} {:port loc-rtcp-port} :ack sdp))] (update-data call-id [:uri-to] (-> ok :headers :contact first :uri)) (update-data call-id [:headers] (-> ok :headers)) ;(update-data call-id [:bye] (.makeResponse sip rq)) (.send sip (conv/to-js ok))) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 500) (wait-for-bye call-id sip-ctrl {:name callee-name :dest {:host (:local-ip config)}})))))))) :else (log/error "Unsupported sip method" (:method nrq)))))] ;; Initialisation of create-server: prepare RDV, sip signalisation incoming channel. (log/debug :lol1) (>! rdv-ctrl :rdv) (log/debug :lol0.5) (>! out-rdv-ctrl :rdv) (circ/update-data rdv-id [:sip-chan] incoming-sip) (circ/update-data out-rdv-id [:sip-chan] incoming-sip) (.start sip (cljs/clj->js {:protocol "UDP"}) process) (log/debug :lol2) ;; FIXME: sip-ch is general and dispatches according to call-id to sub channels. (go-loop [query (<! incoming-sip)] (if (= query :destroy) (do (log/info "SIP lost connectivity, stopping.") (.stop sip) (doseq [call-id @calls] (kill-call config call-id))) (let [cmd (-> query :sip-rq (.readUInt8 0) s/to-cmd) [call-id msg] (-> query :sip-rq s/get-call-id) call-chan (-> call-id (@calls) :sip-ctrl)] (log/info "SIP: call-id:" call-id "-" cmd) (cond ;; try to dispatch to an existing call. Right now, sig messages from SIP client to us, and from herd nw to us are put in the same chan. We might want one for each, and avoid doing things like skip-until. call-chan (go (>! call-chan (merge query {:data msg :call-id call-id :cmd cmd}))) ;; if it's an invite, initiate call. We are the callee. (= cmd :invite) (go (let [caller-rdv-id (.readUInt32BE msg 0) [_ rdv-caller-id mix-id msg] (b/cut msg 4 (+ 4 node-id-len) (+ 4 (* 2 node-id-len))) [caller msg] (b/cut-at-null-byte msg) [id pub] (b/cut msg node-id-len) rdv-data (circ/get-data rdv-id) caller (.toString caller) sip-ctrl (chan) mix-dest (dir/find-by-id mix-id) circuit-path (distinct-hops [(:chosen-mix rdv-data) ;; our mix (:rdv rdv-data) ;; our rdv (dir/find-by-id rdv-caller-id) ;; caller's rdv (dir/find-by-id mix-id) ;; caller's mix {:auth {:pub-B pub :srv-id id}}]) ;; caller ;; rtp rtp-circ (<! (path/get-path :rt)) rtp-data (circ/get-data rtp-circ) rtp-ctrl (:dest-ctrl rtp-data) rtp-notify (:notify rtp-data) rtp-done (chan) rtp-incoming (chan) sdp-dest (chan) [_ local-port] (<! (path/attach-circs-to-new-udp config ;; our local udp socket for exchanging RTP with local sip client. rtp-incoming is caller's RTP which we'll route to the @/port which will be given in 200/OK after sending invite to it. rtp-incoming rtp-done ;; The invite we'll send will have our local sockets @/port as media, so sip client sends us RTP, we'll route it through rtp-circ. sdp-dest)) local-dest {:host (:local-ip config) :port local-port} ;; rtcp rtcp-circ (<! (path/get-path :rt)) rtcp-data (circ/get-data rtcp-circ) rtcp-ctrl (:dest-ctrl rtcp-data) rtcp-notify (:notify rtcp-data) rtcp-done (chan) rtcp-incoming (chan) rtcp-dest (chan) [_ loc-rtcp-port] (<! (path/attach-circs-to-new-udp config ;; our local udp socket for exchanging RTP with local sip client. rtp-incoming is caller's RTP which we'll route to the @/port which will be given in 200/OK after sending invite to it. rtcp-incoming rtcp-done ;; The invite we'll send will have our local sockets @/port as media, so sip client sends us RTP, we'll route it through rtp-circ. rtcp-dest)) ok-200 (atom {})] (log/info "SIP: invited by" caller "- Call-ID:" call-id "Rdv" caller-rdv-id) (add-call call-id {:sip-ctrl sip-ctrl, :sip-call-id call-id, :state :ringing, :peer-rdv caller-rdv-id :rtcp {:out rtcp-circ} :rt {:out rtp-circ} :headers @headers :uri-to @uri-to}) (if answering-machine (let [exec (.-exec (node/require "child_process"))] ; (.writeFile fs file sdp) (>! rtp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (>! rtcp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (<! rtcp-notify) ;; wait for answer. (<! rtp-notify) ;; wait for answer. (>! rtcp-done rtcp-circ) (>! rtp-done rtp-circ) (go (>! rtcp-dest {:host "127.0.0.1" :port 1234})) (go (>! sdp-dest {:host "127.0.0.1" :port 1234})) (log/info "SIP: RT circuit ready for call" call-id) (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ack s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ack-rtcp s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero)) (let [reply1 (<! (skip-until #(:circ-id %) sip-ctrl)) reply2 (<! (skip-until #(:circ-id %) sip-ctrl)) [rtp-id rtcp-id] (map :circ-id (if (= (:cmd reply1) :ackack-rtcp) [reply2 reply1] [reply1 reply2]))] ;; Wait for caller's rt path's first message. (>! rtp-incoming rtp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (>! rtcp-incoming rtcp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (update-data call-id [:rt :in] rtp-id) (update-data call-id [:rtcp :in] rtcp-id)) (log/info "SIP: got ackack, ready for relay on" call-id) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 100) (log/info "SIP: launching vlc for answering-machine playback") (update-data call-id [:vlc-child] (exec (str "cvlc '" (:answering-machine-file config) "' --play-and-exit --sout '#transcode{acodec=ulaw,channels=1,samplerate=8000}:rtp{dst=127.0.0.1,port-audio=" (:port local-dest) "}'") nil #(do (log/debug "VLC exited with:" %1) (log/debug "VLC stdout:" %2) (log/debug "VLC stdout:" %3) (kill-call config call-id)))) (wait-for-bye call-id sip-ctrl nil)) (do (.send sip (conv/to-js (merge (mk-headers "INVITE" call-id caller @headers @uri-to local-dest) ;; Send our crafted invite with local udp port as "caller's" media session (mk-sdp (:codec config) local-dest {:port loc-rtcp-port} :invite)))) (let [user-answer (<! (skip-until #(let [status (-> % :nrq :status) {user-answer :nrq} %] (cond (> 200 status) false (< 200 status) true :else (do (go (>! sdp-dest (get-sdp-dest user-answer))) ;; FIXME one go should do, test (go (>! rtcp-dest (get-sdp-rtcp user-answer))) (reset! ok-200 user-answer)))) sip-ctrl))] (if (not= 200 (-> user-answer :nrq :status)) (kill-call config call-id) (do (>! rtp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (>! rtcp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (<! rtcp-notify) ;; wait for answer. (<! rtp-notify) ;; wait for answer. (log/info "SIP: RT circuit ready for call" call-id) (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ack s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ack-rtcp s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero)) (let [reply1 (<! (skip-until #(:circ-id %) sip-ctrl)) reply2 (<! (skip-until #(:circ-id %) sip-ctrl)) [rtp-id rtcp-id] (map :circ-id (if (= (:cmd reply1) :ackack-rtcp) [reply2 reply1] [reply1 reply2]))] ;; Wait for caller's rt path's first message. (>! rtp-incoming rtp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (>! rtcp-incoming rtcp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (update-data call-id [:rt :in] rtp-id) (update-data call-id [:rtcp :in] rtcp-id)) (let [ok (mk-ack @ok-200 call-id)] (update-data call-id [:uri-to] (-> ok :uri)) (update-data call-id [:headers] (-> ok :headers)) (.send sip (conv/to-js ok))) (log/info "SIP: got ackack, ready for relay on" call-id) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 100) (wait-for-bye call-id sip-ctrl {:name <NAME> :dest {:host (:local-ip config)}})))))))) ;; loop waiting for bye. :else (log/info "SIP: incoming message with unknown call id:" call-id "-- dropping.")) (recur (<! incoming-sip))))) (log/info "SIP proxy listening on default UDP SIP port") (when answering-machine (let [name (:answering-machine-name config) sip-dir-dest (first (select #(= (:role %) :sip-dir))) rdv-data (circ/get-data rdv-id) register #(go (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/register config name out-rdv-id rdv-id (-> rdv-data :rdv :auth :srv-id)) ;; send register to dir, ack to sip client: (sd/register-to-mix config name mix-id) ;; register our sip user name (needed for last step of incoming rt circs, without giving our ip to caller) (reset! my-name name))] (register) (js/setInterval register (/ (:sip-register-interval config) 2))))) (when (:debug config) (js/setInterval (fn [] (let [rtp-conns (filter #(-> % second :rtp-stats) (c/get-all))] (doseq [[socket {[total rtp-seq] :rtp-stats circ-id :circuit}] rtp-conns] (c/update-data socket [:rtp-stats] [0 rtp-seq]) (log/debug "RTP Status:" total "drops on circuit" circ-id "in the last 5 seconds")))) 5000))) incoming-sip)) ;; replace all uris, tags, ports by hc defaults. ;; {method REGISTER ;; uri sip:localhost ; URI ;; version 2.0 ;; headers {contact [{name "herd" ;; uri sip:herd@127.0.0.1:18750;transport=udp;registering_acc=localhost ; URI ;; params {expires 600}}] ;; user-agent Jitsi2.5.5104Linux ; becomes herd-version. ;; call-id 659987c14fca0876dc89d5fa4ec715e5@0:0:0:0:0:0:0:0 ; this changes. ;; from {name "herd" ;; uri sip:herd@localhost ; URI ;; params {tag 81429e45}} ; tag. ;; via [{version 2.0 ;; protocol UDP ;; host 127.0.0.1 ; remove this. remove via entirely? ;; port 18750 ;; params {branch z9hG4bK-313432-de5cc56153489d6de96fa6deeabaab8f ;; received 127.0.0.1}}] ; and this ;; expires 600 ;; max-forwards 70 ;; content-length 0 ;; to {name "herd" ;; uri sip:herd@localhost ;; params {}} ;; cseq {seq 1 ;; method REGISTER}} ;; content } ;; media session. ;; B2BUA ;; Ann Server <NAME> ;; | | | | ;; | INVITE F1 | | | ;; |------------------->| | | ;; | 100 Trying F2 | | | ;; |<-------------------| | INVITE F3 | ;; | | |------------------->| ;; | | | 100 Trying F4 | ;; | | |<-------------------| ;; | | | 180 Ringing F5 | ;; | 180 Ringing F6 | |<-------------------| ;; |<-------------------| | | ;; | | | 200 OK F7 | ;; | 200 OK F8 | |<-------------------| ;; |<-------------------| | ACK F9 | ;; | ACK F10 | |------------------->| ;; |------------------->| | | ;; | RTP Media | | RTP Media | ;; |<==================>| |<==================>| ;; | BYE F11 | | | ;; |------------------->| | BYE F12 | ;; | 200 OK F13 | |------------------->| ;; |<-------------------| | 200 OK F14 | ;; | | |<-------------------| ;; | | | | ;; presence stuff ;; (comment ;; {:method PUBLISH ;; :uri sip:me@localhost ;; :version 2.0 ;; :headers {:via [{:version 2.0 :protocol UDP :host 127.0.0.1 :port 9669 ;; :params {:branch z9hG4bK-373037-96f223ef93a23586ffc02df09af2cc53 ;; :received 127.0.0.1}}] ;; :content-type application/pidf+xml ;; :expires 3600 ;; :max-forwards 70 ;; :event presence ;; :content-length 401 ;; :to {:name "me" ;; :uri sip:me@localhost ;; :params {}} ;; :cseq {:seq 2 ;; :method PUBLISH} ;; :contact [{:name "me" ;; :uri sip:me@127.0.0.1:9669;transport=udp;registering_acc=localhost ;; :params {}}] ;; :user-agent Jitsi2.5.5104Linux ;; :call-id a091313efa9d8c5f2c7471c2952d21de@0:0:0:0:0:0:0:0 ;; :from {:name "me" ;; :uri sip:me@localhost ;; :params {:tag c4c41a24}}} ;; :content <?xml version="1.0" encoding="UTF-8" standalone="no"?><presence xmlns="urn:ietf:params:xml:ns:pidf" xmlns:dm="urn:ietf:params:xml:ns:pidf:data-model" xmlns:rpid="urn:ietf:params:xml:ns:pidf:rpid" entity="sip:me@localhost"><dm:personid="p2856"><rpid:activities/></dm:person><tuple id="t5430"><status><basic>open</basic></status><contact>sip:me@localhost</contact><note>Online</note></tuple></presence>}) ;; ;; ;; (comment ;; {:method SUBSCRIBE ;; :uri sip:me@localhost ;; :version 2.0 ;; :headers {:via [{:version 2.0 ;; :protocol UDP ;; :host 127.0.0.1 ;; :port 55590 ;; :params {:branch z9hG4bK-373037-cae0467c2ff1881dad572e4d6c2c8c93 ;; :received 127.0.0.1}}] ;; :expires 3600 ;; :max-forwards 70 ;; :event message-summary ;; :content-length 0 ;; :to {:name "me" ;; :uri sip:me@localhost ;; :params {}} ;; :cseq {:seq 1 ;; :method SUBSCRIBE} ;; :contact [{:name "me" ;; :uri sip:me@127.0.0.1:55590;transport=udp;registering_acc=localhost ;; :params {}}] ;; :user-agent Jitsi2.5.5104Linux ;; :accept application/simple-message-summary ;; :call-id 9fe891081a73da36fd0d1984409fedb5@0:0:0:0:0:0:0:0 ;; :from {:name "me" ;; :uri sip:me@localhost ;; :params {:tag ba13e9ef}}} ;; ;; {:method INVITE ;; :uri sip:lol@172.17.0.7 ;; :version 2.0 ;; :headers {:supported " replaces, 100rel, timer, norefersub," ;; :via [{:version 2.0 ;; :protocol UDP ;; :host 172.17.42.1 ;; :port 5555 ;; :params {:rport 5555 ;; :branch z9hG4bKPjb3bfc8f5-ced1-42ce-ade2-495d7bad0c60 ;; :received 172.17.42.1}}] ;; :content-type "application/sdp" ;; :max-forwards 70 ;; :content-length 230 ;; :to {:name nil ;; :uri "sip:lol@172.17.0.7" ;; :params {}} ;; :cseq {:seq 9058 ;; :method INVITE} ;; :session-expires 1800 ;; :contact [{:name nil ;; :uri "sip:aoeu1@172.17.42.1:5555;transport=UDP;ob" ;; :params {}}] ;; :user-agent "PJSUA v1.14.0 Linux-3.13.5/x86_64/glibc-2.17 " ;; :allow " PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS," ;; :call-id "4e6eb96d-c8e5-482b-ac12-f0cb9076655b" ;; :from {:name nil ;; :uri "sip:aoeu1@172.17.0.7" ;; :params {:tag 676d64bf-a738-48fe-9b6b-6c108f484edd}} ;; :min-se 90} ;; :content "v=0 ;; o=- 3606712585 3606712585 IN IP4 192.168.127.12 ;; s=pjmedia ;; c=IN IP4 192.168.127.12 ;; t=0 0 ;; a=X-nat:0 ;; m=audio 4000 RTP/AVP 96 ;; a=rtcp:4001 IN IP4 192.168.127.12 ;; a=sendrecv ;; a=rtpmap:96 telephone-event/8000 ;; a=fmtp:96 0-15" }
true
(ns herd-node.sip (:require [cljs.core :as cljs] [cljs.nodejs :as node] [cljs.core.async :refer [chan <! >!]] [clojure.string :as str] [clojure.walk :as walk] [herd-node.log :as log] [herd-node.buf :as b] [herd-node.parse :as conv] [herd-node.conns :as c] [herd-node.conn-mgr :as conn] [herd-node.circ :as circ] [herd-node.path :as path] [herd-node.dir :as dir] [herd-node.dtls-comm :as dtls] [herd-node.sip-dir :as sd] [herd-node.sip-helpers :as s]) (:require-macros [cljs.core.async.macros :as m :refer [go-loop go]])) ;; Call management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; call data: ;; {:sip-ctrl sip channel dedicated to that call ;; :sip-call-id sip id we're feeding to our SIP client ;; :state state of the call} (def calls (atom {})) (def sip-to-call-id (atom {})) (defn add-sip-call [sip-id call-id] (swap! sip-to-call-id merge {sip-id call-id})) (defn add-call [call-id data] (when (:sip-call-id data) (add-sip-call (:sip-call-id data) call-id)) (swap! calls merge {call-id data})) (defn update-data [call-id keys data] (swap! calls assoc-in (cons call-id keys) data)) (defn rm-call [call-id] (when-let [sip-id (-> call-id (@calls) :sip-call-id)] (swap! sip-to-call-id dissoc sip-id)) (swap! calls dissoc call-id)) (defn kill-call [config call-id] (let [call (@calls call-id) flat-sel #(map second (select-keys %1 %2)) vlc (:vlc-child call)] (log/info "SIP killing call:" call-id) (doseq [r [:rt :rtcp] i [:in :out]] (->> call r i (circ/destroy config))) (when vlc (try (.kill js/process (.-pid vlc) "SIGKILL") (catch js/Object e (log/c-info e "VLC already exited.")))) (rm-call call-id))) (defn mk-call-id [] (-> (node/require "crypto") (.randomBytes 16) (.toString "hex"))) ;; SIP sdp creation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mk-ack [ok-200 call-id] "Creates an ACK based on the 200 ok headers." (let [h (:headers ok-200)] {:method "ACK" :uri (-> ok-200 :headers :contact first :uri) :headers {:to (-> h :to) :from (-> h :from) :call-id call-id :cseq {:method "ACK" :seq (-> h :cseq :seq)} :via []}})) (defn mk-headers [method call-id caller headers uri-to {ip :host}] "create headers for generating an invite. Uses the headers that we saved during register." {:uri uri-to :method method :headers (merge {:to {:uri uri-to} :from {:uri (str/replace (-> headers :from :uri) #"sip:\w+@" (str "sip:" caller "@")) :name caller} :call-id call-id ;:via ; thankfully, sip.js takes care of this one. :contact [{:name nil :uri (str "sip:" caller "@" ip ":5060;transport=UDP;ob") :params {}}] :cseq {:seq 1 ;(rand-int 888888) :method method}} ;; FIXME (rand-int 0xFFFFFFFF) is what we'd want. (when (= "INVITE" method) {:content-type "application/sdp"}))}) (defn mk-sdp [codec {ip :host port :port} {rtcp-port :port} method & [sdp]] ;; FIXME: Codec is temporary "generates SDP for invite or 200/ok. codec choice is hardcoded for now." (let [to-string #(apply str (interleave % (repeat "\r\n")))] (if sdp (let [[owner-sess-id owner-sess-version] (next (re-find #"o=.*\b(\d+) (\d+) IN IP" sdp)) sdp (str/replace sdp #"o=.*" (str "o=- " owner-sess-id " " (inc (js/parseInt owner-sess-version)) " IN IP4 " ip)) ;; should completely generate these, inc of that thing is only needed on re-offer/re-negotiation. sdp (str/replace sdp #"c=.*" (str "c=IN IP4 " ip)) sdp (str/replace sdp #"(m=video).*" (str "$1 " rtcp-port " RTP/AVP 105 99")) sdp (str/replace sdp #"m=audio \d+ .*" (str "m=audio " port " RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101")) ;sdp (->> sdp str/split-lines (filter #(or (not= "a" (first %)) ; (re-find #"X-nat|sendrecv|rtpmap:9 |rtcp" %)))) ] {:content sdp}) {:content (to-string ["v=0" (str "o=- 3607434973 3607434973 IN IP4 " ip) "s=-" (str "c=IN IP4 " ip) "t=0 0" "a=X-nat:0" (condp = codec :pcma (str "m=audio " port " RTP/AVP 8 96 97 98 9 100 102 0 103 3 104 101") :pcmu (str "m=audio " port " RTP/AVP 0 96 97 98 9 100 102 8 103 3 104 101") :opus (str "m=audio " port " RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101") :g722 (str "m=audio " port " RTP/AVP 9 96 97 98 100 102 0 8 103 3 104 101")) ;(str "a=rtcp:" rtcp-port " IN IP4 " ip) ;; FIXME nothing open for that yet. "a=rtpmap:96 opus/48000/2" "a=fmtp:96 usedtx=1" "a=rtpmap:97 SILK/24000" "a=rtpmap:98 SILK/16000" "a=rtpmap:9 G722/8000" "a=rtpmap:100 speex/32000" "a=rtpmap:102 speex/16000" "a=rtpmap:0 PCMU/8000" "a=rtpmap:8 PCMA/8000" "a=rtpmap:103 iLBC/8000" "a=rtpmap:3 GSM/8000" "a=rtpmap:104 speex/8000" "a=rtpmap:101 telephone-event/8000" "a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level" (str "m=video " rtcp-port " RTP/AVP 105 99") "a=recvonly" "a=rtpmap:105 H264/90000" "a=fmtp:105 profile-level-id=4DE01f;packetization-mode=1" "a=imageattr:105 send * recv [x=[0-1366],y=[0-768]]" "a=rtpmap:99 H264/90000" "a=fmtp:99 profile-level-id=4DE01f" "a=imageattr:99 send * recv [x=[0-1366],y=[0-768]]" ])}))) ;; [ ;; "v=0 ;; o=william 0 0 IN IP4 PI:IP_ADDRESS:192.168.127.12END_PI ;; s=- ;; c=IN IP4 PI:IP_ADDRESS:192.168.127.12END_PI ;; t=0 0 ;; m=audio 5024 RTP/AVP 96 97 98 9 100 102 0 8 103 3 104 101 ;; a=rtpmap:96 opus/48000/2 ;; a=fmtp:96 usedtx=1 ;; a=rtpmap:97 SILK/24000 ;; a=rtpmap:98 SILK/16000 ;; a=rtpmap:9 G722/8000 ;; a=rtpmap:100 speex/32000 ;; a=rtpmap:102 speex/16000 ;; a=rtpmap:0 PCMU/8000 ;; a=rtpmap:8 PCMA/8000 ;; a=rtpmap:103 iLBC/8000 ;; a=rtpmap:3 GSM/8000 ;; a=rtpmap:104 speex/8000 ;; a=rtpmap:101 telephone-event/8000 ;; a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level ;; m=video 5026 RTP/AVP 105 99 ;; a=recvonly ;; a=rtpmap:105 H264/90000 ;; a=fmtp:105 profile-level-id=4DE01f;packetization-mode=1 ;; a=imageattr:105 send * recv [x=[0-1366],y=[0-768]] ;; a=rtpmap:99 H264/90000 ;; a=fmtp:99 profile-level-id=4DE01f ;; a=imageattr:99 send * recv [x=[0-1366],y=[0-768]] ;; " ;; ] ;; Manage local SIP client requests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-server [config] "Creates the listening service that will process the connected SIP client's requests. Application Proxies start this service." (let [incoming-sip (chan) node-id-len (-> config :ntor-values :node-id-len)] ;; Constant we'll be using often. (go (let [sip (node/require "sip") headers (atom {}) uri-to (atom "") my-name (atom "") answering-machine (some #(= % :answering-machine) (:roles config)) ;; Prepare RDV: rdv-id (<! (path/get-path :single)) ;; FIXME we should specify what zone we want our rdv in. rdv-data (circ/get-data rdv-id) rdv-ctrl (:dest-ctrl rdv-data) rdv-notify (:notify rdv-data) ;; Outgoinp RDV: out-rdv-id (<! (path/get-path :single)) ;; FIXME we should specify what zone we want our rdv in. out-rdv-data (circ/get-data out-rdv-id) out-rdv-ctrl (:dest-ctrl out-rdv-data) out-rdv-notify (:notify out-rdv-data) ;; Prepare MIX SIG: mix-id (<! (path/get-path :one-hop)) ;; SDP parsing: get-sdp-dest (fn [rq] {:port (->> (:content rq) (re-seq #"(?m)m\=(audio)\s+(\d+)") first last) :host (second (re-find #"(?m)c\=IN IP4 ((\d+\.){3}\d+)" (:content rq)))}) get-sdp-rtcp (fn [rq] {:port (->> (:content rq) (re-seq #"(?m)m\=(video)\s*(\d+)") first last) :host (second (re-find #"(?m)c\=IN IP4 ((\d+\.){3}\d+)" (:content rq)))}) ;; temp helper select #(->> (dir/get-net-info) seq (map second) (filter %) shuffle) ;; FIXME -> this should be shared by path. distinct-hops (fn [[m1 r1 r2 m2 c]] "We are already connected to m1. Remove duplicate hops (only happens on same zone calls)." (let [id= #(= (-> %1 :auth :srv-id b/hx) (-> %2 :auth :srv-id b/hx))] (cond (id= m1 m2) [c] (or (id= r1 r2) (id= m1 r2)) [r1 m2 c] (id= r2 m2) [r2 m2 c] :else [r1 r2 m2 c]))) ;;print-hops (fn [path] ;; used for testing distinct-hops ;; (doseq [h path] ;; (println :path (-> h :auth :srv-id b/hx)))) ;; sip channel processing: skip-until (fn [found-it? from] (go-loop [r (<! from)] (if (found-it? r) r (recur (<! from))))) wait-for-bye (fn [call-id sip-ctrl {name :name local-dest :dest}] (let [{bye :bye sip-call-id :sip-call-id headers :headers uri-to :uri-to} (@calls call-id)] (skip-until #(when (or (= "BYE" (-> % :nrq :method)) (< 200 (-> % :nrq :status)) (= :bye %)) ;(.send sip bye) ;(->> (mk-headers "BYE" sip-call-id name headers uri-to local-dest) ; (merge {:content ""}) ; conv/to-js ; (.send sip)) (kill-call config call-id)) sip-ctrl))) add-sip-ctrl-to-rt-circs (fn [call-id sip-ctrl] (doseq [r [:rt :rtcp] i [:in :out] :let [circ-id (->> call-id (@calls) r i)]] (circ/update-data circ-id [:sip-ctrl] sip-ctrl))) ;; Process SIP logic: process (fn process [rq] (let [nrq (-> rq cljs/js->clj walk/keywordize-keys) contact (-> nrq :headers :contact first) name (str/replace (or (-> contact :name) ;; get name and remove surrounding "". (->> contact :uri (re-find #"sip:(.*)@") second)) #"\"" "")] ;; debug <-- ;; (println) ;; (println :nrq nrq) ;; (println :cid (-> nrq :headers :call-id (@sip-to-call-id) (@calls))) ;; (println :cid @sip-to-call-id (-> nrq :headers :call-id )) ;; debug --> (cond ;; if call is recognised: (-> nrq :headers :call-id (@sip-to-call-id)) (go (>! (-> nrq :headers :call-id (@sip-to-call-id) (@calls) :sip-ctrl) {:nrq nrq :rq rq})) (= (:method nrq) "REGISTER") (let [rdv-data (circ/get-data out-rdv-id) sip-dir-dest (first (select #(= (:role %) :sip-dir))) ack (.makeResponse sip rq 200 "OK")] ;; prepare sip successful answer (println :l (doall (map :role (select identity)))) (if (:auth sip-dir-dest) (go (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/register config name out-rdv-id rdv-id (-> rdv-data :rdv :auth :srv-id)) ;; send register to dir, ack to sip client: (sd/register-to-mix config name mix-id) ;; register our sip user name (needed for last step of incoming rt circs, without giving our ip to caller) (.send sip ack) ;; --- SIP: answer sip client, successfully registered. (reset! my-name name) (reset! uri-to (-> contact :uri)) ;; save uri & headers for building invite later: (reset! headers (-> ack cljs/js->clj walk/keywordize-keys :headers))) (do (log/error "Could not find SIP DIR in herd network") ;; debug <-- (doall (->> (dir/get-net-info) seq (map second) (map #(dissoc % :auth)) (map println))) ;; debug --> (.send sip (.makeResponse sip rq "404" "NOT FOUND"))))) (= (:method nrq) "BYE") (.send sip (.makeResponse sip rq "200" "OK")) (= (:method nrq) "SUBSCRIBE") (condp = (-> nrq :headers :event) "presence.winfo" (do (println (:event nrq)) ;; and register the gringo. (.send sip (.makeResponse sip rq 200 "OK"))) "message-summary" (do (println :200 :OK) (.send sip (.makeResponse sip rq 200 "OK"))) (.send sip (.makeResponse sip rq 501 "Not Implemented"))) (= (:method nrq) "PUBLISH") (when false (go (if (= "presence" (-> nrq :headers :event)) (let [parse-xml (-> (node/require "xml2js") .-parseString) xml (chan)] ;; debug <-- (parse-xml (:content nrq) #(go (println %2) (>! xml %2))) (println (-> (<! xml) cljs/js->clj walk/keywordize-keys)) ;; debug --> (.send sip (.makeResponse sip rq 200 "OK"))) (do (log/error "SIP: Unsupported PUBLISH event:" (-> nrq :headers :event)) (.send sip (.makeResponse sip rq 501 "Not Implemented")))))) (= (:method nrq) "OPTIONS") (.send sip (.makeResponse sip rq 200 "OK")) ;; Take care of invite: SIP client sent an invite. ;; this means we are the caller. The following will find the callee & initiate call: (= (:method nrq) "INVITE") (go (let [sip-call-id (-> nrq :headers :call-id) call-id (mk-call-id) sip-ctrl (chan) callee-name (second (re-find #"sip:(.*)@" (:uri nrq))) ;; get callee name sdp (:content nrq) sip-dir-dest (first (select #(= (:role %) :sip-dir)))] (add-call call-id {:sip-ctrl sip-ctrl :sip-call-id sip-call-id :state :ringing :headers (-> (.makeResponse sip rq 200 "OK") cljs/js->clj walk/keywordize-keys :headers) :uri-to (-> contact :uri)}) (assert (:auth sip-dir-dest) "Could not find SIP DIR in herd network") (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/query config callee-name out-rdv-id call-id) ;; query for callee's rdv (log/info "SIP:" "initiating call" call-id "to" callee-name) (let [query-reply-rdv (<! sip-ctrl) ;; get query reply rdv-data (circ/get-data rdv-id)] (if (= :error (-> query-reply-rdv :sip-rq (.readUInt8 0) s/to-cmd)) ;; FIXME: assert this instead. (do (log/error "Query for" callee-name "failed.") (.send sip (.makeResponse sip rq 404 "NOT FOUND"))) (let [callee-rdv (:data query-reply-rdv) callee-rdv-cid (.readUInt32BE callee-rdv 0) callee-rdv-id (.slice callee-rdv 4 (+ 4 node-id-len)) sdp-dest (get-sdp-dest nrq) rtcp-dest (get-sdp-rtcp nrq)] ;; parse sdp to find where the SIP client expects to receive incoming RTP. (println sdp-dest) (println rtcp-dest) (assert callee-rdv-id (str "SIP: Could not find callee's mix:" name)) (update-data call-id [:peer-rdv] callee-rdv-cid) (.send sip (.makeResponse sip rq 100 "TRYING")) ;; inform the SIP client we have initiated the call. (if (not (b/b= callee-rdv-id (-> out-rdv-id circ/get-data :rdv :auth :srv-id))) (do (>! out-rdv-ctrl (dir/find-by-id callee-rdv-id)) (<! out-rdv-notify) (log/debug "Extended to callee's RDV")) (do (>! out-rdv-ctrl :drop-last) (<! out-rdv-notify) (log/debug "We already are on callee's RDV"))) ;; FIXME: once this works we'll add relay-sip extend to callee so rdv can't read demand, ;; and client can match our HS against the keys he has for his contacts. (circ/relay-sip config out-rdv-id :f-enc (b/cat (-> :invite s/from-cmd b/new1) ;; Send invite to callee. include our rdv-id so callee can send sig to us. (b/new call-id) b/zero (b/new4 callee-rdv-cid) (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (b/new name) b/zero (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (let [reply1 (<! sip-ctrl) reply2 (<! sip-ctrl) [rtp-rep rtcp-rep] (if (= (:cmd reply1) :ack-rtcp) [reply2 reply1] [reply1 reply2])] ;; and now we wait for ack (assert (= (:cmd rtp-rep) :ack) (str "Something went wrong with call" call-id)) (.send sip (.makeResponse sip rq 180 "RINGING")) ;; we received an answer (non error) from callee, inform our SIP client that callee's phone is ringing (let [[rdv-callee-id mix-id id pub] (b/cut (:data rtp-rep) node-id-len (* 2 node-id-len) (* 3 node-id-len)) rtp-circ (<! (path/get-path :rt)) rtp-data (circ/get-data rtp-circ) rtp-ctrl (:dest-ctrl rtp-data) rtp-notify (:notify rtp-data) rtp-done (chan) [_ local-port] (<! (path/attach-circs-to-new-udp config ;; create local udp socket. in-circ will be sent to sdp-dest, the SIP client's RTP media. out-circ is where data from the sip client will be sent through to callee. (go (:circ-id rtp-rep)) rtp-done (go sdp-dest))) rtcp-circ (<! (path/get-path :rt)) rtcp-data (circ/get-data rtcp-circ) rtcp-ctrl (:dest-ctrl rtcp-data) rtcp-notify (:notify rtcp-data) rtcp-done (chan) [_ loc-rtcp-port] (<! (path/attach-circs-to-new-udp config ;; create local udp socket. in-circ will be sent to sdp-dest, the SIP client's RTP media. out-circ is where data from the sip client will be sent through to callee. (go (:circ-id rtcp-rep)) rtcp-done (go rtcp-dest))) circuit-path (distinct-hops [(:chosen-mix rdv-data) ;; our mix (:rdv rdv-data) ;; our rdv (dir/find-by-id rdv-callee-id) ;; callee's rdv (dir/find-by-id mix-id) ;; callee's mix {:auth {:pub-B pub :srv-id id}}])] ;; callee. (>! rtp-ctrl circuit-path) ;; connect to callee using given path. (>! rtcp-ctrl circuit-path) ;; connect to callee using given path. (<! rtp-notify) ;; wait until ready. (<! rtcp-notify) ;; wait until ready. (>! rtcp-done rtcp-circ) (>! rtp-done rtp-circ) (log/info "SIP: RT circuits ready for outgoing data on:" call-id) (update-data call-id [:rt] {:in (:circ-id rtp-rep) :out rtp-circ}) ;; FIXME if needed add chans. (update-data call-id [:rtcp] {:in (:circ-id rtcp-rep) :out rtcp-circ}) ;; FIXME if needed add chans. (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ackack s/from-cmd b/new1) ;; send final ack to callee, with call-id so it knows that this circuit will be used for our outgoing (its incoming) RTP. (b/new call-id) b/zero)) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ackack-rtcp s/from-cmd b/new1) ;; send final ack to callee, with call-id so it knows that this circuit will be used for our outgoing (its incoming) RTP. (b/new call-id) b/zero)) (log/info "SIP: sent ackack, ready for relay on" call-id) (let [ok (merge (assoc-in (assoc-in (conv/to-clj (.makeResponse sip rq 200 "OK")) ;; Send our client a 200 OK, with out-circ's listening udp as "callee's" dest (what caller thinks is the callee actually is herd). [:headers :content-type] "application/sdp") ;; inelegant, testing. [:headers :contact] [{:name nil :uri (str "sip:" callee-name "@" (:local-ip config) ":5060;transport=UDP;ob") :params {}}]) (mk-sdp (:codec config) {:host (:local-ip config) :port local-port} {:port loc-rtcp-port} :ack sdp))] (update-data call-id [:uri-to] (-> ok :headers :contact first :uri)) (update-data call-id [:headers] (-> ok :headers)) ;(update-data call-id [:bye] (.makeResponse sip rq)) (.send sip (conv/to-js ok))) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 500) (wait-for-bye call-id sip-ctrl {:name callee-name :dest {:host (:local-ip config)}})))))))) :else (log/error "Unsupported sip method" (:method nrq)))))] ;; Initialisation of create-server: prepare RDV, sip signalisation incoming channel. (log/debug :lol1) (>! rdv-ctrl :rdv) (log/debug :lol0.5) (>! out-rdv-ctrl :rdv) (circ/update-data rdv-id [:sip-chan] incoming-sip) (circ/update-data out-rdv-id [:sip-chan] incoming-sip) (.start sip (cljs/clj->js {:protocol "UDP"}) process) (log/debug :lol2) ;; FIXME: sip-ch is general and dispatches according to call-id to sub channels. (go-loop [query (<! incoming-sip)] (if (= query :destroy) (do (log/info "SIP lost connectivity, stopping.") (.stop sip) (doseq [call-id @calls] (kill-call config call-id))) (let [cmd (-> query :sip-rq (.readUInt8 0) s/to-cmd) [call-id msg] (-> query :sip-rq s/get-call-id) call-chan (-> call-id (@calls) :sip-ctrl)] (log/info "SIP: call-id:" call-id "-" cmd) (cond ;; try to dispatch to an existing call. Right now, sig messages from SIP client to us, and from herd nw to us are put in the same chan. We might want one for each, and avoid doing things like skip-until. call-chan (go (>! call-chan (merge query {:data msg :call-id call-id :cmd cmd}))) ;; if it's an invite, initiate call. We are the callee. (= cmd :invite) (go (let [caller-rdv-id (.readUInt32BE msg 0) [_ rdv-caller-id mix-id msg] (b/cut msg 4 (+ 4 node-id-len) (+ 4 (* 2 node-id-len))) [caller msg] (b/cut-at-null-byte msg) [id pub] (b/cut msg node-id-len) rdv-data (circ/get-data rdv-id) caller (.toString caller) sip-ctrl (chan) mix-dest (dir/find-by-id mix-id) circuit-path (distinct-hops [(:chosen-mix rdv-data) ;; our mix (:rdv rdv-data) ;; our rdv (dir/find-by-id rdv-caller-id) ;; caller's rdv (dir/find-by-id mix-id) ;; caller's mix {:auth {:pub-B pub :srv-id id}}]) ;; caller ;; rtp rtp-circ (<! (path/get-path :rt)) rtp-data (circ/get-data rtp-circ) rtp-ctrl (:dest-ctrl rtp-data) rtp-notify (:notify rtp-data) rtp-done (chan) rtp-incoming (chan) sdp-dest (chan) [_ local-port] (<! (path/attach-circs-to-new-udp config ;; our local udp socket for exchanging RTP with local sip client. rtp-incoming is caller's RTP which we'll route to the @/port which will be given in 200/OK after sending invite to it. rtp-incoming rtp-done ;; The invite we'll send will have our local sockets @/port as media, so sip client sends us RTP, we'll route it through rtp-circ. sdp-dest)) local-dest {:host (:local-ip config) :port local-port} ;; rtcp rtcp-circ (<! (path/get-path :rt)) rtcp-data (circ/get-data rtcp-circ) rtcp-ctrl (:dest-ctrl rtcp-data) rtcp-notify (:notify rtcp-data) rtcp-done (chan) rtcp-incoming (chan) rtcp-dest (chan) [_ loc-rtcp-port] (<! (path/attach-circs-to-new-udp config ;; our local udp socket for exchanging RTP with local sip client. rtp-incoming is caller's RTP which we'll route to the @/port which will be given in 200/OK after sending invite to it. rtcp-incoming rtcp-done ;; The invite we'll send will have our local sockets @/port as media, so sip client sends us RTP, we'll route it through rtp-circ. rtcp-dest)) ok-200 (atom {})] (log/info "SIP: invited by" caller "- Call-ID:" call-id "Rdv" caller-rdv-id) (add-call call-id {:sip-ctrl sip-ctrl, :sip-call-id call-id, :state :ringing, :peer-rdv caller-rdv-id :rtcp {:out rtcp-circ} :rt {:out rtp-circ} :headers @headers :uri-to @uri-to}) (if answering-machine (let [exec (.-exec (node/require "child_process"))] ; (.writeFile fs file sdp) (>! rtp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (>! rtcp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (<! rtcp-notify) ;; wait for answer. (<! rtp-notify) ;; wait for answer. (>! rtcp-done rtcp-circ) (>! rtp-done rtp-circ) (go (>! rtcp-dest {:host "127.0.0.1" :port 1234})) (go (>! sdp-dest {:host "127.0.0.1" :port 1234})) (log/info "SIP: RT circuit ready for call" call-id) (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ack s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ack-rtcp s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero)) (let [reply1 (<! (skip-until #(:circ-id %) sip-ctrl)) reply2 (<! (skip-until #(:circ-id %) sip-ctrl)) [rtp-id rtcp-id] (map :circ-id (if (= (:cmd reply1) :ackack-rtcp) [reply2 reply1] [reply1 reply2]))] ;; Wait for caller's rt path's first message. (>! rtp-incoming rtp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (>! rtcp-incoming rtcp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (update-data call-id [:rt :in] rtp-id) (update-data call-id [:rtcp :in] rtcp-id)) (log/info "SIP: got ackack, ready for relay on" call-id) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 100) (log/info "SIP: launching vlc for answering-machine playback") (update-data call-id [:vlc-child] (exec (str "cvlc '" (:answering-machine-file config) "' --play-and-exit --sout '#transcode{acodec=ulaw,channels=1,samplerate=8000}:rtp{dst=127.0.0.1,port-audio=" (:port local-dest) "}'") nil #(do (log/debug "VLC exited with:" %1) (log/debug "VLC stdout:" %2) (log/debug "VLC stdout:" %3) (kill-call config call-id)))) (wait-for-bye call-id sip-ctrl nil)) (do (.send sip (conv/to-js (merge (mk-headers "INVITE" call-id caller @headers @uri-to local-dest) ;; Send our crafted invite with local udp port as "caller's" media session (mk-sdp (:codec config) local-dest {:port loc-rtcp-port} :invite)))) (let [user-answer (<! (skip-until #(let [status (-> % :nrq :status) {user-answer :nrq} %] (cond (> 200 status) false (< 200 status) true :else (do (go (>! sdp-dest (get-sdp-dest user-answer))) ;; FIXME one go should do, test (go (>! rtcp-dest (get-sdp-rtcp user-answer))) (reset! ok-200 user-answer)))) sip-ctrl))] (if (not= 200 (-> user-answer :nrq :status)) (kill-call config call-id) (do (>! rtp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (>! rtcp-ctrl circuit-path) ;; connect to caller's mix & then to caller. (<! rtcp-notify) ;; wait for answer. (<! rtp-notify) ;; wait for answer. (log/info "SIP: RT circuit ready for call" call-id) (circ/relay-sip config rtp-circ :f-enc (b/cat (-> :ack s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero (-> rdv-data :rdv :auth :srv-id) (-> @path/chosen-mix :auth :srv-id) (-> config :auth :herd-id :id) (-> config :auth :herd-id :pub))) (circ/relay-sip config rtcp-circ :f-enc (b/cat (-> :ack-rtcp s/from-cmd b/new1) ;; Send ack to caller, with our mix's coordinates so he can create an rt-path to us to send rtp. (b/new call-id) b/zero)) (let [reply1 (<! (skip-until #(:circ-id %) sip-ctrl)) reply2 (<! (skip-until #(:circ-id %) sip-ctrl)) [rtp-id rtcp-id] (map :circ-id (if (= (:cmd reply1) :ackack-rtcp) [reply2 reply1] [reply1 reply2]))] ;; Wait for caller's rt path's first message. (>! rtp-incoming rtp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (>! rtcp-incoming rtcp-id) ;; inform attach-local-udp-to-simplex-circs that we have incoming-rtp to attach to socket. (update-data call-id [:rt :in] rtp-id) (update-data call-id [:rtcp :in] rtcp-id)) (let [ok (mk-ack @ok-200 call-id)] (update-data call-id [:uri-to] (-> ok :uri)) (update-data call-id [:headers] (-> ok :headers)) (.send sip (conv/to-js ok))) (log/info "SIP: got ackack, ready for relay on" call-id) (add-sip-ctrl-to-rt-circs call-id sip-ctrl) (js/setInterval #(dtls/relay-ping config rtcp-circ) 100) (wait-for-bye call-id sip-ctrl {:name PI:NAME:<NAME>END_PI :dest {:host (:local-ip config)}})))))))) ;; loop waiting for bye. :else (log/info "SIP: incoming message with unknown call id:" call-id "-- dropping.")) (recur (<! incoming-sip))))) (log/info "SIP proxy listening on default UDP SIP port") (when answering-machine (let [name (:answering-machine-name config) sip-dir-dest (first (select #(= (:role %) :sip-dir))) rdv-data (circ/get-data rdv-id) register #(go (>! out-rdv-ctrl sip-dir-dest) ;; --- RDV: connect to sip dir to send register (<! out-rdv-notify) ;; wait until connected to send (sd/register config name out-rdv-id rdv-id (-> rdv-data :rdv :auth :srv-id)) ;; send register to dir, ack to sip client: (sd/register-to-mix config name mix-id) ;; register our sip user name (needed for last step of incoming rt circs, without giving our ip to caller) (reset! my-name name))] (register) (js/setInterval register (/ (:sip-register-interval config) 2))))) (when (:debug config) (js/setInterval (fn [] (let [rtp-conns (filter #(-> % second :rtp-stats) (c/get-all))] (doseq [[socket {[total rtp-seq] :rtp-stats circ-id :circuit}] rtp-conns] (c/update-data socket [:rtp-stats] [0 rtp-seq]) (log/debug "RTP Status:" total "drops on circuit" circ-id "in the last 5 seconds")))) 5000))) incoming-sip)) ;; replace all uris, tags, ports by hc defaults. ;; {method REGISTER ;; uri sip:localhost ; URI ;; version 2.0 ;; headers {contact [{name "herd" ;; uri sip:herd@127.0.0.1:18750;transport=udp;registering_acc=localhost ; URI ;; params {expires 600}}] ;; user-agent Jitsi2.5.5104Linux ; becomes herd-version. ;; call-id 659987c14fca0876dc89d5fa4ec715e5@0:0:0:0:0:0:0:0 ; this changes. ;; from {name "herd" ;; uri sip:herd@localhost ; URI ;; params {tag 81429e45}} ; tag. ;; via [{version 2.0 ;; protocol UDP ;; host 127.0.0.1 ; remove this. remove via entirely? ;; port 18750 ;; params {branch z9hG4bK-313432-de5cc56153489d6de96fa6deeabaab8f ;; received 127.0.0.1}}] ; and this ;; expires 600 ;; max-forwards 70 ;; content-length 0 ;; to {name "herd" ;; uri sip:herd@localhost ;; params {}} ;; cseq {seq 1 ;; method REGISTER}} ;; content } ;; media session. ;; B2BUA ;; Ann Server PI:NAME:<NAME>END_PI ;; | | | | ;; | INVITE F1 | | | ;; |------------------->| | | ;; | 100 Trying F2 | | | ;; |<-------------------| | INVITE F3 | ;; | | |------------------->| ;; | | | 100 Trying F4 | ;; | | |<-------------------| ;; | | | 180 Ringing F5 | ;; | 180 Ringing F6 | |<-------------------| ;; |<-------------------| | | ;; | | | 200 OK F7 | ;; | 200 OK F8 | |<-------------------| ;; |<-------------------| | ACK F9 | ;; | ACK F10 | |------------------->| ;; |------------------->| | | ;; | RTP Media | | RTP Media | ;; |<==================>| |<==================>| ;; | BYE F11 | | | ;; |------------------->| | BYE F12 | ;; | 200 OK F13 | |------------------->| ;; |<-------------------| | 200 OK F14 | ;; | | |<-------------------| ;; | | | | ;; presence stuff ;; (comment ;; {:method PUBLISH ;; :uri sip:me@localhost ;; :version 2.0 ;; :headers {:via [{:version 2.0 :protocol UDP :host 127.0.0.1 :port 9669 ;; :params {:branch z9hG4bK-373037-96f223ef93a23586ffc02df09af2cc53 ;; :received 127.0.0.1}}] ;; :content-type application/pidf+xml ;; :expires 3600 ;; :max-forwards 70 ;; :event presence ;; :content-length 401 ;; :to {:name "me" ;; :uri sip:me@localhost ;; :params {}} ;; :cseq {:seq 2 ;; :method PUBLISH} ;; :contact [{:name "me" ;; :uri sip:me@127.0.0.1:9669;transport=udp;registering_acc=localhost ;; :params {}}] ;; :user-agent Jitsi2.5.5104Linux ;; :call-id a091313efa9d8c5f2c7471c2952d21de@0:0:0:0:0:0:0:0 ;; :from {:name "me" ;; :uri sip:me@localhost ;; :params {:tag c4c41a24}}} ;; :content <?xml version="1.0" encoding="UTF-8" standalone="no"?><presence xmlns="urn:ietf:params:xml:ns:pidf" xmlns:dm="urn:ietf:params:xml:ns:pidf:data-model" xmlns:rpid="urn:ietf:params:xml:ns:pidf:rpid" entity="sip:me@localhost"><dm:personid="p2856"><rpid:activities/></dm:person><tuple id="t5430"><status><basic>open</basic></status><contact>sip:me@localhost</contact><note>Online</note></tuple></presence>}) ;; ;; ;; (comment ;; {:method SUBSCRIBE ;; :uri sip:me@localhost ;; :version 2.0 ;; :headers {:via [{:version 2.0 ;; :protocol UDP ;; :host 127.0.0.1 ;; :port 55590 ;; :params {:branch z9hG4bK-373037-cae0467c2ff1881dad572e4d6c2c8c93 ;; :received 127.0.0.1}}] ;; :expires 3600 ;; :max-forwards 70 ;; :event message-summary ;; :content-length 0 ;; :to {:name "me" ;; :uri sip:me@localhost ;; :params {}} ;; :cseq {:seq 1 ;; :method SUBSCRIBE} ;; :contact [{:name "me" ;; :uri sip:me@127.0.0.1:55590;transport=udp;registering_acc=localhost ;; :params {}}] ;; :user-agent Jitsi2.5.5104Linux ;; :accept application/simple-message-summary ;; :call-id 9fe891081a73da36fd0d1984409fedb5@0:0:0:0:0:0:0:0 ;; :from {:name "me" ;; :uri sip:me@localhost ;; :params {:tag ba13e9ef}}} ;; ;; {:method INVITE ;; :uri sip:lol@172.17.0.7 ;; :version 2.0 ;; :headers {:supported " replaces, 100rel, timer, norefersub," ;; :via [{:version 2.0 ;; :protocol UDP ;; :host 172.17.42.1 ;; :port 5555 ;; :params {:rport 5555 ;; :branch z9hG4bKPjb3bfc8f5-ced1-42ce-ade2-495d7bad0c60 ;; :received 172.17.42.1}}] ;; :content-type "application/sdp" ;; :max-forwards 70 ;; :content-length 230 ;; :to {:name nil ;; :uri "sip:lol@172.17.0.7" ;; :params {}} ;; :cseq {:seq 9058 ;; :method INVITE} ;; :session-expires 1800 ;; :contact [{:name nil ;; :uri "sip:aoeu1@172.17.42.1:5555;transport=UDP;ob" ;; :params {}}] ;; :user-agent "PJSUA v1.14.0 Linux-3.13.5/x86_64/glibc-2.17 " ;; :allow " PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS," ;; :call-id "4e6eb96d-c8e5-482b-ac12-f0cb9076655b" ;; :from {:name nil ;; :uri "sip:aoeu1@172.17.0.7" ;; :params {:tag 676d64bf-a738-48fe-9b6b-6c108f484edd}} ;; :min-se 90} ;; :content "v=0 ;; o=- 3606712585 3606712585 IN IP4 PI:IP_ADDRESS:192.168.127.12END_PI ;; s=pjmedia ;; c=IN IP4 PI:IP_ADDRESS:192.168.127.12END_PI ;; t=0 0 ;; a=X-nat:0 ;; m=audio 4000 RTP/AVP 96 ;; a=rtcp:4001 IN IP4 PI:IP_ADDRESS:192.168.127.12END_PI ;; a=sendrecv ;; a=rtpmap:96 telephone-event/8000 ;; a=fmtp:96 0-15" }
[ { "context": "style style\n :id id\n :name name}\n [:> flexbox {:justify-content \"between\"\n ", "end": 4154, "score": 0.9982097148895264, "start": 4150, "tag": "NAME", "value": "name" } ]
src/cljs/my_website/components/navbar.cljs
sansarip/my-website
0
(ns my-website.components.navbar (:require [reagent.core :as r] [my-website.utilities :refer [word-concat wrap-all-children omit-nil-keyword-args on-unit]] [my-website.components.flexbox :refer [flexbox]] [my-website.styles :refer [color-palette font-families]] [spade.core :refer [defclass]] [my-website.components.menuitem :refer [menuitem]] [my-website.components.icon :refer [icon]] [my-website.macros :refer-macros [assoc-component-state]] [debounce] [on-click-outside])) (def default-width-collapsible "768px") (defclass navbar-class [& {:keys [inverse width-collapsible] :or {inverse false width-collapsible "768px"}}] (at-media {:screen :only :max-width width-collapsible} [".hide-desktop-navbar-children" {:display "none"}]) (at-media {:screen :only :min-width (on-unit inc width-collapsible)} [".hide-mobile-bars" {:display "none"}]) {:color (str (if inverse "white" (:primary color-palette)))} ["h1" {:color "white"}] ["h2" {:color "white"}] ["h3" {:color "white"}] ["h4" {:color "white"}] [".hide-mobile-navbar-children" {:opacity "0"}] [".mobile-navbar-children" {:max-height "0" :overflow "hidden" :transition "max-height 1s ease, opacity .5s ease-in"}] [".grow" {:max-height "20em"}]) (defn toggle-mobile-navbar-children-element [el] (-> el (.-classList) (.toggle "hide-mobile-navbar-children")) (-> el (.-classList) (.toggle "grow"))) (defn toggle-mobile-navbar-children [this] (let [el (-> js/document (.getElementById (.. this -state -mobileNavbarChildrenId)))] (toggle-mobile-navbar-children-element el) (set! (.. this -state -isShowingMobileNavbarChildren) (not (-> el .-classList (.contains "hide-mobile-navbar-children")))))) (defn hide-mobile-navbar-children-element [el] (let [is-showing (not (-> el .-classList (.contains "hide-mobile-navbar-children")))] (and is-showing (toggle-mobile-navbar-children-element el)))) (defn hide-mobile-navbar-children [this] (let [width-collapsible (or (.. this -props -widthCollapsible) default-width-collapsible)] (and (> (.-innerWidth js/window) (js/parseFloat width-collapsible)) (.. this -state -isShowingMobileNavbarChildren) (toggle-mobile-navbar-children this)))) (defn get-initial-state-fn [this] #js {:mobileNavbarChildrenId (str (random-uuid)) :isShowingMobileNavbarChildren false :hideMobileNavbarChildrenFn (debounce #(hide-mobile-navbar-children this) 100)}) (defn mount-fn [this] (-> js/window (.addEventListener "resize" (.. this -state -hideMobileNavbarChildrenFn)))) (defn unmount-fn [this] (-> js/window (.removeEventListener "resize" (.. this -state -hideMobileNavbarChildrenFn)))) (defn render-fn [this] (let [children (.. this -props -children) title (.. this -props -title) as (.. this -props -as) classes (.. this -props -extraClasses) inverse (.. this -props -inverse) style (.. this -props -style) padding (.. this -props -padding) width-collapsible (or (.. this -props -widthCollapsible) default-width-collapsible) background-color (.. this -props -backgroundColor) id (.. this -props -id) name (.. this -props -name)] [:div {:class (omit-nil-keyword-args navbar-class :width-collapsible width-collapsible :inverse inverse) :style style :id id :name name} [:> flexbox {:justify-content "between" :extra-classes classes :align-items "center" :padding padding :background-color background-color} (wrap-all-children (if as (js->clj as) :h3) title) [:> flexbox {:justify-content "space-around" :extra-classes "hide-desktop-navbar-children" :grow true :width "auto" :wrap "wrap"} children] [:> menuitem {:extra-classes "hide-mobile-bars" :inverse inverse} [:> icon {:icon-name "bars" :inherit-color true :strength "strong" :inverse true :on-click #(toggle-mobile-navbar-children this)}]]] [:> flexbox {:justify-content "around" :extra-classes "hide-mobile-navbar-children mobile-navbar-children" :id (.. this -state -mobileNavbarChildrenId) :background-color background-color :flex-direction "column" :wrap "none" :align-content "around" :align-items "center" :grow true} children]])) (def navbar (on-click-outside (r/create-class {:display-name :navbar :get-initial-state get-initial-state-fn :component-did-mount mount-fn :component-will-unmount unmount-fn :render render-fn :handleClickOutside #(doall (map hide-mobile-navbar-children-element (.from js/Array (.querySelectorAll js/document ".mobile-navbar-children"))))})))
34842
(ns my-website.components.navbar (:require [reagent.core :as r] [my-website.utilities :refer [word-concat wrap-all-children omit-nil-keyword-args on-unit]] [my-website.components.flexbox :refer [flexbox]] [my-website.styles :refer [color-palette font-families]] [spade.core :refer [defclass]] [my-website.components.menuitem :refer [menuitem]] [my-website.components.icon :refer [icon]] [my-website.macros :refer-macros [assoc-component-state]] [debounce] [on-click-outside])) (def default-width-collapsible "768px") (defclass navbar-class [& {:keys [inverse width-collapsible] :or {inverse false width-collapsible "768px"}}] (at-media {:screen :only :max-width width-collapsible} [".hide-desktop-navbar-children" {:display "none"}]) (at-media {:screen :only :min-width (on-unit inc width-collapsible)} [".hide-mobile-bars" {:display "none"}]) {:color (str (if inverse "white" (:primary color-palette)))} ["h1" {:color "white"}] ["h2" {:color "white"}] ["h3" {:color "white"}] ["h4" {:color "white"}] [".hide-mobile-navbar-children" {:opacity "0"}] [".mobile-navbar-children" {:max-height "0" :overflow "hidden" :transition "max-height 1s ease, opacity .5s ease-in"}] [".grow" {:max-height "20em"}]) (defn toggle-mobile-navbar-children-element [el] (-> el (.-classList) (.toggle "hide-mobile-navbar-children")) (-> el (.-classList) (.toggle "grow"))) (defn toggle-mobile-navbar-children [this] (let [el (-> js/document (.getElementById (.. this -state -mobileNavbarChildrenId)))] (toggle-mobile-navbar-children-element el) (set! (.. this -state -isShowingMobileNavbarChildren) (not (-> el .-classList (.contains "hide-mobile-navbar-children")))))) (defn hide-mobile-navbar-children-element [el] (let [is-showing (not (-> el .-classList (.contains "hide-mobile-navbar-children")))] (and is-showing (toggle-mobile-navbar-children-element el)))) (defn hide-mobile-navbar-children [this] (let [width-collapsible (or (.. this -props -widthCollapsible) default-width-collapsible)] (and (> (.-innerWidth js/window) (js/parseFloat width-collapsible)) (.. this -state -isShowingMobileNavbarChildren) (toggle-mobile-navbar-children this)))) (defn get-initial-state-fn [this] #js {:mobileNavbarChildrenId (str (random-uuid)) :isShowingMobileNavbarChildren false :hideMobileNavbarChildrenFn (debounce #(hide-mobile-navbar-children this) 100)}) (defn mount-fn [this] (-> js/window (.addEventListener "resize" (.. this -state -hideMobileNavbarChildrenFn)))) (defn unmount-fn [this] (-> js/window (.removeEventListener "resize" (.. this -state -hideMobileNavbarChildrenFn)))) (defn render-fn [this] (let [children (.. this -props -children) title (.. this -props -title) as (.. this -props -as) classes (.. this -props -extraClasses) inverse (.. this -props -inverse) style (.. this -props -style) padding (.. this -props -padding) width-collapsible (or (.. this -props -widthCollapsible) default-width-collapsible) background-color (.. this -props -backgroundColor) id (.. this -props -id) name (.. this -props -name)] [:div {:class (omit-nil-keyword-args navbar-class :width-collapsible width-collapsible :inverse inverse) :style style :id id :name <NAME>} [:> flexbox {:justify-content "between" :extra-classes classes :align-items "center" :padding padding :background-color background-color} (wrap-all-children (if as (js->clj as) :h3) title) [:> flexbox {:justify-content "space-around" :extra-classes "hide-desktop-navbar-children" :grow true :width "auto" :wrap "wrap"} children] [:> menuitem {:extra-classes "hide-mobile-bars" :inverse inverse} [:> icon {:icon-name "bars" :inherit-color true :strength "strong" :inverse true :on-click #(toggle-mobile-navbar-children this)}]]] [:> flexbox {:justify-content "around" :extra-classes "hide-mobile-navbar-children mobile-navbar-children" :id (.. this -state -mobileNavbarChildrenId) :background-color background-color :flex-direction "column" :wrap "none" :align-content "around" :align-items "center" :grow true} children]])) (def navbar (on-click-outside (r/create-class {:display-name :navbar :get-initial-state get-initial-state-fn :component-did-mount mount-fn :component-will-unmount unmount-fn :render render-fn :handleClickOutside #(doall (map hide-mobile-navbar-children-element (.from js/Array (.querySelectorAll js/document ".mobile-navbar-children"))))})))
true
(ns my-website.components.navbar (:require [reagent.core :as r] [my-website.utilities :refer [word-concat wrap-all-children omit-nil-keyword-args on-unit]] [my-website.components.flexbox :refer [flexbox]] [my-website.styles :refer [color-palette font-families]] [spade.core :refer [defclass]] [my-website.components.menuitem :refer [menuitem]] [my-website.components.icon :refer [icon]] [my-website.macros :refer-macros [assoc-component-state]] [debounce] [on-click-outside])) (def default-width-collapsible "768px") (defclass navbar-class [& {:keys [inverse width-collapsible] :or {inverse false width-collapsible "768px"}}] (at-media {:screen :only :max-width width-collapsible} [".hide-desktop-navbar-children" {:display "none"}]) (at-media {:screen :only :min-width (on-unit inc width-collapsible)} [".hide-mobile-bars" {:display "none"}]) {:color (str (if inverse "white" (:primary color-palette)))} ["h1" {:color "white"}] ["h2" {:color "white"}] ["h3" {:color "white"}] ["h4" {:color "white"}] [".hide-mobile-navbar-children" {:opacity "0"}] [".mobile-navbar-children" {:max-height "0" :overflow "hidden" :transition "max-height 1s ease, opacity .5s ease-in"}] [".grow" {:max-height "20em"}]) (defn toggle-mobile-navbar-children-element [el] (-> el (.-classList) (.toggle "hide-mobile-navbar-children")) (-> el (.-classList) (.toggle "grow"))) (defn toggle-mobile-navbar-children [this] (let [el (-> js/document (.getElementById (.. this -state -mobileNavbarChildrenId)))] (toggle-mobile-navbar-children-element el) (set! (.. this -state -isShowingMobileNavbarChildren) (not (-> el .-classList (.contains "hide-mobile-navbar-children")))))) (defn hide-mobile-navbar-children-element [el] (let [is-showing (not (-> el .-classList (.contains "hide-mobile-navbar-children")))] (and is-showing (toggle-mobile-navbar-children-element el)))) (defn hide-mobile-navbar-children [this] (let [width-collapsible (or (.. this -props -widthCollapsible) default-width-collapsible)] (and (> (.-innerWidth js/window) (js/parseFloat width-collapsible)) (.. this -state -isShowingMobileNavbarChildren) (toggle-mobile-navbar-children this)))) (defn get-initial-state-fn [this] #js {:mobileNavbarChildrenId (str (random-uuid)) :isShowingMobileNavbarChildren false :hideMobileNavbarChildrenFn (debounce #(hide-mobile-navbar-children this) 100)}) (defn mount-fn [this] (-> js/window (.addEventListener "resize" (.. this -state -hideMobileNavbarChildrenFn)))) (defn unmount-fn [this] (-> js/window (.removeEventListener "resize" (.. this -state -hideMobileNavbarChildrenFn)))) (defn render-fn [this] (let [children (.. this -props -children) title (.. this -props -title) as (.. this -props -as) classes (.. this -props -extraClasses) inverse (.. this -props -inverse) style (.. this -props -style) padding (.. this -props -padding) width-collapsible (or (.. this -props -widthCollapsible) default-width-collapsible) background-color (.. this -props -backgroundColor) id (.. this -props -id) name (.. this -props -name)] [:div {:class (omit-nil-keyword-args navbar-class :width-collapsible width-collapsible :inverse inverse) :style style :id id :name PI:NAME:<NAME>END_PI} [:> flexbox {:justify-content "between" :extra-classes classes :align-items "center" :padding padding :background-color background-color} (wrap-all-children (if as (js->clj as) :h3) title) [:> flexbox {:justify-content "space-around" :extra-classes "hide-desktop-navbar-children" :grow true :width "auto" :wrap "wrap"} children] [:> menuitem {:extra-classes "hide-mobile-bars" :inverse inverse} [:> icon {:icon-name "bars" :inherit-color true :strength "strong" :inverse true :on-click #(toggle-mobile-navbar-children this)}]]] [:> flexbox {:justify-content "around" :extra-classes "hide-mobile-navbar-children mobile-navbar-children" :id (.. this -state -mobileNavbarChildrenId) :background-color background-color :flex-direction "column" :wrap "none" :align-content "around" :align-items "center" :grow true} children]])) (def navbar (on-click-outside (r/create-class {:display-name :navbar :get-initial-state get-initial-state-fn :component-did-mount mount-fn :component-will-unmount unmount-fn :render render-fn :handleClickOutside #(doall (map hide-mobile-navbar-children-element (.from js/Array (.querySelectorAll js/document ".mobile-navbar-children"))))})))
[ { "context": "ample from the SC book (actually taken from one of Sam Aaron's videos)\n(definst wobble [noise-rate 3 freq-mul ", "end": 139, "score": 0.986670196056366, "start": 130, "tag": "NAME", "value": "Sam Aaron" }, { "context": " and receiving them on port 8000, i.e. 'acosc.exe 127.0.0.1 7000 8000' from the shell.\n(let [client (osc-clie", "end": 1003, "score": 0.9964569807052612, "start": 994, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
data/train/clojure/a7e76d14c80c0e6ce4f36079cec32d571ccfca13demo.clj
harshp8l/deep-learning-lang-detection
84
(ns demo (:use [overtone.device.audiocubes] [overtone.live])) ;; Example from the SC book (actually taken from one of Sam Aaron's videos) (definst wobble [noise-rate 3 freq-mul 15 variance 3 base-note 80 wobble-mul 1 echo 2] (let [noise (lf-noise1 noise-rate) saws (mul-add (lf-saw (* wobble-mul 5)) variance 2) freq (midicps (mul-add noise freq-mul (+ saws base-note))) src (* 1.0 (sin-osc freq))] (comb-n src 1 0.3 echo))) ;; Start the noise! (wobble) ;; Cube handler - assumes a single connected cube (ignores the 'cube' value on messages) ;; and maps proximity sensors to base-note, echo and noise-rate properties of the wobble ;; instrument. The same sensors (the ones on faces 0,1 and 2) are mapped to RGB values so ;; you get a glowing cube controlling the instrument parameters when manipulated. ;; This assumes an audiocube OSC bridge running on localhost sending messages on port 7000 ;; and receiving them on port 8000, i.e. 'acosc.exe 127.0.0.1 7000 8000' from the shell. (let [client (osc-client "localhost" 8000) colour {:red (atom 0.0) :green (atom 0.0) :blue (atom 0.0)}] (osc-handle (osc-server 7000) "/audiocubes" (mk-cube-handler :sensor-updated ; Sensor value updated (fn [cube face sensor-value] (do (case face 0 (do (reset! (colour :red) (* sensor-value 255)) (ctl wobble :base-note (+ 50 (* sensor-value 60)))) 1 (do (reset! (colour :green) (* sensor-value 255)) (ctl wobble :echo (* sensor-value 40))) 2 (do (reset! (colour :blue) (* sensor-value 255)) (ctl wobble :noise-rate (+ 1 (* sensor-value 40)))) nil)) (set-colour client cube @(colour :red) @(colour :green) @(colour :blue)) ) )))
49358
(ns demo (:use [overtone.device.audiocubes] [overtone.live])) ;; Example from the SC book (actually taken from one of <NAME>'s videos) (definst wobble [noise-rate 3 freq-mul 15 variance 3 base-note 80 wobble-mul 1 echo 2] (let [noise (lf-noise1 noise-rate) saws (mul-add (lf-saw (* wobble-mul 5)) variance 2) freq (midicps (mul-add noise freq-mul (+ saws base-note))) src (* 1.0 (sin-osc freq))] (comb-n src 1 0.3 echo))) ;; Start the noise! (wobble) ;; Cube handler - assumes a single connected cube (ignores the 'cube' value on messages) ;; and maps proximity sensors to base-note, echo and noise-rate properties of the wobble ;; instrument. The same sensors (the ones on faces 0,1 and 2) are mapped to RGB values so ;; you get a glowing cube controlling the instrument parameters when manipulated. ;; This assumes an audiocube OSC bridge running on localhost sending messages on port 7000 ;; and receiving them on port 8000, i.e. 'acosc.exe 127.0.0.1 7000 8000' from the shell. (let [client (osc-client "localhost" 8000) colour {:red (atom 0.0) :green (atom 0.0) :blue (atom 0.0)}] (osc-handle (osc-server 7000) "/audiocubes" (mk-cube-handler :sensor-updated ; Sensor value updated (fn [cube face sensor-value] (do (case face 0 (do (reset! (colour :red) (* sensor-value 255)) (ctl wobble :base-note (+ 50 (* sensor-value 60)))) 1 (do (reset! (colour :green) (* sensor-value 255)) (ctl wobble :echo (* sensor-value 40))) 2 (do (reset! (colour :blue) (* sensor-value 255)) (ctl wobble :noise-rate (+ 1 (* sensor-value 40)))) nil)) (set-colour client cube @(colour :red) @(colour :green) @(colour :blue)) ) )))
true
(ns demo (:use [overtone.device.audiocubes] [overtone.live])) ;; Example from the SC book (actually taken from one of PI:NAME:<NAME>END_PI's videos) (definst wobble [noise-rate 3 freq-mul 15 variance 3 base-note 80 wobble-mul 1 echo 2] (let [noise (lf-noise1 noise-rate) saws (mul-add (lf-saw (* wobble-mul 5)) variance 2) freq (midicps (mul-add noise freq-mul (+ saws base-note))) src (* 1.0 (sin-osc freq))] (comb-n src 1 0.3 echo))) ;; Start the noise! (wobble) ;; Cube handler - assumes a single connected cube (ignores the 'cube' value on messages) ;; and maps proximity sensors to base-note, echo and noise-rate properties of the wobble ;; instrument. The same sensors (the ones on faces 0,1 and 2) are mapped to RGB values so ;; you get a glowing cube controlling the instrument parameters when manipulated. ;; This assumes an audiocube OSC bridge running on localhost sending messages on port 7000 ;; and receiving them on port 8000, i.e. 'acosc.exe 127.0.0.1 7000 8000' from the shell. (let [client (osc-client "localhost" 8000) colour {:red (atom 0.0) :green (atom 0.0) :blue (atom 0.0)}] (osc-handle (osc-server 7000) "/audiocubes" (mk-cube-handler :sensor-updated ; Sensor value updated (fn [cube face sensor-value] (do (case face 0 (do (reset! (colour :red) (* sensor-value 255)) (ctl wobble :base-note (+ 50 (* sensor-value 60)))) 1 (do (reset! (colour :green) (* sensor-value 255)) (ctl wobble :echo (* sensor-value 40))) 2 (do (reset! (colour :blue) (* sensor-value 255)) (ctl wobble :noise-rate (+ 1 (* sensor-value 40)))) nil)) (set-colour client cube @(colour :red) @(colour :green) @(colour :blue)) ) )))
[ { "context": ";; (c) Copyright 2014-2015 David Pollak (@dpp, feeder.of.the.bears at gmail)\n;;\n;; http:/", "end": 39, "score": 0.9998388290405273, "start": 27, "tag": "NAME", "value": "David Pollak" }, { "context": ";; (c) Copyright 2014-2015 David Pollak (@dpp, feeder.of.the.bears at gmail)\n;;\n;; http://www.a", "end": 45, "score": 0.9995402097702026, "start": 40, "tag": "USERNAME", "value": "(@dpp" } ]
test/visi/core/runtime_test.clj
visicorp/visi-core
7
;; (c) Copyright 2014-2015 David Pollak (@dpp, feeder.of.the.bears at gmail) ;; ;; 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 visi.core.runtime-test (:require [clojure.test :as t] [visi.core.parser :as vp] [visi.core.runtime :as vr] [visi.core.util :as vu] [instaparse.core :as insta])) (def FIXME true)
36668
;; (c) Copyright 2014-2015 <NAME> (@dpp, feeder.of.the.bears at gmail) ;; ;; 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 visi.core.runtime-test (:require [clojure.test :as t] [visi.core.parser :as vp] [visi.core.runtime :as vr] [visi.core.util :as vu] [instaparse.core :as insta])) (def FIXME true)
true
;; (c) Copyright 2014-2015 PI:NAME:<NAME>END_PI (@dpp, feeder.of.the.bears at gmail) ;; ;; 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 visi.core.runtime-test (:require [clojure.test :as t] [visi.core.parser :as vp] [visi.core.runtime :as vr] [visi.core.util :as vu] [instaparse.core :as insta])) (def FIXME true)
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.92864990234375, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-core/src/test/clojure/pigpen/functional/set_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.functional.set-test (:require [pigpen.functional-test :as t] [pigpen.extensions.test :refer [test-diff]] [pigpen.set :as pig-set] [pigpen.fold :as fold])) (t/deftest test-distinct "normal distinct" [harness] (test-diff (->> (t/data harness [5 1 2 3 4 3 2 1 5]) (pig-set/distinct) (t/dump harness) (sort)) '[1 2 3 4 5])) (t/deftest test-concat "normal concat" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/concat data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[1 2 2 3 3 3 4 4 5]))) (t/deftest test-union "normal union" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/union data1 data2 data3)] (test-diff (set (t/dump harness command)) '#{1 2 3 4 5}))) (t/deftest test-union-multiset "normal union multiset" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/union-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[1 2 2 3 3 3 4 4 5]))) (t/deftest test-intersection "normal intersection" [harness] (let [data1 (t/data harness [1 2 3 3]) data2 (t/data harness [3 2 3 4 3]) data3 (t/data harness [3 4 3 5 2]) command (pig-set/intersection data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[2 3]))) (t/deftest test-intersection-multiset "normal intersection multiset" [harness] (let [data1 (t/data harness [1 2 3 3]) data2 (t/data harness [3 2 3 4 3]) data3 (t/data harness [3 4 3 5 2]) command (pig-set/intersection-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[2 3 3]))) (t/deftest test-difference "normal difference" [harness] (let [data1 (t/data harness [1 2 3 3 3 4 5]) data2 (t/data harness [1 2]) data3 (t/data harness [4 5]) command (pig-set/difference data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[3]))) (t/deftest test-difference-multiset "normal difference multiset" [harness] (let [data1 (t/data harness [1 2 3 3 3 4 5]) data2 (t/data harness [1 2 3]) data3 (t/data harness [3 4 5]) command (pig-set/difference-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[3])))
1047
;; ;; ;; 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.functional.set-test (:require [pigpen.functional-test :as t] [pigpen.extensions.test :refer [test-diff]] [pigpen.set :as pig-set] [pigpen.fold :as fold])) (t/deftest test-distinct "normal distinct" [harness] (test-diff (->> (t/data harness [5 1 2 3 4 3 2 1 5]) (pig-set/distinct) (t/dump harness) (sort)) '[1 2 3 4 5])) (t/deftest test-concat "normal concat" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/concat data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[1 2 2 3 3 3 4 4 5]))) (t/deftest test-union "normal union" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/union data1 data2 data3)] (test-diff (set (t/dump harness command)) '#{1 2 3 4 5}))) (t/deftest test-union-multiset "normal union multiset" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/union-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[1 2 2 3 3 3 4 4 5]))) (t/deftest test-intersection "normal intersection" [harness] (let [data1 (t/data harness [1 2 3 3]) data2 (t/data harness [3 2 3 4 3]) data3 (t/data harness [3 4 3 5 2]) command (pig-set/intersection data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[2 3]))) (t/deftest test-intersection-multiset "normal intersection multiset" [harness] (let [data1 (t/data harness [1 2 3 3]) data2 (t/data harness [3 2 3 4 3]) data3 (t/data harness [3 4 3 5 2]) command (pig-set/intersection-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[2 3 3]))) (t/deftest test-difference "normal difference" [harness] (let [data1 (t/data harness [1 2 3 3 3 4 5]) data2 (t/data harness [1 2]) data3 (t/data harness [4 5]) command (pig-set/difference data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[3]))) (t/deftest test-difference-multiset "normal difference multiset" [harness] (let [data1 (t/data harness [1 2 3 3 3 4 5]) data2 (t/data harness [1 2 3]) data3 (t/data harness [3 4 5]) command (pig-set/difference-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[3])))
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.functional.set-test (:require [pigpen.functional-test :as t] [pigpen.extensions.test :refer [test-diff]] [pigpen.set :as pig-set] [pigpen.fold :as fold])) (t/deftest test-distinct "normal distinct" [harness] (test-diff (->> (t/data harness [5 1 2 3 4 3 2 1 5]) (pig-set/distinct) (t/dump harness) (sort)) '[1 2 3 4 5])) (t/deftest test-concat "normal concat" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/concat data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[1 2 2 3 3 3 4 4 5]))) (t/deftest test-union "normal union" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/union data1 data2 data3)] (test-diff (set (t/dump harness command)) '#{1 2 3 4 5}))) (t/deftest test-union-multiset "normal union multiset" [harness] (let [data1 (t/data harness [1 2 3]) data2 (t/data harness [2 3 4]) data3 (t/data harness [3 4 5]) command (pig-set/union-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[1 2 2 3 3 3 4 4 5]))) (t/deftest test-intersection "normal intersection" [harness] (let [data1 (t/data harness [1 2 3 3]) data2 (t/data harness [3 2 3 4 3]) data3 (t/data harness [3 4 3 5 2]) command (pig-set/intersection data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[2 3]))) (t/deftest test-intersection-multiset "normal intersection multiset" [harness] (let [data1 (t/data harness [1 2 3 3]) data2 (t/data harness [3 2 3 4 3]) data3 (t/data harness [3 4 3 5 2]) command (pig-set/intersection-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[2 3 3]))) (t/deftest test-difference "normal difference" [harness] (let [data1 (t/data harness [1 2 3 3 3 4 5]) data2 (t/data harness [1 2]) data3 (t/data harness [4 5]) command (pig-set/difference data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[3]))) (t/deftest test-difference-multiset "normal difference multiset" [harness] (let [data1 (t/data harness [1 2 3 3 3 4 5]) data2 (t/data harness [1 2 3]) data3 (t/data harness [3 4 5]) command (pig-set/difference-multiset data1 data2 data3)] (test-diff (sort (t/dump harness command)) '[3])))
[ { "context": "ilability \" :description c-name :duration 0 :key \"retData\"})\r\n ;(swap! app-state assoc-in [:param-sel] [])", "end": 3330, "score": 0.9451630115509033, "start": 3323, "tag": "KEY", "value": "retData" } ]
src/weblarda3/core.cljs
lacros-tropos/weblarda3
0
(ns weblarda3.core (:require [reagent.core :as reagent] [cljs.core.async :as async] [cljs-http.client :as http] [antizer.reagent :as ant] [clojure.string :as string] [clojure.set :as set] [goog.iter] [weblarda3.vis :as vis])) ;; tiny helpers ;; (in-ns 'weblarda3.core) (defn keys-to-str "combine the keys [:a :b] to a string separated with a|b" [list] ;(console.log (str list)) (goog.iter/join (clj->js (map name list)) "|")) (defn str-to-keys "" [str] (vec (string/split str #"\|"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Vars ; dev or hard coded ;(def host "http://larda.tropos.de/larda3/") (def host "http://larda3.tropos.de/") ;get from index.html <script> tag ;(def host (first (string/split js/hostaddr #"\?"))) (println "set host " host) (defonce app-state (reagent/atom {:c-list ["dummy"] :c-selected "lacros_dacapo" :c-info {} :param-sel ["MIRA|Zg"] :max-files 30 :host host})) (swap! app-state assoc-in [:host] host) (println (get @app-state :host)) (defonce modal1 (reagent/atom {:show false :title "" :content "loading.."})) (defn join-sys-param "given a system and a vec of parameters return [sys|param1 sys|param2 ...]" [system params] (mapv #(keys-to-str [system %]) params)) (defn all-params [info] (let [systems (keys (get info :connectors))] (mapv #(join-sys-param % (keys (get-in info [:connectors % :params]))) systems))) (defn max-no-files [sel-param-to-path] (let [; convert the selected paths form system|param to [[sys param] [sys param]] selected-path (mapv #(string/split % #"\|") (vals sel-param-to-path)) ; extract the availability hashmaps into vector avail-all (mapv #(get-in @app-state [:c-info :connectors (keyword (first %)) :avail (keyword (second %))]) selected-path) ; take just the values just-no (mapv vals avail-all) max-per-day (apply max (flatten just-no)) max-files-per-day (if (nil? max-per-day) 24 max-per-day)] ;(println "selected-pahts" selected-path) ;(println "max-files-per-day" max-files-per-day) (swap! app-state assoc-in [:max-files] max-files-per-day))) (defn set-initial-selection [c-info] (let [param-sel (get @app-state :param-sel) params (flatten (all-params c-info)) valid-params (set/intersection (set param-sel) (set params)) set-params (if (empty? valid-params) [(first params)] (vec valid-params))] ;(println "param-sel at set-initial" param-sel) ;(println "valid params " valid-params set-params) (swap! app-state assoc-in [:param-sel] set-params))) (defn get-search [] ; ?interval=1549385800.0-1549396800.0%2C0-8000&params=CLOUDNET|WIDTH (let [params (string/join "," (get-in @app-state [:param-sel]))] (str "?camp=" (get @app-state :c-selected) "&params=" params))) ;; http request stuff (defn hex-comma-and-split [str] (if str (string/split (string/replace str #"%2C" ",") #",") [])) (defn fetch-c-info [c-name] (ant/notification-open {:message "loading data availability " :description c-name :duration 0 :key "retData"}) ;(swap! app-state assoc-in [:param-sel] []) (async/go (let [response (async/<! (http/get (str host "api/" c-name "/") {:as :json :with-credentials? false}))] ;(println (:status response) (:body response)) (println "fetched new c-info for " c-name (:status response)) (ant/notification-close "retData") (ant/notification-info {:message "Hint" :description "right-click on parameter to display description text" :duration 40}) (ant/notification-info {:message "Hint" :description "left-click on day to access explorer" :duration 40}) (set-initial-selection (get-in response [:body])) (swap! app-state assoc-in [:c-info] (get-in response [:body]))) (js/window.history.replaceState (clj->js nil) (clj->js nil) (get-search)) (max-no-files (vis/map-params-to-path (get-in @app-state [:param-sel]) (get-in @app-state [:c-info :connectors]))) ) ) (async/go (let [response (async/<! (http/get (str host "api/") {:as :json :with-credentials? false})) ;query-string (.. address -search) query-string (.. js/window -location -search) query-camp (second (re-find #"camp=([^&]*)" query-string)) query-params (hex-comma-and-split (second (re-find #"params=([^&]*)" query-string)))] (println "found camp string " query-camp (get-in response [:body :campaign_list])) (println "found param string ", query-params) (if-not (some #{(get-in @app-state [:c-selected])} (get-in response [:body :campaign_list])) (swap! app-state assoc-in [:c-selected] (first (get-in response [:body :campaign_list])))) (if (and (not (nil? query-camp)) (some #{query-camp} (get-in response [:body :campaign_list]))) (swap! app-state assoc-in [:c-selected] query-camp)) (if-not (nil? query-params) (swap! app-state assoc-in [:param-sel] query-params)) ; at first check if Query_String provided campaign (println "fetch campaign list" (:status response) (:body response)) (fetch-c-info (get @app-state :c-selected)) (swap! app-state assoc-in [:c-list] (get-in response [:body :campaign_list])))) (defn fetch-description [param_string] (let [c-name (get-in @app-state [:c-selected]) [system param] (str-to-keys param_string)] (println "request string" (str host "description/" c-name "/" system "/" param)) (swap! modal1 assoc-in [:title] (str system ": " param)) (async/go (let [response (async/<! (http/get (str host "description/" c-name "/" system "/" param) {:as :raw :with-credentials? false}))] ;(println "retrieved" (:status response) (:body response)) (println "fetched new description string " c-name system param (:status response)) (swap! modal1 assoc-in [:content] (get-in response [:body])))))) ;; change functions (defn change-campaign [c-name] (let [query-string (.. js/window -location -search)] (if (count query-string) (js/window.history.replaceState (clj->js nil) (clj->js nil) (string/replace query-string #"camp=([^&]*)" (str "camp=" c-name))))) (swap! app-state assoc-in [:c-selected] (js->clj c-name)) (fetch-c-info c-name)) (defn update-sel-params [list] (let [valid_list (filter #(string/includes? % "|") (js->clj list))] (println "update-selparams valid_list" valid_list) (max-no-files (vis/map-params-to-path valid_list (get-in @app-state [:c-info :connectors]))) (swap! app-state assoc-in [:param-sel] (filterv #(not (string/includes? % ":")) valid_list)) (js/window.history.replaceState (clj->js nil) (clj->js nil) (get-search)) )) (defn regroup-param-path [param-path] (let [paths (vec (set (vals param-path))) path-param (mapv (fn [p] [p (mapv first (filter #(= p (val %)) param-path))]) paths)] (into {} path-param))) (defn right-click-tree [inp] (let [param_string (-> inp .-node .-props .-eventKey) valid? (string/includes? param_string "|")] (if valid? (do (fetch-description param_string) (swap! modal1 update-in [:show] not)) (ant/notification-error {:message "Error" :description (str "Description only available for paramters, not systems")})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Page (defn select-campaign [] [:div "campaign " [ant/select {:showSearch true :placeholder "select campaign" :value (get-in @app-state [:c-selected]) :onChange change-campaign :style {:width "150px"} :size "small"} (for [c-name (get-in @app-state [:c-list])] ^{:key c-name} [ant/select-option {:value c-name} c-name])] [:br] "max files " [ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "40px" :text-align "right"} :value (get-in @app-state [:max-files]) :onChange #(swap! app-state assoc-in [:max-files] (js->clj (js/parseInt (.. % -target -value))))}]]) ;(defn tree-nodes [system] ;(println "tree-nodes" system) ;(for [param (keys (get-in @app-state [:c-info :connectors (keyword system) :params]))] [ant/tree-tree-node {:title param}])) (defn params-tree [] [ant/tree {:checkable true :onCheck update-sel-params :onRightClick right-click-tree :checkedKeys (get @app-state :param-sel) :multiple false} (doall (for [system (sort (keys (get-in @app-state [:c-info :connectors])))] ^{:key system} [ant/tree-tree-node {:title system :selectable false :style {:font-size 12}} (for [param (sort (keys (get-in @app-state [:c-info :connectors (keyword system) :params])))] ^{:key (keys-to-str [system param])} [ant/tree-tree-node {:title param}])]))]) (defn line-in-info [k v] [:tr [:td (first (string/split k #"\|"))] [:td (second (string/split k #"\|"))] [:td (goog.iter/join (clj->js (mapv #(second (string/split % #"\|")) v)) ", ")]]) (defn info-area [] (fn [] (let [param-sel (get-in @app-state [:param-sel]) connectors (get-in @app-state [:c-info :connectors]) sel-param-to-path (vis/map-params-to-path param-sel connectors) regrouped (regroup-param-path sel-param-to-path)] (println "info-area" regrouped) (if (> (count (keys regrouped)) 4) (ant/notification-error {:message "Error" :description (str "Too may file identifiers selected. Reduce to 4")})) [:div.info-area [:table [:thead [:tr [:th "System"] [:th "File identifier"] [:th "Parameters"]]] [:tbody (for [[k v] regrouped] ^{:key k} [line-in-info k v])]]]))) (defn calendar-component [] (reagent/create-class {:reagent-render #(vis/calendar-render app-state) :component-did-mount #(vis/calendar-did-mount app-state) :component-did-update #(vis/calendar-did-mount app-state)})) (defn display-modal [] (fn [] [ant/modal {:visible (get-in @modal1 [:show]) :title (str "Description " (get-in @modal1 [:title])) :on-ok #(reset! modal1 {:show false :title "" :content "loading..."}) :on-cancel #(reset! modal1 {:show false :title "" :content "loading..."})} (reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (string/replace (get-in @modal1 [:content]) #"\n" "<br />")}}])])) (defn page [] [:div [:h1 "Data availability"] [:div#contents [:div#menu [select-campaign] [params-tree]] [:div#right (if-not (empty? (get @app-state :c-info)) [info-area]) (if-not (empty? (get @app-state :c-info)) [calendar-component])]] ;[:br][ant/col {:span 24} [:div (str (get @app-state :param-sel))][:div (str @app-state)]] [display-modal] [:br]]) ;; Initialize App ; (defn dev-setup [] ; (when ^boolean js/goog.DEBUG ; (enable-console-print!) ; (println "dev mode"))) (enable-console-print!) (defn reload [] (reagent/render [page] (.getElementById js/document "app"))) (defn ^:export main [] ;(dev-setup) (reload)) (comment *ns* (in-ns 'weblarda3.core) (str/replace (.. js/window -location -search) #"camp=([^&]*)" "new") (require weblarda3.core :reload-all))
91683
(ns weblarda3.core (:require [reagent.core :as reagent] [cljs.core.async :as async] [cljs-http.client :as http] [antizer.reagent :as ant] [clojure.string :as string] [clojure.set :as set] [goog.iter] [weblarda3.vis :as vis])) ;; tiny helpers ;; (in-ns 'weblarda3.core) (defn keys-to-str "combine the keys [:a :b] to a string separated with a|b" [list] ;(console.log (str list)) (goog.iter/join (clj->js (map name list)) "|")) (defn str-to-keys "" [str] (vec (string/split str #"\|"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Vars ; dev or hard coded ;(def host "http://larda.tropos.de/larda3/") (def host "http://larda3.tropos.de/") ;get from index.html <script> tag ;(def host (first (string/split js/hostaddr #"\?"))) (println "set host " host) (defonce app-state (reagent/atom {:c-list ["dummy"] :c-selected "lacros_dacapo" :c-info {} :param-sel ["MIRA|Zg"] :max-files 30 :host host})) (swap! app-state assoc-in [:host] host) (println (get @app-state :host)) (defonce modal1 (reagent/atom {:show false :title "" :content "loading.."})) (defn join-sys-param "given a system and a vec of parameters return [sys|param1 sys|param2 ...]" [system params] (mapv #(keys-to-str [system %]) params)) (defn all-params [info] (let [systems (keys (get info :connectors))] (mapv #(join-sys-param % (keys (get-in info [:connectors % :params]))) systems))) (defn max-no-files [sel-param-to-path] (let [; convert the selected paths form system|param to [[sys param] [sys param]] selected-path (mapv #(string/split % #"\|") (vals sel-param-to-path)) ; extract the availability hashmaps into vector avail-all (mapv #(get-in @app-state [:c-info :connectors (keyword (first %)) :avail (keyword (second %))]) selected-path) ; take just the values just-no (mapv vals avail-all) max-per-day (apply max (flatten just-no)) max-files-per-day (if (nil? max-per-day) 24 max-per-day)] ;(println "selected-pahts" selected-path) ;(println "max-files-per-day" max-files-per-day) (swap! app-state assoc-in [:max-files] max-files-per-day))) (defn set-initial-selection [c-info] (let [param-sel (get @app-state :param-sel) params (flatten (all-params c-info)) valid-params (set/intersection (set param-sel) (set params)) set-params (if (empty? valid-params) [(first params)] (vec valid-params))] ;(println "param-sel at set-initial" param-sel) ;(println "valid params " valid-params set-params) (swap! app-state assoc-in [:param-sel] set-params))) (defn get-search [] ; ?interval=1549385800.0-1549396800.0%2C0-8000&params=CLOUDNET|WIDTH (let [params (string/join "," (get-in @app-state [:param-sel]))] (str "?camp=" (get @app-state :c-selected) "&params=" params))) ;; http request stuff (defn hex-comma-and-split [str] (if str (string/split (string/replace str #"%2C" ",") #",") [])) (defn fetch-c-info [c-name] (ant/notification-open {:message "loading data availability " :description c-name :duration 0 :key "<KEY>"}) ;(swap! app-state assoc-in [:param-sel] []) (async/go (let [response (async/<! (http/get (str host "api/" c-name "/") {:as :json :with-credentials? false}))] ;(println (:status response) (:body response)) (println "fetched new c-info for " c-name (:status response)) (ant/notification-close "retData") (ant/notification-info {:message "Hint" :description "right-click on parameter to display description text" :duration 40}) (ant/notification-info {:message "Hint" :description "left-click on day to access explorer" :duration 40}) (set-initial-selection (get-in response [:body])) (swap! app-state assoc-in [:c-info] (get-in response [:body]))) (js/window.history.replaceState (clj->js nil) (clj->js nil) (get-search)) (max-no-files (vis/map-params-to-path (get-in @app-state [:param-sel]) (get-in @app-state [:c-info :connectors]))) ) ) (async/go (let [response (async/<! (http/get (str host "api/") {:as :json :with-credentials? false})) ;query-string (.. address -search) query-string (.. js/window -location -search) query-camp (second (re-find #"camp=([^&]*)" query-string)) query-params (hex-comma-and-split (second (re-find #"params=([^&]*)" query-string)))] (println "found camp string " query-camp (get-in response [:body :campaign_list])) (println "found param string ", query-params) (if-not (some #{(get-in @app-state [:c-selected])} (get-in response [:body :campaign_list])) (swap! app-state assoc-in [:c-selected] (first (get-in response [:body :campaign_list])))) (if (and (not (nil? query-camp)) (some #{query-camp} (get-in response [:body :campaign_list]))) (swap! app-state assoc-in [:c-selected] query-camp)) (if-not (nil? query-params) (swap! app-state assoc-in [:param-sel] query-params)) ; at first check if Query_String provided campaign (println "fetch campaign list" (:status response) (:body response)) (fetch-c-info (get @app-state :c-selected)) (swap! app-state assoc-in [:c-list] (get-in response [:body :campaign_list])))) (defn fetch-description [param_string] (let [c-name (get-in @app-state [:c-selected]) [system param] (str-to-keys param_string)] (println "request string" (str host "description/" c-name "/" system "/" param)) (swap! modal1 assoc-in [:title] (str system ": " param)) (async/go (let [response (async/<! (http/get (str host "description/" c-name "/" system "/" param) {:as :raw :with-credentials? false}))] ;(println "retrieved" (:status response) (:body response)) (println "fetched new description string " c-name system param (:status response)) (swap! modal1 assoc-in [:content] (get-in response [:body])))))) ;; change functions (defn change-campaign [c-name] (let [query-string (.. js/window -location -search)] (if (count query-string) (js/window.history.replaceState (clj->js nil) (clj->js nil) (string/replace query-string #"camp=([^&]*)" (str "camp=" c-name))))) (swap! app-state assoc-in [:c-selected] (js->clj c-name)) (fetch-c-info c-name)) (defn update-sel-params [list] (let [valid_list (filter #(string/includes? % "|") (js->clj list))] (println "update-selparams valid_list" valid_list) (max-no-files (vis/map-params-to-path valid_list (get-in @app-state [:c-info :connectors]))) (swap! app-state assoc-in [:param-sel] (filterv #(not (string/includes? % ":")) valid_list)) (js/window.history.replaceState (clj->js nil) (clj->js nil) (get-search)) )) (defn regroup-param-path [param-path] (let [paths (vec (set (vals param-path))) path-param (mapv (fn [p] [p (mapv first (filter #(= p (val %)) param-path))]) paths)] (into {} path-param))) (defn right-click-tree [inp] (let [param_string (-> inp .-node .-props .-eventKey) valid? (string/includes? param_string "|")] (if valid? (do (fetch-description param_string) (swap! modal1 update-in [:show] not)) (ant/notification-error {:message "Error" :description (str "Description only available for paramters, not systems")})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Page (defn select-campaign [] [:div "campaign " [ant/select {:showSearch true :placeholder "select campaign" :value (get-in @app-state [:c-selected]) :onChange change-campaign :style {:width "150px"} :size "small"} (for [c-name (get-in @app-state [:c-list])] ^{:key c-name} [ant/select-option {:value c-name} c-name])] [:br] "max files " [ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "40px" :text-align "right"} :value (get-in @app-state [:max-files]) :onChange #(swap! app-state assoc-in [:max-files] (js->clj (js/parseInt (.. % -target -value))))}]]) ;(defn tree-nodes [system] ;(println "tree-nodes" system) ;(for [param (keys (get-in @app-state [:c-info :connectors (keyword system) :params]))] [ant/tree-tree-node {:title param}])) (defn params-tree [] [ant/tree {:checkable true :onCheck update-sel-params :onRightClick right-click-tree :checkedKeys (get @app-state :param-sel) :multiple false} (doall (for [system (sort (keys (get-in @app-state [:c-info :connectors])))] ^{:key system} [ant/tree-tree-node {:title system :selectable false :style {:font-size 12}} (for [param (sort (keys (get-in @app-state [:c-info :connectors (keyword system) :params])))] ^{:key (keys-to-str [system param])} [ant/tree-tree-node {:title param}])]))]) (defn line-in-info [k v] [:tr [:td (first (string/split k #"\|"))] [:td (second (string/split k #"\|"))] [:td (goog.iter/join (clj->js (mapv #(second (string/split % #"\|")) v)) ", ")]]) (defn info-area [] (fn [] (let [param-sel (get-in @app-state [:param-sel]) connectors (get-in @app-state [:c-info :connectors]) sel-param-to-path (vis/map-params-to-path param-sel connectors) regrouped (regroup-param-path sel-param-to-path)] (println "info-area" regrouped) (if (> (count (keys regrouped)) 4) (ant/notification-error {:message "Error" :description (str "Too may file identifiers selected. Reduce to 4")})) [:div.info-area [:table [:thead [:tr [:th "System"] [:th "File identifier"] [:th "Parameters"]]] [:tbody (for [[k v] regrouped] ^{:key k} [line-in-info k v])]]]))) (defn calendar-component [] (reagent/create-class {:reagent-render #(vis/calendar-render app-state) :component-did-mount #(vis/calendar-did-mount app-state) :component-did-update #(vis/calendar-did-mount app-state)})) (defn display-modal [] (fn [] [ant/modal {:visible (get-in @modal1 [:show]) :title (str "Description " (get-in @modal1 [:title])) :on-ok #(reset! modal1 {:show false :title "" :content "loading..."}) :on-cancel #(reset! modal1 {:show false :title "" :content "loading..."})} (reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (string/replace (get-in @modal1 [:content]) #"\n" "<br />")}}])])) (defn page [] [:div [:h1 "Data availability"] [:div#contents [:div#menu [select-campaign] [params-tree]] [:div#right (if-not (empty? (get @app-state :c-info)) [info-area]) (if-not (empty? (get @app-state :c-info)) [calendar-component])]] ;[:br][ant/col {:span 24} [:div (str (get @app-state :param-sel))][:div (str @app-state)]] [display-modal] [:br]]) ;; Initialize App ; (defn dev-setup [] ; (when ^boolean js/goog.DEBUG ; (enable-console-print!) ; (println "dev mode"))) (enable-console-print!) (defn reload [] (reagent/render [page] (.getElementById js/document "app"))) (defn ^:export main [] ;(dev-setup) (reload)) (comment *ns* (in-ns 'weblarda3.core) (str/replace (.. js/window -location -search) #"camp=([^&]*)" "new") (require weblarda3.core :reload-all))
true
(ns weblarda3.core (:require [reagent.core :as reagent] [cljs.core.async :as async] [cljs-http.client :as http] [antizer.reagent :as ant] [clojure.string :as string] [clojure.set :as set] [goog.iter] [weblarda3.vis :as vis])) ;; tiny helpers ;; (in-ns 'weblarda3.core) (defn keys-to-str "combine the keys [:a :b] to a string separated with a|b" [list] ;(console.log (str list)) (goog.iter/join (clj->js (map name list)) "|")) (defn str-to-keys "" [str] (vec (string/split str #"\|"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Vars ; dev or hard coded ;(def host "http://larda.tropos.de/larda3/") (def host "http://larda3.tropos.de/") ;get from index.html <script> tag ;(def host (first (string/split js/hostaddr #"\?"))) (println "set host " host) (defonce app-state (reagent/atom {:c-list ["dummy"] :c-selected "lacros_dacapo" :c-info {} :param-sel ["MIRA|Zg"] :max-files 30 :host host})) (swap! app-state assoc-in [:host] host) (println (get @app-state :host)) (defonce modal1 (reagent/atom {:show false :title "" :content "loading.."})) (defn join-sys-param "given a system and a vec of parameters return [sys|param1 sys|param2 ...]" [system params] (mapv #(keys-to-str [system %]) params)) (defn all-params [info] (let [systems (keys (get info :connectors))] (mapv #(join-sys-param % (keys (get-in info [:connectors % :params]))) systems))) (defn max-no-files [sel-param-to-path] (let [; convert the selected paths form system|param to [[sys param] [sys param]] selected-path (mapv #(string/split % #"\|") (vals sel-param-to-path)) ; extract the availability hashmaps into vector avail-all (mapv #(get-in @app-state [:c-info :connectors (keyword (first %)) :avail (keyword (second %))]) selected-path) ; take just the values just-no (mapv vals avail-all) max-per-day (apply max (flatten just-no)) max-files-per-day (if (nil? max-per-day) 24 max-per-day)] ;(println "selected-pahts" selected-path) ;(println "max-files-per-day" max-files-per-day) (swap! app-state assoc-in [:max-files] max-files-per-day))) (defn set-initial-selection [c-info] (let [param-sel (get @app-state :param-sel) params (flatten (all-params c-info)) valid-params (set/intersection (set param-sel) (set params)) set-params (if (empty? valid-params) [(first params)] (vec valid-params))] ;(println "param-sel at set-initial" param-sel) ;(println "valid params " valid-params set-params) (swap! app-state assoc-in [:param-sel] set-params))) (defn get-search [] ; ?interval=1549385800.0-1549396800.0%2C0-8000&params=CLOUDNET|WIDTH (let [params (string/join "," (get-in @app-state [:param-sel]))] (str "?camp=" (get @app-state :c-selected) "&params=" params))) ;; http request stuff (defn hex-comma-and-split [str] (if str (string/split (string/replace str #"%2C" ",") #",") [])) (defn fetch-c-info [c-name] (ant/notification-open {:message "loading data availability " :description c-name :duration 0 :key "PI:KEY:<KEY>END_PI"}) ;(swap! app-state assoc-in [:param-sel] []) (async/go (let [response (async/<! (http/get (str host "api/" c-name "/") {:as :json :with-credentials? false}))] ;(println (:status response) (:body response)) (println "fetched new c-info for " c-name (:status response)) (ant/notification-close "retData") (ant/notification-info {:message "Hint" :description "right-click on parameter to display description text" :duration 40}) (ant/notification-info {:message "Hint" :description "left-click on day to access explorer" :duration 40}) (set-initial-selection (get-in response [:body])) (swap! app-state assoc-in [:c-info] (get-in response [:body]))) (js/window.history.replaceState (clj->js nil) (clj->js nil) (get-search)) (max-no-files (vis/map-params-to-path (get-in @app-state [:param-sel]) (get-in @app-state [:c-info :connectors]))) ) ) (async/go (let [response (async/<! (http/get (str host "api/") {:as :json :with-credentials? false})) ;query-string (.. address -search) query-string (.. js/window -location -search) query-camp (second (re-find #"camp=([^&]*)" query-string)) query-params (hex-comma-and-split (second (re-find #"params=([^&]*)" query-string)))] (println "found camp string " query-camp (get-in response [:body :campaign_list])) (println "found param string ", query-params) (if-not (some #{(get-in @app-state [:c-selected])} (get-in response [:body :campaign_list])) (swap! app-state assoc-in [:c-selected] (first (get-in response [:body :campaign_list])))) (if (and (not (nil? query-camp)) (some #{query-camp} (get-in response [:body :campaign_list]))) (swap! app-state assoc-in [:c-selected] query-camp)) (if-not (nil? query-params) (swap! app-state assoc-in [:param-sel] query-params)) ; at first check if Query_String provided campaign (println "fetch campaign list" (:status response) (:body response)) (fetch-c-info (get @app-state :c-selected)) (swap! app-state assoc-in [:c-list] (get-in response [:body :campaign_list])))) (defn fetch-description [param_string] (let [c-name (get-in @app-state [:c-selected]) [system param] (str-to-keys param_string)] (println "request string" (str host "description/" c-name "/" system "/" param)) (swap! modal1 assoc-in [:title] (str system ": " param)) (async/go (let [response (async/<! (http/get (str host "description/" c-name "/" system "/" param) {:as :raw :with-credentials? false}))] ;(println "retrieved" (:status response) (:body response)) (println "fetched new description string " c-name system param (:status response)) (swap! modal1 assoc-in [:content] (get-in response [:body])))))) ;; change functions (defn change-campaign [c-name] (let [query-string (.. js/window -location -search)] (if (count query-string) (js/window.history.replaceState (clj->js nil) (clj->js nil) (string/replace query-string #"camp=([^&]*)" (str "camp=" c-name))))) (swap! app-state assoc-in [:c-selected] (js->clj c-name)) (fetch-c-info c-name)) (defn update-sel-params [list] (let [valid_list (filter #(string/includes? % "|") (js->clj list))] (println "update-selparams valid_list" valid_list) (max-no-files (vis/map-params-to-path valid_list (get-in @app-state [:c-info :connectors]))) (swap! app-state assoc-in [:param-sel] (filterv #(not (string/includes? % ":")) valid_list)) (js/window.history.replaceState (clj->js nil) (clj->js nil) (get-search)) )) (defn regroup-param-path [param-path] (let [paths (vec (set (vals param-path))) path-param (mapv (fn [p] [p (mapv first (filter #(= p (val %)) param-path))]) paths)] (into {} path-param))) (defn right-click-tree [inp] (let [param_string (-> inp .-node .-props .-eventKey) valid? (string/includes? param_string "|")] (if valid? (do (fetch-description param_string) (swap! modal1 update-in [:show] not)) (ant/notification-error {:message "Error" :description (str "Description only available for paramters, not systems")})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Page (defn select-campaign [] [:div "campaign " [ant/select {:showSearch true :placeholder "select campaign" :value (get-in @app-state [:c-selected]) :onChange change-campaign :style {:width "150px"} :size "small"} (for [c-name (get-in @app-state [:c-list])] ^{:key c-name} [ant/select-option {:value c-name} c-name])] [:br] "max files " [ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "40px" :text-align "right"} :value (get-in @app-state [:max-files]) :onChange #(swap! app-state assoc-in [:max-files] (js->clj (js/parseInt (.. % -target -value))))}]]) ;(defn tree-nodes [system] ;(println "tree-nodes" system) ;(for [param (keys (get-in @app-state [:c-info :connectors (keyword system) :params]))] [ant/tree-tree-node {:title param}])) (defn params-tree [] [ant/tree {:checkable true :onCheck update-sel-params :onRightClick right-click-tree :checkedKeys (get @app-state :param-sel) :multiple false} (doall (for [system (sort (keys (get-in @app-state [:c-info :connectors])))] ^{:key system} [ant/tree-tree-node {:title system :selectable false :style {:font-size 12}} (for [param (sort (keys (get-in @app-state [:c-info :connectors (keyword system) :params])))] ^{:key (keys-to-str [system param])} [ant/tree-tree-node {:title param}])]))]) (defn line-in-info [k v] [:tr [:td (first (string/split k #"\|"))] [:td (second (string/split k #"\|"))] [:td (goog.iter/join (clj->js (mapv #(second (string/split % #"\|")) v)) ", ")]]) (defn info-area [] (fn [] (let [param-sel (get-in @app-state [:param-sel]) connectors (get-in @app-state [:c-info :connectors]) sel-param-to-path (vis/map-params-to-path param-sel connectors) regrouped (regroup-param-path sel-param-to-path)] (println "info-area" regrouped) (if (> (count (keys regrouped)) 4) (ant/notification-error {:message "Error" :description (str "Too may file identifiers selected. Reduce to 4")})) [:div.info-area [:table [:thead [:tr [:th "System"] [:th "File identifier"] [:th "Parameters"]]] [:tbody (for [[k v] regrouped] ^{:key k} [line-in-info k v])]]]))) (defn calendar-component [] (reagent/create-class {:reagent-render #(vis/calendar-render app-state) :component-did-mount #(vis/calendar-did-mount app-state) :component-did-update #(vis/calendar-did-mount app-state)})) (defn display-modal [] (fn [] [ant/modal {:visible (get-in @modal1 [:show]) :title (str "Description " (get-in @modal1 [:title])) :on-ok #(reset! modal1 {:show false :title "" :content "loading..."}) :on-cancel #(reset! modal1 {:show false :title "" :content "loading..."})} (reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (string/replace (get-in @modal1 [:content]) #"\n" "<br />")}}])])) (defn page [] [:div [:h1 "Data availability"] [:div#contents [:div#menu [select-campaign] [params-tree]] [:div#right (if-not (empty? (get @app-state :c-info)) [info-area]) (if-not (empty? (get @app-state :c-info)) [calendar-component])]] ;[:br][ant/col {:span 24} [:div (str (get @app-state :param-sel))][:div (str @app-state)]] [display-modal] [:br]]) ;; Initialize App ; (defn dev-setup [] ; (when ^boolean js/goog.DEBUG ; (enable-console-print!) ; (println "dev mode"))) (enable-console-print!) (defn reload [] (reagent/render [page] (.getElementById js/document "app"))) (defn ^:export main [] ;(dev-setup) (reload)) (comment *ns* (in-ns 'weblarda3.core) (str/replace (.. js/window -location -search) #"camp=([^&]*)" "new") (require weblarda3.core :reload-all))
[ { "context": " `({:entity ~person-schema :tuples ~(list {:name \"John Doe\" :Address {:Address1 \"123 Main\" :City \"Springfiel", "end": 1194, "score": 0.9997431635856628, "start": 1186, "tag": "NAME", "value": "John Doe" }, { "context": "ema :tuples [\"name,Address.Address1,Address.City\\nJohn Doe,123 Main,Springfield\\n\"]}]\n (format-r", "end": 1344, "score": 0.9997037649154663, "start": 1336, "tag": "NAME", "value": "John Doe" }, { "context": " `({:entity ~person-schema :tuples ~(list {:Name \"John Doe\" :Address {:Address1 \"123 Main\" :City \"Springfiel", "end": 2800, "score": 0.9996288418769836, "start": 2792, "tag": "NAME", "value": "John Doe" }, { "context": "\",\\\"Address.Address1\\\",\\\"Address.City\\\") VALUES ('John Doe','123 Main','Springfield');\\n\"]}]\n (f", "end": 2995, "score": 0.9995533227920532, "start": 2987, "tag": "NAME", "value": "John Doe" }, { "context": "a `({:entity ~person-table :tuples ~(list {:name \"John Doe\" :Address {:Address1 \"123 Main\" :City \"Springfiel", "end": 4714, "score": 0.9997807741165161, "start": 4706, "tag": "NAME", "value": "John Doe" }, { "context": "version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><Person><name>John Doe</name><Address><Address1>123 Main</Address1><City", "end": 4883, "score": 0.9997613430023193, "start": 4875, "tag": "NAME", "value": "John Doe" }, { "context": " nil \n :properties [{:name \"Name\" :type :string}\n ", "end": 5216, "score": 0.8478638529777527, "start": 5212, "tag": "NAME", "value": "Name" }, { "context": "rson-table \n :tuples [{:name \"John Doe\" \n :DOB (LocalDate/", "end": 5386, "score": 0.9998356103897095, "start": 5378, "tag": "NAME", "value": "John Doe" }, { "context": "version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><Person><name>John Doe</name><DOB>2019-01-01</DOB></Person>\"]}]\n ", "end": 5580, "score": 0.9997771382331848, "start": 5572, "tag": "NAME", "value": "John Doe" } ]
test/blutwurst/tuple_formatter_test.clj
michaeljmcd/blutwurst
0
(ns blutwurst.tuple-formatter-test (:import (java.time ZonedDateTime OffsetDateTime ZoneOffset Instant LocalDate)) (:require [clojure.test :refer :all] [clojure.pprint :refer :all] [blutwurst.logging-fixture :refer :all] [blutwurst.tuple-formatter :refer :all])) (use-fixtures :each logging-fixture) (def simple-schema {:name "Example" :schema "foo" :properties [{:name "A" :type :integer} {:name "B" :type :string}]}) (def person-schema {:name "Person" :schema nil :properties [{:name "Address" :type :complex} {:name "Name" :type :string}] :dependencies [{:target-schema nil :target-name "Address" :dependency-name nil :links {"Address" :embedded}}]}) (deftest csv-formatter-test (testing "Generating a CSV from rows." (let [spec {:format :csv} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `[{:entity ~table :tuples ["A,B\n1,2\n"]}] (format-rows spec rows))))) (testing "Flattens out embedded objects." (let [spec {:format :csv} data `({:entity ~person-schema :tuples ~(list {:name "John Doe" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-schema :tuples ["name,Address.Address1,Address.City\nJohn Doe,123 Main,Springfield\n"]}] (format-rows spec data)))))) (deftest edn-formatter-test (testing "Generating an EDN file from rows." (let [spec {:format :edn} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `[{:entity ~table :tuples ["{:A 1, :B 2}"]}] (format-rows spec rows)))))) (deftest sql-formatter-test (testing "Basic SQL generation with integer-only values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,2);\n"]}) (format-rows spec rows))))) (testing "SQL generation quotes and escapes string values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :string) rows `({:entity ~table :tuples ({:A 1 :B "Then O'Kelly came in with the \t hatchett."})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,'Then O''Kelly came in with the \t hatchett.');\n"]}) (format-rows spec rows))))) (testing "SQL generation flattens out embedded objects." (let [spec {:format :sql} data `({:entity ~person-schema :tuples ~(list {:Name "John Doe" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-schema :tuples ["INSERT INTO \"Person\" (\"Name\",\"Address.Address1\",\"Address.City\") VALUES ('John Doe','123 Main','Springfield');\n"]}] (format-rows spec data))))) (testing "SQL generation formats DATE values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :datetime) rows `({:entity ~table :tuples ({:A 1 :B ~(ZonedDateTime/ofInstant (Instant/ofEpochMilli 1109741401000) (ZoneOffset/ofHours -6))})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,'2005-03-01T23:30:01.000-06:00');\n"]}) (format-rows spec rows)))))) (deftest json-formatter-test (testing "Basic JSON generation." (let [spec {:format :json} table simple-schema rows `({:entity ~table :tuples ({:A 1 :B "\"Thus sayeth...\""})})] (is (= `[{:entity ~table :tuples ["[{\"A\":1,\"B\":\"\\\"Thus sayeth...\\\"\"}]"]}] (format-rows spec rows)))))) (deftest xml-formatter-test (testing "Basic XML generation." (let [spec {:format :xml} table simple-schema rows `({:entity ~table :tuples ({:A 1 :B "\"Thus sayeth...\""} {:A 2 :B "three"})}) result (format-rows spec rows)] (is (= `[{:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B>\"Thus sayeth...\"</B></Example>" "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>2</A><B>three</B></Example>"]}] result)))) (testing "XML generation with embedded objects." (let [spec {:format :xml} person-table {:name "Person" :schema nil :properties [{:name "Address" :type :complex} {:name "Name" :type :string}]} data `({:entity ~person-table :tuples ~(list {:name "John Doe" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Person><name>John Doe</name><Address><Address1>123 Main</Address1><City>Springfield</City></Address></Person>"]}] (format-rows spec data))))) (testing "XML generation with local dates." (let [spec {:format :xml} person-table {:name "Person" :schema nil :properties [{:name "Name" :type :string} {:name "DOB" :type :date}]} data (list {:entity person-table :tuples [{:name "John Doe" :DOB (LocalDate/of 2019 1 1)}]})] (is (= [{:entity person-table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Person><name>John Doe</name><DOB>2019-01-01</DOB></Person>"]}] (format-rows spec data))))) (testing "XML generation with DATETIME values." (let [spec {:format :xml} table (assoc-in simple-schema [:properties 1 :type] :datetime) data `({:entity ~table :tuples ({:A 1 :B ~(ZonedDateTime/ofInstant (Instant/ofEpochMilli 1109741401000) (ZoneOffset/ofHours -6))})})] (is (= `({:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B>2005-03-01T23:30:01-06:00</B></Example>"]}) (format-rows spec data))))) (testing "Basic XML generation with sequences." (let [spec {:format :xml} table (-> simple-schema (assoc-in [:properties 1 :type] :sequence) (assoc-in [:properties 1 :properties] [{:name "items" :type :integer}])) rows `({:entity ~table :tuples ({:A 1 :B [1 2]} {:A 2 :B [3 5 6]})}) result (format-rows spec rows)] (is (= `[{:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B><item>1</item><item>2</item></B></Example>" "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>2</A><B><item>3</item><item>5</item><item>6</item></B></Example>"]}] result)))))
23085
(ns blutwurst.tuple-formatter-test (:import (java.time ZonedDateTime OffsetDateTime ZoneOffset Instant LocalDate)) (:require [clojure.test :refer :all] [clojure.pprint :refer :all] [blutwurst.logging-fixture :refer :all] [blutwurst.tuple-formatter :refer :all])) (use-fixtures :each logging-fixture) (def simple-schema {:name "Example" :schema "foo" :properties [{:name "A" :type :integer} {:name "B" :type :string}]}) (def person-schema {:name "Person" :schema nil :properties [{:name "Address" :type :complex} {:name "Name" :type :string}] :dependencies [{:target-schema nil :target-name "Address" :dependency-name nil :links {"Address" :embedded}}]}) (deftest csv-formatter-test (testing "Generating a CSV from rows." (let [spec {:format :csv} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `[{:entity ~table :tuples ["A,B\n1,2\n"]}] (format-rows spec rows))))) (testing "Flattens out embedded objects." (let [spec {:format :csv} data `({:entity ~person-schema :tuples ~(list {:name "<NAME>" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-schema :tuples ["name,Address.Address1,Address.City\n<NAME>,123 Main,Springfield\n"]}] (format-rows spec data)))))) (deftest edn-formatter-test (testing "Generating an EDN file from rows." (let [spec {:format :edn} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `[{:entity ~table :tuples ["{:A 1, :B 2}"]}] (format-rows spec rows)))))) (deftest sql-formatter-test (testing "Basic SQL generation with integer-only values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,2);\n"]}) (format-rows spec rows))))) (testing "SQL generation quotes and escapes string values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :string) rows `({:entity ~table :tuples ({:A 1 :B "Then O'Kelly came in with the \t hatchett."})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,'Then O''Kelly came in with the \t hatchett.');\n"]}) (format-rows spec rows))))) (testing "SQL generation flattens out embedded objects." (let [spec {:format :sql} data `({:entity ~person-schema :tuples ~(list {:Name "<NAME>" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-schema :tuples ["INSERT INTO \"Person\" (\"Name\",\"Address.Address1\",\"Address.City\") VALUES ('<NAME>','123 Main','Springfield');\n"]}] (format-rows spec data))))) (testing "SQL generation formats DATE values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :datetime) rows `({:entity ~table :tuples ({:A 1 :B ~(ZonedDateTime/ofInstant (Instant/ofEpochMilli 1109741401000) (ZoneOffset/ofHours -6))})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,'2005-03-01T23:30:01.000-06:00');\n"]}) (format-rows spec rows)))))) (deftest json-formatter-test (testing "Basic JSON generation." (let [spec {:format :json} table simple-schema rows `({:entity ~table :tuples ({:A 1 :B "\"Thus sayeth...\""})})] (is (= `[{:entity ~table :tuples ["[{\"A\":1,\"B\":\"\\\"Thus sayeth...\\\"\"}]"]}] (format-rows spec rows)))))) (deftest xml-formatter-test (testing "Basic XML generation." (let [spec {:format :xml} table simple-schema rows `({:entity ~table :tuples ({:A 1 :B "\"Thus sayeth...\""} {:A 2 :B "three"})}) result (format-rows spec rows)] (is (= `[{:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B>\"Thus sayeth...\"</B></Example>" "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>2</A><B>three</B></Example>"]}] result)))) (testing "XML generation with embedded objects." (let [spec {:format :xml} person-table {:name "Person" :schema nil :properties [{:name "Address" :type :complex} {:name "Name" :type :string}]} data `({:entity ~person-table :tuples ~(list {:name "<NAME>" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Person><name><NAME></name><Address><Address1>123 Main</Address1><City>Springfield</City></Address></Person>"]}] (format-rows spec data))))) (testing "XML generation with local dates." (let [spec {:format :xml} person-table {:name "Person" :schema nil :properties [{:name "<NAME>" :type :string} {:name "DOB" :type :date}]} data (list {:entity person-table :tuples [{:name "<NAME>" :DOB (LocalDate/of 2019 1 1)}]})] (is (= [{:entity person-table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Person><name><NAME></name><DOB>2019-01-01</DOB></Person>"]}] (format-rows spec data))))) (testing "XML generation with DATETIME values." (let [spec {:format :xml} table (assoc-in simple-schema [:properties 1 :type] :datetime) data `({:entity ~table :tuples ({:A 1 :B ~(ZonedDateTime/ofInstant (Instant/ofEpochMilli 1109741401000) (ZoneOffset/ofHours -6))})})] (is (= `({:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B>2005-03-01T23:30:01-06:00</B></Example>"]}) (format-rows spec data))))) (testing "Basic XML generation with sequences." (let [spec {:format :xml} table (-> simple-schema (assoc-in [:properties 1 :type] :sequence) (assoc-in [:properties 1 :properties] [{:name "items" :type :integer}])) rows `({:entity ~table :tuples ({:A 1 :B [1 2]} {:A 2 :B [3 5 6]})}) result (format-rows spec rows)] (is (= `[{:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B><item>1</item><item>2</item></B></Example>" "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>2</A><B><item>3</item><item>5</item><item>6</item></B></Example>"]}] result)))))
true
(ns blutwurst.tuple-formatter-test (:import (java.time ZonedDateTime OffsetDateTime ZoneOffset Instant LocalDate)) (:require [clojure.test :refer :all] [clojure.pprint :refer :all] [blutwurst.logging-fixture :refer :all] [blutwurst.tuple-formatter :refer :all])) (use-fixtures :each logging-fixture) (def simple-schema {:name "Example" :schema "foo" :properties [{:name "A" :type :integer} {:name "B" :type :string}]}) (def person-schema {:name "Person" :schema nil :properties [{:name "Address" :type :complex} {:name "Name" :type :string}] :dependencies [{:target-schema nil :target-name "Address" :dependency-name nil :links {"Address" :embedded}}]}) (deftest csv-formatter-test (testing "Generating a CSV from rows." (let [spec {:format :csv} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `[{:entity ~table :tuples ["A,B\n1,2\n"]}] (format-rows spec rows))))) (testing "Flattens out embedded objects." (let [spec {:format :csv} data `({:entity ~person-schema :tuples ~(list {:name "PI:NAME:<NAME>END_PI" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-schema :tuples ["name,Address.Address1,Address.City\nPI:NAME:<NAME>END_PI,123 Main,Springfield\n"]}] (format-rows spec data)))))) (deftest edn-formatter-test (testing "Generating an EDN file from rows." (let [spec {:format :edn} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `[{:entity ~table :tuples ["{:A 1, :B 2}"]}] (format-rows spec rows)))))) (deftest sql-formatter-test (testing "Basic SQL generation with integer-only values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :integer) rows `({:entity ~table :tuples ({:A 1 :B 2})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,2);\n"]}) (format-rows spec rows))))) (testing "SQL generation quotes and escapes string values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :string) rows `({:entity ~table :tuples ({:A 1 :B "Then O'Kelly came in with the \t hatchett."})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,'Then O''Kelly came in with the \t hatchett.');\n"]}) (format-rows spec rows))))) (testing "SQL generation flattens out embedded objects." (let [spec {:format :sql} data `({:entity ~person-schema :tuples ~(list {:Name "PI:NAME:<NAME>END_PI" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-schema :tuples ["INSERT INTO \"Person\" (\"Name\",\"Address.Address1\",\"Address.City\") VALUES ('PI:NAME:<NAME>END_PI','123 Main','Springfield');\n"]}] (format-rows spec data))))) (testing "SQL generation formats DATE values." (let [spec {:format :sql} table (assoc-in simple-schema [:properties 1 :type] :datetime) rows `({:entity ~table :tuples ({:A 1 :B ~(ZonedDateTime/ofInstant (Instant/ofEpochMilli 1109741401000) (ZoneOffset/ofHours -6))})})] (is (= `({:entity ~table :tuples ["INSERT INTO \"foo\".\"Example\" (\"A\",\"B\") VALUES (1,'2005-03-01T23:30:01.000-06:00');\n"]}) (format-rows spec rows)))))) (deftest json-formatter-test (testing "Basic JSON generation." (let [spec {:format :json} table simple-schema rows `({:entity ~table :tuples ({:A 1 :B "\"Thus sayeth...\""})})] (is (= `[{:entity ~table :tuples ["[{\"A\":1,\"B\":\"\\\"Thus sayeth...\\\"\"}]"]}] (format-rows spec rows)))))) (deftest xml-formatter-test (testing "Basic XML generation." (let [spec {:format :xml} table simple-schema rows `({:entity ~table :tuples ({:A 1 :B "\"Thus sayeth...\""} {:A 2 :B "three"})}) result (format-rows spec rows)] (is (= `[{:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B>\"Thus sayeth...\"</B></Example>" "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>2</A><B>three</B></Example>"]}] result)))) (testing "XML generation with embedded objects." (let [spec {:format :xml} person-table {:name "Person" :schema nil :properties [{:name "Address" :type :complex} {:name "Name" :type :string}]} data `({:entity ~person-table :tuples ~(list {:name "PI:NAME:<NAME>END_PI" :Address {:Address1 "123 Main" :City "Springfield"}})})] (is (= [{:entity person-table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Person><name>PI:NAME:<NAME>END_PI</name><Address><Address1>123 Main</Address1><City>Springfield</City></Address></Person>"]}] (format-rows spec data))))) (testing "XML generation with local dates." (let [spec {:format :xml} person-table {:name "Person" :schema nil :properties [{:name "PI:NAME:<NAME>END_PI" :type :string} {:name "DOB" :type :date}]} data (list {:entity person-table :tuples [{:name "PI:NAME:<NAME>END_PI" :DOB (LocalDate/of 2019 1 1)}]})] (is (= [{:entity person-table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Person><name>PI:NAME:<NAME>END_PI</name><DOB>2019-01-01</DOB></Person>"]}] (format-rows spec data))))) (testing "XML generation with DATETIME values." (let [spec {:format :xml} table (assoc-in simple-schema [:properties 1 :type] :datetime) data `({:entity ~table :tuples ({:A 1 :B ~(ZonedDateTime/ofInstant (Instant/ofEpochMilli 1109741401000) (ZoneOffset/ofHours -6))})})] (is (= `({:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B>2005-03-01T23:30:01-06:00</B></Example>"]}) (format-rows spec data))))) (testing "Basic XML generation with sequences." (let [spec {:format :xml} table (-> simple-schema (assoc-in [:properties 1 :type] :sequence) (assoc-in [:properties 1 :properties] [{:name "items" :type :integer}])) rows `({:entity ~table :tuples ({:A 1 :B [1 2]} {:A 2 :B [3 5 6]})}) result (format-rows spec rows)] (is (= `[{:entity ~table :tuples ["<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>1</A><B><item>1</item><item>2</item></B></Example>" "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Example><A>2</A><B><item>3</item><item>5</item><item>6</item></B></Example>"]}] result)))))
[ { "context": "ment for ClojureScript\"\n :url \"http://github.com/nrepl/weasel\"\n :license {:name \"Unlicense\"\n ", "end": 120, "score": 0.9990707039833069, "start": 115, "tag": "USERNAME", "value": "nrepl" }, { "context": "scm {:name \"git\"\n :url \"https://github.com/nrepl/weasel\"}\n\n :dependencies [[org.clojure/clojure \"", "end": 300, "score": 0.9990571737289429, "start": 295, "tag": "USERNAME", "value": "nrepl" }, { "context": "[:developer\n [:name \"Tom Jakubowski\"]\n [:email \"tom@crys", "end": 811, "score": 0.9994391202926636, "start": 797, "tag": "NAME", "value": "Tom Jakubowski" }, { "context": "kubowski\"]\n [:email \"tom@crystae.net\"]\n [:url \"https://gi", "end": 868, "score": 0.999930202960968, "start": 853, "tag": "EMAIL", "value": "tom@crystae.net" }, { "context": " [:url \"https://github.com/tomjakubowski\"]]]\n :profiles {:dev {:dependencies [[cider/pigg", "end": 940, "score": 0.9996397495269775, "start": 927, "tag": "USERNAME", "value": "tomjakubowski" } ]
project.clj
FelipeCortez/weasel
0
(defproject weasel "0.7.2" :description "websocket REPL environment for ClojureScript" :url "http://github.com/nrepl/weasel" :license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE" :distribution :repo} :scm {:name "git" :url "https://github.com/nrepl/weasel"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/clojurescript "1.10.520"] [http-kit "2.3.0"]] :deploy-repositories [["clojars" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]] :pom-addition [:developers [:developer [:name "Tom Jakubowski"] [:email "tom@crystae.net"] [:url "https://github.com/tomjakubowski"]]] :profiles {:dev {:dependencies [[cider/piggieback "0.4.2"]]}} :source-paths ["src/clj" "src/cljs"])
86363
(defproject weasel "0.7.2" :description "websocket REPL environment for ClojureScript" :url "http://github.com/nrepl/weasel" :license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE" :distribution :repo} :scm {:name "git" :url "https://github.com/nrepl/weasel"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/clojurescript "1.10.520"] [http-kit "2.3.0"]] :deploy-repositories [["clojars" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]] :pom-addition [:developers [:developer [:name "<NAME>"] [:email "<EMAIL>"] [:url "https://github.com/tomjakubowski"]]] :profiles {:dev {:dependencies [[cider/piggieback "0.4.2"]]}} :source-paths ["src/clj" "src/cljs"])
true
(defproject weasel "0.7.2" :description "websocket REPL environment for ClojureScript" :url "http://github.com/nrepl/weasel" :license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE" :distribution :repo} :scm {:name "git" :url "https://github.com/nrepl/weasel"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/clojurescript "1.10.520"] [http-kit "2.3.0"]] :deploy-repositories [["clojars" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]] :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:url "https://github.com/tomjakubowski"]]] :profiles {:dev {:dependencies [[cider/piggieback "0.4.2"]]}} :source-paths ["src/clj" "src/cljs"])
[ { "context": "IMEOUT (seconds 5))\n(def ^:const LAUNCH_TASK_KEY \"diracLaunchTask\")\n(def ^:const LAUNCH_TASK_MESSAGE \"dirac-launch-", "end": 1378, "score": 0.9933149218559265, "start": 1363, "tag": "KEY", "value": "diracLaunchTask" }, { "context": " 22555)\n\n(def ^:const AUTOMATION_ENTRY_POINT_KEY \"diracAutomateDevTools\")\n(def ^:const FLUSH_PENDING_FEEDBACK_MESSAGES_KE", "end": 2608, "score": 0.9756090044975281, "start": 2587, "tag": "KEY", "value": "diracAutomateDevTools" }, { "context": "(def ^:const FLUSH_PENDING_FEEDBACK_MESSAGES_KEY \"diracFlushPendingFeedbackMessages\")\n(def ^:const DIRAC_INTERCOM_KEY \"diracIntercom\"", "end": 2694, "score": 0.9359516501426697, "start": 2661, "tag": "KEY", "value": "diracFlushPendingFeedbackMessages" }, { "context": "edbackMessages\")\n(def ^:const DIRAC_INTERCOM_KEY \"diracIntercom\")\n\n(def dirac-devtools-window-top (env :dirac-dev", "end": 2743, "score": 0.948298454284668, "start": 2730, "tag": "KEY", "value": "diracIntercom" } ]
src/settings/dirac/settings.clj
pvinis/dirac
0
(ns dirac.settings (:require [environ.core :refer [env]])) ; we want this stuff to be accessible both from clojure and clojurescript ; -- time ------------------------------------------------------------------------------------------------------------------- (def ^:const SECOND 1000) (def ^:const MINUTE (* 60 SECOND)) (defmacro seconds [v] (* SECOND v)) (defmacro minutes [v] (* MINUTE v)) (defmacro milisec [v] v) ; --------------------------------------------------------------------------------------------------------------------------- (def ^:const BACKEND_TESTS_NREPL_SERVER_TIMEOUT (seconds 60)) (def ^:const BACKEND_TESTS_NREPL_SERVER_HOST "localhost") (def ^:const BACKEND_TESTS_NREPL_SERVER_PORT 7230) ; -1000 from defaults (def ^:const BACKEND_TESTS_NREPL_TUNNEL_HOST "localhost") (def ^:const BACKEND_TESTS_NREPL_TUNNEL_PORT 7231) ; -1000 from defaults (def ^:const BACKEND_TESTS_WEASEL_HOST "localhost") (def ^:const BACKEND_TESTS_WEASEL_PORT 7232) ; -1000 from defaults (def ^:const DIRAC_AGENT_BOOT_TIME (seconds 2)) (def ^:const TRANSCRIPT_MATCH_TIMEOUT (seconds 5)) (def ^:const LAUNCH_TASK_KEY "diracLaunchTask") (def ^:const LAUNCH_TASK_MESSAGE "dirac-launch-task") (def ^:const MARION_INITIAL_WAIT_TIME (seconds 1)) (def ^:const MARION_RECONNECTION_ATTEMPT_DELAY (seconds 2)) (def ^:const MARION_MESSAGE_REPLY_TIMEOUT (seconds 10)) (def ^:const DEFAULT_TASK_TIMEOUT (minutes 5)) (def ^:const DEFAULT_TEST_HTML_LOAD_TIMEOUT (seconds 5)) (def ^:const SIGNAL_SERVER_CLOSE_WAIT_TIMEOUT (milisec 500)) (def ^:const PENDING_REPLIES_WAIT_TIMEOUT (seconds 2)) (def ^:const SIGNAL_CLIENT_TASK_RESULT_DELAY (milisec 0)) (def ^:const SIGNAL_CLIENT_CLOSE_DELAY (milisec 0)) (def ^:const SIGNAL_SERVER_MAX_CONNECTION_TIME (seconds 5)) (def ^:const ACTUAL_TRANSCRIPTS_ROOT_PATH "test/browser/transcripts/actual/") (def ^:const EXPECTED_TRANSCRIPTS_ROOT_PATH "test/browser/transcripts/expected/") (def ^:const TRANSCRIPT_LABEL_PADDING_LENGTH 17) (def ^:const TRANSCRIPT_LABEL_PADDING_TYPE :right) (def ^:const BROWSER_CONNECTION_MINIMAL_COOLDOWN (seconds 4)) (def ^:const SCRIPT_RUNNER_LAUNCH_DELAY (seconds 2)) (def ^:const FIXTURES_SERVER_HOST "localhost") (def ^:const FIXTURES_SERVER_PORT 9090) (def ^:const SIGNAL_SERVER_HOST "localhost") (def ^:const SIGNAL_SERVER_PORT 22555) (def ^:const AUTOMATION_ENTRY_POINT_KEY "diracAutomateDevTools") (def ^:const FLUSH_PENDING_FEEDBACK_MESSAGES_KEY "diracFlushPendingFeedbackMessages") (def ^:const DIRAC_INTERCOM_KEY "diracIntercom") (def dirac-devtools-window-top (env :dirac-devtools-window-top)) (def dirac-devtools-window-left (env :dirac-devtools-window-left)) (def dirac-devtools-window-width (env :dirac-devtools-window-width)) (def dirac-devtools-window-height (env :dirac-devtools-window-height)) (def dirac-runner-window-top (env :dirac-runner-window-top)) (def dirac-runner-window-left (env :dirac-runner-window-left)) (def dirac-runner-window-width (env :dirac-runner-window-width)) (def dirac-runner-window-height (env :dirac-runner-window-height)) (def dirac-scenario-window-top (env :dirac-scenario-window-top)) (def dirac-scenario-window-left (env :dirac-scenario-window-left)) (def dirac-scenario-window-width (env :dirac-scenario-window-width)) (def dirac-scenario-window-height (env :dirac-scenario-window-height)) (def chrome-remote-debugging-port (env :dirac-chrome-remote-debugging-port)) (def chrome-remote-debugging-host (env :dirac-chrome-remote-debugging-host)) ; -- macro wrappers --------------------------------------------------------------------------------------------------------- ; macros allow us to potentially expose the constants to cljs (defmacro get-backend-tests-nrepl-server-timeout [] BACKEND_TESTS_NREPL_SERVER_TIMEOUT) (defmacro get-backend-tests-nrepl-server-host [] BACKEND_TESTS_NREPL_SERVER_HOST) (defmacro get-backend-tests-nrepl-server-port [] BACKEND_TESTS_NREPL_SERVER_PORT) (defmacro get-backend-tests-nrepl-server-url [] (str "nrepl://" (get-backend-tests-nrepl-server-host) ":" (get-backend-tests-nrepl-server-port))) (defmacro get-backend-tests-nrepl-tunnel-port [] BACKEND_TESTS_NREPL_TUNNEL_PORT) (defmacro get-backend-tests-nrepl-tunnel-host [] BACKEND_TESTS_NREPL_TUNNEL_HOST) (defmacro get-backend-tests-nrepl-tunnel-url [] (str "ws://" (get-backend-tests-nrepl-tunnel-host) ":" (get-backend-tests-nrepl-tunnel-port))) (defmacro get-backend-tests-weasel-host [] BACKEND_TESTS_WEASEL_HOST) (defmacro get-backend-tests-weasel-port [] BACKEND_TESTS_WEASEL_PORT) (defmacro get-dirac-agent-boot-time [] DIRAC_AGENT_BOOT_TIME) (defmacro get-launch-task-key [] LAUNCH_TASK_KEY) (defmacro get-launch-task-message [] LAUNCH_TASK_MESSAGE) (defmacro get-transcript-match-timeout [] TRANSCRIPT_MATCH_TIMEOUT) (defmacro get-marion-initial-wait-time [] MARION_INITIAL_WAIT_TIME) (defmacro get-marion-reconnection-attempt-delay [] MARION_RECONNECTION_ATTEMPT_DELAY) (defmacro get-marion-message-reply-timeout [] MARION_MESSAGE_REPLY_TIMEOUT) (defmacro get-default-task-timeout [] DEFAULT_TASK_TIMEOUT) (defmacro get-default-test-html-load-timeout [] DEFAULT_TEST_HTML_LOAD_TIMEOUT) (defmacro get-signal-server-close-wait-timeout [] SIGNAL_SERVER_CLOSE_WAIT_TIMEOUT) (defmacro get-actual-transcripts-root-path [] ACTUAL_TRANSCRIPTS_ROOT_PATH) (defmacro get-expected-transcripts-root-path [] EXPECTED_TRANSCRIPTS_ROOT_PATH) (defmacro get-dirac-devtools-window-top [] dirac-devtools-window-top) (defmacro get-dirac-devtools-window-left [] dirac-devtools-window-left) (defmacro get-dirac-devtools-window-width [] dirac-devtools-window-width) (defmacro get-dirac-devtools-window-height [] dirac-devtools-window-height) (defmacro get-dirac-runner-window-top [] dirac-runner-window-top) (defmacro get-dirac-runner-window-left [] dirac-runner-window-left) (defmacro get-dirac-runner-window-width [] dirac-runner-window-width) (defmacro get-dirac-runner-window-height [] dirac-runner-window-height) (defmacro get-dirac-scenario-window-top [] dirac-scenario-window-top) (defmacro get-dirac-scenario-window-left [] dirac-scenario-window-left) (defmacro get-dirac-scenario-window-width [] dirac-scenario-window-width) (defmacro get-dirac-scenario-window-height [] dirac-scenario-window-height) (defmacro get-transcript-label-padding-length [] TRANSCRIPT_LABEL_PADDING_LENGTH) (defmacro get-transcript-label-padding-type [] TRANSCRIPT_LABEL_PADDING_TYPE) (defmacro get-browser-connection-minimal-cooldown [] BROWSER_CONNECTION_MINIMAL_COOLDOWN) (defmacro get-script-runner-launch-delay [] SCRIPT_RUNNER_LAUNCH_DELAY) (defmacro get-fixtures-server-host [] FIXTURES_SERVER_HOST) (defmacro get-fixtures-server-port [] FIXTURES_SERVER_PORT) (defmacro get-fixtures-server-url [] (str "http://" (get-fixtures-server-host) ":" (get-fixtures-server-port))) (defmacro get-signal-server-host [] SIGNAL_SERVER_HOST) (defmacro get-signal-server-port [] SIGNAL_SERVER_PORT) (defmacro get-signal-server-url [] (str "ws://" (get-signal-server-host) ":" (get-signal-server-port))) (defmacro get-chrome-remote-debugging-port [] (if (some? chrome-remote-debugging-port) (Integer/parseInt chrome-remote-debugging-port))) (defmacro get-chrome-remote-debugging-host [] chrome-remote-debugging-host) (defmacro get-pending-replies-wait-timeout [] PENDING_REPLIES_WAIT_TIMEOUT) (defmacro get-signal-client-task-result-delay [] SIGNAL_CLIENT_TASK_RESULT_DELAY) (defmacro get-signal-client-close-delay [] SIGNAL_CLIENT_CLOSE_DELAY) (defmacro get-signal-server-max-connection-time [] SIGNAL_SERVER_MAX_CONNECTION_TIME) (defmacro get-automation-entry-point-key [] AUTOMATION_ENTRY_POINT_KEY) (defmacro get-flush-pending-feedback-messages-key [] FLUSH_PENDING_FEEDBACK_MESSAGES_KEY) (defmacro get-dirac-intercom-key [] DIRAC_INTERCOM_KEY)
66018
(ns dirac.settings (:require [environ.core :refer [env]])) ; we want this stuff to be accessible both from clojure and clojurescript ; -- time ------------------------------------------------------------------------------------------------------------------- (def ^:const SECOND 1000) (def ^:const MINUTE (* 60 SECOND)) (defmacro seconds [v] (* SECOND v)) (defmacro minutes [v] (* MINUTE v)) (defmacro milisec [v] v) ; --------------------------------------------------------------------------------------------------------------------------- (def ^:const BACKEND_TESTS_NREPL_SERVER_TIMEOUT (seconds 60)) (def ^:const BACKEND_TESTS_NREPL_SERVER_HOST "localhost") (def ^:const BACKEND_TESTS_NREPL_SERVER_PORT 7230) ; -1000 from defaults (def ^:const BACKEND_TESTS_NREPL_TUNNEL_HOST "localhost") (def ^:const BACKEND_TESTS_NREPL_TUNNEL_PORT 7231) ; -1000 from defaults (def ^:const BACKEND_TESTS_WEASEL_HOST "localhost") (def ^:const BACKEND_TESTS_WEASEL_PORT 7232) ; -1000 from defaults (def ^:const DIRAC_AGENT_BOOT_TIME (seconds 2)) (def ^:const TRANSCRIPT_MATCH_TIMEOUT (seconds 5)) (def ^:const LAUNCH_TASK_KEY "<KEY>") (def ^:const LAUNCH_TASK_MESSAGE "dirac-launch-task") (def ^:const MARION_INITIAL_WAIT_TIME (seconds 1)) (def ^:const MARION_RECONNECTION_ATTEMPT_DELAY (seconds 2)) (def ^:const MARION_MESSAGE_REPLY_TIMEOUT (seconds 10)) (def ^:const DEFAULT_TASK_TIMEOUT (minutes 5)) (def ^:const DEFAULT_TEST_HTML_LOAD_TIMEOUT (seconds 5)) (def ^:const SIGNAL_SERVER_CLOSE_WAIT_TIMEOUT (milisec 500)) (def ^:const PENDING_REPLIES_WAIT_TIMEOUT (seconds 2)) (def ^:const SIGNAL_CLIENT_TASK_RESULT_DELAY (milisec 0)) (def ^:const SIGNAL_CLIENT_CLOSE_DELAY (milisec 0)) (def ^:const SIGNAL_SERVER_MAX_CONNECTION_TIME (seconds 5)) (def ^:const ACTUAL_TRANSCRIPTS_ROOT_PATH "test/browser/transcripts/actual/") (def ^:const EXPECTED_TRANSCRIPTS_ROOT_PATH "test/browser/transcripts/expected/") (def ^:const TRANSCRIPT_LABEL_PADDING_LENGTH 17) (def ^:const TRANSCRIPT_LABEL_PADDING_TYPE :right) (def ^:const BROWSER_CONNECTION_MINIMAL_COOLDOWN (seconds 4)) (def ^:const SCRIPT_RUNNER_LAUNCH_DELAY (seconds 2)) (def ^:const FIXTURES_SERVER_HOST "localhost") (def ^:const FIXTURES_SERVER_PORT 9090) (def ^:const SIGNAL_SERVER_HOST "localhost") (def ^:const SIGNAL_SERVER_PORT 22555) (def ^:const AUTOMATION_ENTRY_POINT_KEY "<KEY>") (def ^:const FLUSH_PENDING_FEEDBACK_MESSAGES_KEY "<KEY>") (def ^:const DIRAC_INTERCOM_KEY "<KEY>") (def dirac-devtools-window-top (env :dirac-devtools-window-top)) (def dirac-devtools-window-left (env :dirac-devtools-window-left)) (def dirac-devtools-window-width (env :dirac-devtools-window-width)) (def dirac-devtools-window-height (env :dirac-devtools-window-height)) (def dirac-runner-window-top (env :dirac-runner-window-top)) (def dirac-runner-window-left (env :dirac-runner-window-left)) (def dirac-runner-window-width (env :dirac-runner-window-width)) (def dirac-runner-window-height (env :dirac-runner-window-height)) (def dirac-scenario-window-top (env :dirac-scenario-window-top)) (def dirac-scenario-window-left (env :dirac-scenario-window-left)) (def dirac-scenario-window-width (env :dirac-scenario-window-width)) (def dirac-scenario-window-height (env :dirac-scenario-window-height)) (def chrome-remote-debugging-port (env :dirac-chrome-remote-debugging-port)) (def chrome-remote-debugging-host (env :dirac-chrome-remote-debugging-host)) ; -- macro wrappers --------------------------------------------------------------------------------------------------------- ; macros allow us to potentially expose the constants to cljs (defmacro get-backend-tests-nrepl-server-timeout [] BACKEND_TESTS_NREPL_SERVER_TIMEOUT) (defmacro get-backend-tests-nrepl-server-host [] BACKEND_TESTS_NREPL_SERVER_HOST) (defmacro get-backend-tests-nrepl-server-port [] BACKEND_TESTS_NREPL_SERVER_PORT) (defmacro get-backend-tests-nrepl-server-url [] (str "nrepl://" (get-backend-tests-nrepl-server-host) ":" (get-backend-tests-nrepl-server-port))) (defmacro get-backend-tests-nrepl-tunnel-port [] BACKEND_TESTS_NREPL_TUNNEL_PORT) (defmacro get-backend-tests-nrepl-tunnel-host [] BACKEND_TESTS_NREPL_TUNNEL_HOST) (defmacro get-backend-tests-nrepl-tunnel-url [] (str "ws://" (get-backend-tests-nrepl-tunnel-host) ":" (get-backend-tests-nrepl-tunnel-port))) (defmacro get-backend-tests-weasel-host [] BACKEND_TESTS_WEASEL_HOST) (defmacro get-backend-tests-weasel-port [] BACKEND_TESTS_WEASEL_PORT) (defmacro get-dirac-agent-boot-time [] DIRAC_AGENT_BOOT_TIME) (defmacro get-launch-task-key [] LAUNCH_TASK_KEY) (defmacro get-launch-task-message [] LAUNCH_TASK_MESSAGE) (defmacro get-transcript-match-timeout [] TRANSCRIPT_MATCH_TIMEOUT) (defmacro get-marion-initial-wait-time [] MARION_INITIAL_WAIT_TIME) (defmacro get-marion-reconnection-attempt-delay [] MARION_RECONNECTION_ATTEMPT_DELAY) (defmacro get-marion-message-reply-timeout [] MARION_MESSAGE_REPLY_TIMEOUT) (defmacro get-default-task-timeout [] DEFAULT_TASK_TIMEOUT) (defmacro get-default-test-html-load-timeout [] DEFAULT_TEST_HTML_LOAD_TIMEOUT) (defmacro get-signal-server-close-wait-timeout [] SIGNAL_SERVER_CLOSE_WAIT_TIMEOUT) (defmacro get-actual-transcripts-root-path [] ACTUAL_TRANSCRIPTS_ROOT_PATH) (defmacro get-expected-transcripts-root-path [] EXPECTED_TRANSCRIPTS_ROOT_PATH) (defmacro get-dirac-devtools-window-top [] dirac-devtools-window-top) (defmacro get-dirac-devtools-window-left [] dirac-devtools-window-left) (defmacro get-dirac-devtools-window-width [] dirac-devtools-window-width) (defmacro get-dirac-devtools-window-height [] dirac-devtools-window-height) (defmacro get-dirac-runner-window-top [] dirac-runner-window-top) (defmacro get-dirac-runner-window-left [] dirac-runner-window-left) (defmacro get-dirac-runner-window-width [] dirac-runner-window-width) (defmacro get-dirac-runner-window-height [] dirac-runner-window-height) (defmacro get-dirac-scenario-window-top [] dirac-scenario-window-top) (defmacro get-dirac-scenario-window-left [] dirac-scenario-window-left) (defmacro get-dirac-scenario-window-width [] dirac-scenario-window-width) (defmacro get-dirac-scenario-window-height [] dirac-scenario-window-height) (defmacro get-transcript-label-padding-length [] TRANSCRIPT_LABEL_PADDING_LENGTH) (defmacro get-transcript-label-padding-type [] TRANSCRIPT_LABEL_PADDING_TYPE) (defmacro get-browser-connection-minimal-cooldown [] BROWSER_CONNECTION_MINIMAL_COOLDOWN) (defmacro get-script-runner-launch-delay [] SCRIPT_RUNNER_LAUNCH_DELAY) (defmacro get-fixtures-server-host [] FIXTURES_SERVER_HOST) (defmacro get-fixtures-server-port [] FIXTURES_SERVER_PORT) (defmacro get-fixtures-server-url [] (str "http://" (get-fixtures-server-host) ":" (get-fixtures-server-port))) (defmacro get-signal-server-host [] SIGNAL_SERVER_HOST) (defmacro get-signal-server-port [] SIGNAL_SERVER_PORT) (defmacro get-signal-server-url [] (str "ws://" (get-signal-server-host) ":" (get-signal-server-port))) (defmacro get-chrome-remote-debugging-port [] (if (some? chrome-remote-debugging-port) (Integer/parseInt chrome-remote-debugging-port))) (defmacro get-chrome-remote-debugging-host [] chrome-remote-debugging-host) (defmacro get-pending-replies-wait-timeout [] PENDING_REPLIES_WAIT_TIMEOUT) (defmacro get-signal-client-task-result-delay [] SIGNAL_CLIENT_TASK_RESULT_DELAY) (defmacro get-signal-client-close-delay [] SIGNAL_CLIENT_CLOSE_DELAY) (defmacro get-signal-server-max-connection-time [] SIGNAL_SERVER_MAX_CONNECTION_TIME) (defmacro get-automation-entry-point-key [] AUTOMATION_ENTRY_POINT_KEY) (defmacro get-flush-pending-feedback-messages-key [] FLUSH_PENDING_FEEDBACK_MESSAGES_KEY) (defmacro get-dirac-intercom-key [] DIRAC_INTERCOM_KEY)
true
(ns dirac.settings (:require [environ.core :refer [env]])) ; we want this stuff to be accessible both from clojure and clojurescript ; -- time ------------------------------------------------------------------------------------------------------------------- (def ^:const SECOND 1000) (def ^:const MINUTE (* 60 SECOND)) (defmacro seconds [v] (* SECOND v)) (defmacro minutes [v] (* MINUTE v)) (defmacro milisec [v] v) ; --------------------------------------------------------------------------------------------------------------------------- (def ^:const BACKEND_TESTS_NREPL_SERVER_TIMEOUT (seconds 60)) (def ^:const BACKEND_TESTS_NREPL_SERVER_HOST "localhost") (def ^:const BACKEND_TESTS_NREPL_SERVER_PORT 7230) ; -1000 from defaults (def ^:const BACKEND_TESTS_NREPL_TUNNEL_HOST "localhost") (def ^:const BACKEND_TESTS_NREPL_TUNNEL_PORT 7231) ; -1000 from defaults (def ^:const BACKEND_TESTS_WEASEL_HOST "localhost") (def ^:const BACKEND_TESTS_WEASEL_PORT 7232) ; -1000 from defaults (def ^:const DIRAC_AGENT_BOOT_TIME (seconds 2)) (def ^:const TRANSCRIPT_MATCH_TIMEOUT (seconds 5)) (def ^:const LAUNCH_TASK_KEY "PI:KEY:<KEY>END_PI") (def ^:const LAUNCH_TASK_MESSAGE "dirac-launch-task") (def ^:const MARION_INITIAL_WAIT_TIME (seconds 1)) (def ^:const MARION_RECONNECTION_ATTEMPT_DELAY (seconds 2)) (def ^:const MARION_MESSAGE_REPLY_TIMEOUT (seconds 10)) (def ^:const DEFAULT_TASK_TIMEOUT (minutes 5)) (def ^:const DEFAULT_TEST_HTML_LOAD_TIMEOUT (seconds 5)) (def ^:const SIGNAL_SERVER_CLOSE_WAIT_TIMEOUT (milisec 500)) (def ^:const PENDING_REPLIES_WAIT_TIMEOUT (seconds 2)) (def ^:const SIGNAL_CLIENT_TASK_RESULT_DELAY (milisec 0)) (def ^:const SIGNAL_CLIENT_CLOSE_DELAY (milisec 0)) (def ^:const SIGNAL_SERVER_MAX_CONNECTION_TIME (seconds 5)) (def ^:const ACTUAL_TRANSCRIPTS_ROOT_PATH "test/browser/transcripts/actual/") (def ^:const EXPECTED_TRANSCRIPTS_ROOT_PATH "test/browser/transcripts/expected/") (def ^:const TRANSCRIPT_LABEL_PADDING_LENGTH 17) (def ^:const TRANSCRIPT_LABEL_PADDING_TYPE :right) (def ^:const BROWSER_CONNECTION_MINIMAL_COOLDOWN (seconds 4)) (def ^:const SCRIPT_RUNNER_LAUNCH_DELAY (seconds 2)) (def ^:const FIXTURES_SERVER_HOST "localhost") (def ^:const FIXTURES_SERVER_PORT 9090) (def ^:const SIGNAL_SERVER_HOST "localhost") (def ^:const SIGNAL_SERVER_PORT 22555) (def ^:const AUTOMATION_ENTRY_POINT_KEY "PI:KEY:<KEY>END_PI") (def ^:const FLUSH_PENDING_FEEDBACK_MESSAGES_KEY "PI:KEY:<KEY>END_PI") (def ^:const DIRAC_INTERCOM_KEY "PI:KEY:<KEY>END_PI") (def dirac-devtools-window-top (env :dirac-devtools-window-top)) (def dirac-devtools-window-left (env :dirac-devtools-window-left)) (def dirac-devtools-window-width (env :dirac-devtools-window-width)) (def dirac-devtools-window-height (env :dirac-devtools-window-height)) (def dirac-runner-window-top (env :dirac-runner-window-top)) (def dirac-runner-window-left (env :dirac-runner-window-left)) (def dirac-runner-window-width (env :dirac-runner-window-width)) (def dirac-runner-window-height (env :dirac-runner-window-height)) (def dirac-scenario-window-top (env :dirac-scenario-window-top)) (def dirac-scenario-window-left (env :dirac-scenario-window-left)) (def dirac-scenario-window-width (env :dirac-scenario-window-width)) (def dirac-scenario-window-height (env :dirac-scenario-window-height)) (def chrome-remote-debugging-port (env :dirac-chrome-remote-debugging-port)) (def chrome-remote-debugging-host (env :dirac-chrome-remote-debugging-host)) ; -- macro wrappers --------------------------------------------------------------------------------------------------------- ; macros allow us to potentially expose the constants to cljs (defmacro get-backend-tests-nrepl-server-timeout [] BACKEND_TESTS_NREPL_SERVER_TIMEOUT) (defmacro get-backend-tests-nrepl-server-host [] BACKEND_TESTS_NREPL_SERVER_HOST) (defmacro get-backend-tests-nrepl-server-port [] BACKEND_TESTS_NREPL_SERVER_PORT) (defmacro get-backend-tests-nrepl-server-url [] (str "nrepl://" (get-backend-tests-nrepl-server-host) ":" (get-backend-tests-nrepl-server-port))) (defmacro get-backend-tests-nrepl-tunnel-port [] BACKEND_TESTS_NREPL_TUNNEL_PORT) (defmacro get-backend-tests-nrepl-tunnel-host [] BACKEND_TESTS_NREPL_TUNNEL_HOST) (defmacro get-backend-tests-nrepl-tunnel-url [] (str "ws://" (get-backend-tests-nrepl-tunnel-host) ":" (get-backend-tests-nrepl-tunnel-port))) (defmacro get-backend-tests-weasel-host [] BACKEND_TESTS_WEASEL_HOST) (defmacro get-backend-tests-weasel-port [] BACKEND_TESTS_WEASEL_PORT) (defmacro get-dirac-agent-boot-time [] DIRAC_AGENT_BOOT_TIME) (defmacro get-launch-task-key [] LAUNCH_TASK_KEY) (defmacro get-launch-task-message [] LAUNCH_TASK_MESSAGE) (defmacro get-transcript-match-timeout [] TRANSCRIPT_MATCH_TIMEOUT) (defmacro get-marion-initial-wait-time [] MARION_INITIAL_WAIT_TIME) (defmacro get-marion-reconnection-attempt-delay [] MARION_RECONNECTION_ATTEMPT_DELAY) (defmacro get-marion-message-reply-timeout [] MARION_MESSAGE_REPLY_TIMEOUT) (defmacro get-default-task-timeout [] DEFAULT_TASK_TIMEOUT) (defmacro get-default-test-html-load-timeout [] DEFAULT_TEST_HTML_LOAD_TIMEOUT) (defmacro get-signal-server-close-wait-timeout [] SIGNAL_SERVER_CLOSE_WAIT_TIMEOUT) (defmacro get-actual-transcripts-root-path [] ACTUAL_TRANSCRIPTS_ROOT_PATH) (defmacro get-expected-transcripts-root-path [] EXPECTED_TRANSCRIPTS_ROOT_PATH) (defmacro get-dirac-devtools-window-top [] dirac-devtools-window-top) (defmacro get-dirac-devtools-window-left [] dirac-devtools-window-left) (defmacro get-dirac-devtools-window-width [] dirac-devtools-window-width) (defmacro get-dirac-devtools-window-height [] dirac-devtools-window-height) (defmacro get-dirac-runner-window-top [] dirac-runner-window-top) (defmacro get-dirac-runner-window-left [] dirac-runner-window-left) (defmacro get-dirac-runner-window-width [] dirac-runner-window-width) (defmacro get-dirac-runner-window-height [] dirac-runner-window-height) (defmacro get-dirac-scenario-window-top [] dirac-scenario-window-top) (defmacro get-dirac-scenario-window-left [] dirac-scenario-window-left) (defmacro get-dirac-scenario-window-width [] dirac-scenario-window-width) (defmacro get-dirac-scenario-window-height [] dirac-scenario-window-height) (defmacro get-transcript-label-padding-length [] TRANSCRIPT_LABEL_PADDING_LENGTH) (defmacro get-transcript-label-padding-type [] TRANSCRIPT_LABEL_PADDING_TYPE) (defmacro get-browser-connection-minimal-cooldown [] BROWSER_CONNECTION_MINIMAL_COOLDOWN) (defmacro get-script-runner-launch-delay [] SCRIPT_RUNNER_LAUNCH_DELAY) (defmacro get-fixtures-server-host [] FIXTURES_SERVER_HOST) (defmacro get-fixtures-server-port [] FIXTURES_SERVER_PORT) (defmacro get-fixtures-server-url [] (str "http://" (get-fixtures-server-host) ":" (get-fixtures-server-port))) (defmacro get-signal-server-host [] SIGNAL_SERVER_HOST) (defmacro get-signal-server-port [] SIGNAL_SERVER_PORT) (defmacro get-signal-server-url [] (str "ws://" (get-signal-server-host) ":" (get-signal-server-port))) (defmacro get-chrome-remote-debugging-port [] (if (some? chrome-remote-debugging-port) (Integer/parseInt chrome-remote-debugging-port))) (defmacro get-chrome-remote-debugging-host [] chrome-remote-debugging-host) (defmacro get-pending-replies-wait-timeout [] PENDING_REPLIES_WAIT_TIMEOUT) (defmacro get-signal-client-task-result-delay [] SIGNAL_CLIENT_TASK_RESULT_DELAY) (defmacro get-signal-client-close-delay [] SIGNAL_CLIENT_CLOSE_DELAY) (defmacro get-signal-server-max-connection-time [] SIGNAL_SERVER_MAX_CONNECTION_TIME) (defmacro get-automation-entry-point-key [] AUTOMATION_ENTRY_POINT_KEY) (defmacro get-flush-pending-feedback-messages-key [] FLUSH_PENDING_FEEDBACK_MESSAGES_KEY) (defmacro get-dirac-intercom-key [] DIRAC_INTERCOM_KEY)
[ { "context": "fmethod for performance experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017", "end": 269, "score": 0.7179064750671387, "start": 266, "tag": "EMAIL", "value": "pal" }, { "context": "thod for performance experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-06-02", "end": 275, "score": 0.6999842524528503, "start": 269, "tag": "NAME", "value": "isades" }, { "context": "or performance experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-06-02\"\n :version \"2017-06-06\"}", "end": 302, "score": 0.8437950611114502, "start": 276, "tag": "EMAIL", "value": "dot lakes at gmail dot com" } ]
src/main/clojure/palisades/lakes/elements/generic/dynamic2.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.generic.dynamic2 {:doc "Fork of defmulti/defmethod for performance experiments." :author "palisades dot lakes at gmail dot com" :since "2017-06-02" :version "2017-06-06"} (:refer-clojure :exclude [defmethod defmulti get-method methods prefer-method prefers remove-all-methods remove-method])) ;;---------------------------------------------------------------- (defmacro defdynafn2 "Creates a new dynamic function. The docstring and attr-map are optional. Options are key-value pairs" {:arglists '([name docstring? attr-map? & options]) :added "1.0"} [mm-name & options] (let [docstring (if (string? (first options)) (first options) nil) options (if (string? (first options)) (next options) options) m (if (map? (first options)) (first options) {}) options (if (map? (first options)) (next options) options) m (if docstring (assoc m :doc docstring) m) m (if (meta mm-name) (conj (meta mm-name) m) m)] (let [options (apply hash-map options)] #_(check-valid-options options :default :hierarchy) `(let [v# (def ~mm-name)] (when-not (and (.hasRoot v#) (instance? palisades.lakes.elements.java.generic.DynamicFn2 (deref v#))) (def ~(with-meta mm-name m) (palisades.lakes.elements.java.generic.DynamicFn2. ~(name mm-name)))))))) ;;---------------------------------------------------------------- ;; TODO: better method name (defmacro defmethod "Creates and installs a new method of the dynamic function with the given signature." {:added "1.0"} ([dynafn [c0 c1] & fn-tail] `(.addMethod ~(with-meta dynafn {:tag 'palisades.lakes.elements.java.generic.DynamicFn2}) ~(with-meta c0 {:tag 'Class}) ~(with-meta c1 {:tag 'Class}) (fn ~dynafn ~@fn-tail)))) #_(defn remove-all-methods "Removes all of the methods of the dynamic function." {:added "1.2" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.reset dynafn)) (defn remove-method "Removes the method of the dynamic function with the 2 class signature." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c0 ^Class c1] (.removeMethod dynafn c0 c1)) (defn prefer-method "Causes the dynamic function to prefer matches of <code>c00 c01</code> over <code>c10 c11</code>." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c00 ^Class c01 ^Class c10 ^Class c11] (.preferMethod dynafn c00 c01 c10 c11)) ;; TODO: return something more useful in the general case #_(defn methods "Given a dynamic function, returns a map of dispatch values -> dispatch fns" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.getMethodTable dynafn)) (defn get-method "Given a dynamic function and a dispatch value, returns the matching method, if any." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c0 ^Class c1] (.getMethod dynafn c0 c1)) ;; TODO: return something more useful in the general case #_(defn prefers "Given a dynamic function, returns a map of preferred value -> set of other values" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.getPreferTable dynafn)) ;;----------------------------------------------------------------
120867
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.generic.dynamic2 {:doc "Fork of defmulti/defmethod for performance experiments." :author "<EMAIL> <NAME> <EMAIL>" :since "2017-06-02" :version "2017-06-06"} (:refer-clojure :exclude [defmethod defmulti get-method methods prefer-method prefers remove-all-methods remove-method])) ;;---------------------------------------------------------------- (defmacro defdynafn2 "Creates a new dynamic function. The docstring and attr-map are optional. Options are key-value pairs" {:arglists '([name docstring? attr-map? & options]) :added "1.0"} [mm-name & options] (let [docstring (if (string? (first options)) (first options) nil) options (if (string? (first options)) (next options) options) m (if (map? (first options)) (first options) {}) options (if (map? (first options)) (next options) options) m (if docstring (assoc m :doc docstring) m) m (if (meta mm-name) (conj (meta mm-name) m) m)] (let [options (apply hash-map options)] #_(check-valid-options options :default :hierarchy) `(let [v# (def ~mm-name)] (when-not (and (.hasRoot v#) (instance? palisades.lakes.elements.java.generic.DynamicFn2 (deref v#))) (def ~(with-meta mm-name m) (palisades.lakes.elements.java.generic.DynamicFn2. ~(name mm-name)))))))) ;;---------------------------------------------------------------- ;; TODO: better method name (defmacro defmethod "Creates and installs a new method of the dynamic function with the given signature." {:added "1.0"} ([dynafn [c0 c1] & fn-tail] `(.addMethod ~(with-meta dynafn {:tag 'palisades.lakes.elements.java.generic.DynamicFn2}) ~(with-meta c0 {:tag 'Class}) ~(with-meta c1 {:tag 'Class}) (fn ~dynafn ~@fn-tail)))) #_(defn remove-all-methods "Removes all of the methods of the dynamic function." {:added "1.2" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.reset dynafn)) (defn remove-method "Removes the method of the dynamic function with the 2 class signature." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c0 ^Class c1] (.removeMethod dynafn c0 c1)) (defn prefer-method "Causes the dynamic function to prefer matches of <code>c00 c01</code> over <code>c10 c11</code>." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c00 ^Class c01 ^Class c10 ^Class c11] (.preferMethod dynafn c00 c01 c10 c11)) ;; TODO: return something more useful in the general case #_(defn methods "Given a dynamic function, returns a map of dispatch values -> dispatch fns" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.getMethodTable dynafn)) (defn get-method "Given a dynamic function and a dispatch value, returns the matching method, if any." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c0 ^Class c1] (.getMethod dynafn c0 c1)) ;; TODO: return something more useful in the general case #_(defn prefers "Given a dynamic function, returns a map of preferred value -> set of other values" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.getPreferTable dynafn)) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.generic.dynamic2 {:doc "Fork of defmulti/defmethod for performance experiments." :author "PI:EMAIL:<EMAIL>END_PI PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI" :since "2017-06-02" :version "2017-06-06"} (:refer-clojure :exclude [defmethod defmulti get-method methods prefer-method prefers remove-all-methods remove-method])) ;;---------------------------------------------------------------- (defmacro defdynafn2 "Creates a new dynamic function. The docstring and attr-map are optional. Options are key-value pairs" {:arglists '([name docstring? attr-map? & options]) :added "1.0"} [mm-name & options] (let [docstring (if (string? (first options)) (first options) nil) options (if (string? (first options)) (next options) options) m (if (map? (first options)) (first options) {}) options (if (map? (first options)) (next options) options) m (if docstring (assoc m :doc docstring) m) m (if (meta mm-name) (conj (meta mm-name) m) m)] (let [options (apply hash-map options)] #_(check-valid-options options :default :hierarchy) `(let [v# (def ~mm-name)] (when-not (and (.hasRoot v#) (instance? palisades.lakes.elements.java.generic.DynamicFn2 (deref v#))) (def ~(with-meta mm-name m) (palisades.lakes.elements.java.generic.DynamicFn2. ~(name mm-name)))))))) ;;---------------------------------------------------------------- ;; TODO: better method name (defmacro defmethod "Creates and installs a new method of the dynamic function with the given signature." {:added "1.0"} ([dynafn [c0 c1] & fn-tail] `(.addMethod ~(with-meta dynafn {:tag 'palisades.lakes.elements.java.generic.DynamicFn2}) ~(with-meta c0 {:tag 'Class}) ~(with-meta c1 {:tag 'Class}) (fn ~dynafn ~@fn-tail)))) #_(defn remove-all-methods "Removes all of the methods of the dynamic function." {:added "1.2" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.reset dynafn)) (defn remove-method "Removes the method of the dynamic function with the 2 class signature." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c0 ^Class c1] (.removeMethod dynafn c0 c1)) (defn prefer-method "Causes the dynamic function to prefer matches of <code>c00 c01</code> over <code>c10 c11</code>." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c00 ^Class c01 ^Class c10 ^Class c11] (.preferMethod dynafn c00 c01 c10 c11)) ;; TODO: return something more useful in the general case #_(defn methods "Given a dynamic function, returns a map of dispatch values -> dispatch fns" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.getMethodTable dynafn)) (defn get-method "Given a dynamic function and a dispatch value, returns the matching method, if any." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn ^Class c0 ^Class c1] (.getMethod dynafn c0 c1)) ;; TODO: return something more useful in the general case #_(defn prefers "Given a dynamic function, returns a map of preferred value -> set of other values" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.DynamicFn2 dynafn] (.getPreferTable dynafn)) ;;----------------------------------------------------------------
[ { "context": "eckbuilder-bg\"}\n {:name \"Dyson Mem Chip\" :ref \"cardbrowser-bg\"}\n ", "end": 4649, "score": 0.9586717486381531, "start": 4635, "tag": "NAME", "value": "Dyson Mem Chip" } ]
src/cljs/netrunner/account.cljs
erbridge/netrunner
0
(ns netrunner.account (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [sablono.core :as sab :include-macros true] [cljs.core.async :refer [chan put!] :as async] [netrunner.auth :refer [authenticated avatar] :as auth] [netrunner.appstate :refer [app-state]] [netrunner.ajax :refer [POST GET]] [netrunner.cardbrowser :refer [cards-channel]])) (def alt-arts-channel (chan)) (defn load-alt-arts [] (go (let [cards (->> (<! (GET "/data/altarts")) :json (filter :versions) (map #(update-in % [:versions] conj "default")) (map #(assoc % :title (some (fn [c] (when (= (:code c) (:code %)) (:title c))) (:cards @app-state)))) (into {} (map (juxt :code identity))))] (swap! app-state assoc :alt-arts cards) (put! alt-arts-channel cards)))) (defn handle-post [event owner url ref] (.preventDefault event) (om/set-state! owner :flash-message "Updating profile...") (swap! app-state assoc-in [:options :sounds] (om/get-state owner :sounds)) (swap! app-state assoc-in [:options :background] (om/get-state owner :background)) (swap! app-state assoc-in [:options :opponent-alt-art] (om/get-state owner :opponent-alt-art)) (swap! app-state assoc-in [:options :sounds-volume] (om/get-state owner :volume)) (.setItem js/localStorage "sounds" (om/get-state owner :sounds)) (.setItem js/localStorage "sounds_volume" (om/get-state owner :volume)) (let [params (:options @app-state)] (go (let [response (<! (POST url params :json))] (if (= (:status response) 200) (om/set-state! owner :flash-message "Profile updated!") (case (:status response) 401 (om/set-state! owner :flash-message "Invalid login or password") 421 (om/set-state! owner :flash-message "No account with that email address exists") :else (om/set-state! owner :flash-message "Profile updated - Please refresh your browser"))))))) (defn image-url [card version] (str "/img/cards/" card (when-not (= version "default") (str "-" version)) ".png")) (defn alt-art-name [type] (case type "alt" "Alternate" "wc2015" "World Champion 2015" "Official")) (defn account-view [user owner] (reify om/IInitState (init-state [this] {:flash-message ""}) om/IWillMount (will-mount [this] (om/set-state! owner :background (get-in @app-state [:options :background])) (om/set-state! owner :sounds (get-in @app-state [:options :sounds])) (om/set-state! owner :opponent-alt-art (get-in @app-state [:options :opponent-alt-art])) (om/set-state! owner :volume (get-in @app-state [:options :sounds-volume])) (go (while true (let [cards (<! alt-arts-channel)] (om/set-state! owner :cards cards))))) om/IRenderState (render-state [this state] (sab/html [:div.container [:div.account [:div {:class (:background (:options @app-state))}] [:div.panel.blue-shade#profile-form {:ref "profile-form"} [:h2 "Settings"] [:p.flash-message (:flash-message state)] [:form {:on-submit #(handle-post % owner "/update-profile" "profile-form")} [:h3 "Avatar"] (om/build avatar user {:opts {:size 38}}) [:a {:href "http://gravatar.com" :target "_blank"} "Change on gravatar.com"] [:h3 {:style {:margin-top "1em"}} "Sounds"] [:div [:label [:input {:type "checkbox" :value true :checked (om/get-state owner :sounds) :on-change #(om/set-state! owner :sounds (.. % -target -checked))}] "Enable sounds"]] [:div {:style {:margin-top "4px" :margin-left "24px"}} "Volume:" [:div [:input {:type "range" :min 1 :max 100 :step 1 :on-change #(om/set-state! owner :volume (.. % -target -value)) :value (om/get-state owner :volume) :disabled (not (om/get-state owner :sounds))}]]] [:h3 {:style {:margin-top "1em"}} "Game board background"] (for [option [{:name "Beanstalk" :ref "home-bg"} {:name "The Root" :ref "lobby-bg"} {:name "Project Atlas" :ref "deckbuilder-bg"} {:name "Dyson Mem Chip" :ref "cardbrowser-bg"} {:name "Fast Track" :ref "about-bg"} {:name "Logos" :ref "reset-bg"}]] [:div.radio [:label [:input {:type "radio" :name "background" :value (:ref option) :on-change #(om/set-state! owner :background (.. % -target -value)) :checked (= (om/get-state owner :background) (:ref option))}] (:name option)]]) [:h3 {:style {:margin-top "1em"}} "Alt arts"] [:div [:label [:input {:type "checkbox" :name "opponent-alt-art" :checked (om/get-state owner :opponent-alt-art) :on-change #(om/set-state! owner :opponent-alt-art (.. % -target -checked))}] "Show opponent's alternate card arts"]] (when (:special user) [:div {:style {:margin-top "10px"}} [:h4 "My alternate card arts"] [:select {:on-change #(do (om/set-state! owner :alt-card (.. % -target -value)) (om/set-state! owner :alt-card-version (get-in @app-state [:options :alt-arts (keyword (.. % -target -value))] "default")))} (for [card (sort-by :title (vals (:alt-arts @app-state)))] [:option {:value (:code card)} (:title card)])] (when (empty? (:alt-arts @app-state)) [:span.fake-link {:style {:margin-left "5px"} :on-click #(load-alt-arts)} "Reload"]) [:div (for [version (get-in @app-state [:alt-arts (om/get-state owner :alt-card) :versions])] (let [url (image-url (om/get-state owner :alt-card) version)] [:div {:style {:float "left" :margin "10px"}} [:div {:style {:text-align "center"}} [:div [:label [:input {:type "radio" :name "alt-art-radio" :value version :on-change #(do (om/set-state! owner :alt-card-version (.. % -target -value)) (swap! app-state update-in [:options :alt-arts] assoc (keyword (om/get-state owner :alt-card)) (.. % -target -value))) :checked (= (om/get-state owner :alt-card-version) version)}] (alt-art-name version)]]] [:div [:img {:style {:width "150px" :margin-top "5px"} :src url :onError #(-> % .-target js/$ .hide) :onLoad #(-> % .-target js/$ .show)}]]]))]]) [:div.button-bar {:style {:clear "both"}} [:button {:style {:margin "2em 0"}} "Update Profile"]]]]]])))) (defn unlogged-view [user owner] (om/component (sab/html [:div.account.panel.blue-shade [:h4 "Sign up to play Netrunner"] [:ul [:li [:a {:href "" :data-target "#register-form" :data-toggle "modal" :on-click (fn [] .focus (js/$ "input[name='email']"))} "Sign up"]] [:li [:a {:href "" :data-target "#login-form" :data-toggle "modal"} "Login"]]]]))) (defn account [{:keys [user]} owner] (om/component (if user (om/build account-view user) (om/build unlogged-view user)))) (om/root account app-state {:target (. js/document (getElementById "account"))})
23503
(ns netrunner.account (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [sablono.core :as sab :include-macros true] [cljs.core.async :refer [chan put!] :as async] [netrunner.auth :refer [authenticated avatar] :as auth] [netrunner.appstate :refer [app-state]] [netrunner.ajax :refer [POST GET]] [netrunner.cardbrowser :refer [cards-channel]])) (def alt-arts-channel (chan)) (defn load-alt-arts [] (go (let [cards (->> (<! (GET "/data/altarts")) :json (filter :versions) (map #(update-in % [:versions] conj "default")) (map #(assoc % :title (some (fn [c] (when (= (:code c) (:code %)) (:title c))) (:cards @app-state)))) (into {} (map (juxt :code identity))))] (swap! app-state assoc :alt-arts cards) (put! alt-arts-channel cards)))) (defn handle-post [event owner url ref] (.preventDefault event) (om/set-state! owner :flash-message "Updating profile...") (swap! app-state assoc-in [:options :sounds] (om/get-state owner :sounds)) (swap! app-state assoc-in [:options :background] (om/get-state owner :background)) (swap! app-state assoc-in [:options :opponent-alt-art] (om/get-state owner :opponent-alt-art)) (swap! app-state assoc-in [:options :sounds-volume] (om/get-state owner :volume)) (.setItem js/localStorage "sounds" (om/get-state owner :sounds)) (.setItem js/localStorage "sounds_volume" (om/get-state owner :volume)) (let [params (:options @app-state)] (go (let [response (<! (POST url params :json))] (if (= (:status response) 200) (om/set-state! owner :flash-message "Profile updated!") (case (:status response) 401 (om/set-state! owner :flash-message "Invalid login or password") 421 (om/set-state! owner :flash-message "No account with that email address exists") :else (om/set-state! owner :flash-message "Profile updated - Please refresh your browser"))))))) (defn image-url [card version] (str "/img/cards/" card (when-not (= version "default") (str "-" version)) ".png")) (defn alt-art-name [type] (case type "alt" "Alternate" "wc2015" "World Champion 2015" "Official")) (defn account-view [user owner] (reify om/IInitState (init-state [this] {:flash-message ""}) om/IWillMount (will-mount [this] (om/set-state! owner :background (get-in @app-state [:options :background])) (om/set-state! owner :sounds (get-in @app-state [:options :sounds])) (om/set-state! owner :opponent-alt-art (get-in @app-state [:options :opponent-alt-art])) (om/set-state! owner :volume (get-in @app-state [:options :sounds-volume])) (go (while true (let [cards (<! alt-arts-channel)] (om/set-state! owner :cards cards))))) om/IRenderState (render-state [this state] (sab/html [:div.container [:div.account [:div {:class (:background (:options @app-state))}] [:div.panel.blue-shade#profile-form {:ref "profile-form"} [:h2 "Settings"] [:p.flash-message (:flash-message state)] [:form {:on-submit #(handle-post % owner "/update-profile" "profile-form")} [:h3 "Avatar"] (om/build avatar user {:opts {:size 38}}) [:a {:href "http://gravatar.com" :target "_blank"} "Change on gravatar.com"] [:h3 {:style {:margin-top "1em"}} "Sounds"] [:div [:label [:input {:type "checkbox" :value true :checked (om/get-state owner :sounds) :on-change #(om/set-state! owner :sounds (.. % -target -checked))}] "Enable sounds"]] [:div {:style {:margin-top "4px" :margin-left "24px"}} "Volume:" [:div [:input {:type "range" :min 1 :max 100 :step 1 :on-change #(om/set-state! owner :volume (.. % -target -value)) :value (om/get-state owner :volume) :disabled (not (om/get-state owner :sounds))}]]] [:h3 {:style {:margin-top "1em"}} "Game board background"] (for [option [{:name "Beanstalk" :ref "home-bg"} {:name "The Root" :ref "lobby-bg"} {:name "Project Atlas" :ref "deckbuilder-bg"} {:name "<NAME>" :ref "cardbrowser-bg"} {:name "Fast Track" :ref "about-bg"} {:name "Logos" :ref "reset-bg"}]] [:div.radio [:label [:input {:type "radio" :name "background" :value (:ref option) :on-change #(om/set-state! owner :background (.. % -target -value)) :checked (= (om/get-state owner :background) (:ref option))}] (:name option)]]) [:h3 {:style {:margin-top "1em"}} "Alt arts"] [:div [:label [:input {:type "checkbox" :name "opponent-alt-art" :checked (om/get-state owner :opponent-alt-art) :on-change #(om/set-state! owner :opponent-alt-art (.. % -target -checked))}] "Show opponent's alternate card arts"]] (when (:special user) [:div {:style {:margin-top "10px"}} [:h4 "My alternate card arts"] [:select {:on-change #(do (om/set-state! owner :alt-card (.. % -target -value)) (om/set-state! owner :alt-card-version (get-in @app-state [:options :alt-arts (keyword (.. % -target -value))] "default")))} (for [card (sort-by :title (vals (:alt-arts @app-state)))] [:option {:value (:code card)} (:title card)])] (when (empty? (:alt-arts @app-state)) [:span.fake-link {:style {:margin-left "5px"} :on-click #(load-alt-arts)} "Reload"]) [:div (for [version (get-in @app-state [:alt-arts (om/get-state owner :alt-card) :versions])] (let [url (image-url (om/get-state owner :alt-card) version)] [:div {:style {:float "left" :margin "10px"}} [:div {:style {:text-align "center"}} [:div [:label [:input {:type "radio" :name "alt-art-radio" :value version :on-change #(do (om/set-state! owner :alt-card-version (.. % -target -value)) (swap! app-state update-in [:options :alt-arts] assoc (keyword (om/get-state owner :alt-card)) (.. % -target -value))) :checked (= (om/get-state owner :alt-card-version) version)}] (alt-art-name version)]]] [:div [:img {:style {:width "150px" :margin-top "5px"} :src url :onError #(-> % .-target js/$ .hide) :onLoad #(-> % .-target js/$ .show)}]]]))]]) [:div.button-bar {:style {:clear "both"}} [:button {:style {:margin "2em 0"}} "Update Profile"]]]]]])))) (defn unlogged-view [user owner] (om/component (sab/html [:div.account.panel.blue-shade [:h4 "Sign up to play Netrunner"] [:ul [:li [:a {:href "" :data-target "#register-form" :data-toggle "modal" :on-click (fn [] .focus (js/$ "input[name='email']"))} "Sign up"]] [:li [:a {:href "" :data-target "#login-form" :data-toggle "modal"} "Login"]]]]))) (defn account [{:keys [user]} owner] (om/component (if user (om/build account-view user) (om/build unlogged-view user)))) (om/root account app-state {:target (. js/document (getElementById "account"))})
true
(ns netrunner.account (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [sablono.core :as sab :include-macros true] [cljs.core.async :refer [chan put!] :as async] [netrunner.auth :refer [authenticated avatar] :as auth] [netrunner.appstate :refer [app-state]] [netrunner.ajax :refer [POST GET]] [netrunner.cardbrowser :refer [cards-channel]])) (def alt-arts-channel (chan)) (defn load-alt-arts [] (go (let [cards (->> (<! (GET "/data/altarts")) :json (filter :versions) (map #(update-in % [:versions] conj "default")) (map #(assoc % :title (some (fn [c] (when (= (:code c) (:code %)) (:title c))) (:cards @app-state)))) (into {} (map (juxt :code identity))))] (swap! app-state assoc :alt-arts cards) (put! alt-arts-channel cards)))) (defn handle-post [event owner url ref] (.preventDefault event) (om/set-state! owner :flash-message "Updating profile...") (swap! app-state assoc-in [:options :sounds] (om/get-state owner :sounds)) (swap! app-state assoc-in [:options :background] (om/get-state owner :background)) (swap! app-state assoc-in [:options :opponent-alt-art] (om/get-state owner :opponent-alt-art)) (swap! app-state assoc-in [:options :sounds-volume] (om/get-state owner :volume)) (.setItem js/localStorage "sounds" (om/get-state owner :sounds)) (.setItem js/localStorage "sounds_volume" (om/get-state owner :volume)) (let [params (:options @app-state)] (go (let [response (<! (POST url params :json))] (if (= (:status response) 200) (om/set-state! owner :flash-message "Profile updated!") (case (:status response) 401 (om/set-state! owner :flash-message "Invalid login or password") 421 (om/set-state! owner :flash-message "No account with that email address exists") :else (om/set-state! owner :flash-message "Profile updated - Please refresh your browser"))))))) (defn image-url [card version] (str "/img/cards/" card (when-not (= version "default") (str "-" version)) ".png")) (defn alt-art-name [type] (case type "alt" "Alternate" "wc2015" "World Champion 2015" "Official")) (defn account-view [user owner] (reify om/IInitState (init-state [this] {:flash-message ""}) om/IWillMount (will-mount [this] (om/set-state! owner :background (get-in @app-state [:options :background])) (om/set-state! owner :sounds (get-in @app-state [:options :sounds])) (om/set-state! owner :opponent-alt-art (get-in @app-state [:options :opponent-alt-art])) (om/set-state! owner :volume (get-in @app-state [:options :sounds-volume])) (go (while true (let [cards (<! alt-arts-channel)] (om/set-state! owner :cards cards))))) om/IRenderState (render-state [this state] (sab/html [:div.container [:div.account [:div {:class (:background (:options @app-state))}] [:div.panel.blue-shade#profile-form {:ref "profile-form"} [:h2 "Settings"] [:p.flash-message (:flash-message state)] [:form {:on-submit #(handle-post % owner "/update-profile" "profile-form")} [:h3 "Avatar"] (om/build avatar user {:opts {:size 38}}) [:a {:href "http://gravatar.com" :target "_blank"} "Change on gravatar.com"] [:h3 {:style {:margin-top "1em"}} "Sounds"] [:div [:label [:input {:type "checkbox" :value true :checked (om/get-state owner :sounds) :on-change #(om/set-state! owner :sounds (.. % -target -checked))}] "Enable sounds"]] [:div {:style {:margin-top "4px" :margin-left "24px"}} "Volume:" [:div [:input {:type "range" :min 1 :max 100 :step 1 :on-change #(om/set-state! owner :volume (.. % -target -value)) :value (om/get-state owner :volume) :disabled (not (om/get-state owner :sounds))}]]] [:h3 {:style {:margin-top "1em"}} "Game board background"] (for [option [{:name "Beanstalk" :ref "home-bg"} {:name "The Root" :ref "lobby-bg"} {:name "Project Atlas" :ref "deckbuilder-bg"} {:name "PI:NAME:<NAME>END_PI" :ref "cardbrowser-bg"} {:name "Fast Track" :ref "about-bg"} {:name "Logos" :ref "reset-bg"}]] [:div.radio [:label [:input {:type "radio" :name "background" :value (:ref option) :on-change #(om/set-state! owner :background (.. % -target -value)) :checked (= (om/get-state owner :background) (:ref option))}] (:name option)]]) [:h3 {:style {:margin-top "1em"}} "Alt arts"] [:div [:label [:input {:type "checkbox" :name "opponent-alt-art" :checked (om/get-state owner :opponent-alt-art) :on-change #(om/set-state! owner :opponent-alt-art (.. % -target -checked))}] "Show opponent's alternate card arts"]] (when (:special user) [:div {:style {:margin-top "10px"}} [:h4 "My alternate card arts"] [:select {:on-change #(do (om/set-state! owner :alt-card (.. % -target -value)) (om/set-state! owner :alt-card-version (get-in @app-state [:options :alt-arts (keyword (.. % -target -value))] "default")))} (for [card (sort-by :title (vals (:alt-arts @app-state)))] [:option {:value (:code card)} (:title card)])] (when (empty? (:alt-arts @app-state)) [:span.fake-link {:style {:margin-left "5px"} :on-click #(load-alt-arts)} "Reload"]) [:div (for [version (get-in @app-state [:alt-arts (om/get-state owner :alt-card) :versions])] (let [url (image-url (om/get-state owner :alt-card) version)] [:div {:style {:float "left" :margin "10px"}} [:div {:style {:text-align "center"}} [:div [:label [:input {:type "radio" :name "alt-art-radio" :value version :on-change #(do (om/set-state! owner :alt-card-version (.. % -target -value)) (swap! app-state update-in [:options :alt-arts] assoc (keyword (om/get-state owner :alt-card)) (.. % -target -value))) :checked (= (om/get-state owner :alt-card-version) version)}] (alt-art-name version)]]] [:div [:img {:style {:width "150px" :margin-top "5px"} :src url :onError #(-> % .-target js/$ .hide) :onLoad #(-> % .-target js/$ .show)}]]]))]]) [:div.button-bar {:style {:clear "both"}} [:button {:style {:margin "2em 0"}} "Update Profile"]]]]]])))) (defn unlogged-view [user owner] (om/component (sab/html [:div.account.panel.blue-shade [:h4 "Sign up to play Netrunner"] [:ul [:li [:a {:href "" :data-target "#register-form" :data-toggle "modal" :on-click (fn [] .focus (js/$ "input[name='email']"))} "Sign up"]] [:li [:a {:href "" :data-target "#login-form" :data-toggle "modal"} "Login"]]]]))) (defn account [{:keys [user]} owner] (om/component (if user (om/build account-view user) (om/build unlogged-view user)))) (om/root account app-state {:target (. js/document (getElementById "account"))})
[ { "context": "s true, :name \"name\", :type \"text\", :placeholder \"Your Nick\"}]]\n [:div.flex.flex-col\n {:style {:font-s", "end": 1530, "score": 0.988055944442749, "start": 1521, "tag": "NAME", "value": "Your Nick" } ]
src/cljs/poker/pages/index.cljc
DogLooksGood/holdem
98
(ns poker.pages.index "Page for index. Signup & login." #?@(:node [] :cljs [(:require [re-frame.core :as re-frame] [poker.events.account] [poker.subs.account] [clojure.string :as str])])) #?(:clj (defn on-signup []) :node (defn on-signup []) :cljs (defn on-signup [e] (let [es (.. e -target -elements) name (aget es "name" "value") avatar (aget es "avatar" "value")] #?(:node nil :cljs (when-not (or (str/blank? name) (str/blank? avatar)) (re-frame/dispatch [:account/signup {:player/name name, :player/avatar avatar}]))) (.preventDefault e)))) #?(:clj (defn render-signup-error []) :node (defn render-signup-error []) :cljs (defn render-signup-error [] (let [error* (re-frame/subscribe [:account/signup-error])] (when @error* [:div.text-red-500 @error*])))) (defn index-page [] [:div.h-screen.w-screen.flex.flex-col.justify-center.items-center [:form.flex.flex-col.justify-center.items-center {:on-submit on-signup, :suppress-hydration-warning true} [:div.leading-9.text-2xl.font-bold.flex.items-center "WELCOME TO HOLDEM!!"] [render-signup-error] [:div.mt-4 [:input {:auto-focus true, :name "name", :type "text", :placeholder "Your Nick"}]] [:div.flex.flex-col {:style {:font-size "3rem"}} [:div.flex [:div "🐡" [:input {:type "radio", :name "avatar", :value "🐡"}]] [:div "🐠" [:input {:type "radio", :name "avatar", :value "🐠"}]] [:div "🐟" [:input {:type "radio", :name "avatar", :value "🐟"}]]] [:div.flex [:div "🐲" [:input {:type "radio", :name "avatar", :value "🐲"}]] [:div "🐴" [:input {:type "radio", :name "avatar", :value "🐴"}]] [:div "🐐" [:input {:type "radio", :name "avatar", :value "🐐"}]]] [:div.flex [:div "🎣" [:input {:type "radio", :name "avatar", :value "🎣"}]] [:div "🐈" [:input {:type "radio", :name "avatar", :value "🐈"}]] [:div "🐕" [:input {:type "radio", :name "avatar", :value "🐕"}]]]] [:button.div.border.border-2.border-black.bg-gray-300.self-stretch.text-center.p-4 "Start"]]])
118510
(ns poker.pages.index "Page for index. Signup & login." #?@(:node [] :cljs [(:require [re-frame.core :as re-frame] [poker.events.account] [poker.subs.account] [clojure.string :as str])])) #?(:clj (defn on-signup []) :node (defn on-signup []) :cljs (defn on-signup [e] (let [es (.. e -target -elements) name (aget es "name" "value") avatar (aget es "avatar" "value")] #?(:node nil :cljs (when-not (or (str/blank? name) (str/blank? avatar)) (re-frame/dispatch [:account/signup {:player/name name, :player/avatar avatar}]))) (.preventDefault e)))) #?(:clj (defn render-signup-error []) :node (defn render-signup-error []) :cljs (defn render-signup-error [] (let [error* (re-frame/subscribe [:account/signup-error])] (when @error* [:div.text-red-500 @error*])))) (defn index-page [] [:div.h-screen.w-screen.flex.flex-col.justify-center.items-center [:form.flex.flex-col.justify-center.items-center {:on-submit on-signup, :suppress-hydration-warning true} [:div.leading-9.text-2xl.font-bold.flex.items-center "WELCOME TO HOLDEM!!"] [render-signup-error] [:div.mt-4 [:input {:auto-focus true, :name "name", :type "text", :placeholder "<NAME>"}]] [:div.flex.flex-col {:style {:font-size "3rem"}} [:div.flex [:div "🐡" [:input {:type "radio", :name "avatar", :value "🐡"}]] [:div "🐠" [:input {:type "radio", :name "avatar", :value "🐠"}]] [:div "🐟" [:input {:type "radio", :name "avatar", :value "🐟"}]]] [:div.flex [:div "🐲" [:input {:type "radio", :name "avatar", :value "🐲"}]] [:div "🐴" [:input {:type "radio", :name "avatar", :value "🐴"}]] [:div "🐐" [:input {:type "radio", :name "avatar", :value "🐐"}]]] [:div.flex [:div "🎣" [:input {:type "radio", :name "avatar", :value "🎣"}]] [:div "🐈" [:input {:type "radio", :name "avatar", :value "🐈"}]] [:div "🐕" [:input {:type "radio", :name "avatar", :value "🐕"}]]]] [:button.div.border.border-2.border-black.bg-gray-300.self-stretch.text-center.p-4 "Start"]]])
true
(ns poker.pages.index "Page for index. Signup & login." #?@(:node [] :cljs [(:require [re-frame.core :as re-frame] [poker.events.account] [poker.subs.account] [clojure.string :as str])])) #?(:clj (defn on-signup []) :node (defn on-signup []) :cljs (defn on-signup [e] (let [es (.. e -target -elements) name (aget es "name" "value") avatar (aget es "avatar" "value")] #?(:node nil :cljs (when-not (or (str/blank? name) (str/blank? avatar)) (re-frame/dispatch [:account/signup {:player/name name, :player/avatar avatar}]))) (.preventDefault e)))) #?(:clj (defn render-signup-error []) :node (defn render-signup-error []) :cljs (defn render-signup-error [] (let [error* (re-frame/subscribe [:account/signup-error])] (when @error* [:div.text-red-500 @error*])))) (defn index-page [] [:div.h-screen.w-screen.flex.flex-col.justify-center.items-center [:form.flex.flex-col.justify-center.items-center {:on-submit on-signup, :suppress-hydration-warning true} [:div.leading-9.text-2xl.font-bold.flex.items-center "WELCOME TO HOLDEM!!"] [render-signup-error] [:div.mt-4 [:input {:auto-focus true, :name "name", :type "text", :placeholder "PI:NAME:<NAME>END_PI"}]] [:div.flex.flex-col {:style {:font-size "3rem"}} [:div.flex [:div "🐡" [:input {:type "radio", :name "avatar", :value "🐡"}]] [:div "🐠" [:input {:type "radio", :name "avatar", :value "🐠"}]] [:div "🐟" [:input {:type "radio", :name "avatar", :value "🐟"}]]] [:div.flex [:div "🐲" [:input {:type "radio", :name "avatar", :value "🐲"}]] [:div "🐴" [:input {:type "radio", :name "avatar", :value "🐴"}]] [:div "🐐" [:input {:type "radio", :name "avatar", :value "🐐"}]]] [:div.flex [:div "🎣" [:input {:type "radio", :name "avatar", :value "🎣"}]] [:div "🐈" [:input {:type "radio", :name "avatar", :value "🐈"}]] [:div "🐕" [:input {:type "radio", :name "avatar", :value "🐕"}]]]] [:button.div.border.border-2.border-black.bg-gray-300.self-stretch.text-center.p-4 "Start"]]])
[ { "context": "reload\n\n(def schema-version \"0\")\n(def schema-key \"chv-schema-version\")\n(def state-key \"chv-state\")\n\n(defn update-versi", "end": 474, "score": 0.9982163310050964, "start": 456, "tag": "KEY", "value": "chv-schema-version" }, { "context": " schema-key \"chv-schema-version\")\n(def state-key \"chv-state\")\n\n(defn update-version-clear-state-if-wrong! []\n", "end": 502, "score": 0.9986605048179626, "start": 493, "tag": "KEY", "value": "chv-state" } ]
src/chronverna/core.cljs
dphilipson/chronverna
2
(ns chronverna.core (:require [reagent.core :as reagent :refer [atom]] [chronverna.setup :as setup] [chronverna.game :as game] [chronverna.components :as components] [cljs.reader :as reader])) (enable-console-print!) (println "Edits to this text should show up in your developer console.") ;; define your app data so that it doesn't get over-written on reload (def schema-version "0") (def schema-key "chv-schema-version") (def state-key "chv-state") (defn update-version-clear-state-if-wrong! [] (let [saved-schema-version (.getItem js/localStorage schema-key)] (when (not= saved-schema-version schema-version) (.removeItem js/localStorage state-key) (.setItem js/localStorage schema-key schema-version)))) (defonce app-state-atom (do (update-version-clear-state-if-wrong!) (let [saved-state-edn (.getItem js/localStorage state-key) saved-state (when saved-state-edn (reader/read-string saved-state-edn))] (atom (or saved-state setup/initial-state))))) ; Setup to Game transition (defn new-game-from-setup [setup-state] (game/new-game-state (setup/get-players setup-state))) ; Reset (defn clear-state! [] (reset! app-state-atom setup/initial-state) (.removeItem js/localStorage state-key)) (defn clear-state-request-confirm! [] (let [confirmed (js/confirm "Quit current game and return to faction select?")] (when confirmed (clear-state!)))) ; Side-effecting actions (defn save-state! [] (.setItem js/localStorage state-key (prn-str @app-state-atom))) (defn swap-state! [f & args] (apply swap! app-state-atom f args)) (defn swap-state-and-save! [f & args] (apply swap-state! f args) (save-state!)) (defn swap-game-state-push-history-save! [f & args] (apply swap-state-and-save! game/update-game-state-add-history f args)) ; Add components with Reagent (when-let [app-container (.getElementById js/document "app")] (reagent/render-component [components/main app-state-atom {:on-add-player #(swap-state! setup/add-player) :on-set-player-color (partial swap-state! setup/set-player-color) :on-set-player-name (partial swap-state! setup/set-player-name) :on-remove-player (partial swap-state! setup/remove-player) :on-start-game #(swap-state! new-game-from-setup) :on-start-round #(swap-game-state-push-history-save! game/start-round) :on-next #(swap-game-state-push-history-save! game/player-selected-next) :on-grow-family #(swap-game-state-push-history-save! game/player-grew-family) :on-take-start-player #(swap-game-state-push-history-save! game/player-took-start-player) :on-pause #(swap-state-and-save! assoc :paused? true) :on-unpause #(swap-state-and-save! assoc :paused? false) :on-undo #(swap-state-and-save! game/undo) :on-redo #(swap-state-and-save! game/redo) :on-reset #(clear-state-request-confirm!)}] app-container)) ; Call advance-to-time on ticks (defn current-time-ms [] (.getTime (js/Date.))) (defonce timer-did-start (do ((fn request-frame [] (if (= (:mode @app-state-atom) :game) (swap-state! game/advance-to-time (current-time-ms))) (js/requestAnimationFrame request-frame))) true)) (defn on-js-reload [] ;; optionally touch your app-state to force rerendering depending on ;; your application ;; (swap! app-state update-in [:__figwheel_counter] inc) )
47830
(ns chronverna.core (:require [reagent.core :as reagent :refer [atom]] [chronverna.setup :as setup] [chronverna.game :as game] [chronverna.components :as components] [cljs.reader :as reader])) (enable-console-print!) (println "Edits to this text should show up in your developer console.") ;; define your app data so that it doesn't get over-written on reload (def schema-version "0") (def schema-key "<KEY>") (def state-key "<KEY>") (defn update-version-clear-state-if-wrong! [] (let [saved-schema-version (.getItem js/localStorage schema-key)] (when (not= saved-schema-version schema-version) (.removeItem js/localStorage state-key) (.setItem js/localStorage schema-key schema-version)))) (defonce app-state-atom (do (update-version-clear-state-if-wrong!) (let [saved-state-edn (.getItem js/localStorage state-key) saved-state (when saved-state-edn (reader/read-string saved-state-edn))] (atom (or saved-state setup/initial-state))))) ; Setup to Game transition (defn new-game-from-setup [setup-state] (game/new-game-state (setup/get-players setup-state))) ; Reset (defn clear-state! [] (reset! app-state-atom setup/initial-state) (.removeItem js/localStorage state-key)) (defn clear-state-request-confirm! [] (let [confirmed (js/confirm "Quit current game and return to faction select?")] (when confirmed (clear-state!)))) ; Side-effecting actions (defn save-state! [] (.setItem js/localStorage state-key (prn-str @app-state-atom))) (defn swap-state! [f & args] (apply swap! app-state-atom f args)) (defn swap-state-and-save! [f & args] (apply swap-state! f args) (save-state!)) (defn swap-game-state-push-history-save! [f & args] (apply swap-state-and-save! game/update-game-state-add-history f args)) ; Add components with Reagent (when-let [app-container (.getElementById js/document "app")] (reagent/render-component [components/main app-state-atom {:on-add-player #(swap-state! setup/add-player) :on-set-player-color (partial swap-state! setup/set-player-color) :on-set-player-name (partial swap-state! setup/set-player-name) :on-remove-player (partial swap-state! setup/remove-player) :on-start-game #(swap-state! new-game-from-setup) :on-start-round #(swap-game-state-push-history-save! game/start-round) :on-next #(swap-game-state-push-history-save! game/player-selected-next) :on-grow-family #(swap-game-state-push-history-save! game/player-grew-family) :on-take-start-player #(swap-game-state-push-history-save! game/player-took-start-player) :on-pause #(swap-state-and-save! assoc :paused? true) :on-unpause #(swap-state-and-save! assoc :paused? false) :on-undo #(swap-state-and-save! game/undo) :on-redo #(swap-state-and-save! game/redo) :on-reset #(clear-state-request-confirm!)}] app-container)) ; Call advance-to-time on ticks (defn current-time-ms [] (.getTime (js/Date.))) (defonce timer-did-start (do ((fn request-frame [] (if (= (:mode @app-state-atom) :game) (swap-state! game/advance-to-time (current-time-ms))) (js/requestAnimationFrame request-frame))) true)) (defn on-js-reload [] ;; optionally touch your app-state to force rerendering depending on ;; your application ;; (swap! app-state update-in [:__figwheel_counter] inc) )
true
(ns chronverna.core (:require [reagent.core :as reagent :refer [atom]] [chronverna.setup :as setup] [chronverna.game :as game] [chronverna.components :as components] [cljs.reader :as reader])) (enable-console-print!) (println "Edits to this text should show up in your developer console.") ;; define your app data so that it doesn't get over-written on reload (def schema-version "0") (def schema-key "PI:KEY:<KEY>END_PI") (def state-key "PI:KEY:<KEY>END_PI") (defn update-version-clear-state-if-wrong! [] (let [saved-schema-version (.getItem js/localStorage schema-key)] (when (not= saved-schema-version schema-version) (.removeItem js/localStorage state-key) (.setItem js/localStorage schema-key schema-version)))) (defonce app-state-atom (do (update-version-clear-state-if-wrong!) (let [saved-state-edn (.getItem js/localStorage state-key) saved-state (when saved-state-edn (reader/read-string saved-state-edn))] (atom (or saved-state setup/initial-state))))) ; Setup to Game transition (defn new-game-from-setup [setup-state] (game/new-game-state (setup/get-players setup-state))) ; Reset (defn clear-state! [] (reset! app-state-atom setup/initial-state) (.removeItem js/localStorage state-key)) (defn clear-state-request-confirm! [] (let [confirmed (js/confirm "Quit current game and return to faction select?")] (when confirmed (clear-state!)))) ; Side-effecting actions (defn save-state! [] (.setItem js/localStorage state-key (prn-str @app-state-atom))) (defn swap-state! [f & args] (apply swap! app-state-atom f args)) (defn swap-state-and-save! [f & args] (apply swap-state! f args) (save-state!)) (defn swap-game-state-push-history-save! [f & args] (apply swap-state-and-save! game/update-game-state-add-history f args)) ; Add components with Reagent (when-let [app-container (.getElementById js/document "app")] (reagent/render-component [components/main app-state-atom {:on-add-player #(swap-state! setup/add-player) :on-set-player-color (partial swap-state! setup/set-player-color) :on-set-player-name (partial swap-state! setup/set-player-name) :on-remove-player (partial swap-state! setup/remove-player) :on-start-game #(swap-state! new-game-from-setup) :on-start-round #(swap-game-state-push-history-save! game/start-round) :on-next #(swap-game-state-push-history-save! game/player-selected-next) :on-grow-family #(swap-game-state-push-history-save! game/player-grew-family) :on-take-start-player #(swap-game-state-push-history-save! game/player-took-start-player) :on-pause #(swap-state-and-save! assoc :paused? true) :on-unpause #(swap-state-and-save! assoc :paused? false) :on-undo #(swap-state-and-save! game/undo) :on-redo #(swap-state-and-save! game/redo) :on-reset #(clear-state-request-confirm!)}] app-container)) ; Call advance-to-time on ticks (defn current-time-ms [] (.getTime (js/Date.))) (defonce timer-did-start (do ((fn request-frame [] (if (= (:mode @app-state-atom) :game) (swap-state! game/advance-to-time (current-time-ms))) (js/requestAnimationFrame request-frame))) true)) (defn on-js-reload [] ;; optionally touch your app-state to force rerendering depending on ;; your application ;; (swap! app-state update-in [:__figwheel_counter] inc) )
[ { "context": " \"Clojure i18n library\"\n :url \"http://github.com/puppetlabs/clj-i18n\"\n :license {:name \"Apache License, Vers", "end": 119, "score": 0.9347796440124512, "start": 109, "tag": "USERNAME", "value": "puppetlabs" }, { "context": "e\n :password :env/clojars_jenkins_password\n :sign-releas", "end": 645, "score": 0.9304175972938538, "start": 617, "tag": "PASSWORD", "value": "env/clojars_jenkins_password" } ]
project.clj
janelu2/clj-i18n
0
(defproject puppetlabs/i18n "0.4.1-SNAPSHOT" :description "Clojure i18n library" :url "http://github.com/puppetlabs/clj-i18n" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :pedantic? :abort :dependencies [[org.clojure/clojure "1.6.0"] [org.gnu.gettext/libintl "0.18.3"]] :main puppetlabs.i18n.main :aot [puppetlabs.i18n.main] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :env/clojars_jenkins_password :sign-releases false}]])
12412
(defproject puppetlabs/i18n "0.4.1-SNAPSHOT" :description "Clojure i18n library" :url "http://github.com/puppetlabs/clj-i18n" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :pedantic? :abort :dependencies [[org.clojure/clojure "1.6.0"] [org.gnu.gettext/libintl "0.18.3"]] :main puppetlabs.i18n.main :aot [puppetlabs.i18n.main] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :<PASSWORD> :sign-releases false}]])
true
(defproject puppetlabs/i18n "0.4.1-SNAPSHOT" :description "Clojure i18n library" :url "http://github.com/puppetlabs/clj-i18n" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :pedantic? :abort :dependencies [[org.clojure/clojure "1.6.0"] [org.gnu.gettext/libintl "0.18.3"]] :main puppetlabs.i18n.main :aot [puppetlabs.i18n.main] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}]])
[ { "context": "(assoc (UUID/randomUUID) {:name \"HAI!\" :password \"A password\"})\n ", "end": 938, "score": 0.9993205070495605, "start": 928, "tag": "PASSWORD", "value": "A password" } ]
src/docker_testing_demo/core.clj
lfn3/clojure-docker-integration-testing
1
(ns docker-testing-demo.core (:require [clojure.test :as t] [org.httpkit.server :as srv] [clojure.edn :as edn] [org.httpkit.client :as c]) (:gen-class) (:import (java.util UUID))) (defn server-handler [req] (case (:uri req) "/users" {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp))} "/create-user" (do (c/post "http://database/users" {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp) (edn/read-string) (assoc (UUID/randomUUID) {:name "HAI!" :password "A password"}) (pr-str))}) {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp))}))) (defn server [] (prn "Starting server on 80") (srv/run-server server-handler {:port 80})) (defonce db (atom {})) (defn database-handler [req] (case (:request-method req) :post (swap! db assoc (:uri req) (slurp (.bytes (:body req)))) :get {:body (get @db (:uri req))})) (defn start-database [] (prn "Starting 'database' on 80") (srv/run-server database-handler {:port 80})) (defn test [] (print "Waiting for server to wake up...") (loop [res @(c/get "http://server/users")] (when (not (= 200 (:status res))) (print "...") (recur (c/get "http://server/users")))) (println "\nRunning tests") (->> (t/run-tests 'docker-testing-demo.core) (#(select-keys %1 [:error :fail])) (vals) (reduce +) ;Generate the exit code from the number of fails (System/exit))) (defn -main "Run a server, database, or tests, depending on the " [& args] (let [[type] args] (case type "server" (server) "database" (start-database) (test)))) (t/use-fixtures :each (fn [f] @(c/post "http://database/users" {:body "{}"}) (f))) (t/deftest users-starts-empty (t/is (= {} (edn/read-string (slurp (.bytes (:body @(c/get "http://server/users")))))))) (t/deftest adding-a-user-works @(c/get "http://server/create-user") (t/is (= 1 (count (edn/read-string (slurp (.bytes (:body @(c/get "http://server/users")))))))))
31380
(ns docker-testing-demo.core (:require [clojure.test :as t] [org.httpkit.server :as srv] [clojure.edn :as edn] [org.httpkit.client :as c]) (:gen-class) (:import (java.util UUID))) (defn server-handler [req] (case (:uri req) "/users" {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp))} "/create-user" (do (c/post "http://database/users" {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp) (edn/read-string) (assoc (UUID/randomUUID) {:name "HAI!" :password "<PASSWORD>"}) (pr-str))}) {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp))}))) (defn server [] (prn "Starting server on 80") (srv/run-server server-handler {:port 80})) (defonce db (atom {})) (defn database-handler [req] (case (:request-method req) :post (swap! db assoc (:uri req) (slurp (.bytes (:body req)))) :get {:body (get @db (:uri req))})) (defn start-database [] (prn "Starting 'database' on 80") (srv/run-server database-handler {:port 80})) (defn test [] (print "Waiting for server to wake up...") (loop [res @(c/get "http://server/users")] (when (not (= 200 (:status res))) (print "...") (recur (c/get "http://server/users")))) (println "\nRunning tests") (->> (t/run-tests 'docker-testing-demo.core) (#(select-keys %1 [:error :fail])) (vals) (reduce +) ;Generate the exit code from the number of fails (System/exit))) (defn -main "Run a server, database, or tests, depending on the " [& args] (let [[type] args] (case type "server" (server) "database" (start-database) (test)))) (t/use-fixtures :each (fn [f] @(c/post "http://database/users" {:body "{}"}) (f))) (t/deftest users-starts-empty (t/is (= {} (edn/read-string (slurp (.bytes (:body @(c/get "http://server/users")))))))) (t/deftest adding-a-user-works @(c/get "http://server/create-user") (t/is (= 1 (count (edn/read-string (slurp (.bytes (:body @(c/get "http://server/users")))))))))
true
(ns docker-testing-demo.core (:require [clojure.test :as t] [org.httpkit.server :as srv] [clojure.edn :as edn] [org.httpkit.client :as c]) (:gen-class) (:import (java.util UUID))) (defn server-handler [req] (case (:uri req) "/users" {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp))} "/create-user" (do (c/post "http://database/users" {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp) (edn/read-string) (assoc (UUID/randomUUID) {:name "HAI!" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (pr-str))}) {:body (-> @(c/get "http://database/users") :body (.bytes) (slurp))}))) (defn server [] (prn "Starting server on 80") (srv/run-server server-handler {:port 80})) (defonce db (atom {})) (defn database-handler [req] (case (:request-method req) :post (swap! db assoc (:uri req) (slurp (.bytes (:body req)))) :get {:body (get @db (:uri req))})) (defn start-database [] (prn "Starting 'database' on 80") (srv/run-server database-handler {:port 80})) (defn test [] (print "Waiting for server to wake up...") (loop [res @(c/get "http://server/users")] (when (not (= 200 (:status res))) (print "...") (recur (c/get "http://server/users")))) (println "\nRunning tests") (->> (t/run-tests 'docker-testing-demo.core) (#(select-keys %1 [:error :fail])) (vals) (reduce +) ;Generate the exit code from the number of fails (System/exit))) (defn -main "Run a server, database, or tests, depending on the " [& args] (let [[type] args] (case type "server" (server) "database" (start-database) (test)))) (t/use-fixtures :each (fn [f] @(c/post "http://database/users" {:body "{}"}) (f))) (t/deftest users-starts-empty (t/is (= {} (edn/read-string (slurp (.bytes (:body @(c/get "http://server/users")))))))) (t/deftest adding-a-user-works @(c/get "http://server/create-user") (t/is (= 1 (count (edn/read-string (slurp (.bytes (:body @(c/get "http://server/users")))))))))
[ { "context": "ername :env/nexus_jenkins_username\n :password :env/nexus_jenkins_password\n :sign-releases false })\n\n(def heap-size-from-", "end": 164, "score": 0.8707956075668335, "start": 138, "tag": "PASSWORD", "value": "env/nexus_jenkins_password" }, { "context": "server-release.jar\"\n :lein-ezbake {:vars {:user \"puppet\"\n :group \"puppet\"\n ", "end": 4192, "score": 0.9751892685890198, "start": 4186, "tag": "USERNAME", "value": "puppet" }, { "context": " ;; https://github.com/technomancy/leiningen/issues/2216\n ", "end": 9802, "score": 0.9996641278266907, "start": 9791, "tag": "USERNAME", "value": "technomancy" } ]
project.clj
adreyer/puppetserver
0
(def ps-version "6.0.0-master-SNAPSHOT") (defn deploy-info [url] { :url url :username :env/nexus_jenkins_username :password :env/nexus_jenkins_password :sign-releases false }) (def heap-size-from-profile-clj (let [profile-clj (io/file (System/getenv "HOME") ".lein" "profiles.clj")] (if (.exists profile-clj) (-> profile-clj slurp read-string (get-in [:user :puppetserver-heap-size]))))) (defn heap-size [default-heap-size heap-size-type] (or (System/getenv "PUPPETSERVER_HEAP_SIZE") heap-size-from-profile-clj (do (println "Using" default-heap-size heap-size-type "heap since not set via PUPPETSERVER_HEAP_SIZE environment variable or" "user.puppetserver-heap-size in ~/.lein/profiles.clj file. Set to at" "least 5G for best performance during test runs.") default-heap-size))) (def figwheel-version "0.3.7") (def cljsbuild-version "1.1.7") (def clojurescript-version "1.10.238") (defproject puppetlabs/puppetserver ps-version :description "Puppet Server" :min-lein-version "2.7.1" :parent-project {:coords [puppetlabs/clj-parent "2.1.0"] :inherit [:managed-dependencies]} :dependencies [[org.clojure/clojure] ;; See SERVER-2216 [org.clojure/tools.nrepl "0.2.13"] [slingshot] [circleci/clj-yaml] [org.yaml/snakeyaml] [commons-lang] [commons-io] [clj-time] [prismatic/schema] [me.raynes/fs] [liberator] [org.apache.commons/commons-exec] [io.dropwizard.metrics/metrics-core] [com.fasterxml.jackson.module/jackson-module-afterburner] ;; We do not currently use this dependency directly, but ;; we have documentation that shows how users can use it to ;; send their logs to logstash, so we include it in the jar. ;; we may use it directly in the future ;; We are using an exlusion here because logback dependencies should ;; be inherited from trapperkeeper to avoid accidentally bringing ;; in different versions of the three different logback artifacts [net.logstash.logback/logstash-logback-encoder] [puppetlabs/jruby-utils "2.0.0"] [puppetlabs/jruby-deps "9.1.16.0-1"] ;; JRuby 1.7.x and trapperkeeper (via core.async) both bring in ;; asm dependencies. Deferring to clj-parent to resolve the version. [org.ow2.asm/asm-all] [puppetlabs/trapperkeeper] [puppetlabs/trapperkeeper-authorization] [puppetlabs/trapperkeeper-comidi-metrics] [puppetlabs/trapperkeeper-metrics] [puppetlabs/trapperkeeper-scheduler] [puppetlabs/trapperkeeper-status] [puppetlabs/kitchensink] [puppetlabs/ssl-utils] [puppetlabs/ring-middleware] [puppetlabs/dujour-version-check] [puppetlabs/http-client] [puppetlabs/comidi] [puppetlabs/i18n] ;; dependencies for clojurescript dashboard [puppetlabs/cljs-dashboard-widgets "0.1.1"] [org.clojure/clojurescript ~clojurescript-version] [cljs-http "0.1.36"]] :main puppetlabs.trapperkeeper.main :pedantic? :abort :source-paths ["src/clj"] :java-source-paths ["src/java"] :test-paths ["test/unit" "test/integration"] :resource-paths ["resources" "src/ruby" "target/js-resources"] :repositories [["releases" "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/"] ["snapshots" "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/"]] :plugins [[lein-parent "0.3.1"] [puppetlabs/i18n "0.8.0"]] :uberjar-name "puppet-server-release.jar" :lein-ezbake {:vars {:user "puppet" :group "puppet" :build-type "foss" :java-args ~(str "-Xms2g -Xmx2g " "-Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger") :create-dirs ["/opt/puppetlabs/server/data/puppetserver/jars"] :repo-target "puppet6" :nonfinal-repo-target "puppet6-nightly" :bootstrap-source :services-d :logrotate-enabled false} :resources {:dir "tmp/ezbake-resources"} :config-dir "ezbake/config" :system-config-dir "ezbake/system-config"} :deploy-repositories [["releases" ~(deploy-info "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/")] ["snapshots" ~(deploy-info "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/")]] ;; By declaring a classifier here and a corresponding profile below we'll get an additional jar ;; during `lein jar` that has all the code in the test/ directory. Downstream projects can then ;; depend on this test jar using a :classifier in their :dependencies to reuse the test utility ;; code that we have. :classifiers [["test" :testutils]] :cljsbuild {:builds {:app {:source-paths ["src/cljs"] :compiler {:output-to "target/js-resources/puppetlabs/puppetserver/public/js/puppetserver-dashboard.js" :output-dir "target/js-resources/puppetlabs/puppetserver/public/js/out" :asset-path "js/out" :optimizations :none :pretty-print true :main "puppetlabs.puppetserver.dashboard.production"}}}} :profiles {:dev {:source-paths ["dev"] :dependencies [[org.clojure/tools.namespace] [puppetlabs/trapperkeeper-webserver-jetty9 nil] [puppetlabs/trapperkeeper-webserver-jetty9 nil :classifier "test"] [puppetlabs/trapperkeeper nil :classifier "test" :scope "test"] [puppetlabs/trapperkeeper-metrics :classifier "test" :scope "test"] [puppetlabs/kitchensink nil :classifier "test" :scope "test"] [ring-basic-authentication] [ring/ring-mock] [grimradical/clj-semver "0.3.0" :exclusions [org.clojure/clojure]] [beckon] [com.cemerick/url "0.1.1"] ;; dependencies for cljs development [figwheel-sidecar "0.5.4-6" :exclusions [org.clojure/clojure]]] ;; dev profile config for clojurescript dev :plugins [[lein-cljsbuild ~cljsbuild-version :exclusions [org.clojure/clojurescript]] [lein-figwheel "0.5.4-6" :exclusions [org.clojure/clojure org.clojure/core.cache commons-io commons-codec]]] :figwheel {:http-server-root "puppetlabs/puppetserver/public" :server-port 3449 :repl false} :cljsbuild {:builds {:app {:source-paths ["dev-cljs"] :compiler {:main "puppetlabs.puppetserver.dashboard.dev" :source-map true}}}} ;; SERVER-332, enable SSLv3 for unit tests that exercise SSLv3 :jvm-opts ["-Djava.security.properties=./dev-resources/java.security"]} :testutils {:source-paths ^:replace ["test/unit" "test/integration"]} :test { ;; NOTE: In core.async version 0.2.382, the default size for ;; the core.async dispatch thread pool was reduced from ;; (42 + (2 * num-cpus)) to... eight. The jruby metrics tests ;; use core.async and need more than eight threads to run ;; properly; this setting overrides the default value. Without ;; it the metrics tests will hang. :jvm-opts ["-Dclojure.core.async.pool-size=50"] } :ezbake {:dependencies ^:replace [;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NOTE: we need to explicitly pass in `nil` values ;; for the version numbers here in order to correctly ;; inherit the versions from our parent project. ;; This is because of a bug in lein 2.7.1 that ;; prevents the deps from being processed properly ;; with `:managed-dependencies` when you specify ;; dependencies in a profile. See: ;; https://github.com/technomancy/leiningen/issues/2216 ;; Hopefully we can remove those `nil`s (if we care) ;; and this comment when lein 2.7.2 is available. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we need to explicitly pull in our parent project's ;; clojure version here, because without it, lein ;; brings in its own version, and older versions of ;; lein depend on clojure 1.6. [org.clojure/clojure nil] ;; I honestly don't know why we should need this ;; But building with ezbake is consistently failing and ;; pulling in an old build of clojurescript without it. [org.clojure/clojurescript ~clojurescript-version] [puppetlabs/puppetserver ~ps-version] [puppetlabs/trapperkeeper-webserver-jetty9 nil] [org.clojure/tools.nrepl nil]] :plugins [[lein-cljsbuild ~cljsbuild-version :exclusions [org.clojure/clojurescript org.apache.commons/commons-compress]] [puppetlabs/lein-ezbake "1.8.5"]] :hooks [leiningen.cljsbuild] :name "puppetserver"} :uberjar {:aot [puppetlabs.trapperkeeper.main] :dependencies [[puppetlabs/trapperkeeper-webserver-jetty9 nil]]} :ci {:plugins [[lein-pprint "1.1.1"] [lein-exec "0.3.7"]]} :voom {:plugins [[lein-voom "0.1.0-20150115_230705-gd96d771" :exclusions [org.clojure/clojure]]]}} :test-selectors {:integration :integration :unit (complement :integration)} :aliases {"gem" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.gem" "--config" "./dev/puppetserver.conf" "--"] "ruby" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.ruby" "--config" "./dev/puppetserver.conf" "--"] "irb" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.irb" "--config" "./dev/puppetserver.conf" "--"]} :jvm-opts ["-Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger" "-XX:+UseG1GC" ~(str "-Xms" (heap-size "1G" "min")) ~(str "-Xmx" (heap-size "2G" "max")) "-XX:+IgnoreUnrecognizedVMOptions" "--add-modules=java.xml.bind" "--add-modules=java.xml.ws"] :repl-options {:init-ns dev-tools} ;; This is used to merge the locales.clj of all the dependencies into a single ;; file inside the uberjar :uberjar-merge-with {"locales.clj" [(comp read-string slurp) (fn [new prev] (if (map? prev) [new prev] (conj prev new))) #(spit %1 (pr-str %2))]} )
56825
(def ps-version "6.0.0-master-SNAPSHOT") (defn deploy-info [url] { :url url :username :env/nexus_jenkins_username :password :<PASSWORD> :sign-releases false }) (def heap-size-from-profile-clj (let [profile-clj (io/file (System/getenv "HOME") ".lein" "profiles.clj")] (if (.exists profile-clj) (-> profile-clj slurp read-string (get-in [:user :puppetserver-heap-size]))))) (defn heap-size [default-heap-size heap-size-type] (or (System/getenv "PUPPETSERVER_HEAP_SIZE") heap-size-from-profile-clj (do (println "Using" default-heap-size heap-size-type "heap since not set via PUPPETSERVER_HEAP_SIZE environment variable or" "user.puppetserver-heap-size in ~/.lein/profiles.clj file. Set to at" "least 5G for best performance during test runs.") default-heap-size))) (def figwheel-version "0.3.7") (def cljsbuild-version "1.1.7") (def clojurescript-version "1.10.238") (defproject puppetlabs/puppetserver ps-version :description "Puppet Server" :min-lein-version "2.7.1" :parent-project {:coords [puppetlabs/clj-parent "2.1.0"] :inherit [:managed-dependencies]} :dependencies [[org.clojure/clojure] ;; See SERVER-2216 [org.clojure/tools.nrepl "0.2.13"] [slingshot] [circleci/clj-yaml] [org.yaml/snakeyaml] [commons-lang] [commons-io] [clj-time] [prismatic/schema] [me.raynes/fs] [liberator] [org.apache.commons/commons-exec] [io.dropwizard.metrics/metrics-core] [com.fasterxml.jackson.module/jackson-module-afterburner] ;; We do not currently use this dependency directly, but ;; we have documentation that shows how users can use it to ;; send their logs to logstash, so we include it in the jar. ;; we may use it directly in the future ;; We are using an exlusion here because logback dependencies should ;; be inherited from trapperkeeper to avoid accidentally bringing ;; in different versions of the three different logback artifacts [net.logstash.logback/logstash-logback-encoder] [puppetlabs/jruby-utils "2.0.0"] [puppetlabs/jruby-deps "9.1.16.0-1"] ;; JRuby 1.7.x and trapperkeeper (via core.async) both bring in ;; asm dependencies. Deferring to clj-parent to resolve the version. [org.ow2.asm/asm-all] [puppetlabs/trapperkeeper] [puppetlabs/trapperkeeper-authorization] [puppetlabs/trapperkeeper-comidi-metrics] [puppetlabs/trapperkeeper-metrics] [puppetlabs/trapperkeeper-scheduler] [puppetlabs/trapperkeeper-status] [puppetlabs/kitchensink] [puppetlabs/ssl-utils] [puppetlabs/ring-middleware] [puppetlabs/dujour-version-check] [puppetlabs/http-client] [puppetlabs/comidi] [puppetlabs/i18n] ;; dependencies for clojurescript dashboard [puppetlabs/cljs-dashboard-widgets "0.1.1"] [org.clojure/clojurescript ~clojurescript-version] [cljs-http "0.1.36"]] :main puppetlabs.trapperkeeper.main :pedantic? :abort :source-paths ["src/clj"] :java-source-paths ["src/java"] :test-paths ["test/unit" "test/integration"] :resource-paths ["resources" "src/ruby" "target/js-resources"] :repositories [["releases" "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/"] ["snapshots" "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/"]] :plugins [[lein-parent "0.3.1"] [puppetlabs/i18n "0.8.0"]] :uberjar-name "puppet-server-release.jar" :lein-ezbake {:vars {:user "puppet" :group "puppet" :build-type "foss" :java-args ~(str "-Xms2g -Xmx2g " "-Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger") :create-dirs ["/opt/puppetlabs/server/data/puppetserver/jars"] :repo-target "puppet6" :nonfinal-repo-target "puppet6-nightly" :bootstrap-source :services-d :logrotate-enabled false} :resources {:dir "tmp/ezbake-resources"} :config-dir "ezbake/config" :system-config-dir "ezbake/system-config"} :deploy-repositories [["releases" ~(deploy-info "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/")] ["snapshots" ~(deploy-info "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/")]] ;; By declaring a classifier here and a corresponding profile below we'll get an additional jar ;; during `lein jar` that has all the code in the test/ directory. Downstream projects can then ;; depend on this test jar using a :classifier in their :dependencies to reuse the test utility ;; code that we have. :classifiers [["test" :testutils]] :cljsbuild {:builds {:app {:source-paths ["src/cljs"] :compiler {:output-to "target/js-resources/puppetlabs/puppetserver/public/js/puppetserver-dashboard.js" :output-dir "target/js-resources/puppetlabs/puppetserver/public/js/out" :asset-path "js/out" :optimizations :none :pretty-print true :main "puppetlabs.puppetserver.dashboard.production"}}}} :profiles {:dev {:source-paths ["dev"] :dependencies [[org.clojure/tools.namespace] [puppetlabs/trapperkeeper-webserver-jetty9 nil] [puppetlabs/trapperkeeper-webserver-jetty9 nil :classifier "test"] [puppetlabs/trapperkeeper nil :classifier "test" :scope "test"] [puppetlabs/trapperkeeper-metrics :classifier "test" :scope "test"] [puppetlabs/kitchensink nil :classifier "test" :scope "test"] [ring-basic-authentication] [ring/ring-mock] [grimradical/clj-semver "0.3.0" :exclusions [org.clojure/clojure]] [beckon] [com.cemerick/url "0.1.1"] ;; dependencies for cljs development [figwheel-sidecar "0.5.4-6" :exclusions [org.clojure/clojure]]] ;; dev profile config for clojurescript dev :plugins [[lein-cljsbuild ~cljsbuild-version :exclusions [org.clojure/clojurescript]] [lein-figwheel "0.5.4-6" :exclusions [org.clojure/clojure org.clojure/core.cache commons-io commons-codec]]] :figwheel {:http-server-root "puppetlabs/puppetserver/public" :server-port 3449 :repl false} :cljsbuild {:builds {:app {:source-paths ["dev-cljs"] :compiler {:main "puppetlabs.puppetserver.dashboard.dev" :source-map true}}}} ;; SERVER-332, enable SSLv3 for unit tests that exercise SSLv3 :jvm-opts ["-Djava.security.properties=./dev-resources/java.security"]} :testutils {:source-paths ^:replace ["test/unit" "test/integration"]} :test { ;; NOTE: In core.async version 0.2.382, the default size for ;; the core.async dispatch thread pool was reduced from ;; (42 + (2 * num-cpus)) to... eight. The jruby metrics tests ;; use core.async and need more than eight threads to run ;; properly; this setting overrides the default value. Without ;; it the metrics tests will hang. :jvm-opts ["-Dclojure.core.async.pool-size=50"] } :ezbake {:dependencies ^:replace [;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NOTE: we need to explicitly pass in `nil` values ;; for the version numbers here in order to correctly ;; inherit the versions from our parent project. ;; This is because of a bug in lein 2.7.1 that ;; prevents the deps from being processed properly ;; with `:managed-dependencies` when you specify ;; dependencies in a profile. See: ;; https://github.com/technomancy/leiningen/issues/2216 ;; Hopefully we can remove those `nil`s (if we care) ;; and this comment when lein 2.7.2 is available. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we need to explicitly pull in our parent project's ;; clojure version here, because without it, lein ;; brings in its own version, and older versions of ;; lein depend on clojure 1.6. [org.clojure/clojure nil] ;; I honestly don't know why we should need this ;; But building with ezbake is consistently failing and ;; pulling in an old build of clojurescript without it. [org.clojure/clojurescript ~clojurescript-version] [puppetlabs/puppetserver ~ps-version] [puppetlabs/trapperkeeper-webserver-jetty9 nil] [org.clojure/tools.nrepl nil]] :plugins [[lein-cljsbuild ~cljsbuild-version :exclusions [org.clojure/clojurescript org.apache.commons/commons-compress]] [puppetlabs/lein-ezbake "1.8.5"]] :hooks [leiningen.cljsbuild] :name "puppetserver"} :uberjar {:aot [puppetlabs.trapperkeeper.main] :dependencies [[puppetlabs/trapperkeeper-webserver-jetty9 nil]]} :ci {:plugins [[lein-pprint "1.1.1"] [lein-exec "0.3.7"]]} :voom {:plugins [[lein-voom "0.1.0-20150115_230705-gd96d771" :exclusions [org.clojure/clojure]]]}} :test-selectors {:integration :integration :unit (complement :integration)} :aliases {"gem" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.gem" "--config" "./dev/puppetserver.conf" "--"] "ruby" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.ruby" "--config" "./dev/puppetserver.conf" "--"] "irb" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.irb" "--config" "./dev/puppetserver.conf" "--"]} :jvm-opts ["-Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger" "-XX:+UseG1GC" ~(str "-Xms" (heap-size "1G" "min")) ~(str "-Xmx" (heap-size "2G" "max")) "-XX:+IgnoreUnrecognizedVMOptions" "--add-modules=java.xml.bind" "--add-modules=java.xml.ws"] :repl-options {:init-ns dev-tools} ;; This is used to merge the locales.clj of all the dependencies into a single ;; file inside the uberjar :uberjar-merge-with {"locales.clj" [(comp read-string slurp) (fn [new prev] (if (map? prev) [new prev] (conj prev new))) #(spit %1 (pr-str %2))]} )
true
(def ps-version "6.0.0-master-SNAPSHOT") (defn deploy-info [url] { :url url :username :env/nexus_jenkins_username :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false }) (def heap-size-from-profile-clj (let [profile-clj (io/file (System/getenv "HOME") ".lein" "profiles.clj")] (if (.exists profile-clj) (-> profile-clj slurp read-string (get-in [:user :puppetserver-heap-size]))))) (defn heap-size [default-heap-size heap-size-type] (or (System/getenv "PUPPETSERVER_HEAP_SIZE") heap-size-from-profile-clj (do (println "Using" default-heap-size heap-size-type "heap since not set via PUPPETSERVER_HEAP_SIZE environment variable or" "user.puppetserver-heap-size in ~/.lein/profiles.clj file. Set to at" "least 5G for best performance during test runs.") default-heap-size))) (def figwheel-version "0.3.7") (def cljsbuild-version "1.1.7") (def clojurescript-version "1.10.238") (defproject puppetlabs/puppetserver ps-version :description "Puppet Server" :min-lein-version "2.7.1" :parent-project {:coords [puppetlabs/clj-parent "2.1.0"] :inherit [:managed-dependencies]} :dependencies [[org.clojure/clojure] ;; See SERVER-2216 [org.clojure/tools.nrepl "0.2.13"] [slingshot] [circleci/clj-yaml] [org.yaml/snakeyaml] [commons-lang] [commons-io] [clj-time] [prismatic/schema] [me.raynes/fs] [liberator] [org.apache.commons/commons-exec] [io.dropwizard.metrics/metrics-core] [com.fasterxml.jackson.module/jackson-module-afterburner] ;; We do not currently use this dependency directly, but ;; we have documentation that shows how users can use it to ;; send their logs to logstash, so we include it in the jar. ;; we may use it directly in the future ;; We are using an exlusion here because logback dependencies should ;; be inherited from trapperkeeper to avoid accidentally bringing ;; in different versions of the three different logback artifacts [net.logstash.logback/logstash-logback-encoder] [puppetlabs/jruby-utils "2.0.0"] [puppetlabs/jruby-deps "9.1.16.0-1"] ;; JRuby 1.7.x and trapperkeeper (via core.async) both bring in ;; asm dependencies. Deferring to clj-parent to resolve the version. [org.ow2.asm/asm-all] [puppetlabs/trapperkeeper] [puppetlabs/trapperkeeper-authorization] [puppetlabs/trapperkeeper-comidi-metrics] [puppetlabs/trapperkeeper-metrics] [puppetlabs/trapperkeeper-scheduler] [puppetlabs/trapperkeeper-status] [puppetlabs/kitchensink] [puppetlabs/ssl-utils] [puppetlabs/ring-middleware] [puppetlabs/dujour-version-check] [puppetlabs/http-client] [puppetlabs/comidi] [puppetlabs/i18n] ;; dependencies for clojurescript dashboard [puppetlabs/cljs-dashboard-widgets "0.1.1"] [org.clojure/clojurescript ~clojurescript-version] [cljs-http "0.1.36"]] :main puppetlabs.trapperkeeper.main :pedantic? :abort :source-paths ["src/clj"] :java-source-paths ["src/java"] :test-paths ["test/unit" "test/integration"] :resource-paths ["resources" "src/ruby" "target/js-resources"] :repositories [["releases" "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/"] ["snapshots" "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/"]] :plugins [[lein-parent "0.3.1"] [puppetlabs/i18n "0.8.0"]] :uberjar-name "puppet-server-release.jar" :lein-ezbake {:vars {:user "puppet" :group "puppet" :build-type "foss" :java-args ~(str "-Xms2g -Xmx2g " "-Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger") :create-dirs ["/opt/puppetlabs/server/data/puppetserver/jars"] :repo-target "puppet6" :nonfinal-repo-target "puppet6-nightly" :bootstrap-source :services-d :logrotate-enabled false} :resources {:dir "tmp/ezbake-resources"} :config-dir "ezbake/config" :system-config-dir "ezbake/system-config"} :deploy-repositories [["releases" ~(deploy-info "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/")] ["snapshots" ~(deploy-info "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/")]] ;; By declaring a classifier here and a corresponding profile below we'll get an additional jar ;; during `lein jar` that has all the code in the test/ directory. Downstream projects can then ;; depend on this test jar using a :classifier in their :dependencies to reuse the test utility ;; code that we have. :classifiers [["test" :testutils]] :cljsbuild {:builds {:app {:source-paths ["src/cljs"] :compiler {:output-to "target/js-resources/puppetlabs/puppetserver/public/js/puppetserver-dashboard.js" :output-dir "target/js-resources/puppetlabs/puppetserver/public/js/out" :asset-path "js/out" :optimizations :none :pretty-print true :main "puppetlabs.puppetserver.dashboard.production"}}}} :profiles {:dev {:source-paths ["dev"] :dependencies [[org.clojure/tools.namespace] [puppetlabs/trapperkeeper-webserver-jetty9 nil] [puppetlabs/trapperkeeper-webserver-jetty9 nil :classifier "test"] [puppetlabs/trapperkeeper nil :classifier "test" :scope "test"] [puppetlabs/trapperkeeper-metrics :classifier "test" :scope "test"] [puppetlabs/kitchensink nil :classifier "test" :scope "test"] [ring-basic-authentication] [ring/ring-mock] [grimradical/clj-semver "0.3.0" :exclusions [org.clojure/clojure]] [beckon] [com.cemerick/url "0.1.1"] ;; dependencies for cljs development [figwheel-sidecar "0.5.4-6" :exclusions [org.clojure/clojure]]] ;; dev profile config for clojurescript dev :plugins [[lein-cljsbuild ~cljsbuild-version :exclusions [org.clojure/clojurescript]] [lein-figwheel "0.5.4-6" :exclusions [org.clojure/clojure org.clojure/core.cache commons-io commons-codec]]] :figwheel {:http-server-root "puppetlabs/puppetserver/public" :server-port 3449 :repl false} :cljsbuild {:builds {:app {:source-paths ["dev-cljs"] :compiler {:main "puppetlabs.puppetserver.dashboard.dev" :source-map true}}}} ;; SERVER-332, enable SSLv3 for unit tests that exercise SSLv3 :jvm-opts ["-Djava.security.properties=./dev-resources/java.security"]} :testutils {:source-paths ^:replace ["test/unit" "test/integration"]} :test { ;; NOTE: In core.async version 0.2.382, the default size for ;; the core.async dispatch thread pool was reduced from ;; (42 + (2 * num-cpus)) to... eight. The jruby metrics tests ;; use core.async and need more than eight threads to run ;; properly; this setting overrides the default value. Without ;; it the metrics tests will hang. :jvm-opts ["-Dclojure.core.async.pool-size=50"] } :ezbake {:dependencies ^:replace [;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NOTE: we need to explicitly pass in `nil` values ;; for the version numbers here in order to correctly ;; inherit the versions from our parent project. ;; This is because of a bug in lein 2.7.1 that ;; prevents the deps from being processed properly ;; with `:managed-dependencies` when you specify ;; dependencies in a profile. See: ;; https://github.com/technomancy/leiningen/issues/2216 ;; Hopefully we can remove those `nil`s (if we care) ;; and this comment when lein 2.7.2 is available. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; we need to explicitly pull in our parent project's ;; clojure version here, because without it, lein ;; brings in its own version, and older versions of ;; lein depend on clojure 1.6. [org.clojure/clojure nil] ;; I honestly don't know why we should need this ;; But building with ezbake is consistently failing and ;; pulling in an old build of clojurescript without it. [org.clojure/clojurescript ~clojurescript-version] [puppetlabs/puppetserver ~ps-version] [puppetlabs/trapperkeeper-webserver-jetty9 nil] [org.clojure/tools.nrepl nil]] :plugins [[lein-cljsbuild ~cljsbuild-version :exclusions [org.clojure/clojurescript org.apache.commons/commons-compress]] [puppetlabs/lein-ezbake "1.8.5"]] :hooks [leiningen.cljsbuild] :name "puppetserver"} :uberjar {:aot [puppetlabs.trapperkeeper.main] :dependencies [[puppetlabs/trapperkeeper-webserver-jetty9 nil]]} :ci {:plugins [[lein-pprint "1.1.1"] [lein-exec "0.3.7"]]} :voom {:plugins [[lein-voom "0.1.0-20150115_230705-gd96d771" :exclusions [org.clojure/clojure]]]}} :test-selectors {:integration :integration :unit (complement :integration)} :aliases {"gem" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.gem" "--config" "./dev/puppetserver.conf" "--"] "ruby" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.ruby" "--config" "./dev/puppetserver.conf" "--"] "irb" ["trampoline" "run" "-m" "puppetlabs.puppetserver.cli.irb" "--config" "./dev/puppetserver.conf" "--"]} :jvm-opts ["-Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger" "-XX:+UseG1GC" ~(str "-Xms" (heap-size "1G" "min")) ~(str "-Xmx" (heap-size "2G" "max")) "-XX:+IgnoreUnrecognizedVMOptions" "--add-modules=java.xml.bind" "--add-modules=java.xml.ws"] :repl-options {:init-ns dev-tools} ;; This is used to merge the locales.clj of all the dependencies into a single ;; file inside the uberjar :uberjar-merge-with {"locales.clj" [(comp read-string slurp) (fn [new prev] (if (map? prev) [new prev] (conj prev new))) #(spit %1 (pr-str %2))]} )
[ { "context": "--------------\n;; rel\n\n(defrel man p)\n\n(fact man 'Bob)\n(fact man 'John)\n(fact man 'Ricky)\n\n(defrel woma", "end": 24411, "score": 0.9926538467407227, "start": 24408, "tag": "NAME", "value": "Bob" }, { "context": "; rel\n\n(defrel man p)\n\n(fact man 'Bob)\n(fact man 'John)\n(fact man 'Ricky)\n\n(defrel woman p)\n(fact woman ", "end": 24428, "score": 0.9985897541046143, "start": 24424, "tag": "NAME", "value": "John" }, { "context": "n p)\n\n(fact man 'Bob)\n(fact man 'John)\n(fact man 'Ricky)\n\n(defrel woman p)\n(fact woman 'Mary)\n(fact woman", "end": 24446, "score": 0.995945394039154, "start": 24441, "tag": "NAME", "value": "Ricky" }, { "context": "\n(fact man 'Ricky)\n\n(defrel woman p)\n(fact woman 'Mary)\n(fact woman 'Martha)\n(fact woman 'Lucy)\n\n(defrel", "end": 24483, "score": 0.977441668510437, "start": 24479, "tag": "NAME", "value": "Mary" }, { "context": "\n(defrel woman p)\n(fact woman 'Mary)\n(fact woman 'Martha)\n(fact woman 'Lucy)\n\n(defrel likes p1 p2)\n(fact l", "end": 24504, "score": 0.9924919605255127, "start": 24498, "tag": "NAME", "value": "Martha" }, { "context": "ct woman 'Mary)\n(fact woman 'Martha)\n(fact woman 'Lucy)\n\n(defrel likes p1 p2)\n(fact likes 'Bob 'Mary)\n(f", "end": 24523, "score": 0.9727927446365356, "start": 24519, "tag": "NAME", "value": "Lucy" }, { "context": "t woman 'Lucy)\n\n(defrel likes p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ri", "end": 24563, "score": 0.9956454038619995, "start": 24560, "tag": "NAME", "value": "Bob" }, { "context": "an 'Lucy)\n\n(defrel likes p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'L", "end": 24569, "score": 0.9944467544555664, "start": 24565, "tag": "NAME", "value": "Mary" }, { "context": "likes p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p", "end": 24588, "score": 0.9971082210540771, "start": 24584, "tag": "NAME", "value": "John" }, { "context": "p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact ", "end": 24596, "score": 0.9969124794006348, "start": 24590, "tag": "NAME", "value": "Martha" }, { "context": "ob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact fun 'Lucy)\n\n(deftest", "end": 24616, "score": 0.9850430488586426, "start": 24611, "tag": "NAME", "value": "Ricky" }, { "context": "y)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact fun 'Lucy)\n\n(deftest test-", "end": 24622, "score": 0.9836830496788025, "start": 24618, "tag": "NAME", "value": "Lucy" }, { "context": "ct likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact fun 'Lucy)\n\n(deftest test-rel-1\n (is (= (run* [q]\n ", "end": 24655, "score": 0.9403823614120483, "start": 24651, "tag": "NAME", "value": "Lucy" }, { "context": " (fun y)\n (== q [x y])))\n '([Ricky Lucy]))))\n\n;; -----------------------------------", "end": 24812, "score": 0.8625386953353882, "start": 24807, "tag": "NAME", "value": "Ricky" }, { "context": "n y)\n (== q [x y])))\n '([Ricky Lucy]))))\n\n;; ----------------------------------------", "end": 24817, "score": 0.8570965528488159, "start": 24813, "tag": "NAME", "value": "Lucy" } ]
src/test/clojure/clojure/core/logic/tests.clj
cgrand/core.logic
1
(ns clojure.core.logic.tests (:refer-clojure :exclude [==]) (:use [clojure.core.logic :exclude [is]] :reload) (:use clojure.test)) ;; ============================================================================= ;; unify ;; ----------------------------------------------------------------------------- ;; nil (deftest unify-nil-object-1 (is (= (unify empty-s nil 1) false))) (deftest unify-nil-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x nil)] (is (= (unify empty-s nil x) os)))) (deftest unify-nil-lseq-1 (let [x (lvar 'x)] (is (= (unify empty-s nil (lcons 1 x)) false)))) (deftest unify-nil-map-1 (let [x (lvar 'x)] (is (= (unify empty-s nil {}) false)))) (deftest unify-nil-set-1 (let [x (lvar 'x)] (is (= (unify empty-s nil #{}) false)))) ;; ----------------------------------------------------------------------------- ;; object (deftest unify-object-nil-1 (is (= (unify empty-s 1 nil)))) (deftest unify-object-object-1 (is (= (unify empty-s 1 1) empty-s))) (deftest unify-object-object-2 (is (= (unify empty-s :foo :foo) empty-s))) (deftest unify-object-object-3 (is (= (unify empty-s 'foo 'foo) empty-s))) (deftest unify-object-object-4 (is (= (unify empty-s "foo" "foo") empty-s))) (deftest unify-object-object-5 (is (= (unify empty-s 1 2) false))) (deftest unify-object-object-6 (is (= (unify empty-s 2 1) false))) (deftest unify-object-object-7 (is (= (unify empty-s :foo :bar) false))) (deftest unify-object-object-8 (is (= (unify empty-s 'foo 'bar) false))) (deftest unify-object-object-9 (is (= (unify empty-s "foo" "bar") false))) (deftest unify-object-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s 1 x) os)))) (deftest unify-object-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s 1 (lcons 1 'x)) false)))) (deftest unify-object-seq-1 (is (= (unify empty-s 1 '()) false))) (deftest unify-object-seq-2 (is (= (unify empty-s 1 '[]) false))) (deftest unify-object-map-1 (is (= (unify empty-s 1 {}) false))) (deftest unify-object-set-1 (is (= (unify empty-s 1 #{}) false))) ;; ----------------------------------------------------------------------------- ;; lvar (deftest unify-lvar-object-1 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s x 1) os)))) (deftest unify-lvar-lvar-1 (let [x (lvar 'x) y (lvar 'y) os (ext-no-check empty-s x y)] (is (= (unify empty-s x y) os)))) (deftest unify-lvar-lcons-1 (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (ext-no-check empty-s x l)] (is (= (unify empty-s x l) os)))) (deftest unify-lvar-seq-1 (let [x (lvar 'x) os (ext-no-check empty-s x [])] (is (= (unify empty-s x []) os)))) (deftest unify-lvar-seq-2 (let [x (lvar 'x) os (ext-no-check empty-s x [1 2 3])] (is (= (unify empty-s x [1 2 3]) os)))) (deftest unify-lvar-seq-3 (let [x (lvar 'x) os (ext-no-check empty-s x '())] (is (= (unify empty-s x '()) os)))) (deftest unify-lvar-seq-4 (let [x (lvar 'x) os (ext-no-check empty-s x '(1 2 3))] (is (= (unify empty-s x '(1 2 3)) os)))) (deftest unify-lvar-map-1 (let [x (lvar 'x) os (ext-no-check empty-s x {})] (is (= (unify empty-s x {}) os)))) (deftest unify-lvar-map-2 (let [x (lvar 'x) os (ext-no-check empty-s x {1 2 3 4})] (is (= (unify empty-s x {1 2 3 4}) os)))) (deftest unify-lvar-set-1 (let [x (lvar 'x) os (ext-no-check empty-s x #{})] (is (= (unify empty-s x #{}) os)))) (deftest unify-lvar-set-2 (let [x (lvar 'x) os (ext-no-check empty-s x #{1 2 3})] (is (= (unify empty-s x #{1 2 3}) os)))) ;; ----------------------------------------------------------------------------- ;; lcons (deftest unify-lcons-object-1 (let [x (lvar 'x)] (is (= (unify empty-s (lcons 1 x) 1) false)))) (deftest unify-lcons-lvar-1 (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (ext-no-check empty-s x l)] (is (= (unify empty-s l x) os)))) (deftest unify-lcons-lcons-1 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 x) lc2 (lcons 1 y) os (ext-no-check empty-s x y)] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-2 (let [x (lvar 'x) y (lvar 'y) z (lvar 'z) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons z y)) os (-> empty-s (ext-no-check x y) (ext-no-check z 2))] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-3 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 (lcons 3 y))) os (ext-no-check empty-s x (lcons 3 y))] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-4 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 3 (lcons 4 y)))] (is (= (unify empty-s lc1 lc2) false)))) (deftest unify-lcons-lcons-5 (let [x (lvar 'x) y (lvar 'y) lc2 (lcons 1 (lcons 2 x)) lc1 (lcons 1 (lcons 3 (lcons 4 y)))] (is (= (unify empty-s lc1 lc2) false)))) (deftest unify-lcons-lcons-6 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 y)) os (ext-no-check empty-s x y)] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-seq-1 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (ext-no-check empty-s x '(3 4))] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-2 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons y (lcons 3 x))) l1 '(1 2 3 4) os (-> empty-s (ext-no-check x '(4)) (ext-no-check y 2))] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-3 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 (lcons 3 x))) l1 '(1 2 3) os (ext-no-check empty-s x '())] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-4 (let [x (lvar 'x) lc1 (lcons 1 (lcons 3 x)) l1 '(1 2 3 4)] (is (= (unify empty-s lc1 l1) false)))) (deftest unify-lcons-seq-5 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 3 4 5)] (is (= (unify empty-s lc1 l1) false)))) (deftest unify-lcons-map-1 (is (= (unify empty-s (lcons 1 (lvar 'x)) {}) false))) (deftest unify-lcons-set-1 (is (= (unify empty-s (lcons 1 (lvar 'x)) #{}) false))) ;; ----------------------------------------------------------------------------- ;; seq (deftest unify-seq-object-1 (is (= (unify empty-s '() 1) false))) (deftest unify-seq-object-2 (is (= (unify empty-s [] 1) false))) (deftest unify-seq-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x [])] (is (= (unify empty-s [] x) os)))) (deftest unify-seq-lcons-1 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (ext-no-check empty-s x '(3 4))] (is (= (unify empty-s l1 lc1) os)))) (deftest unify-seq-seq-1 (is (= (unify empty-s [1 2 3] [1 2 3]) empty-s))) (deftest unify-seq-seq-2 (is (= (unify empty-s '(1 2 3) [1 2 3]) empty-s))) (deftest unify-seq-seq-3 (is (= (unify empty-s '(1 2 3) '(1 2 3)) empty-s))) (deftest unify-seq-seq-4 (let [x (lvar 'x) os (ext-no-check empty-s x 2)] (is (= (unify empty-s `(1 ~x 3) `(1 2 3)) os)))) (deftest unify-seq-seq-5 (is (= (unify empty-s [1 2] [1 2 3]) false))) (deftest unify-seq-seq-6 (is (= (unify empty-s '(1 2) [1 2 3]) false))) (deftest unify-seq-seq-7 (is (= (unify empty-s [1 2 3] [3 2 1]) false))) (deftest unify-seq-seq-8 (is (= (unify empty-s '() '()) empty-s))) (deftest unify-seq-seq-9 (is (= (unify empty-s '() '(1)) false))) (deftest unify-seq-seq-10 (is (= (unify empty-s '(1) '()) false))) (deftest unify-seq-seq-11 (is (= (unify empty-s [[1 2]] [[1 2]]) empty-s))) (deftest unify-seq-seq-12 (is (= (unify empty-s [[1 2]] [[2 1]]) false))) (deftest unify-seq-seq-13 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s [[x 2]] [[1 2]]) os)))) (deftest unify-seq-seq-14 (let [x (lvar 'x) os (ext-no-check empty-s x [1 2])] (is (= (unify empty-s [x] [[1 2]]) os)))) (deftest unify-seq-seq-15 (let [x (lvar 'x) y (lvar 'y) u (lvar 'u) v (lvar 'v) os (-> empty-s (ext-no-check x 'b) (ext-no-check y 'a))] (is (= (unify empty-s ['a x] [y 'b]) os)))) (deftest unify-seq-map-1 (is (= (unify empty-s [] {}) false))) (deftest unify-seq-map-2 (is (= (unify empty-s '() {}) false))) (deftest unify-seq-set-1 (is (= (unify empty-s [] #{}) false))) (deftest unify-seq-set-2 (is (= (unify empty-s '() #{}) false))) ;; ----------------------------------------------------------------------------- ;; map (deftest unify-map-object-1 (is (= (unify empty-s {} 1) false))) (deftest unify-map-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x {})] (is (= (unify empty-s {} x) os)))) (deftest unify-map-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s {} (lcons 1 x)) false)))) (deftest unify-map-seq-1 (is (= (unify empty-s {} '()) false))) (deftest unify-map-map-1 (is (= (unify empty-s {} {}) empty-s))) (deftest unify-map-map-2 (is (= (unify empty-s {1 2 3 4} {1 2 3 4}) empty-s))) (deftest unify-map-map-3 (is (= (unify empty-s {1 2} {1 2 3 4}) false))) (deftest unify-map-map-4 (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 2 3 x} os (ext-no-check empty-s x 4)] (is (= (unify empty-s m1 m2) os)))) (deftest unify-map-map-5 (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 4 3 x}] (is (= (unify empty-s m1 m2) false)))) (deftest unify-map-set-1 (is (= (unify empty-s {} #{}) false))) ;; ----------------------------------------------------------------------------- ;; set (deftest unify-set-object-1 (is (= (unify empty-s #{} 1) false))) (deftest unify-set-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x #{})] (is (= (unify empty-s #{} x) os)))) (deftest unify-set-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s #{} (lcons 1 x)) false)))) (deftest unify-set-seq-1 (is (= (unify empty-s #{} '()) false))) (deftest unify-set-map-1 (is (= (unify empty-s #{} {}) false))) (deftest unify-set-set-1 (is (= (unify empty-s #{} #{}) empty-s))) (deftest unify-set-set-2 (is (= (unify empty-s #{} #{1}) false))) (deftest unify-set-set-3 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s #{x} #{1}) os)))) (deftest unify-set-set-4 (let [x (lvar 'x) y (lvar 'y) os (-> empty-s (ext-no-check x 2) (ext-no-check y 1))] (is (= (unify empty-s #{1 x} #{2 y}) os)))) (deftest unify-set-set-5 (let [x (lvar 'x) y (lvar 'y) os (-> empty-s (ext-no-check x 2) (ext-no-check y 1))] (is (= (unify empty-s #{x 1} #{2 y}) os)))) (deftest unify-set-set-6 (let [a (lvar 'a) b (lvar 'b) c (lvar 'c) d (lvar 'd) s (.s (unify empty-s #{a b 3 4 5} #{1 2 3 c d}))] (is (and (= (count s) 4) (= (set (keys s)) #{a b c d}) (= (set (vals s)) #{1 2 4 5}))))) (deftest unify-set-set-7 (let [a (lvar 'a) b (lvar 'b) c (lvar 'c) d (lvar 'd)] (is (= (unify empty-s #{a b 9 4 5} #{1 2 3 c d}) false)))) ;; ============================================================================= ;; walk (deftest test-basic-walk (is (= (let [x (lvar 'x) y (lvar 'y) ss (to-s [[x 5] [y x]])] (walk ss y)) 5))) (deftest test-deep-walk (is (= (let [[x y z c b a :as s] (map lvar '[x y z c b a]) ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (walk ss a)) 5))) ;; ============================================================================= ;; reify (deftest test-reify-lvar-name (is (= (let [x (lvar 'x) y (lvar 'y)] (reify-lvar-name (to-s [[x 5] [y x]]))) '_.2))) ;; ============================================================================= ;; walk* (deftest test-walk* (is (= (let [x (lvar 'x) y (lvar 'y)] (walk* (to-s [[x 5] [y x]]) `(~x ~y))) '(5 5)))) ;; ============================================================================= ;; run and unify (deftest test-basic-unify (is (= (run* [q] (== true q)) '(true)))) (deftest test-basic-unify-2 (is (= (run* [q] (fresh [x y] (== [x y] [1 5]) (== [x y] q))) [[1 5]]))) (deftest test-basic-unify-3 (is (= (run* [q] (fresh [x y] (== [x y] q))) '[[_.0 _.1]]))) ;; ============================================================================= ;; fail (deftest test-basic-failure (is (= (run* [q] fail (== true q)) []))) ;; ============================================================================= ;; Basic (deftest test-all (is (= (run* [q] (all (== 1 1) (== q true))) '(true)))) ;; ============================================================================= ;; TRS (defn pairo [p] (fresh [a d] (== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) s#] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (defn rembero [x l out] (conde [(== '() l) (== '() out)] [(fresh [a d] (conso a d l) (== x a) (== d out))] [(fresh [a d res] (conso a d l) (conso a res out) (rembero x d res))])) ;; ============================================================================= ;; conde (deftest test-basic-conde (is (= (run* [x] (conde [(== x 'olive) succeed] [succeed succeed] [(== x 'oil) succeed])) '[olive _.0 oil]))) (deftest test-basic-conde-2 (is (= (run* [r] (fresh [x y] (conde [(== 'split x) (== 'pea y)] [(== 'navy x) (== 'bean y)]) (== (cons x (cons y ())) r))) '[(split pea) (navy bean)]))) (defn teacupo [x] (conde [(== 'tea x) s#] [(== 'cup x) s#])) (deftest test-basic-conde-e-3 (is (= (run* [r] (fresh [x y] (conde [(teacupo x) (== true y) s#] [(== false x) (== true y)]) (== (cons x (cons y ())) r))) '((false true) (tea true) (cup true))))) ;; ============================================================================= ;; conso (deftest test-conso (is (= (run* [q] (fresh [a d] (conso a d '()) (== (cons a d) q)) [])))) (deftest test-conso-1 (let [a (lvar 'a) d (lvar 'd)] (is (= (run* [q] (conso a d q)) [(lcons a d)])))) (deftest test-conso-2 (is (= (run* [q] (== [q] nil)) []))) (deftest test-conso-3 (is (= (run* [q] (conso 'a nil q)) '[(a)]))) (deftest test-conso-4 (is (= (run* [q] (conso 'a '(d) q)) '[(a d)]))) (deftest test-conso-empty-list (is (= (run* [q] (conso 'a q '(a))) '[()]))) (deftest test-conso-5 (is (= (run* [q] (conso q '(b c) '(a b c))) '[a]))) ;; ============================================================================= ;; firsto (deftest test-firsto (is (= (run* [q] (firsto q '(1 2))) (list (lcons '(1 2) (lvar 'x)))))) ;; ============================================================================= ;; resto (deftest test-resto (is (= (run* [q] (resto q '(1 2))) '[(_.0 1 2)]))) (deftest test-resto-2 (is (= (run* [q] (resto q [1 2])) '[(_.0 1 2)]))) (deftest test-resto-3 (is (= (run* [q] (resto [1 2] q)) '[(2)]))) (deftest test-resto-4 (is (= (run* [q] (resto [1 2 3 4 5 6 7 8] q)) '[(2 3 4 5 6 7 8)]))) ;; ============================================================================= ;; flatteno (deftest test-flatteno (is (= (run* [x] (flatteno '[[a b] c] x)) '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ()))))) ;; ============================================================================= ;; membero (deftest membero-1 (is (= (run* [q] (all (== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]])))) (deftest membero-2 (is (= (run* [q] (all (== q [(lvar) (lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar] _.0] [[foo _.0] [_.1 bar]] [[_.0 bar] [foo _.1]] [_.0 [foo bar]])))) ;; ----------------------------------------------------------------------------- ;; rembero (deftest rembero-1 (is (= (run 1 [q] (rembero 'b '(a b c b d) q)) '((a c b d))))) ;; ----------------------------------------------------------------------------- ;; conde clause count (defn digit-1 [x] (conde [(== 0 x)])) (defn digit-4 [x] (conde [(== 0 x)] [(== 1 x)] [(== 2 x)] [(== 3 x)])) (deftest test-conde-1-clause (is (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (== q [x y]))) '([0 0])))) (deftest test-conde-4-clauses (is (= (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (== q [x y]))) '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3])))) ;; ----------------------------------------------------------------------------- ;; anyo (defn anyo [q] (conde [q s#] [(anyo q)])) (deftest test-anyo-1 (is (= (run 1 [q] (anyo s#) (== true q)) (list true)))) (deftest test-anyo-2 (is (= (run 5 [q] (anyo s#) (== true q)) (list true true true true true)))) ;; ----------------------------------------------------------------------------- ;; divergence (def f1 (fresh [] f1)) (deftest test-divergence-1 (is (= (run 1 [q] (conde [f1] [(== false false)])) '(_.0)))) (deftest test-divergence-2 (is (= (run 1 [q] (conde [f1 (== false false)] [(== false false)])) '(_.0)))) (def f2 (fresh [] (conde [f2 (conde [f2] [(== false false)])] [(== false false)]))) (deftest test-divergence-3 (is (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0)))) ;; ----------------------------------------------------------------------------- ;; conda (soft-cut) (deftest test-conda-1 (is (= (run* [x] (conda [(== 'olive x) s#] [(== 'oil x) s#] [u#])) '(olive)))) (deftest test-conda-2 (is (= (run* [x] (conda [(== 'virgin x) u#] [(== 'olive x) s#] [(== 'oil x) s#] [u#])) '()))) (deftest test-conda-3 (is (= (run* [x] (fresh (x y) (== 'split x) (== 'pea y) (conda [(== 'split x) (== x y)] [s#])) (== true x)) '()))) (deftest test-conda-4 (is (= (run* [x] (fresh (x y) (== 'split x) (== 'pea y) (conda [(== x y) (== 'split x)] [s#])) (== true x)) '(true)))) (defn not-pastao [x] (conda [(== 'pasta x) u#] [s#])) (deftest test-conda-5 (is (= (run* [x] (conda [(not-pastao x)] [(== 'spaghetti x)])) '(spaghetti)))) ;; ----------------------------------------------------------------------------- ;; condu (committed-choice) (defn onceo [g] (condu (g s#))) (deftest test-condu-1 (is (= (run* [x] (onceo (teacupo x))) '(tea)))) (deftest test-condu-2 (is (= (run* [r] (conde [(teacupo r) s#] [(== false r) s#])) '(false tea cup)))) (deftest test-condu-3 (is (= (run* [r] (conda [(teacupo r) s#] [(== false r) s#])) '(tea cup)))) ;; ----------------------------------------------------------------------------- ;; disequality (deftest test-disequality-1 (is (= (run* [q] (fresh [x] (!= x 1) (== q x))) '(_.0)))) (deftest test-disequality-2 (is (= (run* [q] (fresh [x] (== q x) (!= x 1))) '(_.0)))) (deftest test-disequality-3 (is (= (run* [q] (fresh [x] (!= x 1) (== x 1) (== q x))) ()))) (deftest test-disequality-4 (is (= (run* [q] (fresh [x] (== x 1) (!= x 1) (== q x))) ()))) (deftest test-disequality-5 (is (= (run* [q] (fresh [x y] (!= x y) (== x 1) (== y 1) (== q x))) ()))) (deftest test-disequality-6 (is (= (run* [q] (fresh [x y] (== x 1) (== y 1) (!= x y) (== q x))) ()))) (deftest test-disequality-7 (is (= (run* [q] (fresh [x y] (== x 1) (!= x y) (== y 2) (== q x))) '(1)))) (deftest test-disequality-8 (is (= (run* [q] (fresh [x y] (!= [x 2] [y 1]) (== x 1) (== y 3) (== q [x y]))) '([1 3])))) (deftest test-disequality-9 (is (= (run* [q] (fresh [x y] (== x 1) (== y 3) (!= [x 2] [y 1]) (== q [x y]))) '([1 3])))) (deftest test-disequality-10 (is (= (run* [q] (fresh [x y] (!= [x 2] [1 y]) (== x 1) (== y 2) (== q [x y]))) ()))) (deftest test-disequality-11 (is (= (run* [q] (fresh [x y] (== x 1) (== y 2) (!= [x 2] [1 y]) (== q [x y]))) ()))) (deftest test-disequality-12 (is (= (run* [q] (fresh [x y z] (!= x y) (== y z) (== x z) (== q x))) ()))) (deftest test-disequality-13 (is (= (run* [q] (fresh [x y z] (== y z) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-14 (is (= (run* [q] (fresh [x y z] (== z y) (== x z) (!= x y) (== q x))) ()))) ;; ----------------------------------------------------------------------------- ;; tabled (defne arco [x y] ([:a :b]) ([:b :a]) ([:b :d])) (def patho (tabled [x y] (conde [(arco x y)] [(fresh [z] (arco x z) (patho z y))]))) (deftest test-tabled-1 (is (= (run* [q] (patho :a q)) '(:b :a :d)))) (defne arco-2 [x y] ([1 2]) ([1 4]) ([1 3]) ([2 3]) ([2 5]) ([3 4]) ([3 5]) ([4 5])) (def patho-2 (tabled [x y] (conde [(arco-2 x y)] [(fresh [z] (arco-2 x z) (patho-2 z y))]))) (deftest test-tabled-2 (let [r (set (run* [q] (patho-2 1 q)))] (is (and (= (count r) 4) (= r #{2 3 4 5}))))) ;; ----------------------------------------------------------------------------- ;; rel (defrel man p) (fact man 'Bob) (fact man 'John) (fact man 'Ricky) (defrel woman p) (fact woman 'Mary) (fact woman 'Martha) (fact woman 'Lucy) (defrel likes p1 p2) (fact likes 'Bob 'Mary) (fact likes 'John 'Martha) (fact likes 'Ricky 'Lucy) (defrel fun p) (fact fun 'Lucy) (deftest test-rel-1 (is (= (run* [q] (fresh [x y] (likes x y) (fun y) (== q [x y]))) '([Ricky Lucy])))) ;; ----------------------------------------------------------------------------- ;; nil in collection (deftest test-nil-in-coll-1 (is (= (run* [q] (== q [nil])) '([nil])))) (deftest test-nil-in-coll-2 (is (= (run* [q] (== q [1 nil])) '([1 nil])))) (deftest test-nil-in-coll-3 (is (= (run* [q] (== q [nil 1])) '([nil 1])))) (deftest test-nil-in-coll-4 (is (= (run* [q] (== q '(nil))) '((nil))))) (deftest test-nil-in-coll-5 (is (= (run* [q] (== q {:foo nil})) '({:foo nil})))) (deftest test-nil-in-coll-6 (is (= (run* [q] (== q {nil :foo})) '({nil :foo})))) ;; ----------------------------------------------------------------------------- ;; Unifier (deftest test-unifier-1 (is (= (unifier '(?x ?y) '(1 2)) '(1 2)))) (deftest test-unifier-2 (is (= (unifier '(?x ?y 3) '(1 2 ?z)) '(1 2 3)))) (deftest test-unifier-3 (is (= (unifier '[(?x . ?y) 3] [[1 2] 3]) '[(1 2) 3]))) (deftest test-unifier-4 (is (= (unifier '(?x . ?y) '(1 . ?z)) (lcons 1 '_.0)))) (deftest test-unifier-5 (is (= (unifier '(?x 2 . ?y) '(1 2 3 4 5)) '(1 2 3 4 5)))) (deftest test-unifier-6 (is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5)) nil))) (deftest test-binding-map-1 (is (= (binding-map '(?x ?y) '(1 2)) '{?x 1 ?y 2}))) (deftest test-binding-map-2 (is (= (binding-map '(?x ?y 3) '(1 2 ?z)) '{?x 1 ?y 2 ?z 3}))) (deftest test-binding-map-3 (is (= (binding-map '[(?x . ?y) 3] [[1 2] 3]) '{?x 1 ?y (2)}))) (deftest test-binding-map-4 (is (= (binding-map '(?x . ?y) '(1 . ?z)) '{?z _.0, ?x 1, ?y _.0}))) (deftest test-binding-map-5 (is (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5)) '{?x 1 ?y (3 4 5)}))) (deftest test-binding-map-6 (is (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5)) nil))) ;; ----------------------------------------------------------------------------- ;; Occurs Check (deftest test-occurs-check-1 (is (= (run* [q] (== q [q])) ()))) ;; ----------------------------------------------------------------------------- ;; Unifications that should fail (deftest test-unify-fail-1 (is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-2 (is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-3 (is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d]))) ()))) ;; ----------------------------------------------------------------------------- ;; Pattern matching functions preserve metadata (defne ^:tabled dummy "Docstring" [x l] ([_ [x . tail]]) ([_ [head . tail]] (membero x tail))) (deftest test-metadata-defne (is (= (-> #'dummy meta :tabled) true)) (is (= (-> #'dummy meta :doc) "Docstring")))
63500
(ns clojure.core.logic.tests (:refer-clojure :exclude [==]) (:use [clojure.core.logic :exclude [is]] :reload) (:use clojure.test)) ;; ============================================================================= ;; unify ;; ----------------------------------------------------------------------------- ;; nil (deftest unify-nil-object-1 (is (= (unify empty-s nil 1) false))) (deftest unify-nil-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x nil)] (is (= (unify empty-s nil x) os)))) (deftest unify-nil-lseq-1 (let [x (lvar 'x)] (is (= (unify empty-s nil (lcons 1 x)) false)))) (deftest unify-nil-map-1 (let [x (lvar 'x)] (is (= (unify empty-s nil {}) false)))) (deftest unify-nil-set-1 (let [x (lvar 'x)] (is (= (unify empty-s nil #{}) false)))) ;; ----------------------------------------------------------------------------- ;; object (deftest unify-object-nil-1 (is (= (unify empty-s 1 nil)))) (deftest unify-object-object-1 (is (= (unify empty-s 1 1) empty-s))) (deftest unify-object-object-2 (is (= (unify empty-s :foo :foo) empty-s))) (deftest unify-object-object-3 (is (= (unify empty-s 'foo 'foo) empty-s))) (deftest unify-object-object-4 (is (= (unify empty-s "foo" "foo") empty-s))) (deftest unify-object-object-5 (is (= (unify empty-s 1 2) false))) (deftest unify-object-object-6 (is (= (unify empty-s 2 1) false))) (deftest unify-object-object-7 (is (= (unify empty-s :foo :bar) false))) (deftest unify-object-object-8 (is (= (unify empty-s 'foo 'bar) false))) (deftest unify-object-object-9 (is (= (unify empty-s "foo" "bar") false))) (deftest unify-object-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s 1 x) os)))) (deftest unify-object-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s 1 (lcons 1 'x)) false)))) (deftest unify-object-seq-1 (is (= (unify empty-s 1 '()) false))) (deftest unify-object-seq-2 (is (= (unify empty-s 1 '[]) false))) (deftest unify-object-map-1 (is (= (unify empty-s 1 {}) false))) (deftest unify-object-set-1 (is (= (unify empty-s 1 #{}) false))) ;; ----------------------------------------------------------------------------- ;; lvar (deftest unify-lvar-object-1 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s x 1) os)))) (deftest unify-lvar-lvar-1 (let [x (lvar 'x) y (lvar 'y) os (ext-no-check empty-s x y)] (is (= (unify empty-s x y) os)))) (deftest unify-lvar-lcons-1 (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (ext-no-check empty-s x l)] (is (= (unify empty-s x l) os)))) (deftest unify-lvar-seq-1 (let [x (lvar 'x) os (ext-no-check empty-s x [])] (is (= (unify empty-s x []) os)))) (deftest unify-lvar-seq-2 (let [x (lvar 'x) os (ext-no-check empty-s x [1 2 3])] (is (= (unify empty-s x [1 2 3]) os)))) (deftest unify-lvar-seq-3 (let [x (lvar 'x) os (ext-no-check empty-s x '())] (is (= (unify empty-s x '()) os)))) (deftest unify-lvar-seq-4 (let [x (lvar 'x) os (ext-no-check empty-s x '(1 2 3))] (is (= (unify empty-s x '(1 2 3)) os)))) (deftest unify-lvar-map-1 (let [x (lvar 'x) os (ext-no-check empty-s x {})] (is (= (unify empty-s x {}) os)))) (deftest unify-lvar-map-2 (let [x (lvar 'x) os (ext-no-check empty-s x {1 2 3 4})] (is (= (unify empty-s x {1 2 3 4}) os)))) (deftest unify-lvar-set-1 (let [x (lvar 'x) os (ext-no-check empty-s x #{})] (is (= (unify empty-s x #{}) os)))) (deftest unify-lvar-set-2 (let [x (lvar 'x) os (ext-no-check empty-s x #{1 2 3})] (is (= (unify empty-s x #{1 2 3}) os)))) ;; ----------------------------------------------------------------------------- ;; lcons (deftest unify-lcons-object-1 (let [x (lvar 'x)] (is (= (unify empty-s (lcons 1 x) 1) false)))) (deftest unify-lcons-lvar-1 (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (ext-no-check empty-s x l)] (is (= (unify empty-s l x) os)))) (deftest unify-lcons-lcons-1 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 x) lc2 (lcons 1 y) os (ext-no-check empty-s x y)] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-2 (let [x (lvar 'x) y (lvar 'y) z (lvar 'z) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons z y)) os (-> empty-s (ext-no-check x y) (ext-no-check z 2))] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-3 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 (lcons 3 y))) os (ext-no-check empty-s x (lcons 3 y))] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-4 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 3 (lcons 4 y)))] (is (= (unify empty-s lc1 lc2) false)))) (deftest unify-lcons-lcons-5 (let [x (lvar 'x) y (lvar 'y) lc2 (lcons 1 (lcons 2 x)) lc1 (lcons 1 (lcons 3 (lcons 4 y)))] (is (= (unify empty-s lc1 lc2) false)))) (deftest unify-lcons-lcons-6 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 y)) os (ext-no-check empty-s x y)] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-seq-1 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (ext-no-check empty-s x '(3 4))] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-2 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons y (lcons 3 x))) l1 '(1 2 3 4) os (-> empty-s (ext-no-check x '(4)) (ext-no-check y 2))] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-3 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 (lcons 3 x))) l1 '(1 2 3) os (ext-no-check empty-s x '())] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-4 (let [x (lvar 'x) lc1 (lcons 1 (lcons 3 x)) l1 '(1 2 3 4)] (is (= (unify empty-s lc1 l1) false)))) (deftest unify-lcons-seq-5 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 3 4 5)] (is (= (unify empty-s lc1 l1) false)))) (deftest unify-lcons-map-1 (is (= (unify empty-s (lcons 1 (lvar 'x)) {}) false))) (deftest unify-lcons-set-1 (is (= (unify empty-s (lcons 1 (lvar 'x)) #{}) false))) ;; ----------------------------------------------------------------------------- ;; seq (deftest unify-seq-object-1 (is (= (unify empty-s '() 1) false))) (deftest unify-seq-object-2 (is (= (unify empty-s [] 1) false))) (deftest unify-seq-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x [])] (is (= (unify empty-s [] x) os)))) (deftest unify-seq-lcons-1 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (ext-no-check empty-s x '(3 4))] (is (= (unify empty-s l1 lc1) os)))) (deftest unify-seq-seq-1 (is (= (unify empty-s [1 2 3] [1 2 3]) empty-s))) (deftest unify-seq-seq-2 (is (= (unify empty-s '(1 2 3) [1 2 3]) empty-s))) (deftest unify-seq-seq-3 (is (= (unify empty-s '(1 2 3) '(1 2 3)) empty-s))) (deftest unify-seq-seq-4 (let [x (lvar 'x) os (ext-no-check empty-s x 2)] (is (= (unify empty-s `(1 ~x 3) `(1 2 3)) os)))) (deftest unify-seq-seq-5 (is (= (unify empty-s [1 2] [1 2 3]) false))) (deftest unify-seq-seq-6 (is (= (unify empty-s '(1 2) [1 2 3]) false))) (deftest unify-seq-seq-7 (is (= (unify empty-s [1 2 3] [3 2 1]) false))) (deftest unify-seq-seq-8 (is (= (unify empty-s '() '()) empty-s))) (deftest unify-seq-seq-9 (is (= (unify empty-s '() '(1)) false))) (deftest unify-seq-seq-10 (is (= (unify empty-s '(1) '()) false))) (deftest unify-seq-seq-11 (is (= (unify empty-s [[1 2]] [[1 2]]) empty-s))) (deftest unify-seq-seq-12 (is (= (unify empty-s [[1 2]] [[2 1]]) false))) (deftest unify-seq-seq-13 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s [[x 2]] [[1 2]]) os)))) (deftest unify-seq-seq-14 (let [x (lvar 'x) os (ext-no-check empty-s x [1 2])] (is (= (unify empty-s [x] [[1 2]]) os)))) (deftest unify-seq-seq-15 (let [x (lvar 'x) y (lvar 'y) u (lvar 'u) v (lvar 'v) os (-> empty-s (ext-no-check x 'b) (ext-no-check y 'a))] (is (= (unify empty-s ['a x] [y 'b]) os)))) (deftest unify-seq-map-1 (is (= (unify empty-s [] {}) false))) (deftest unify-seq-map-2 (is (= (unify empty-s '() {}) false))) (deftest unify-seq-set-1 (is (= (unify empty-s [] #{}) false))) (deftest unify-seq-set-2 (is (= (unify empty-s '() #{}) false))) ;; ----------------------------------------------------------------------------- ;; map (deftest unify-map-object-1 (is (= (unify empty-s {} 1) false))) (deftest unify-map-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x {})] (is (= (unify empty-s {} x) os)))) (deftest unify-map-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s {} (lcons 1 x)) false)))) (deftest unify-map-seq-1 (is (= (unify empty-s {} '()) false))) (deftest unify-map-map-1 (is (= (unify empty-s {} {}) empty-s))) (deftest unify-map-map-2 (is (= (unify empty-s {1 2 3 4} {1 2 3 4}) empty-s))) (deftest unify-map-map-3 (is (= (unify empty-s {1 2} {1 2 3 4}) false))) (deftest unify-map-map-4 (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 2 3 x} os (ext-no-check empty-s x 4)] (is (= (unify empty-s m1 m2) os)))) (deftest unify-map-map-5 (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 4 3 x}] (is (= (unify empty-s m1 m2) false)))) (deftest unify-map-set-1 (is (= (unify empty-s {} #{}) false))) ;; ----------------------------------------------------------------------------- ;; set (deftest unify-set-object-1 (is (= (unify empty-s #{} 1) false))) (deftest unify-set-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x #{})] (is (= (unify empty-s #{} x) os)))) (deftest unify-set-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s #{} (lcons 1 x)) false)))) (deftest unify-set-seq-1 (is (= (unify empty-s #{} '()) false))) (deftest unify-set-map-1 (is (= (unify empty-s #{} {}) false))) (deftest unify-set-set-1 (is (= (unify empty-s #{} #{}) empty-s))) (deftest unify-set-set-2 (is (= (unify empty-s #{} #{1}) false))) (deftest unify-set-set-3 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s #{x} #{1}) os)))) (deftest unify-set-set-4 (let [x (lvar 'x) y (lvar 'y) os (-> empty-s (ext-no-check x 2) (ext-no-check y 1))] (is (= (unify empty-s #{1 x} #{2 y}) os)))) (deftest unify-set-set-5 (let [x (lvar 'x) y (lvar 'y) os (-> empty-s (ext-no-check x 2) (ext-no-check y 1))] (is (= (unify empty-s #{x 1} #{2 y}) os)))) (deftest unify-set-set-6 (let [a (lvar 'a) b (lvar 'b) c (lvar 'c) d (lvar 'd) s (.s (unify empty-s #{a b 3 4 5} #{1 2 3 c d}))] (is (and (= (count s) 4) (= (set (keys s)) #{a b c d}) (= (set (vals s)) #{1 2 4 5}))))) (deftest unify-set-set-7 (let [a (lvar 'a) b (lvar 'b) c (lvar 'c) d (lvar 'd)] (is (= (unify empty-s #{a b 9 4 5} #{1 2 3 c d}) false)))) ;; ============================================================================= ;; walk (deftest test-basic-walk (is (= (let [x (lvar 'x) y (lvar 'y) ss (to-s [[x 5] [y x]])] (walk ss y)) 5))) (deftest test-deep-walk (is (= (let [[x y z c b a :as s] (map lvar '[x y z c b a]) ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (walk ss a)) 5))) ;; ============================================================================= ;; reify (deftest test-reify-lvar-name (is (= (let [x (lvar 'x) y (lvar 'y)] (reify-lvar-name (to-s [[x 5] [y x]]))) '_.2))) ;; ============================================================================= ;; walk* (deftest test-walk* (is (= (let [x (lvar 'x) y (lvar 'y)] (walk* (to-s [[x 5] [y x]]) `(~x ~y))) '(5 5)))) ;; ============================================================================= ;; run and unify (deftest test-basic-unify (is (= (run* [q] (== true q)) '(true)))) (deftest test-basic-unify-2 (is (= (run* [q] (fresh [x y] (== [x y] [1 5]) (== [x y] q))) [[1 5]]))) (deftest test-basic-unify-3 (is (= (run* [q] (fresh [x y] (== [x y] q))) '[[_.0 _.1]]))) ;; ============================================================================= ;; fail (deftest test-basic-failure (is (= (run* [q] fail (== true q)) []))) ;; ============================================================================= ;; Basic (deftest test-all (is (= (run* [q] (all (== 1 1) (== q true))) '(true)))) ;; ============================================================================= ;; TRS (defn pairo [p] (fresh [a d] (== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) s#] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (defn rembero [x l out] (conde [(== '() l) (== '() out)] [(fresh [a d] (conso a d l) (== x a) (== d out))] [(fresh [a d res] (conso a d l) (conso a res out) (rembero x d res))])) ;; ============================================================================= ;; conde (deftest test-basic-conde (is (= (run* [x] (conde [(== x 'olive) succeed] [succeed succeed] [(== x 'oil) succeed])) '[olive _.0 oil]))) (deftest test-basic-conde-2 (is (= (run* [r] (fresh [x y] (conde [(== 'split x) (== 'pea y)] [(== 'navy x) (== 'bean y)]) (== (cons x (cons y ())) r))) '[(split pea) (navy bean)]))) (defn teacupo [x] (conde [(== 'tea x) s#] [(== 'cup x) s#])) (deftest test-basic-conde-e-3 (is (= (run* [r] (fresh [x y] (conde [(teacupo x) (== true y) s#] [(== false x) (== true y)]) (== (cons x (cons y ())) r))) '((false true) (tea true) (cup true))))) ;; ============================================================================= ;; conso (deftest test-conso (is (= (run* [q] (fresh [a d] (conso a d '()) (== (cons a d) q)) [])))) (deftest test-conso-1 (let [a (lvar 'a) d (lvar 'd)] (is (= (run* [q] (conso a d q)) [(lcons a d)])))) (deftest test-conso-2 (is (= (run* [q] (== [q] nil)) []))) (deftest test-conso-3 (is (= (run* [q] (conso 'a nil q)) '[(a)]))) (deftest test-conso-4 (is (= (run* [q] (conso 'a '(d) q)) '[(a d)]))) (deftest test-conso-empty-list (is (= (run* [q] (conso 'a q '(a))) '[()]))) (deftest test-conso-5 (is (= (run* [q] (conso q '(b c) '(a b c))) '[a]))) ;; ============================================================================= ;; firsto (deftest test-firsto (is (= (run* [q] (firsto q '(1 2))) (list (lcons '(1 2) (lvar 'x)))))) ;; ============================================================================= ;; resto (deftest test-resto (is (= (run* [q] (resto q '(1 2))) '[(_.0 1 2)]))) (deftest test-resto-2 (is (= (run* [q] (resto q [1 2])) '[(_.0 1 2)]))) (deftest test-resto-3 (is (= (run* [q] (resto [1 2] q)) '[(2)]))) (deftest test-resto-4 (is (= (run* [q] (resto [1 2 3 4 5 6 7 8] q)) '[(2 3 4 5 6 7 8)]))) ;; ============================================================================= ;; flatteno (deftest test-flatteno (is (= (run* [x] (flatteno '[[a b] c] x)) '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ()))))) ;; ============================================================================= ;; membero (deftest membero-1 (is (= (run* [q] (all (== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]])))) (deftest membero-2 (is (= (run* [q] (all (== q [(lvar) (lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar] _.0] [[foo _.0] [_.1 bar]] [[_.0 bar] [foo _.1]] [_.0 [foo bar]])))) ;; ----------------------------------------------------------------------------- ;; rembero (deftest rembero-1 (is (= (run 1 [q] (rembero 'b '(a b c b d) q)) '((a c b d))))) ;; ----------------------------------------------------------------------------- ;; conde clause count (defn digit-1 [x] (conde [(== 0 x)])) (defn digit-4 [x] (conde [(== 0 x)] [(== 1 x)] [(== 2 x)] [(== 3 x)])) (deftest test-conde-1-clause (is (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (== q [x y]))) '([0 0])))) (deftest test-conde-4-clauses (is (= (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (== q [x y]))) '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3])))) ;; ----------------------------------------------------------------------------- ;; anyo (defn anyo [q] (conde [q s#] [(anyo q)])) (deftest test-anyo-1 (is (= (run 1 [q] (anyo s#) (== true q)) (list true)))) (deftest test-anyo-2 (is (= (run 5 [q] (anyo s#) (== true q)) (list true true true true true)))) ;; ----------------------------------------------------------------------------- ;; divergence (def f1 (fresh [] f1)) (deftest test-divergence-1 (is (= (run 1 [q] (conde [f1] [(== false false)])) '(_.0)))) (deftest test-divergence-2 (is (= (run 1 [q] (conde [f1 (== false false)] [(== false false)])) '(_.0)))) (def f2 (fresh [] (conde [f2 (conde [f2] [(== false false)])] [(== false false)]))) (deftest test-divergence-3 (is (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0)))) ;; ----------------------------------------------------------------------------- ;; conda (soft-cut) (deftest test-conda-1 (is (= (run* [x] (conda [(== 'olive x) s#] [(== 'oil x) s#] [u#])) '(olive)))) (deftest test-conda-2 (is (= (run* [x] (conda [(== 'virgin x) u#] [(== 'olive x) s#] [(== 'oil x) s#] [u#])) '()))) (deftest test-conda-3 (is (= (run* [x] (fresh (x y) (== 'split x) (== 'pea y) (conda [(== 'split x) (== x y)] [s#])) (== true x)) '()))) (deftest test-conda-4 (is (= (run* [x] (fresh (x y) (== 'split x) (== 'pea y) (conda [(== x y) (== 'split x)] [s#])) (== true x)) '(true)))) (defn not-pastao [x] (conda [(== 'pasta x) u#] [s#])) (deftest test-conda-5 (is (= (run* [x] (conda [(not-pastao x)] [(== 'spaghetti x)])) '(spaghetti)))) ;; ----------------------------------------------------------------------------- ;; condu (committed-choice) (defn onceo [g] (condu (g s#))) (deftest test-condu-1 (is (= (run* [x] (onceo (teacupo x))) '(tea)))) (deftest test-condu-2 (is (= (run* [r] (conde [(teacupo r) s#] [(== false r) s#])) '(false tea cup)))) (deftest test-condu-3 (is (= (run* [r] (conda [(teacupo r) s#] [(== false r) s#])) '(tea cup)))) ;; ----------------------------------------------------------------------------- ;; disequality (deftest test-disequality-1 (is (= (run* [q] (fresh [x] (!= x 1) (== q x))) '(_.0)))) (deftest test-disequality-2 (is (= (run* [q] (fresh [x] (== q x) (!= x 1))) '(_.0)))) (deftest test-disequality-3 (is (= (run* [q] (fresh [x] (!= x 1) (== x 1) (== q x))) ()))) (deftest test-disequality-4 (is (= (run* [q] (fresh [x] (== x 1) (!= x 1) (== q x))) ()))) (deftest test-disequality-5 (is (= (run* [q] (fresh [x y] (!= x y) (== x 1) (== y 1) (== q x))) ()))) (deftest test-disequality-6 (is (= (run* [q] (fresh [x y] (== x 1) (== y 1) (!= x y) (== q x))) ()))) (deftest test-disequality-7 (is (= (run* [q] (fresh [x y] (== x 1) (!= x y) (== y 2) (== q x))) '(1)))) (deftest test-disequality-8 (is (= (run* [q] (fresh [x y] (!= [x 2] [y 1]) (== x 1) (== y 3) (== q [x y]))) '([1 3])))) (deftest test-disequality-9 (is (= (run* [q] (fresh [x y] (== x 1) (== y 3) (!= [x 2] [y 1]) (== q [x y]))) '([1 3])))) (deftest test-disequality-10 (is (= (run* [q] (fresh [x y] (!= [x 2] [1 y]) (== x 1) (== y 2) (== q [x y]))) ()))) (deftest test-disequality-11 (is (= (run* [q] (fresh [x y] (== x 1) (== y 2) (!= [x 2] [1 y]) (== q [x y]))) ()))) (deftest test-disequality-12 (is (= (run* [q] (fresh [x y z] (!= x y) (== y z) (== x z) (== q x))) ()))) (deftest test-disequality-13 (is (= (run* [q] (fresh [x y z] (== y z) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-14 (is (= (run* [q] (fresh [x y z] (== z y) (== x z) (!= x y) (== q x))) ()))) ;; ----------------------------------------------------------------------------- ;; tabled (defne arco [x y] ([:a :b]) ([:b :a]) ([:b :d])) (def patho (tabled [x y] (conde [(arco x y)] [(fresh [z] (arco x z) (patho z y))]))) (deftest test-tabled-1 (is (= (run* [q] (patho :a q)) '(:b :a :d)))) (defne arco-2 [x y] ([1 2]) ([1 4]) ([1 3]) ([2 3]) ([2 5]) ([3 4]) ([3 5]) ([4 5])) (def patho-2 (tabled [x y] (conde [(arco-2 x y)] [(fresh [z] (arco-2 x z) (patho-2 z y))]))) (deftest test-tabled-2 (let [r (set (run* [q] (patho-2 1 q)))] (is (and (= (count r) 4) (= r #{2 3 4 5}))))) ;; ----------------------------------------------------------------------------- ;; rel (defrel man p) (fact man '<NAME>) (fact man '<NAME>) (fact man '<NAME>) (defrel woman p) (fact woman '<NAME>) (fact woman '<NAME>) (fact woman '<NAME>) (defrel likes p1 p2) (fact likes '<NAME> '<NAME>) (fact likes '<NAME> '<NAME>) (fact likes '<NAME> '<NAME>) (defrel fun p) (fact fun '<NAME>) (deftest test-rel-1 (is (= (run* [q] (fresh [x y] (likes x y) (fun y) (== q [x y]))) '([<NAME> <NAME>])))) ;; ----------------------------------------------------------------------------- ;; nil in collection (deftest test-nil-in-coll-1 (is (= (run* [q] (== q [nil])) '([nil])))) (deftest test-nil-in-coll-2 (is (= (run* [q] (== q [1 nil])) '([1 nil])))) (deftest test-nil-in-coll-3 (is (= (run* [q] (== q [nil 1])) '([nil 1])))) (deftest test-nil-in-coll-4 (is (= (run* [q] (== q '(nil))) '((nil))))) (deftest test-nil-in-coll-5 (is (= (run* [q] (== q {:foo nil})) '({:foo nil})))) (deftest test-nil-in-coll-6 (is (= (run* [q] (== q {nil :foo})) '({nil :foo})))) ;; ----------------------------------------------------------------------------- ;; Unifier (deftest test-unifier-1 (is (= (unifier '(?x ?y) '(1 2)) '(1 2)))) (deftest test-unifier-2 (is (= (unifier '(?x ?y 3) '(1 2 ?z)) '(1 2 3)))) (deftest test-unifier-3 (is (= (unifier '[(?x . ?y) 3] [[1 2] 3]) '[(1 2) 3]))) (deftest test-unifier-4 (is (= (unifier '(?x . ?y) '(1 . ?z)) (lcons 1 '_.0)))) (deftest test-unifier-5 (is (= (unifier '(?x 2 . ?y) '(1 2 3 4 5)) '(1 2 3 4 5)))) (deftest test-unifier-6 (is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5)) nil))) (deftest test-binding-map-1 (is (= (binding-map '(?x ?y) '(1 2)) '{?x 1 ?y 2}))) (deftest test-binding-map-2 (is (= (binding-map '(?x ?y 3) '(1 2 ?z)) '{?x 1 ?y 2 ?z 3}))) (deftest test-binding-map-3 (is (= (binding-map '[(?x . ?y) 3] [[1 2] 3]) '{?x 1 ?y (2)}))) (deftest test-binding-map-4 (is (= (binding-map '(?x . ?y) '(1 . ?z)) '{?z _.0, ?x 1, ?y _.0}))) (deftest test-binding-map-5 (is (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5)) '{?x 1 ?y (3 4 5)}))) (deftest test-binding-map-6 (is (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5)) nil))) ;; ----------------------------------------------------------------------------- ;; Occurs Check (deftest test-occurs-check-1 (is (= (run* [q] (== q [q])) ()))) ;; ----------------------------------------------------------------------------- ;; Unifications that should fail (deftest test-unify-fail-1 (is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-2 (is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-3 (is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d]))) ()))) ;; ----------------------------------------------------------------------------- ;; Pattern matching functions preserve metadata (defne ^:tabled dummy "Docstring" [x l] ([_ [x . tail]]) ([_ [head . tail]] (membero x tail))) (deftest test-metadata-defne (is (= (-> #'dummy meta :tabled) true)) (is (= (-> #'dummy meta :doc) "Docstring")))
true
(ns clojure.core.logic.tests (:refer-clojure :exclude [==]) (:use [clojure.core.logic :exclude [is]] :reload) (:use clojure.test)) ;; ============================================================================= ;; unify ;; ----------------------------------------------------------------------------- ;; nil (deftest unify-nil-object-1 (is (= (unify empty-s nil 1) false))) (deftest unify-nil-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x nil)] (is (= (unify empty-s nil x) os)))) (deftest unify-nil-lseq-1 (let [x (lvar 'x)] (is (= (unify empty-s nil (lcons 1 x)) false)))) (deftest unify-nil-map-1 (let [x (lvar 'x)] (is (= (unify empty-s nil {}) false)))) (deftest unify-nil-set-1 (let [x (lvar 'x)] (is (= (unify empty-s nil #{}) false)))) ;; ----------------------------------------------------------------------------- ;; object (deftest unify-object-nil-1 (is (= (unify empty-s 1 nil)))) (deftest unify-object-object-1 (is (= (unify empty-s 1 1) empty-s))) (deftest unify-object-object-2 (is (= (unify empty-s :foo :foo) empty-s))) (deftest unify-object-object-3 (is (= (unify empty-s 'foo 'foo) empty-s))) (deftest unify-object-object-4 (is (= (unify empty-s "foo" "foo") empty-s))) (deftest unify-object-object-5 (is (= (unify empty-s 1 2) false))) (deftest unify-object-object-6 (is (= (unify empty-s 2 1) false))) (deftest unify-object-object-7 (is (= (unify empty-s :foo :bar) false))) (deftest unify-object-object-8 (is (= (unify empty-s 'foo 'bar) false))) (deftest unify-object-object-9 (is (= (unify empty-s "foo" "bar") false))) (deftest unify-object-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s 1 x) os)))) (deftest unify-object-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s 1 (lcons 1 'x)) false)))) (deftest unify-object-seq-1 (is (= (unify empty-s 1 '()) false))) (deftest unify-object-seq-2 (is (= (unify empty-s 1 '[]) false))) (deftest unify-object-map-1 (is (= (unify empty-s 1 {}) false))) (deftest unify-object-set-1 (is (= (unify empty-s 1 #{}) false))) ;; ----------------------------------------------------------------------------- ;; lvar (deftest unify-lvar-object-1 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s x 1) os)))) (deftest unify-lvar-lvar-1 (let [x (lvar 'x) y (lvar 'y) os (ext-no-check empty-s x y)] (is (= (unify empty-s x y) os)))) (deftest unify-lvar-lcons-1 (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (ext-no-check empty-s x l)] (is (= (unify empty-s x l) os)))) (deftest unify-lvar-seq-1 (let [x (lvar 'x) os (ext-no-check empty-s x [])] (is (= (unify empty-s x []) os)))) (deftest unify-lvar-seq-2 (let [x (lvar 'x) os (ext-no-check empty-s x [1 2 3])] (is (= (unify empty-s x [1 2 3]) os)))) (deftest unify-lvar-seq-3 (let [x (lvar 'x) os (ext-no-check empty-s x '())] (is (= (unify empty-s x '()) os)))) (deftest unify-lvar-seq-4 (let [x (lvar 'x) os (ext-no-check empty-s x '(1 2 3))] (is (= (unify empty-s x '(1 2 3)) os)))) (deftest unify-lvar-map-1 (let [x (lvar 'x) os (ext-no-check empty-s x {})] (is (= (unify empty-s x {}) os)))) (deftest unify-lvar-map-2 (let [x (lvar 'x) os (ext-no-check empty-s x {1 2 3 4})] (is (= (unify empty-s x {1 2 3 4}) os)))) (deftest unify-lvar-set-1 (let [x (lvar 'x) os (ext-no-check empty-s x #{})] (is (= (unify empty-s x #{}) os)))) (deftest unify-lvar-set-2 (let [x (lvar 'x) os (ext-no-check empty-s x #{1 2 3})] (is (= (unify empty-s x #{1 2 3}) os)))) ;; ----------------------------------------------------------------------------- ;; lcons (deftest unify-lcons-object-1 (let [x (lvar 'x)] (is (= (unify empty-s (lcons 1 x) 1) false)))) (deftest unify-lcons-lvar-1 (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (ext-no-check empty-s x l)] (is (= (unify empty-s l x) os)))) (deftest unify-lcons-lcons-1 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 x) lc2 (lcons 1 y) os (ext-no-check empty-s x y)] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-2 (let [x (lvar 'x) y (lvar 'y) z (lvar 'z) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons z y)) os (-> empty-s (ext-no-check x y) (ext-no-check z 2))] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-3 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 (lcons 3 y))) os (ext-no-check empty-s x (lcons 3 y))] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-lcons-4 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 3 (lcons 4 y)))] (is (= (unify empty-s lc1 lc2) false)))) (deftest unify-lcons-lcons-5 (let [x (lvar 'x) y (lvar 'y) lc2 (lcons 1 (lcons 2 x)) lc1 (lcons 1 (lcons 3 (lcons 4 y)))] (is (= (unify empty-s lc1 lc2) false)))) (deftest unify-lcons-lcons-6 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 y)) os (ext-no-check empty-s x y)] (is (= (unify empty-s lc1 lc2) os)))) (deftest unify-lcons-seq-1 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (ext-no-check empty-s x '(3 4))] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-2 (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons y (lcons 3 x))) l1 '(1 2 3 4) os (-> empty-s (ext-no-check x '(4)) (ext-no-check y 2))] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-3 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 (lcons 3 x))) l1 '(1 2 3) os (ext-no-check empty-s x '())] (is (= (unify empty-s lc1 l1) os)))) (deftest unify-lcons-seq-4 (let [x (lvar 'x) lc1 (lcons 1 (lcons 3 x)) l1 '(1 2 3 4)] (is (= (unify empty-s lc1 l1) false)))) (deftest unify-lcons-seq-5 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 3 4 5)] (is (= (unify empty-s lc1 l1) false)))) (deftest unify-lcons-map-1 (is (= (unify empty-s (lcons 1 (lvar 'x)) {}) false))) (deftest unify-lcons-set-1 (is (= (unify empty-s (lcons 1 (lvar 'x)) #{}) false))) ;; ----------------------------------------------------------------------------- ;; seq (deftest unify-seq-object-1 (is (= (unify empty-s '() 1) false))) (deftest unify-seq-object-2 (is (= (unify empty-s [] 1) false))) (deftest unify-seq-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x [])] (is (= (unify empty-s [] x) os)))) (deftest unify-seq-lcons-1 (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (ext-no-check empty-s x '(3 4))] (is (= (unify empty-s l1 lc1) os)))) (deftest unify-seq-seq-1 (is (= (unify empty-s [1 2 3] [1 2 3]) empty-s))) (deftest unify-seq-seq-2 (is (= (unify empty-s '(1 2 3) [1 2 3]) empty-s))) (deftest unify-seq-seq-3 (is (= (unify empty-s '(1 2 3) '(1 2 3)) empty-s))) (deftest unify-seq-seq-4 (let [x (lvar 'x) os (ext-no-check empty-s x 2)] (is (= (unify empty-s `(1 ~x 3) `(1 2 3)) os)))) (deftest unify-seq-seq-5 (is (= (unify empty-s [1 2] [1 2 3]) false))) (deftest unify-seq-seq-6 (is (= (unify empty-s '(1 2) [1 2 3]) false))) (deftest unify-seq-seq-7 (is (= (unify empty-s [1 2 3] [3 2 1]) false))) (deftest unify-seq-seq-8 (is (= (unify empty-s '() '()) empty-s))) (deftest unify-seq-seq-9 (is (= (unify empty-s '() '(1)) false))) (deftest unify-seq-seq-10 (is (= (unify empty-s '(1) '()) false))) (deftest unify-seq-seq-11 (is (= (unify empty-s [[1 2]] [[1 2]]) empty-s))) (deftest unify-seq-seq-12 (is (= (unify empty-s [[1 2]] [[2 1]]) false))) (deftest unify-seq-seq-13 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s [[x 2]] [[1 2]]) os)))) (deftest unify-seq-seq-14 (let [x (lvar 'x) os (ext-no-check empty-s x [1 2])] (is (= (unify empty-s [x] [[1 2]]) os)))) (deftest unify-seq-seq-15 (let [x (lvar 'x) y (lvar 'y) u (lvar 'u) v (lvar 'v) os (-> empty-s (ext-no-check x 'b) (ext-no-check y 'a))] (is (= (unify empty-s ['a x] [y 'b]) os)))) (deftest unify-seq-map-1 (is (= (unify empty-s [] {}) false))) (deftest unify-seq-map-2 (is (= (unify empty-s '() {}) false))) (deftest unify-seq-set-1 (is (= (unify empty-s [] #{}) false))) (deftest unify-seq-set-2 (is (= (unify empty-s '() #{}) false))) ;; ----------------------------------------------------------------------------- ;; map (deftest unify-map-object-1 (is (= (unify empty-s {} 1) false))) (deftest unify-map-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x {})] (is (= (unify empty-s {} x) os)))) (deftest unify-map-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s {} (lcons 1 x)) false)))) (deftest unify-map-seq-1 (is (= (unify empty-s {} '()) false))) (deftest unify-map-map-1 (is (= (unify empty-s {} {}) empty-s))) (deftest unify-map-map-2 (is (= (unify empty-s {1 2 3 4} {1 2 3 4}) empty-s))) (deftest unify-map-map-3 (is (= (unify empty-s {1 2} {1 2 3 4}) false))) (deftest unify-map-map-4 (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 2 3 x} os (ext-no-check empty-s x 4)] (is (= (unify empty-s m1 m2) os)))) (deftest unify-map-map-5 (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 4 3 x}] (is (= (unify empty-s m1 m2) false)))) (deftest unify-map-set-1 (is (= (unify empty-s {} #{}) false))) ;; ----------------------------------------------------------------------------- ;; set (deftest unify-set-object-1 (is (= (unify empty-s #{} 1) false))) (deftest unify-set-lvar-1 (let [x (lvar 'x) os (ext-no-check empty-s x #{})] (is (= (unify empty-s #{} x) os)))) (deftest unify-set-lcons-1 (let [x (lvar 'x)] (is (= (unify empty-s #{} (lcons 1 x)) false)))) (deftest unify-set-seq-1 (is (= (unify empty-s #{} '()) false))) (deftest unify-set-map-1 (is (= (unify empty-s #{} {}) false))) (deftest unify-set-set-1 (is (= (unify empty-s #{} #{}) empty-s))) (deftest unify-set-set-2 (is (= (unify empty-s #{} #{1}) false))) (deftest unify-set-set-3 (let [x (lvar 'x) os (ext-no-check empty-s x 1)] (is (= (unify empty-s #{x} #{1}) os)))) (deftest unify-set-set-4 (let [x (lvar 'x) y (lvar 'y) os (-> empty-s (ext-no-check x 2) (ext-no-check y 1))] (is (= (unify empty-s #{1 x} #{2 y}) os)))) (deftest unify-set-set-5 (let [x (lvar 'x) y (lvar 'y) os (-> empty-s (ext-no-check x 2) (ext-no-check y 1))] (is (= (unify empty-s #{x 1} #{2 y}) os)))) (deftest unify-set-set-6 (let [a (lvar 'a) b (lvar 'b) c (lvar 'c) d (lvar 'd) s (.s (unify empty-s #{a b 3 4 5} #{1 2 3 c d}))] (is (and (= (count s) 4) (= (set (keys s)) #{a b c d}) (= (set (vals s)) #{1 2 4 5}))))) (deftest unify-set-set-7 (let [a (lvar 'a) b (lvar 'b) c (lvar 'c) d (lvar 'd)] (is (= (unify empty-s #{a b 9 4 5} #{1 2 3 c d}) false)))) ;; ============================================================================= ;; walk (deftest test-basic-walk (is (= (let [x (lvar 'x) y (lvar 'y) ss (to-s [[x 5] [y x]])] (walk ss y)) 5))) (deftest test-deep-walk (is (= (let [[x y z c b a :as s] (map lvar '[x y z c b a]) ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (walk ss a)) 5))) ;; ============================================================================= ;; reify (deftest test-reify-lvar-name (is (= (let [x (lvar 'x) y (lvar 'y)] (reify-lvar-name (to-s [[x 5] [y x]]))) '_.2))) ;; ============================================================================= ;; walk* (deftest test-walk* (is (= (let [x (lvar 'x) y (lvar 'y)] (walk* (to-s [[x 5] [y x]]) `(~x ~y))) '(5 5)))) ;; ============================================================================= ;; run and unify (deftest test-basic-unify (is (= (run* [q] (== true q)) '(true)))) (deftest test-basic-unify-2 (is (= (run* [q] (fresh [x y] (== [x y] [1 5]) (== [x y] q))) [[1 5]]))) (deftest test-basic-unify-3 (is (= (run* [q] (fresh [x y] (== [x y] q))) '[[_.0 _.1]]))) ;; ============================================================================= ;; fail (deftest test-basic-failure (is (= (run* [q] fail (== true q)) []))) ;; ============================================================================= ;; Basic (deftest test-all (is (= (run* [q] (all (== 1 1) (== q true))) '(true)))) ;; ============================================================================= ;; TRS (defn pairo [p] (fresh [a d] (== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) s#] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (defn rembero [x l out] (conde [(== '() l) (== '() out)] [(fresh [a d] (conso a d l) (== x a) (== d out))] [(fresh [a d res] (conso a d l) (conso a res out) (rembero x d res))])) ;; ============================================================================= ;; conde (deftest test-basic-conde (is (= (run* [x] (conde [(== x 'olive) succeed] [succeed succeed] [(== x 'oil) succeed])) '[olive _.0 oil]))) (deftest test-basic-conde-2 (is (= (run* [r] (fresh [x y] (conde [(== 'split x) (== 'pea y)] [(== 'navy x) (== 'bean y)]) (== (cons x (cons y ())) r))) '[(split pea) (navy bean)]))) (defn teacupo [x] (conde [(== 'tea x) s#] [(== 'cup x) s#])) (deftest test-basic-conde-e-3 (is (= (run* [r] (fresh [x y] (conde [(teacupo x) (== true y) s#] [(== false x) (== true y)]) (== (cons x (cons y ())) r))) '((false true) (tea true) (cup true))))) ;; ============================================================================= ;; conso (deftest test-conso (is (= (run* [q] (fresh [a d] (conso a d '()) (== (cons a d) q)) [])))) (deftest test-conso-1 (let [a (lvar 'a) d (lvar 'd)] (is (= (run* [q] (conso a d q)) [(lcons a d)])))) (deftest test-conso-2 (is (= (run* [q] (== [q] nil)) []))) (deftest test-conso-3 (is (= (run* [q] (conso 'a nil q)) '[(a)]))) (deftest test-conso-4 (is (= (run* [q] (conso 'a '(d) q)) '[(a d)]))) (deftest test-conso-empty-list (is (= (run* [q] (conso 'a q '(a))) '[()]))) (deftest test-conso-5 (is (= (run* [q] (conso q '(b c) '(a b c))) '[a]))) ;; ============================================================================= ;; firsto (deftest test-firsto (is (= (run* [q] (firsto q '(1 2))) (list (lcons '(1 2) (lvar 'x)))))) ;; ============================================================================= ;; resto (deftest test-resto (is (= (run* [q] (resto q '(1 2))) '[(_.0 1 2)]))) (deftest test-resto-2 (is (= (run* [q] (resto q [1 2])) '[(_.0 1 2)]))) (deftest test-resto-3 (is (= (run* [q] (resto [1 2] q)) '[(2)]))) (deftest test-resto-4 (is (= (run* [q] (resto [1 2 3 4 5 6 7 8] q)) '[(2 3 4 5 6 7 8)]))) ;; ============================================================================= ;; flatteno (deftest test-flatteno (is (= (run* [x] (flatteno '[[a b] c] x)) '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ()))))) ;; ============================================================================= ;; membero (deftest membero-1 (is (= (run* [q] (all (== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]])))) (deftest membero-2 (is (= (run* [q] (all (== q [(lvar) (lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar] _.0] [[foo _.0] [_.1 bar]] [[_.0 bar] [foo _.1]] [_.0 [foo bar]])))) ;; ----------------------------------------------------------------------------- ;; rembero (deftest rembero-1 (is (= (run 1 [q] (rembero 'b '(a b c b d) q)) '((a c b d))))) ;; ----------------------------------------------------------------------------- ;; conde clause count (defn digit-1 [x] (conde [(== 0 x)])) (defn digit-4 [x] (conde [(== 0 x)] [(== 1 x)] [(== 2 x)] [(== 3 x)])) (deftest test-conde-1-clause (is (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (== q [x y]))) '([0 0])))) (deftest test-conde-4-clauses (is (= (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (== q [x y]))) '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3])))) ;; ----------------------------------------------------------------------------- ;; anyo (defn anyo [q] (conde [q s#] [(anyo q)])) (deftest test-anyo-1 (is (= (run 1 [q] (anyo s#) (== true q)) (list true)))) (deftest test-anyo-2 (is (= (run 5 [q] (anyo s#) (== true q)) (list true true true true true)))) ;; ----------------------------------------------------------------------------- ;; divergence (def f1 (fresh [] f1)) (deftest test-divergence-1 (is (= (run 1 [q] (conde [f1] [(== false false)])) '(_.0)))) (deftest test-divergence-2 (is (= (run 1 [q] (conde [f1 (== false false)] [(== false false)])) '(_.0)))) (def f2 (fresh [] (conde [f2 (conde [f2] [(== false false)])] [(== false false)]))) (deftest test-divergence-3 (is (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0)))) ;; ----------------------------------------------------------------------------- ;; conda (soft-cut) (deftest test-conda-1 (is (= (run* [x] (conda [(== 'olive x) s#] [(== 'oil x) s#] [u#])) '(olive)))) (deftest test-conda-2 (is (= (run* [x] (conda [(== 'virgin x) u#] [(== 'olive x) s#] [(== 'oil x) s#] [u#])) '()))) (deftest test-conda-3 (is (= (run* [x] (fresh (x y) (== 'split x) (== 'pea y) (conda [(== 'split x) (== x y)] [s#])) (== true x)) '()))) (deftest test-conda-4 (is (= (run* [x] (fresh (x y) (== 'split x) (== 'pea y) (conda [(== x y) (== 'split x)] [s#])) (== true x)) '(true)))) (defn not-pastao [x] (conda [(== 'pasta x) u#] [s#])) (deftest test-conda-5 (is (= (run* [x] (conda [(not-pastao x)] [(== 'spaghetti x)])) '(spaghetti)))) ;; ----------------------------------------------------------------------------- ;; condu (committed-choice) (defn onceo [g] (condu (g s#))) (deftest test-condu-1 (is (= (run* [x] (onceo (teacupo x))) '(tea)))) (deftest test-condu-2 (is (= (run* [r] (conde [(teacupo r) s#] [(== false r) s#])) '(false tea cup)))) (deftest test-condu-3 (is (= (run* [r] (conda [(teacupo r) s#] [(== false r) s#])) '(tea cup)))) ;; ----------------------------------------------------------------------------- ;; disequality (deftest test-disequality-1 (is (= (run* [q] (fresh [x] (!= x 1) (== q x))) '(_.0)))) (deftest test-disequality-2 (is (= (run* [q] (fresh [x] (== q x) (!= x 1))) '(_.0)))) (deftest test-disequality-3 (is (= (run* [q] (fresh [x] (!= x 1) (== x 1) (== q x))) ()))) (deftest test-disequality-4 (is (= (run* [q] (fresh [x] (== x 1) (!= x 1) (== q x))) ()))) (deftest test-disequality-5 (is (= (run* [q] (fresh [x y] (!= x y) (== x 1) (== y 1) (== q x))) ()))) (deftest test-disequality-6 (is (= (run* [q] (fresh [x y] (== x 1) (== y 1) (!= x y) (== q x))) ()))) (deftest test-disequality-7 (is (= (run* [q] (fresh [x y] (== x 1) (!= x y) (== y 2) (== q x))) '(1)))) (deftest test-disequality-8 (is (= (run* [q] (fresh [x y] (!= [x 2] [y 1]) (== x 1) (== y 3) (== q [x y]))) '([1 3])))) (deftest test-disequality-9 (is (= (run* [q] (fresh [x y] (== x 1) (== y 3) (!= [x 2] [y 1]) (== q [x y]))) '([1 3])))) (deftest test-disequality-10 (is (= (run* [q] (fresh [x y] (!= [x 2] [1 y]) (== x 1) (== y 2) (== q [x y]))) ()))) (deftest test-disequality-11 (is (= (run* [q] (fresh [x y] (== x 1) (== y 2) (!= [x 2] [1 y]) (== q [x y]))) ()))) (deftest test-disequality-12 (is (= (run* [q] (fresh [x y z] (!= x y) (== y z) (== x z) (== q x))) ()))) (deftest test-disequality-13 (is (= (run* [q] (fresh [x y z] (== y z) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-14 (is (= (run* [q] (fresh [x y z] (== z y) (== x z) (!= x y) (== q x))) ()))) ;; ----------------------------------------------------------------------------- ;; tabled (defne arco [x y] ([:a :b]) ([:b :a]) ([:b :d])) (def patho (tabled [x y] (conde [(arco x y)] [(fresh [z] (arco x z) (patho z y))]))) (deftest test-tabled-1 (is (= (run* [q] (patho :a q)) '(:b :a :d)))) (defne arco-2 [x y] ([1 2]) ([1 4]) ([1 3]) ([2 3]) ([2 5]) ([3 4]) ([3 5]) ([4 5])) (def patho-2 (tabled [x y] (conde [(arco-2 x y)] [(fresh [z] (arco-2 x z) (patho-2 z y))]))) (deftest test-tabled-2 (let [r (set (run* [q] (patho-2 1 q)))] (is (and (= (count r) 4) (= r #{2 3 4 5}))))) ;; ----------------------------------------------------------------------------- ;; rel (defrel man p) (fact man 'PI:NAME:<NAME>END_PI) (fact man 'PI:NAME:<NAME>END_PI) (fact man 'PI:NAME:<NAME>END_PI) (defrel woman p) (fact woman 'PI:NAME:<NAME>END_PI) (fact woman 'PI:NAME:<NAME>END_PI) (fact woman 'PI:NAME:<NAME>END_PI) (defrel likes p1 p2) (fact likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI) (fact likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI) (fact likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI) (defrel fun p) (fact fun 'PI:NAME:<NAME>END_PI) (deftest test-rel-1 (is (= (run* [q] (fresh [x y] (likes x y) (fun y) (== q [x y]))) '([PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI])))) ;; ----------------------------------------------------------------------------- ;; nil in collection (deftest test-nil-in-coll-1 (is (= (run* [q] (== q [nil])) '([nil])))) (deftest test-nil-in-coll-2 (is (= (run* [q] (== q [1 nil])) '([1 nil])))) (deftest test-nil-in-coll-3 (is (= (run* [q] (== q [nil 1])) '([nil 1])))) (deftest test-nil-in-coll-4 (is (= (run* [q] (== q '(nil))) '((nil))))) (deftest test-nil-in-coll-5 (is (= (run* [q] (== q {:foo nil})) '({:foo nil})))) (deftest test-nil-in-coll-6 (is (= (run* [q] (== q {nil :foo})) '({nil :foo})))) ;; ----------------------------------------------------------------------------- ;; Unifier (deftest test-unifier-1 (is (= (unifier '(?x ?y) '(1 2)) '(1 2)))) (deftest test-unifier-2 (is (= (unifier '(?x ?y 3) '(1 2 ?z)) '(1 2 3)))) (deftest test-unifier-3 (is (= (unifier '[(?x . ?y) 3] [[1 2] 3]) '[(1 2) 3]))) (deftest test-unifier-4 (is (= (unifier '(?x . ?y) '(1 . ?z)) (lcons 1 '_.0)))) (deftest test-unifier-5 (is (= (unifier '(?x 2 . ?y) '(1 2 3 4 5)) '(1 2 3 4 5)))) (deftest test-unifier-6 (is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5)) nil))) (deftest test-binding-map-1 (is (= (binding-map '(?x ?y) '(1 2)) '{?x 1 ?y 2}))) (deftest test-binding-map-2 (is (= (binding-map '(?x ?y 3) '(1 2 ?z)) '{?x 1 ?y 2 ?z 3}))) (deftest test-binding-map-3 (is (= (binding-map '[(?x . ?y) 3] [[1 2] 3]) '{?x 1 ?y (2)}))) (deftest test-binding-map-4 (is (= (binding-map '(?x . ?y) '(1 . ?z)) '{?z _.0, ?x 1, ?y _.0}))) (deftest test-binding-map-5 (is (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5)) '{?x 1 ?y (3 4 5)}))) (deftest test-binding-map-6 (is (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5)) nil))) ;; ----------------------------------------------------------------------------- ;; Occurs Check (deftest test-occurs-check-1 (is (= (run* [q] (== q [q])) ()))) ;; ----------------------------------------------------------------------------- ;; Unifications that should fail (deftest test-unify-fail-1 (is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-2 (is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-3 (is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d]))) ()))) ;; ----------------------------------------------------------------------------- ;; Pattern matching functions preserve metadata (defne ^:tabled dummy "Docstring" [x l] ([_ [x . tail]]) ([_ [head . tail]] (membero x tail))) (deftest test-metadata-defne (is (= (-> #'dummy meta :tabled) true)) (is (= (-> #'dummy meta :doc) "Docstring")))
[ { "context": "el increase-by}))\n\n(increase-cuddle-hunger-level @fred 10)\n;; => {:cuddle-hunger-level 16, :percent-dete", "end": 945, "score": 0.8607107400894165, "start": 941, "tag": "USERNAME", "value": "fred" }, { "context": "ddle-hunger-level 26, :percent-deteriorated 61}\n\n@fred\n;; => {:cuddle-hunger-level 26, :percent-deterior", "end": 1118, "score": 0.8801207542419434, "start": 1114, "tag": "USERNAME", "value": "fred" }, { "context": "d objects\n\n(def ^:dynamic *notification-address* \"dobby@elf.org\")\n\n;; temporarily change the value of a dynamic v", "end": 6061, "score": 0.9999216198921204, "start": 6048, "tag": "EMAIL", "value": "dobby@elf.org" }, { "context": "f a dynamic var\n(binding [*notification-address* \"test@elf.org\"]\n *notification-address*)\n;; => \"test@elf.org\"\n", "end": 6160, "score": 0.9999252557754517, "start": 6148, "tag": "EMAIL", "value": "test@elf.org" }, { "context": " \"test@elf.org\"]\n *notification-address*)\n;; => \"test@elf.org\"\n\n*notification-address*\n;; => \"dobby@elf.org\"\n\n(", "end": 6208, "score": 0.9999245405197144, "start": 6196, "tag": "EMAIL", "value": "test@elf.org" }, { "context": " => \"test@elf.org\"\n\n*notification-address*\n;; => \"dobby@elf.org\"\n\n(def ^:dynamic *troll-thought* nil)\n(defn troll", "end": 6254, "score": 0.9999229311943054, "start": 6241, "tag": "EMAIL", "value": "dobby@elf.org" }, { "context": "ord-count 5))\n\n;; 3.\n\n(def player1 (ref {:handle \"Kirito\" :hitpoints 15/40 :inventory {:sword \"Dual Blades", "end": 8942, "score": 0.7963814735412598, "start": 8936, "tag": "NAME", "value": "Kirito" }, { "context": ":healing-potion 0}}))\n(def player2 (ref {:handle \"Asuna\" :hitpoints 33/40 :inventory {:healing-potion 1}}", "end": 9049, "score": 0.9812427759170532, "start": 9044, "tag": "NAME", "value": "Asuna" }, { "context": "ssoc :hitpoints 40/40))\n\n@player1\n;; => {:handle \"Kirito\",\n;; :hitpoints 40/40,\n;; :inventory {:sw", "end": 9244, "score": 0.960730254650116, "start": 9238, "tag": "NAME", "value": "Kirito" }, { "context": "s\", :healing-potion 0}}\n\n@player2\n;; => {:handle \"Asuna\", :hitpoints 33/40, :inventory {:healing-potion 0", "end": 9364, "score": 0.9769850969314575, "start": 9359, "tag": "NAME", "value": "Asuna" } ]
code/clojure-noob/src/clojure_noob/ch10.clj
itsrainingmani/learn-clojure-in-public
7
(ns clojure-noob.ch10 (:require [clojure.repl :refer :all]) (:gen-class)) (defn- ch10 [] (println "Welcome to Ch10")) (ch10) (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 60})) (println @fred) ;; doesn't block (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))) (future (println)))) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1}))) ;; => {:cuddle-hunger-level 5, :percent-deteriorated 60} (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) ;; function can take multiple args (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) ;; => {:cuddle-hunger-level 16, :percent-deteriorated 61} (swap! fred increase-cuddle-hunger-level 10) ;; => {:cuddle-hunger-level 26, :percent-deteriorated 61} @fred ;; => {:cuddle-hunger-level 26, :percent-deteriorated 61} (update-in {:a {:b 3}} [:a :b] inc) ;; => {:a {:b 4}} (update-in {:a {:b 3}} [:a :b] + 10) ;; => {:a {:b 13}} (swap! fred update-in [:cuddle-hunger-level] + 10) ;; => {:cuddle-hunger-level 22, :percent-deteriorated 61} ;; You can use atoms to retain past state (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current state:" @num)) ;; update an atom without checking it's current value (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) ;; => {:cuddle-hunger-level 0, :percent-deteriorated 0} ;; watch (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) ;; alert when a zombie's shuffle speed reaches 5000 SPH (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to your courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) ;; watch functions take 4 args - a key for reporting, atom being watches, state of the atom before the update and the state of the atom after the update (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) ;; add a watcher - takes in a ref, key and the watcher function (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) (swap! fred update-in [:cuddle-hunger-level] + 30) ;; Validator - what states are allowable for a reference ;; ensure a zombie's percent-deteriorated is between 0 and 100 (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100))) ;; add validator during atom creation (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) ;; (swap! bobby update-in [:percent-deteriorated] + 101) ;; throws an exception ;; Refs (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome "Create an initial sock gnome state with no socks" [name] {:name name :socks #{}}) (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) (:socks @dryer) ;; => #{{:variety "gollumed", :count 2} {:variety "striped", :count 2} ;; {:variety "wool", :count 2} ;; {:variety "passive-aggressive", :count 2} ;; {:variety "argyle", :count 2} {:variety "business", :count 2} ;; {:variety "darned", :count 2} {:variety "polka-dotted", :count 2} ;; {:variety "horsehair", :count 2} {:variety "power", :count 2} ;; {:variety "athletic", :count 2} {:variety "mulleted", :count 2} ;; {:variety "invisible", :count 2}} (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) (steal-sock sock-gnome dryer) (:socks @dryer) ;; => #{{:variety "striped", :count 2} {:variety "wool", :count 2} ;; {:variety "passive-aggressive", :count 2} ;; {:variety "argyle", :count 2} {:variety "business", :count 2} ;; {:variety "darned", :count 2} {:variety "polka-dotted", :count 2} ;; {:variety "horsehair", :count 2} {:variety "power", :count 2} ;; {:variety "athletic", :count 2} {:variety "gollumed", :count 1} ;; {:variety "mulleted", :count 2} {:variety "invisible", :count 2}} (:socks @sock-gnome) ;; => #{{:variety "gollumed", :count 1}} (def counter (ref 0)) (future (dosync (alter counter inc) (println @counter) (Thread/sleep 500) (alter counter inc) (println @counter))) (Thread/sleep 250) (println @counter) ;; commute (defn sleep-print-update [sleep-time thread-name update-fn] (fn [state] (Thread/sleep sleep-time) (println (str thread-name ": " state)) (update-fn state))) (def counter (ref 0)) (future (dosync (commute counter (sleep-print-update 100 "Thread A" inc)))) (future (dosync (commute counter (sleep-print-update 150 "Thread B" inc)))) @counter ;; => 2 ;; var ;; associations between symbols and objects (def ^:dynamic *notification-address* "dobby@elf.org") ;; temporarily change the value of a dynamic var (binding [*notification-address* "test@elf.org"] *notification-address*) ;; => "test@elf.org" *notification-address* ;; => "dobby@elf.org" (def ^:dynamic *troll-thought* nil) (defn troll-riddle [your-answer] (let [number "man meat"] (when (thread-bound? #'*troll-thought*) ;; checks if the var has been bound (set! *troll-thought* number)) (if (= number your-answer) "TROLL: You can cross the bridge!" "TROLL: Time to eat you, succulent human!"))) (binding [*troll-thought* nil] (println (troll-riddle 2)) (println "Succulent Human: OOOH! The answer was " *troll-thought*)) *troll-thought* ;; var root (def power-source "hair") (alter-var-root #'power-source (fn [_] "7 eleven parking lot")) power-source ;; => "7 eleven parking lot" (with-redefs [*out* *out*] (doto (Thread. #(println "with redefs allows me to show up in REPL")) .start .join)) ;; pmap (defn always-1 [] 1) (take 5 (repeatedly always-1)) ;; => (1 1 1 1 1) (take 5 (repeatedly (partial rand-int 10))) ;; => (6 6 8 7 9) (def alphabet-length 26) (def letters (mapv (comp str char (partial + 65)) (range alphabet-length))) (defn random-string "Returns a random string of specified length" [length] (apply str (take length (repeatedly #(rand-nth letters))))) (defn random-string-list [list-length string-length] (doall (take list-length (repeatedly (partial random-string string-length))))) (def orc-names (random-string-list 3000 7000)) ;; (time (dorun (map clojure.string/lower-case orc-names))) ;; "Elapsed time: 295.426771 msecs" ;; (time (dorun (pmap clojure.string/lower-case orc-names))) ;; "Elapsed time: 129.370606 msecs" ;; increasing the grain size (def numbers [1 2 3 4 5 6 7 8 9 10]) (partition-all 3 numbers) ;; grain size is one (pmap inc numbers) ;; grain size is three (apply concat (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers))) ;; using doall forces the lazy sequence returned by map to be realized ;; Chapter Exercises ;; 1. (def a (atom 0)) (swap! a inc) (swap! a inc) @a ;; => 2 ;; 2. (defn get-quote [] (slurp "https://www.braveclojure.com/random-quote")) (defn quote-word-count [num-quotes] (let [word-freq (atom {})] (dotimes [i num-quotes] (deref (future (let [cur-quote (as-> (get-quote) x (clojure.string/replace x #"--" "") (clojure.string/replace x #"\n" "") (clojure.string/lower-case x)) cur-freq (frequencies (clojure.string/split cur-quote #" "))] (swap! word-freq merge cur-freq))))) (deref word-freq))) (println (quote-word-count 5)) ;; 3. (def player1 (ref {:handle "Kirito" :hitpoints 15/40 :inventory {:sword "Dual Blades" :healing-potion 0}})) (def player2 (ref {:handle "Asuna" :hitpoints 33/40 :inventory {:healing-potion 1}})) (dosync (alter player2 update-in [:inventory :healing-potion] dec) (alter player1 assoc :hitpoints 40/40)) @player1 ;; => {:handle "Kirito", ;; :hitpoints 40/40, ;; :inventory {:sword "Dual Blades", :healing-potion 0}} @player2 ;; => {:handle "Asuna", :hitpoints 33/40, :inventory {:healing-potion 0}}
38059
(ns clojure-noob.ch10 (:require [clojure.repl :refer :all]) (:gen-class)) (defn- ch10 [] (println "Welcome to Ch10")) (ch10) (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 60})) (println @fred) ;; doesn't block (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))) (future (println)))) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1}))) ;; => {:cuddle-hunger-level 5, :percent-deteriorated 60} (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) ;; function can take multiple args (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) ;; => {:cuddle-hunger-level 16, :percent-deteriorated 61} (swap! fred increase-cuddle-hunger-level 10) ;; => {:cuddle-hunger-level 26, :percent-deteriorated 61} @fred ;; => {:cuddle-hunger-level 26, :percent-deteriorated 61} (update-in {:a {:b 3}} [:a :b] inc) ;; => {:a {:b 4}} (update-in {:a {:b 3}} [:a :b] + 10) ;; => {:a {:b 13}} (swap! fred update-in [:cuddle-hunger-level] + 10) ;; => {:cuddle-hunger-level 22, :percent-deteriorated 61} ;; You can use atoms to retain past state (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current state:" @num)) ;; update an atom without checking it's current value (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) ;; => {:cuddle-hunger-level 0, :percent-deteriorated 0} ;; watch (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) ;; alert when a zombie's shuffle speed reaches 5000 SPH (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to your courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) ;; watch functions take 4 args - a key for reporting, atom being watches, state of the atom before the update and the state of the atom after the update (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) ;; add a watcher - takes in a ref, key and the watcher function (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) (swap! fred update-in [:cuddle-hunger-level] + 30) ;; Validator - what states are allowable for a reference ;; ensure a zombie's percent-deteriorated is between 0 and 100 (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100))) ;; add validator during atom creation (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) ;; (swap! bobby update-in [:percent-deteriorated] + 101) ;; throws an exception ;; Refs (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome "Create an initial sock gnome state with no socks" [name] {:name name :socks #{}}) (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) (:socks @dryer) ;; => #{{:variety "gollumed", :count 2} {:variety "striped", :count 2} ;; {:variety "wool", :count 2} ;; {:variety "passive-aggressive", :count 2} ;; {:variety "argyle", :count 2} {:variety "business", :count 2} ;; {:variety "darned", :count 2} {:variety "polka-dotted", :count 2} ;; {:variety "horsehair", :count 2} {:variety "power", :count 2} ;; {:variety "athletic", :count 2} {:variety "mulleted", :count 2} ;; {:variety "invisible", :count 2}} (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) (steal-sock sock-gnome dryer) (:socks @dryer) ;; => #{{:variety "striped", :count 2} {:variety "wool", :count 2} ;; {:variety "passive-aggressive", :count 2} ;; {:variety "argyle", :count 2} {:variety "business", :count 2} ;; {:variety "darned", :count 2} {:variety "polka-dotted", :count 2} ;; {:variety "horsehair", :count 2} {:variety "power", :count 2} ;; {:variety "athletic", :count 2} {:variety "gollumed", :count 1} ;; {:variety "mulleted", :count 2} {:variety "invisible", :count 2}} (:socks @sock-gnome) ;; => #{{:variety "gollumed", :count 1}} (def counter (ref 0)) (future (dosync (alter counter inc) (println @counter) (Thread/sleep 500) (alter counter inc) (println @counter))) (Thread/sleep 250) (println @counter) ;; commute (defn sleep-print-update [sleep-time thread-name update-fn] (fn [state] (Thread/sleep sleep-time) (println (str thread-name ": " state)) (update-fn state))) (def counter (ref 0)) (future (dosync (commute counter (sleep-print-update 100 "Thread A" inc)))) (future (dosync (commute counter (sleep-print-update 150 "Thread B" inc)))) @counter ;; => 2 ;; var ;; associations between symbols and objects (def ^:dynamic *notification-address* "<EMAIL>") ;; temporarily change the value of a dynamic var (binding [*notification-address* "<EMAIL>"] *notification-address*) ;; => "<EMAIL>" *notification-address* ;; => "<EMAIL>" (def ^:dynamic *troll-thought* nil) (defn troll-riddle [your-answer] (let [number "man meat"] (when (thread-bound? #'*troll-thought*) ;; checks if the var has been bound (set! *troll-thought* number)) (if (= number your-answer) "TROLL: You can cross the bridge!" "TROLL: Time to eat you, succulent human!"))) (binding [*troll-thought* nil] (println (troll-riddle 2)) (println "Succulent Human: OOOH! The answer was " *troll-thought*)) *troll-thought* ;; var root (def power-source "hair") (alter-var-root #'power-source (fn [_] "7 eleven parking lot")) power-source ;; => "7 eleven parking lot" (with-redefs [*out* *out*] (doto (Thread. #(println "with redefs allows me to show up in REPL")) .start .join)) ;; pmap (defn always-1 [] 1) (take 5 (repeatedly always-1)) ;; => (1 1 1 1 1) (take 5 (repeatedly (partial rand-int 10))) ;; => (6 6 8 7 9) (def alphabet-length 26) (def letters (mapv (comp str char (partial + 65)) (range alphabet-length))) (defn random-string "Returns a random string of specified length" [length] (apply str (take length (repeatedly #(rand-nth letters))))) (defn random-string-list [list-length string-length] (doall (take list-length (repeatedly (partial random-string string-length))))) (def orc-names (random-string-list 3000 7000)) ;; (time (dorun (map clojure.string/lower-case orc-names))) ;; "Elapsed time: 295.426771 msecs" ;; (time (dorun (pmap clojure.string/lower-case orc-names))) ;; "Elapsed time: 129.370606 msecs" ;; increasing the grain size (def numbers [1 2 3 4 5 6 7 8 9 10]) (partition-all 3 numbers) ;; grain size is one (pmap inc numbers) ;; grain size is three (apply concat (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers))) ;; using doall forces the lazy sequence returned by map to be realized ;; Chapter Exercises ;; 1. (def a (atom 0)) (swap! a inc) (swap! a inc) @a ;; => 2 ;; 2. (defn get-quote [] (slurp "https://www.braveclojure.com/random-quote")) (defn quote-word-count [num-quotes] (let [word-freq (atom {})] (dotimes [i num-quotes] (deref (future (let [cur-quote (as-> (get-quote) x (clojure.string/replace x #"--" "") (clojure.string/replace x #"\n" "") (clojure.string/lower-case x)) cur-freq (frequencies (clojure.string/split cur-quote #" "))] (swap! word-freq merge cur-freq))))) (deref word-freq))) (println (quote-word-count 5)) ;; 3. (def player1 (ref {:handle "<NAME>" :hitpoints 15/40 :inventory {:sword "Dual Blades" :healing-potion 0}})) (def player2 (ref {:handle "<NAME>" :hitpoints 33/40 :inventory {:healing-potion 1}})) (dosync (alter player2 update-in [:inventory :healing-potion] dec) (alter player1 assoc :hitpoints 40/40)) @player1 ;; => {:handle "<NAME>", ;; :hitpoints 40/40, ;; :inventory {:sword "Dual Blades", :healing-potion 0}} @player2 ;; => {:handle "<NAME>", :hitpoints 33/40, :inventory {:healing-potion 0}}
true
(ns clojure-noob.ch10 (:require [clojure.repl :refer :all]) (:gen-class)) (defn- ch10 [] (println "Welcome to Ch10")) (ch10) (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 60})) (println @fred) ;; doesn't block (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))) (future (println)))) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1}))) ;; => {:cuddle-hunger-level 5, :percent-deteriorated 60} (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) ;; function can take multiple args (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) ;; => {:cuddle-hunger-level 16, :percent-deteriorated 61} (swap! fred increase-cuddle-hunger-level 10) ;; => {:cuddle-hunger-level 26, :percent-deteriorated 61} @fred ;; => {:cuddle-hunger-level 26, :percent-deteriorated 61} (update-in {:a {:b 3}} [:a :b] inc) ;; => {:a {:b 4}} (update-in {:a {:b 3}} [:a :b] + 10) ;; => {:a {:b 13}} (swap! fred update-in [:cuddle-hunger-level] + 10) ;; => {:cuddle-hunger-level 22, :percent-deteriorated 61} ;; You can use atoms to retain past state (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current state:" @num)) ;; update an atom without checking it's current value (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) ;; => {:cuddle-hunger-level 0, :percent-deteriorated 0} ;; watch (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) ;; alert when a zombie's shuffle speed reaches 5000 SPH (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to your courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) ;; watch functions take 4 args - a key for reporting, atom being watches, state of the atom before the update and the state of the atom after the update (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) ;; add a watcher - takes in a ref, key and the watcher function (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) (swap! fred update-in [:cuddle-hunger-level] + 30) ;; Validator - what states are allowable for a reference ;; ensure a zombie's percent-deteriorated is between 0 and 100 (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100))) ;; add validator during atom creation (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) ;; (swap! bobby update-in [:percent-deteriorated] + 101) ;; throws an exception ;; Refs (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome "Create an initial sock gnome state with no socks" [name] {:name name :socks #{}}) (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) (:socks @dryer) ;; => #{{:variety "gollumed", :count 2} {:variety "striped", :count 2} ;; {:variety "wool", :count 2} ;; {:variety "passive-aggressive", :count 2} ;; {:variety "argyle", :count 2} {:variety "business", :count 2} ;; {:variety "darned", :count 2} {:variety "polka-dotted", :count 2} ;; {:variety "horsehair", :count 2} {:variety "power", :count 2} ;; {:variety "athletic", :count 2} {:variety "mulleted", :count 2} ;; {:variety "invisible", :count 2}} (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) (steal-sock sock-gnome dryer) (:socks @dryer) ;; => #{{:variety "striped", :count 2} {:variety "wool", :count 2} ;; {:variety "passive-aggressive", :count 2} ;; {:variety "argyle", :count 2} {:variety "business", :count 2} ;; {:variety "darned", :count 2} {:variety "polka-dotted", :count 2} ;; {:variety "horsehair", :count 2} {:variety "power", :count 2} ;; {:variety "athletic", :count 2} {:variety "gollumed", :count 1} ;; {:variety "mulleted", :count 2} {:variety "invisible", :count 2}} (:socks @sock-gnome) ;; => #{{:variety "gollumed", :count 1}} (def counter (ref 0)) (future (dosync (alter counter inc) (println @counter) (Thread/sleep 500) (alter counter inc) (println @counter))) (Thread/sleep 250) (println @counter) ;; commute (defn sleep-print-update [sleep-time thread-name update-fn] (fn [state] (Thread/sleep sleep-time) (println (str thread-name ": " state)) (update-fn state))) (def counter (ref 0)) (future (dosync (commute counter (sleep-print-update 100 "Thread A" inc)))) (future (dosync (commute counter (sleep-print-update 150 "Thread B" inc)))) @counter ;; => 2 ;; var ;; associations between symbols and objects (def ^:dynamic *notification-address* "PI:EMAIL:<EMAIL>END_PI") ;; temporarily change the value of a dynamic var (binding [*notification-address* "PI:EMAIL:<EMAIL>END_PI"] *notification-address*) ;; => "PI:EMAIL:<EMAIL>END_PI" *notification-address* ;; => "PI:EMAIL:<EMAIL>END_PI" (def ^:dynamic *troll-thought* nil) (defn troll-riddle [your-answer] (let [number "man meat"] (when (thread-bound? #'*troll-thought*) ;; checks if the var has been bound (set! *troll-thought* number)) (if (= number your-answer) "TROLL: You can cross the bridge!" "TROLL: Time to eat you, succulent human!"))) (binding [*troll-thought* nil] (println (troll-riddle 2)) (println "Succulent Human: OOOH! The answer was " *troll-thought*)) *troll-thought* ;; var root (def power-source "hair") (alter-var-root #'power-source (fn [_] "7 eleven parking lot")) power-source ;; => "7 eleven parking lot" (with-redefs [*out* *out*] (doto (Thread. #(println "with redefs allows me to show up in REPL")) .start .join)) ;; pmap (defn always-1 [] 1) (take 5 (repeatedly always-1)) ;; => (1 1 1 1 1) (take 5 (repeatedly (partial rand-int 10))) ;; => (6 6 8 7 9) (def alphabet-length 26) (def letters (mapv (comp str char (partial + 65)) (range alphabet-length))) (defn random-string "Returns a random string of specified length" [length] (apply str (take length (repeatedly #(rand-nth letters))))) (defn random-string-list [list-length string-length] (doall (take list-length (repeatedly (partial random-string string-length))))) (def orc-names (random-string-list 3000 7000)) ;; (time (dorun (map clojure.string/lower-case orc-names))) ;; "Elapsed time: 295.426771 msecs" ;; (time (dorun (pmap clojure.string/lower-case orc-names))) ;; "Elapsed time: 129.370606 msecs" ;; increasing the grain size (def numbers [1 2 3 4 5 6 7 8 9 10]) (partition-all 3 numbers) ;; grain size is one (pmap inc numbers) ;; grain size is three (apply concat (pmap (fn [number-group] (doall (map inc number-group))) (partition-all 3 numbers))) ;; using doall forces the lazy sequence returned by map to be realized ;; Chapter Exercises ;; 1. (def a (atom 0)) (swap! a inc) (swap! a inc) @a ;; => 2 ;; 2. (defn get-quote [] (slurp "https://www.braveclojure.com/random-quote")) (defn quote-word-count [num-quotes] (let [word-freq (atom {})] (dotimes [i num-quotes] (deref (future (let [cur-quote (as-> (get-quote) x (clojure.string/replace x #"--" "") (clojure.string/replace x #"\n" "") (clojure.string/lower-case x)) cur-freq (frequencies (clojure.string/split cur-quote #" "))] (swap! word-freq merge cur-freq))))) (deref word-freq))) (println (quote-word-count 5)) ;; 3. (def player1 (ref {:handle "PI:NAME:<NAME>END_PI" :hitpoints 15/40 :inventory {:sword "Dual Blades" :healing-potion 0}})) (def player2 (ref {:handle "PI:NAME:<NAME>END_PI" :hitpoints 33/40 :inventory {:healing-potion 1}})) (dosync (alter player2 update-in [:inventory :healing-potion] dec) (alter player1 assoc :hitpoints 40/40)) @player1 ;; => {:handle "PI:NAME:<NAME>END_PI", ;; :hitpoints 40/40, ;; :inventory {:sword "Dual Blades", :healing-potion 0}} @player2 ;; => {:handle "PI:NAME:<NAME>END_PI", :hitpoints 33/40, :inventory {:healing-potion 0}}
[ { "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.9997614622116089, "start": 123, "tag": "NAME", "value": "Jony Hudson" } ]
src/darwin/utility/random.clj
drcode/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.utility.random "Random number generators and associated functions. These mirror the functions in clojure.core, but use java's ThreadLocalRandom which works well with multi-threading." (:refer-clojure :exclude [rand rand-int rand-nth]) (:import java.util.concurrent.ThreadLocalRandom)) (defn- nextDouble [] (.nextDouble (ThreadLocalRandom/current))) (defn rand ([] (nextDouble)) ([n] (* n (rand)))) (defn rand-int [n] (int (rand n))) (defn rand-nth [l] (nth l (rand-int (count l))))
83104
; ; This file is part of darwin. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: <NAME> ; ; Released under the MIT license.. ; (ns darwin.utility.random "Random number generators and associated functions. These mirror the functions in clojure.core, but use java's ThreadLocalRandom which works well with multi-threading." (:refer-clojure :exclude [rand rand-int rand-nth]) (:import java.util.concurrent.ThreadLocalRandom)) (defn- nextDouble [] (.nextDouble (ThreadLocalRandom/current))) (defn rand ([] (nextDouble)) ([n] (* n (rand)))) (defn rand-int [n] (int (rand n))) (defn rand-nth [l] (nth l (rand-int (count l))))
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.utility.random "Random number generators and associated functions. These mirror the functions in clojure.core, but use java's ThreadLocalRandom which works well with multi-threading." (:refer-clojure :exclude [rand rand-int rand-nth]) (:import java.util.concurrent.ThreadLocalRandom)) (defn- nextDouble [] (.nextDouble (ThreadLocalRandom/current))) (defn rand ([] (nextDouble)) ([n] (* n (rand)))) (defn rand-int [n] (int (rand n))) (defn rand-nth [l] (nth l (rand-int (count l))))
[ { "context": "the command line from user input.\"\n :author \"Paul Landes\"}\n zensols.cisql.read\n (:import [java.util.re", "end": 90, "score": 0.9998750686645508, "start": 79, "tag": "NAME", "value": "Paul Landes" } ]
src/clojure/zensols/cisql/read.clj
plandes/cisql
12
(ns ^{:doc "Process query at the command line from user input." :author "Paul Landes"} zensols.cisql.read (:import [java.util.regex Matcher]) (:require [clojure.tools.logging :as log] [clojure.string :as s] [instaparse.core :as insta] [zensols.cisql.conf :as conf])) (def ^:private cmd-bnf-fn "Generated DSL parser." (atom nil)) (def ^:private interpolation-prefix "The string prefix used to identify variables used for [[interpolation]]." "@@") (def ^:private interpolate-regexp "The string regular expression used to parse variables used for [[interpolation]]." (re-pattern (str interpolation-prefix "([a-zA-Z0-9_]+)"))) (def ^:dynamic *std-in* nil) (def ^:dynamic *print-prompt* true) (def ^:private line-limit 200) (defn- directive-bnf [directive-name nargs] (->> (cond (= "*" nargs) " (ws arg)*" (= "+" nargs) " (ws arg)+" (= ".." nargs) " (ws arg)?" (= "-" nargs) "ws #\".+\"" (and (number? nargs) (= 0 nargs)) "" (and (number? nargs) (= 1 nargs)) " ws arg" (and (number? nargs) (< 1 nargs)) (->> (repeat nargs " ws arg") (apply str))) (str directive-name " = <'" directive-name "'>"))) (defn- cmd-bnf-def [eoq directives] (let [directives (filter #(:arg-count %) directives)] (->> ["form = ws? directive ws? / sql eoq?" (str "directive = " (s/join " | " (map :name directives))) (->> directives (map #(directive-bnf (:name %) (:arg-count %))) (s/join \newline)) "<arg> = ( <\"'\"> #\"[^']+\" <\"'\"> / #\"[^ ]+\" )" "<ws> = <#\"\\s+\">" (str "sql = <'send' ws> #\".+?(?=" eoq ")\" / #\".+(?=" eoq ")\" / #\".+\"") (str "eoq = <'" eoq "'>")] (s/join \newline)))) (defn set-grammer [end-of-query-separator directives] (->> (cmd-bnf-def end-of-query-separator directives) insta/parser (reset! cmd-bnf-fn))) (defn read-input [line] (let [form (@cmd-bnf-fn line) eoq? (and (= 3 (count form)) (= [:eoq] (nth form 2)))] (if (insta/failure? form) (let [msg (pr-str form)] (throw (ex-info msg {:line line :msg msg})))) (->> (second form) list (cons [:eoq? eoq?]) (into {})))) (defn- process-input [end-fn reset-fn query user-input] (let [{:keys [sql directive eoq?]} (read-input user-input)] (log/tracef "sql: <%s>, dir: <%s>, eoq?: <%s>" sql directive eoq?) (log/tracef "query so far: %s" query) (cond directive (end-fn (merge {:name (first directive)} (if (> (count directive) 1) {:args (rest directive)}))) (= (conf/config :linesep) sql) (if (-> query .toString s/trim empty?) (reset-fn) (end-fn :end-of-query)) true (do (.append query sql) (.append query \newline) (if eoq? (end-fn :end-of-query)))))) ;; lifted directly from `clojure.string` (defn- replace-by [^CharSequence s re f] (let [m (re-matcher re s)] (if (.find m) (let [buffer (StringBuffer. (.length s))] (loop [found true] (if found (do (.appendReplacement m buffer (Matcher/quoteReplacement (f (re-groups m)))) (recur (.find m))) (do (.appendTail m buffer) (.toString buffer))))) s))) (defn interpolate [s m] (letfn [(repfn [[lit vname]] (str (get m (keyword vname) (str interpolation-prefix vname))))] (and s (replace-by s interpolate-regexp repfn)))) (defn read-query "Read a query and process it." [& {:keys [user-input print-prompt] :or {print-prompt *print-prompt*}}] (let [query (StringBuilder.) line-no (atom 1) directive (atom nil)] (letfn [(reset [] (reset! line-no 0)) (end [dir] (log/debugf "query: %s" query) (reset! line-no line-limit) (reset! directive dir))] (while (<= @line-no line-limit) (log/tracef "lines no: %d" @line-no) (let [prompt (try (format (conf/config :prompt) @line-no) (catch Exception e (format "<bad prompt: %s> " e)))] (if print-prompt (print prompt))) (flush) (let [user-input (-> user-input (or (.readLine *std-in*)) (interpolate (conf/config)))] (log/debugf "line: %s" user-input) (cond (nil? user-input) (end :end-of-session) (-> user-input s/trim empty?) (.append query \newline) true (process-input end reset query user-input))) (swap! line-no inc))) (let [query-str (s/trim (.toString query)) query (if-not (empty? query-str) query-str)] (merge (if query {:query query}) {:directive @directive}))))
52775
(ns ^{:doc "Process query at the command line from user input." :author "<NAME>"} zensols.cisql.read (:import [java.util.regex Matcher]) (:require [clojure.tools.logging :as log] [clojure.string :as s] [instaparse.core :as insta] [zensols.cisql.conf :as conf])) (def ^:private cmd-bnf-fn "Generated DSL parser." (atom nil)) (def ^:private interpolation-prefix "The string prefix used to identify variables used for [[interpolation]]." "@@") (def ^:private interpolate-regexp "The string regular expression used to parse variables used for [[interpolation]]." (re-pattern (str interpolation-prefix "([a-zA-Z0-9_]+)"))) (def ^:dynamic *std-in* nil) (def ^:dynamic *print-prompt* true) (def ^:private line-limit 200) (defn- directive-bnf [directive-name nargs] (->> (cond (= "*" nargs) " (ws arg)*" (= "+" nargs) " (ws arg)+" (= ".." nargs) " (ws arg)?" (= "-" nargs) "ws #\".+\"" (and (number? nargs) (= 0 nargs)) "" (and (number? nargs) (= 1 nargs)) " ws arg" (and (number? nargs) (< 1 nargs)) (->> (repeat nargs " ws arg") (apply str))) (str directive-name " = <'" directive-name "'>"))) (defn- cmd-bnf-def [eoq directives] (let [directives (filter #(:arg-count %) directives)] (->> ["form = ws? directive ws? / sql eoq?" (str "directive = " (s/join " | " (map :name directives))) (->> directives (map #(directive-bnf (:name %) (:arg-count %))) (s/join \newline)) "<arg> = ( <\"'\"> #\"[^']+\" <\"'\"> / #\"[^ ]+\" )" "<ws> = <#\"\\s+\">" (str "sql = <'send' ws> #\".+?(?=" eoq ")\" / #\".+(?=" eoq ")\" / #\".+\"") (str "eoq = <'" eoq "'>")] (s/join \newline)))) (defn set-grammer [end-of-query-separator directives] (->> (cmd-bnf-def end-of-query-separator directives) insta/parser (reset! cmd-bnf-fn))) (defn read-input [line] (let [form (@cmd-bnf-fn line) eoq? (and (= 3 (count form)) (= [:eoq] (nth form 2)))] (if (insta/failure? form) (let [msg (pr-str form)] (throw (ex-info msg {:line line :msg msg})))) (->> (second form) list (cons [:eoq? eoq?]) (into {})))) (defn- process-input [end-fn reset-fn query user-input] (let [{:keys [sql directive eoq?]} (read-input user-input)] (log/tracef "sql: <%s>, dir: <%s>, eoq?: <%s>" sql directive eoq?) (log/tracef "query so far: %s" query) (cond directive (end-fn (merge {:name (first directive)} (if (> (count directive) 1) {:args (rest directive)}))) (= (conf/config :linesep) sql) (if (-> query .toString s/trim empty?) (reset-fn) (end-fn :end-of-query)) true (do (.append query sql) (.append query \newline) (if eoq? (end-fn :end-of-query)))))) ;; lifted directly from `clojure.string` (defn- replace-by [^CharSequence s re f] (let [m (re-matcher re s)] (if (.find m) (let [buffer (StringBuffer. (.length s))] (loop [found true] (if found (do (.appendReplacement m buffer (Matcher/quoteReplacement (f (re-groups m)))) (recur (.find m))) (do (.appendTail m buffer) (.toString buffer))))) s))) (defn interpolate [s m] (letfn [(repfn [[lit vname]] (str (get m (keyword vname) (str interpolation-prefix vname))))] (and s (replace-by s interpolate-regexp repfn)))) (defn read-query "Read a query and process it." [& {:keys [user-input print-prompt] :or {print-prompt *print-prompt*}}] (let [query (StringBuilder.) line-no (atom 1) directive (atom nil)] (letfn [(reset [] (reset! line-no 0)) (end [dir] (log/debugf "query: %s" query) (reset! line-no line-limit) (reset! directive dir))] (while (<= @line-no line-limit) (log/tracef "lines no: %d" @line-no) (let [prompt (try (format (conf/config :prompt) @line-no) (catch Exception e (format "<bad prompt: %s> " e)))] (if print-prompt (print prompt))) (flush) (let [user-input (-> user-input (or (.readLine *std-in*)) (interpolate (conf/config)))] (log/debugf "line: %s" user-input) (cond (nil? user-input) (end :end-of-session) (-> user-input s/trim empty?) (.append query \newline) true (process-input end reset query user-input))) (swap! line-no inc))) (let [query-str (s/trim (.toString query)) query (if-not (empty? query-str) query-str)] (merge (if query {:query query}) {:directive @directive}))))
true
(ns ^{:doc "Process query at the command line from user input." :author "PI:NAME:<NAME>END_PI"} zensols.cisql.read (:import [java.util.regex Matcher]) (:require [clojure.tools.logging :as log] [clojure.string :as s] [instaparse.core :as insta] [zensols.cisql.conf :as conf])) (def ^:private cmd-bnf-fn "Generated DSL parser." (atom nil)) (def ^:private interpolation-prefix "The string prefix used to identify variables used for [[interpolation]]." "@@") (def ^:private interpolate-regexp "The string regular expression used to parse variables used for [[interpolation]]." (re-pattern (str interpolation-prefix "([a-zA-Z0-9_]+)"))) (def ^:dynamic *std-in* nil) (def ^:dynamic *print-prompt* true) (def ^:private line-limit 200) (defn- directive-bnf [directive-name nargs] (->> (cond (= "*" nargs) " (ws arg)*" (= "+" nargs) " (ws arg)+" (= ".." nargs) " (ws arg)?" (= "-" nargs) "ws #\".+\"" (and (number? nargs) (= 0 nargs)) "" (and (number? nargs) (= 1 nargs)) " ws arg" (and (number? nargs) (< 1 nargs)) (->> (repeat nargs " ws arg") (apply str))) (str directive-name " = <'" directive-name "'>"))) (defn- cmd-bnf-def [eoq directives] (let [directives (filter #(:arg-count %) directives)] (->> ["form = ws? directive ws? / sql eoq?" (str "directive = " (s/join " | " (map :name directives))) (->> directives (map #(directive-bnf (:name %) (:arg-count %))) (s/join \newline)) "<arg> = ( <\"'\"> #\"[^']+\" <\"'\"> / #\"[^ ]+\" )" "<ws> = <#\"\\s+\">" (str "sql = <'send' ws> #\".+?(?=" eoq ")\" / #\".+(?=" eoq ")\" / #\".+\"") (str "eoq = <'" eoq "'>")] (s/join \newline)))) (defn set-grammer [end-of-query-separator directives] (->> (cmd-bnf-def end-of-query-separator directives) insta/parser (reset! cmd-bnf-fn))) (defn read-input [line] (let [form (@cmd-bnf-fn line) eoq? (and (= 3 (count form)) (= [:eoq] (nth form 2)))] (if (insta/failure? form) (let [msg (pr-str form)] (throw (ex-info msg {:line line :msg msg})))) (->> (second form) list (cons [:eoq? eoq?]) (into {})))) (defn- process-input [end-fn reset-fn query user-input] (let [{:keys [sql directive eoq?]} (read-input user-input)] (log/tracef "sql: <%s>, dir: <%s>, eoq?: <%s>" sql directive eoq?) (log/tracef "query so far: %s" query) (cond directive (end-fn (merge {:name (first directive)} (if (> (count directive) 1) {:args (rest directive)}))) (= (conf/config :linesep) sql) (if (-> query .toString s/trim empty?) (reset-fn) (end-fn :end-of-query)) true (do (.append query sql) (.append query \newline) (if eoq? (end-fn :end-of-query)))))) ;; lifted directly from `clojure.string` (defn- replace-by [^CharSequence s re f] (let [m (re-matcher re s)] (if (.find m) (let [buffer (StringBuffer. (.length s))] (loop [found true] (if found (do (.appendReplacement m buffer (Matcher/quoteReplacement (f (re-groups m)))) (recur (.find m))) (do (.appendTail m buffer) (.toString buffer))))) s))) (defn interpolate [s m] (letfn [(repfn [[lit vname]] (str (get m (keyword vname) (str interpolation-prefix vname))))] (and s (replace-by s interpolate-regexp repfn)))) (defn read-query "Read a query and process it." [& {:keys [user-input print-prompt] :or {print-prompt *print-prompt*}}] (let [query (StringBuilder.) line-no (atom 1) directive (atom nil)] (letfn [(reset [] (reset! line-no 0)) (end [dir] (log/debugf "query: %s" query) (reset! line-no line-limit) (reset! directive dir))] (while (<= @line-no line-limit) (log/tracef "lines no: %d" @line-no) (let [prompt (try (format (conf/config :prompt) @line-no) (catch Exception e (format "<bad prompt: %s> " e)))] (if print-prompt (print prompt))) (flush) (let [user-input (-> user-input (or (.readLine *std-in*)) (interpolate (conf/config)))] (log/debugf "line: %s" user-input) (cond (nil? user-input) (end :end-of-session) (-> user-input s/trim empty?) (.append query \newline) true (process-input end reset query user-input))) (swap! line-no inc))) (let [query-str (s/trim (.toString query)) query (if-not (empty? query-str) query-str)] (merge (if query {:query query}) {:directive @directive}))))
[ { "context": "))\n\n(deftest jobs-permissions-test\n (let [token \"NO_PERMISSIONS_TOKEN\"]\n (assert-invalid-permissions (url/mdb-jobs-u", "end": 2474, "score": 0.9892242550849915, "start": 2454, "tag": "PASSWORD", "value": "NO_PERMISSIONS_TOKEN" } ]
system-int-test/test/cmr/system_int_test/misc/jobs_test.clj
jaybarra/Common-Metadata-Repository
0
(ns cmr.system-int-test.misc.jobs-test "This tests the jobs api." (:require [cheshire.core :as json] [clj-http.client :as client] [clojure.test :refer :all] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.url-helper :as url] [cmr.transmit.config :as transmit-config])) (defn- perform-action-on-jobs "Call the specified endpoint on the jobs api. Parses the response body and returns the status and parsed body." [method app-jobs-url action token] (let [response (client/request {:url (str app-jobs-url (name action)) :method method :accept :json :throw-exceptions false :connection-manager (s/conn-mgr) :headers {"echo-token" token}})] {:status (:status response) :body (json/decode (:body response) true)})) (defn- assert-successful-jobs-control "Pause, resume, and verify status for the given jobs URL using a token with permissions." [url token] (testing "pause returns 204" (is (= 204 (:status (perform-action-on-jobs :post url :pause token))))) ;; Quartz jobs use the database, so we can only check if jobs are paused when we are using ;; the real database (s/only-with-real-database (testing "jobs are marked as paused" (let [response (perform-action-on-jobs :get url :status token)] (is (= {:status 200 :body {:paused true}} response))))) (testing "resume returns 204" (is (= 204 (:status (perform-action-on-jobs :post url :resume token))))) (testing "jobs are not marked as paused" (let [response (perform-action-on-jobs :get url :status token)] (is (= {:status 200 :body {:paused false}} response))))) (defn- assert-invalid-permissions "Ensure the jobs endpoints require a token with ingest system management permission." [url token] (testing "pause returns 401" (is (= 401 (:status (perform-action-on-jobs :post url :pause token))))) (testing "resume returns 401" (is (= 401 (:status (perform-action-on-jobs :post url :resume token))))) (testing "status returns 401" (is (= 401 (:status (perform-action-on-jobs :get url :status token)))))) (deftest general-jobs-test (let [token (transmit-config/echo-system-token)] (assert-successful-jobs-control (url/mdb-jobs-url) token) (assert-successful-jobs-control (url/ingest-jobs-url) token))) (deftest jobs-permissions-test (let [token "NO_PERMISSIONS_TOKEN"] (assert-invalid-permissions (url/mdb-jobs-url) token) (assert-invalid-permissions (url/ingest-jobs-url) token)))
111985
(ns cmr.system-int-test.misc.jobs-test "This tests the jobs api." (:require [cheshire.core :as json] [clj-http.client :as client] [clojure.test :refer :all] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.url-helper :as url] [cmr.transmit.config :as transmit-config])) (defn- perform-action-on-jobs "Call the specified endpoint on the jobs api. Parses the response body and returns the status and parsed body." [method app-jobs-url action token] (let [response (client/request {:url (str app-jobs-url (name action)) :method method :accept :json :throw-exceptions false :connection-manager (s/conn-mgr) :headers {"echo-token" token}})] {:status (:status response) :body (json/decode (:body response) true)})) (defn- assert-successful-jobs-control "Pause, resume, and verify status for the given jobs URL using a token with permissions." [url token] (testing "pause returns 204" (is (= 204 (:status (perform-action-on-jobs :post url :pause token))))) ;; Quartz jobs use the database, so we can only check if jobs are paused when we are using ;; the real database (s/only-with-real-database (testing "jobs are marked as paused" (let [response (perform-action-on-jobs :get url :status token)] (is (= {:status 200 :body {:paused true}} response))))) (testing "resume returns 204" (is (= 204 (:status (perform-action-on-jobs :post url :resume token))))) (testing "jobs are not marked as paused" (let [response (perform-action-on-jobs :get url :status token)] (is (= {:status 200 :body {:paused false}} response))))) (defn- assert-invalid-permissions "Ensure the jobs endpoints require a token with ingest system management permission." [url token] (testing "pause returns 401" (is (= 401 (:status (perform-action-on-jobs :post url :pause token))))) (testing "resume returns 401" (is (= 401 (:status (perform-action-on-jobs :post url :resume token))))) (testing "status returns 401" (is (= 401 (:status (perform-action-on-jobs :get url :status token)))))) (deftest general-jobs-test (let [token (transmit-config/echo-system-token)] (assert-successful-jobs-control (url/mdb-jobs-url) token) (assert-successful-jobs-control (url/ingest-jobs-url) token))) (deftest jobs-permissions-test (let [token "<PASSWORD>"] (assert-invalid-permissions (url/mdb-jobs-url) token) (assert-invalid-permissions (url/ingest-jobs-url) token)))
true
(ns cmr.system-int-test.misc.jobs-test "This tests the jobs api." (:require [cheshire.core :as json] [clj-http.client :as client] [clojure.test :refer :all] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.url-helper :as url] [cmr.transmit.config :as transmit-config])) (defn- perform-action-on-jobs "Call the specified endpoint on the jobs api. Parses the response body and returns the status and parsed body." [method app-jobs-url action token] (let [response (client/request {:url (str app-jobs-url (name action)) :method method :accept :json :throw-exceptions false :connection-manager (s/conn-mgr) :headers {"echo-token" token}})] {:status (:status response) :body (json/decode (:body response) true)})) (defn- assert-successful-jobs-control "Pause, resume, and verify status for the given jobs URL using a token with permissions." [url token] (testing "pause returns 204" (is (= 204 (:status (perform-action-on-jobs :post url :pause token))))) ;; Quartz jobs use the database, so we can only check if jobs are paused when we are using ;; the real database (s/only-with-real-database (testing "jobs are marked as paused" (let [response (perform-action-on-jobs :get url :status token)] (is (= {:status 200 :body {:paused true}} response))))) (testing "resume returns 204" (is (= 204 (:status (perform-action-on-jobs :post url :resume token))))) (testing "jobs are not marked as paused" (let [response (perform-action-on-jobs :get url :status token)] (is (= {:status 200 :body {:paused false}} response))))) (defn- assert-invalid-permissions "Ensure the jobs endpoints require a token with ingest system management permission." [url token] (testing "pause returns 401" (is (= 401 (:status (perform-action-on-jobs :post url :pause token))))) (testing "resume returns 401" (is (= 401 (:status (perform-action-on-jobs :post url :resume token))))) (testing "status returns 401" (is (= 401 (:status (perform-action-on-jobs :get url :status token)))))) (deftest general-jobs-test (let [token (transmit-config/echo-system-token)] (assert-successful-jobs-control (url/mdb-jobs-url) token) (assert-successful-jobs-control (url/ingest-jobs-url) token))) (deftest jobs-permissions-test (let [token "PI:PASSWORD:<PASSWORD>END_PI"] (assert-invalid-permissions (url/mdb-jobs-url) token) (assert-invalid-permissions (url/ingest-jobs-url) token)))
[ { "context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998839497566223, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
test/territory_bro/event_store_test.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.event-store-test (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [territory-bro.db :as db] [territory-bro.event-store :as event-store] [territory-bro.fixtures :refer [db-fixture]] [territory-bro.json :as json] [territory-bro.testutil :refer [re-equals re-contains grab-exception]]) (:import (java.util UUID) (org.postgresql.util PSQLException) (clojure.lang ExceptionInfo))) (use-fixtures :once db-fixture) (defn event->json-no-validate [event] (json/generate-string event)) (defn json->event-no-validate [json] (-> (json/parse-string json) (update :event/type keyword))) (deftest event-store-test ;; bypass validating serializers (binding [event-store/*event->json* event->json-no-validate event-store/*json->event* json->event-no-validate] (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [stream-1 (UUID/randomUUID) stream-2 (UUID/randomUUID) events [{:event/type :event-1 :stuff "foo"} {:event/type :event-2 :stuff "bar"}]] (testing "create new stream" (is (= 2 (event-store/save! conn stream-1 0 events))) (is (= 4 (event-store/save! conn stream-2 0 events)) "should return the global revision of the last written event")) (testing "read stream" (is (= [{:event/stream-id stream-1 :event/stream-revision 1 :event/global-revision 1 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"}] (event-store/read-stream conn stream-1) (event-store/read-stream conn stream-1 {:since 0}) (event-store/read-stream conn stream-1 {:since nil})))) (testing "read stream since revision" (is (= [{:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"}] (event-store/read-stream conn stream-1 {:since 1})))) (testing "read all events" (is (= [{:event/stream-id stream-1 :event/stream-revision 1 :event/global-revision 1 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"} {:event/stream-id stream-2 :event/stream-revision 1 :event/global-revision 3 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-2 :event/stream-revision 2 :event/global-revision 4 :event/type :event-2 :stuff "bar"}] (event-store/read-all-events conn) (event-store/read-all-events conn {:since 0}) (event-store/read-all-events conn {:since nil})))) (testing "read all events since revision" (is (= [{:event/stream-id stream-2 :event/stream-revision 2 :event/global-revision 4 :event/type :event-2 :stuff "bar"}] (event-store/read-all-events conn {:since 3})))) (testing "append to stream" (testing "with concurrency check" (is (= 5 (event-store/save! conn stream-1 2 [{:event/type :event-3 :stuff "gazonk"}])))) (testing "without concurrency check" (is (= 6 (event-store/save! conn stream-1 nil [{:event/type :event-4 :stuff "gazonk"}])))) (is (= [{:event/stream-id stream-1 :event/stream-revision 3 :event/global-revision 5 :event/type :event-3 :stuff "gazonk"} {:event/stream-id stream-1 :event/stream-revision 4 :event/global-revision 6 :event/type :event-4 :stuff "gazonk"}] (event-store/read-stream conn stream-1 {:since 2})))))) (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (testing "error: expected revision too low" (let [stream-id (UUID/randomUUID)] (event-store/save! conn stream-id 0 [{:event/type :event-1}]) (let [^PSQLException exception (grab-exception (event-store/save! conn stream-id 0 [{:event/type :event-2}]))] (is (instance? PSQLException exception)) (is (str/starts-with? (.getMessage exception) (str "ERROR: tried to insert stream revision 1 but it should have been 2\n" " Hint: The transaction might succeed if retried."))) (is (= db/psql-serialization-failure (.getSQLState exception))))))) (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (testing "error: expected revision too high" (let [stream-id (UUID/randomUUID)] (event-store/save! conn stream-id 0 [{:event/type :event-1}]) (let [^PSQLException exception (grab-exception (event-store/save! conn stream-id 2 [{:event/type :event-2}]))] (is (instance? PSQLException exception)) (is (str/starts-with? (.getMessage exception) (str "ERROR: tried to insert stream revision 3 but it should have been 2\n" " Hint: The transaction might succeed if retried."))) (is (= db/psql-serialization-failure (.getSQLState exception))))))))) (deftest event-validation-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [stream-id (UUID/randomUUID)] (testing "validates events on write" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type :dummy-event") (event-store/save! conn stream-id 0 [{:event/type :dummy-event}])))) ;; bypass validating serializers (binding [event-store/*event->json* event->json-no-validate] (event-store/save! conn stream-id 0 [{:event/type :dummy-event}])) (testing "validates events on reading a stream" (is (thrown-with-msg? ExceptionInfo (re-equals "Event schema validation failed") (event-store/read-stream conn stream-id)))) (testing "validates events on reading all events" (is (thrown-with-msg? ExceptionInfo (re-equals "Event schema validation failed") (event-store/read-all-events conn stream-id)))))))
64712
;; 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.event-store-test (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [territory-bro.db :as db] [territory-bro.event-store :as event-store] [territory-bro.fixtures :refer [db-fixture]] [territory-bro.json :as json] [territory-bro.testutil :refer [re-equals re-contains grab-exception]]) (:import (java.util UUID) (org.postgresql.util PSQLException) (clojure.lang ExceptionInfo))) (use-fixtures :once db-fixture) (defn event->json-no-validate [event] (json/generate-string event)) (defn json->event-no-validate [json] (-> (json/parse-string json) (update :event/type keyword))) (deftest event-store-test ;; bypass validating serializers (binding [event-store/*event->json* event->json-no-validate event-store/*json->event* json->event-no-validate] (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [stream-1 (UUID/randomUUID) stream-2 (UUID/randomUUID) events [{:event/type :event-1 :stuff "foo"} {:event/type :event-2 :stuff "bar"}]] (testing "create new stream" (is (= 2 (event-store/save! conn stream-1 0 events))) (is (= 4 (event-store/save! conn stream-2 0 events)) "should return the global revision of the last written event")) (testing "read stream" (is (= [{:event/stream-id stream-1 :event/stream-revision 1 :event/global-revision 1 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"}] (event-store/read-stream conn stream-1) (event-store/read-stream conn stream-1 {:since 0}) (event-store/read-stream conn stream-1 {:since nil})))) (testing "read stream since revision" (is (= [{:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"}] (event-store/read-stream conn stream-1 {:since 1})))) (testing "read all events" (is (= [{:event/stream-id stream-1 :event/stream-revision 1 :event/global-revision 1 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"} {:event/stream-id stream-2 :event/stream-revision 1 :event/global-revision 3 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-2 :event/stream-revision 2 :event/global-revision 4 :event/type :event-2 :stuff "bar"}] (event-store/read-all-events conn) (event-store/read-all-events conn {:since 0}) (event-store/read-all-events conn {:since nil})))) (testing "read all events since revision" (is (= [{:event/stream-id stream-2 :event/stream-revision 2 :event/global-revision 4 :event/type :event-2 :stuff "bar"}] (event-store/read-all-events conn {:since 3})))) (testing "append to stream" (testing "with concurrency check" (is (= 5 (event-store/save! conn stream-1 2 [{:event/type :event-3 :stuff "gazonk"}])))) (testing "without concurrency check" (is (= 6 (event-store/save! conn stream-1 nil [{:event/type :event-4 :stuff "gazonk"}])))) (is (= [{:event/stream-id stream-1 :event/stream-revision 3 :event/global-revision 5 :event/type :event-3 :stuff "gazonk"} {:event/stream-id stream-1 :event/stream-revision 4 :event/global-revision 6 :event/type :event-4 :stuff "gazonk"}] (event-store/read-stream conn stream-1 {:since 2})))))) (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (testing "error: expected revision too low" (let [stream-id (UUID/randomUUID)] (event-store/save! conn stream-id 0 [{:event/type :event-1}]) (let [^PSQLException exception (grab-exception (event-store/save! conn stream-id 0 [{:event/type :event-2}]))] (is (instance? PSQLException exception)) (is (str/starts-with? (.getMessage exception) (str "ERROR: tried to insert stream revision 1 but it should have been 2\n" " Hint: The transaction might succeed if retried."))) (is (= db/psql-serialization-failure (.getSQLState exception))))))) (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (testing "error: expected revision too high" (let [stream-id (UUID/randomUUID)] (event-store/save! conn stream-id 0 [{:event/type :event-1}]) (let [^PSQLException exception (grab-exception (event-store/save! conn stream-id 2 [{:event/type :event-2}]))] (is (instance? PSQLException exception)) (is (str/starts-with? (.getMessage exception) (str "ERROR: tried to insert stream revision 3 but it should have been 2\n" " Hint: The transaction might succeed if retried."))) (is (= db/psql-serialization-failure (.getSQLState exception))))))))) (deftest event-validation-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [stream-id (UUID/randomUUID)] (testing "validates events on write" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type :dummy-event") (event-store/save! conn stream-id 0 [{:event/type :dummy-event}])))) ;; bypass validating serializers (binding [event-store/*event->json* event->json-no-validate] (event-store/save! conn stream-id 0 [{:event/type :dummy-event}])) (testing "validates events on reading a stream" (is (thrown-with-msg? ExceptionInfo (re-equals "Event schema validation failed") (event-store/read-stream conn stream-id)))) (testing "validates events on reading all events" (is (thrown-with-msg? ExceptionInfo (re-equals "Event schema validation failed") (event-store/read-all-events conn stream-id)))))))
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.event-store-test (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [territory-bro.db :as db] [territory-bro.event-store :as event-store] [territory-bro.fixtures :refer [db-fixture]] [territory-bro.json :as json] [territory-bro.testutil :refer [re-equals re-contains grab-exception]]) (:import (java.util UUID) (org.postgresql.util PSQLException) (clojure.lang ExceptionInfo))) (use-fixtures :once db-fixture) (defn event->json-no-validate [event] (json/generate-string event)) (defn json->event-no-validate [json] (-> (json/parse-string json) (update :event/type keyword))) (deftest event-store-test ;; bypass validating serializers (binding [event-store/*event->json* event->json-no-validate event-store/*json->event* json->event-no-validate] (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [stream-1 (UUID/randomUUID) stream-2 (UUID/randomUUID) events [{:event/type :event-1 :stuff "foo"} {:event/type :event-2 :stuff "bar"}]] (testing "create new stream" (is (= 2 (event-store/save! conn stream-1 0 events))) (is (= 4 (event-store/save! conn stream-2 0 events)) "should return the global revision of the last written event")) (testing "read stream" (is (= [{:event/stream-id stream-1 :event/stream-revision 1 :event/global-revision 1 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"}] (event-store/read-stream conn stream-1) (event-store/read-stream conn stream-1 {:since 0}) (event-store/read-stream conn stream-1 {:since nil})))) (testing "read stream since revision" (is (= [{:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"}] (event-store/read-stream conn stream-1 {:since 1})))) (testing "read all events" (is (= [{:event/stream-id stream-1 :event/stream-revision 1 :event/global-revision 1 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-1 :event/stream-revision 2 :event/global-revision 2 :event/type :event-2 :stuff "bar"} {:event/stream-id stream-2 :event/stream-revision 1 :event/global-revision 3 :event/type :event-1 :stuff "foo"} {:event/stream-id stream-2 :event/stream-revision 2 :event/global-revision 4 :event/type :event-2 :stuff "bar"}] (event-store/read-all-events conn) (event-store/read-all-events conn {:since 0}) (event-store/read-all-events conn {:since nil})))) (testing "read all events since revision" (is (= [{:event/stream-id stream-2 :event/stream-revision 2 :event/global-revision 4 :event/type :event-2 :stuff "bar"}] (event-store/read-all-events conn {:since 3})))) (testing "append to stream" (testing "with concurrency check" (is (= 5 (event-store/save! conn stream-1 2 [{:event/type :event-3 :stuff "gazonk"}])))) (testing "without concurrency check" (is (= 6 (event-store/save! conn stream-1 nil [{:event/type :event-4 :stuff "gazonk"}])))) (is (= [{:event/stream-id stream-1 :event/stream-revision 3 :event/global-revision 5 :event/type :event-3 :stuff "gazonk"} {:event/stream-id stream-1 :event/stream-revision 4 :event/global-revision 6 :event/type :event-4 :stuff "gazonk"}] (event-store/read-stream conn stream-1 {:since 2})))))) (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (testing "error: expected revision too low" (let [stream-id (UUID/randomUUID)] (event-store/save! conn stream-id 0 [{:event/type :event-1}]) (let [^PSQLException exception (grab-exception (event-store/save! conn stream-id 0 [{:event/type :event-2}]))] (is (instance? PSQLException exception)) (is (str/starts-with? (.getMessage exception) (str "ERROR: tried to insert stream revision 1 but it should have been 2\n" " Hint: The transaction might succeed if retried."))) (is (= db/psql-serialization-failure (.getSQLState exception))))))) (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (testing "error: expected revision too high" (let [stream-id (UUID/randomUUID)] (event-store/save! conn stream-id 0 [{:event/type :event-1}]) (let [^PSQLException exception (grab-exception (event-store/save! conn stream-id 2 [{:event/type :event-2}]))] (is (instance? PSQLException exception)) (is (str/starts-with? (.getMessage exception) (str "ERROR: tried to insert stream revision 3 but it should have been 2\n" " Hint: The transaction might succeed if retried."))) (is (= db/psql-serialization-failure (.getSQLState exception))))))))) (deftest event-validation-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (let [stream-id (UUID/randomUUID)] (testing "validates events on write" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type :dummy-event") (event-store/save! conn stream-id 0 [{:event/type :dummy-event}])))) ;; bypass validating serializers (binding [event-store/*event->json* event->json-no-validate] (event-store/save! conn stream-id 0 [{:event/type :dummy-event}])) (testing "validates events on reading a stream" (is (thrown-with-msg? ExceptionInfo (re-equals "Event schema validation failed") (event-store/read-stream conn stream-id)))) (testing "validates events on reading all events" (is (thrown-with-msg? ExceptionInfo (re-equals "Event schema validation failed") (event-store/read-all-events conn stream-id)))))))
[ { "context": "(ns ^{:author \"Sean Dawson\"\n :doc \"Parses a nanoweave transform express", "end": 26, "score": 0.9998635053634644, "start": 15, "tag": "NAME", "value": "Sean Dawson" } ]
src/nanoweave/parsers/expr.clj
NoxHarmonium/nanoweave
0
(ns ^{:author "Sean Dawson" :doc "Parses a nanoweave transform expression.\n An expression combines all the other parsers together and is recursive\n to allow complex transforms to be parsed."} nanoweave.parsers.expr (:require [blancas.kern.core :refer [<:> <|> fwd]] [blancas.kern.expr :refer [chainl1 postfix1 prefix1]] [blancas.kern.lexer.java-style :refer [parens]] [nanoweave.parsers.base :refer [array object]] [nanoweave.parsers.binary-arithmetic :refer [wrapped-add-op wrapped-mul-op]] [nanoweave.parsers.binary-functions :refer [filter-op map-op reduce-op regex-match-op regex-find-op regex-split-op]] [nanoweave.parsers.binary-logic :refer [wrapped-and-op wrapped-eq-op wrapped-or-op wrapped-rel-op wrapped-xor-op]] [nanoweave.parsers.binary-other :refer [closed-range-op concat-op dot-op open-range-op]] [nanoweave.parsers.lambda :refer [function-arguments function-call lambda no-args-lambda no-args-lambda-param]] [nanoweave.parsers.literals :refer [wrapped-bool-lit wrapped-float-lit wrapped-identifier wrapped-nil-lit]] [nanoweave.parsers.pattern-matching :refer [match-scope]] [nanoweave.parsers.scope :refer [else import-statement indexing let-scope when-scope]] [nanoweave.parsers.text :refer [wrapped-interpolated-string regex]] [nanoweave.parsers.unary :refer [wrapped-uni-op]])) ; Forward declarations (declare expr) (def fun-ops "Matches any of the functional binary operators (they have the same precedence)" (<|> map-op filter-op reduce-op regex-match-op regex-find-op regex-split-op)) ; Root Definition (def nweave "Parses a nanoweave structure." (<|> let-scope when-scope import-statement regex wrapped-interpolated-string wrapped-float-lit wrapped-bool-lit else wrapped-nil-lit array object (<|> wrapped-identifier no-args-lambda-param) (<:> no-args-lambda) (<:> lambda) (<:> (parens (fwd expr))) (parens function-arguments))) ; See: http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm ; Concat group needs to be higher than add group because ; it shares the '+' token (def fun-group (chainl1 nweave fun-ops)) (def member-access-group (chainl1 fun-group (<|> dot-op (<:> function-call) (<:> indexing)))) (def concat-group (chainl1 member-access-group concat-op)) (def unary-group (prefix1 concat-group wrapped-uni-op)) (def mul-group (chainl1 unary-group wrapped-mul-op)) (def add-group (chainl1 mul-group wrapped-add-op)) (def rel-group (chainl1 add-group wrapped-rel-op)) (def range-group (chainl1 rel-group (<|> open-range-op closed-range-op))) (def eq-group (chainl1 range-group wrapped-eq-op)) (def and-group (chainl1 eq-group wrapped-and-op)) (def xor-group (chainl1 and-group wrapped-xor-op)) (def or-group (chainl1 xor-group wrapped-or-op)) (def expr (postfix1 or-group match-scope))
93781
(ns ^{:author "<NAME>" :doc "Parses a nanoweave transform expression.\n An expression combines all the other parsers together and is recursive\n to allow complex transforms to be parsed."} nanoweave.parsers.expr (:require [blancas.kern.core :refer [<:> <|> fwd]] [blancas.kern.expr :refer [chainl1 postfix1 prefix1]] [blancas.kern.lexer.java-style :refer [parens]] [nanoweave.parsers.base :refer [array object]] [nanoweave.parsers.binary-arithmetic :refer [wrapped-add-op wrapped-mul-op]] [nanoweave.parsers.binary-functions :refer [filter-op map-op reduce-op regex-match-op regex-find-op regex-split-op]] [nanoweave.parsers.binary-logic :refer [wrapped-and-op wrapped-eq-op wrapped-or-op wrapped-rel-op wrapped-xor-op]] [nanoweave.parsers.binary-other :refer [closed-range-op concat-op dot-op open-range-op]] [nanoweave.parsers.lambda :refer [function-arguments function-call lambda no-args-lambda no-args-lambda-param]] [nanoweave.parsers.literals :refer [wrapped-bool-lit wrapped-float-lit wrapped-identifier wrapped-nil-lit]] [nanoweave.parsers.pattern-matching :refer [match-scope]] [nanoweave.parsers.scope :refer [else import-statement indexing let-scope when-scope]] [nanoweave.parsers.text :refer [wrapped-interpolated-string regex]] [nanoweave.parsers.unary :refer [wrapped-uni-op]])) ; Forward declarations (declare expr) (def fun-ops "Matches any of the functional binary operators (they have the same precedence)" (<|> map-op filter-op reduce-op regex-match-op regex-find-op regex-split-op)) ; Root Definition (def nweave "Parses a nanoweave structure." (<|> let-scope when-scope import-statement regex wrapped-interpolated-string wrapped-float-lit wrapped-bool-lit else wrapped-nil-lit array object (<|> wrapped-identifier no-args-lambda-param) (<:> no-args-lambda) (<:> lambda) (<:> (parens (fwd expr))) (parens function-arguments))) ; See: http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm ; Concat group needs to be higher than add group because ; it shares the '+' token (def fun-group (chainl1 nweave fun-ops)) (def member-access-group (chainl1 fun-group (<|> dot-op (<:> function-call) (<:> indexing)))) (def concat-group (chainl1 member-access-group concat-op)) (def unary-group (prefix1 concat-group wrapped-uni-op)) (def mul-group (chainl1 unary-group wrapped-mul-op)) (def add-group (chainl1 mul-group wrapped-add-op)) (def rel-group (chainl1 add-group wrapped-rel-op)) (def range-group (chainl1 rel-group (<|> open-range-op closed-range-op))) (def eq-group (chainl1 range-group wrapped-eq-op)) (def and-group (chainl1 eq-group wrapped-and-op)) (def xor-group (chainl1 and-group wrapped-xor-op)) (def or-group (chainl1 xor-group wrapped-or-op)) (def expr (postfix1 or-group match-scope))
true
(ns ^{:author "PI:NAME:<NAME>END_PI" :doc "Parses a nanoweave transform expression.\n An expression combines all the other parsers together and is recursive\n to allow complex transforms to be parsed."} nanoweave.parsers.expr (:require [blancas.kern.core :refer [<:> <|> fwd]] [blancas.kern.expr :refer [chainl1 postfix1 prefix1]] [blancas.kern.lexer.java-style :refer [parens]] [nanoweave.parsers.base :refer [array object]] [nanoweave.parsers.binary-arithmetic :refer [wrapped-add-op wrapped-mul-op]] [nanoweave.parsers.binary-functions :refer [filter-op map-op reduce-op regex-match-op regex-find-op regex-split-op]] [nanoweave.parsers.binary-logic :refer [wrapped-and-op wrapped-eq-op wrapped-or-op wrapped-rel-op wrapped-xor-op]] [nanoweave.parsers.binary-other :refer [closed-range-op concat-op dot-op open-range-op]] [nanoweave.parsers.lambda :refer [function-arguments function-call lambda no-args-lambda no-args-lambda-param]] [nanoweave.parsers.literals :refer [wrapped-bool-lit wrapped-float-lit wrapped-identifier wrapped-nil-lit]] [nanoweave.parsers.pattern-matching :refer [match-scope]] [nanoweave.parsers.scope :refer [else import-statement indexing let-scope when-scope]] [nanoweave.parsers.text :refer [wrapped-interpolated-string regex]] [nanoweave.parsers.unary :refer [wrapped-uni-op]])) ; Forward declarations (declare expr) (def fun-ops "Matches any of the functional binary operators (they have the same precedence)" (<|> map-op filter-op reduce-op regex-match-op regex-find-op regex-split-op)) ; Root Definition (def nweave "Parses a nanoweave structure." (<|> let-scope when-scope import-statement regex wrapped-interpolated-string wrapped-float-lit wrapped-bool-lit else wrapped-nil-lit array object (<|> wrapped-identifier no-args-lambda-param) (<:> no-args-lambda) (<:> lambda) (<:> (parens (fwd expr))) (parens function-arguments))) ; See: http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm ; Concat group needs to be higher than add group because ; it shares the '+' token (def fun-group (chainl1 nweave fun-ops)) (def member-access-group (chainl1 fun-group (<|> dot-op (<:> function-call) (<:> indexing)))) (def concat-group (chainl1 member-access-group concat-op)) (def unary-group (prefix1 concat-group wrapped-uni-op)) (def mul-group (chainl1 unary-group wrapped-mul-op)) (def add-group (chainl1 mul-group wrapped-add-op)) (def rel-group (chainl1 add-group wrapped-rel-op)) (def range-group (chainl1 rel-group (<|> open-range-op closed-range-op))) (def eq-group (chainl1 range-group wrapped-eq-op)) (def and-group (chainl1 eq-group wrapped-and-op)) (def xor-group (chainl1 and-group wrapped-xor-op)) (def or-group (chainl1 xor-group wrapped-or-op)) (def expr (postfix1 or-group match-scope))
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9998865127563477, "start": 21, "tag": "NAME", "value": "Peter Monks" }, { "context": " :url \"https://github.com/pmonks/CLJ-2253\"\n :licenses ", "end": 1090, "score": 0.9960072636604309, "start": 1084, "tag": "USERNAME", "value": "pmonks" }, { "context": " :developers [:developer {:id \"pmonks\" :name \"Peter Monks\" :email \"pmonks+CLJ-2253@gma", "end": 1306, "score": 0.9983522295951843, "start": 1300, "tag": "USERNAME", "value": "pmonks" }, { "context": "evelopers [:developer {:id \"pmonks\" :name \"Peter Monks\" :email \"pmonks+CLJ-2253@gmail.com\"}\n ", "end": 1327, "score": 0.9999011158943176, "start": 1316, "tag": "NAME", "value": "Peter Monks" }, { "context": "eloper {:id \"pmonks\" :name \"Peter Monks\" :email \"pmonks+CLJ-2253@gmail.com\"}\n ", "end": 1362, "score": 0.9998589158058167, "start": 1337, "tag": "EMAIL", "value": "pmonks+CLJ-2253@gmail.com" }, { "context": " {:id \"slipset\" :name \"Erik Assum\"}]\n :sc", "end": 1432, "score": 0.9941101670265198, "start": 1425, "tag": "USERNAME", "value": "slipset" }, { "context": " {:id \"slipset\" :name \"Erik Assum\"}]\n :scm {:ur", "end": 1451, "score": 0.999789834022522, "start": 1441, "tag": "NAME", "value": "Erik Assum" }, { "context": " :scm {:url \"https://github.com/pmonks/CLJ-2253\" :connection \"scm:git:git://github.com/p", "end": 1529, "score": 0.9937744736671448, "start": 1523, "tag": "USERNAME", "value": "pmonks" }, { "context": "s/CLJ-2253\" :connection \"scm:git:git://github.com/pmonks/CLJ-2253.git\" :developer-connection \"scm:git:ssh:", "end": 1584, "score": 0.997658908367157, "start": 1578, "tag": "USERNAME", "value": "pmonks" }, { "context": "eveloper-connection \"scm:git:ssh://git@github.com/pmonks/CLJ-2253.git\"}\n :issue-man", "end": 1657, "score": 0.9967458844184875, "start": 1651, "tag": "USERNAME", "value": "pmonks" }, { "context": "gement {:system \"github\" :url \"https://github.com/pmonks/CLJ-2253/issues\"}}))\n", "end": 1764, "score": 0.9996630549430847, "start": 1758, "tag": "USERNAME", "value": "pmonks" } ]
pbr.clj
pmonks/CLJ-2253
0
; ; Copyright © 2021 Peter Monks ; ; 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. ; ; SPDX-License-Identifier: Apache-2.0 ; (def lib 'com.github.pmonks/clj-2253) #_{:clj-kondo/ignore [:unresolved-namespace]} (def version (format "1.0.%s" (b/git-count-revs nil))) (defn set-opts [opts] (assoc opts :lib lib :version version :write-pom true :validate-pom true :pom {:description "A workaround for https://dev.clojure.org/jira/browse/CLJ-2253." :url "https://github.com/pmonks/CLJ-2253" :licenses [:license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html"}] :developers [:developer {:id "pmonks" :name "Peter Monks" :email "pmonks+CLJ-2253@gmail.com"} {:id "slipset" :name "Erik Assum"}] :scm {:url "https://github.com/pmonks/CLJ-2253" :connection "scm:git:git://github.com/pmonks/CLJ-2253.git" :developer-connection "scm:git:ssh://git@github.com/pmonks/CLJ-2253.git"} :issue-management {:system "github" :url "https://github.com/pmonks/CLJ-2253/issues"}}))
118320
; ; 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. ; ; SPDX-License-Identifier: Apache-2.0 ; (def lib 'com.github.pmonks/clj-2253) #_{:clj-kondo/ignore [:unresolved-namespace]} (def version (format "1.0.%s" (b/git-count-revs nil))) (defn set-opts [opts] (assoc opts :lib lib :version version :write-pom true :validate-pom true :pom {:description "A workaround for https://dev.clojure.org/jira/browse/CLJ-2253." :url "https://github.com/pmonks/CLJ-2253" :licenses [:license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html"}] :developers [:developer {:id "pmonks" :name "<NAME>" :email "<EMAIL>"} {:id "slipset" :name "<NAME>"}] :scm {:url "https://github.com/pmonks/CLJ-2253" :connection "scm:git:git://github.com/pmonks/CLJ-2253.git" :developer-connection "scm:git:ssh://git@github.com/pmonks/CLJ-2253.git"} :issue-management {:system "github" :url "https://github.com/pmonks/CLJ-2253/issues"}}))
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. ; ; SPDX-License-Identifier: Apache-2.0 ; (def lib 'com.github.pmonks/clj-2253) #_{:clj-kondo/ignore [:unresolved-namespace]} (def version (format "1.0.%s" (b/git-count-revs nil))) (defn set-opts [opts] (assoc opts :lib lib :version version :write-pom true :validate-pom true :pom {:description "A workaround for https://dev.clojure.org/jira/browse/CLJ-2253." :url "https://github.com/pmonks/CLJ-2253" :licenses [:license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html"}] :developers [:developer {:id "pmonks" :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} {:id "slipset" :name "PI:NAME:<NAME>END_PI"}] :scm {:url "https://github.com/pmonks/CLJ-2253" :connection "scm:git:git://github.com/pmonks/CLJ-2253.git" :developer-connection "scm:git:ssh://git@github.com/pmonks/CLJ-2253.git"} :issue-management {:system "github" :url "https://github.com/pmonks/CLJ-2253/issues"}}))
[ { "context": "456\")\n\n\n(def participant {:_id USER_ID :username \"username\" :writer-records []})\n(def writer-for-objective {", "end": 804, "score": 0.9996299147605896, "start": 796, "tag": "USERNAME", "value": "username" }, { "context": "def writer-for-objective {:_id USER_ID :username \"username\" :writer-records [{:objective-id OBJECTIVE_ID}]})", "end": 886, "score": 0.9995794296264648, "start": 878, "tag": "USERNAME", "value": "username" }, { "context": " :params {:username ?username\n ", "end": 4541, "score": 0.9326807260513306, "start": 4541, "tag": "USERNAME", "value": "" }, { "context": " :params {:username ?username\n :email-a", "end": 4551, "score": 0.9174928069114685, "start": 4543, "tag": "USERNAME", "value": "username" }, { "context": "-address ?error-tag\n \"\" \"abc@def.com\" \"clj-username-invalid-error\"\n \"va", "end": 4842, "score": 0.9975064992904663, "start": 4831, "tag": "EMAIL", "value": "abc@def.com" }, { "context": ":body (json/generate-string {:access_token \"access-token-123\"})}\n (facebook/get-token-info \"ac", "end": 5242, "score": 0.8681978583335876, "start": 5233, "tag": "KEY", "value": "token-123" }, { "context": " :params {:username \"valid\"\n :email-ad", "end": 6276, "score": 0.9931023120880127, "start": 6271, "tag": "USERNAME", "value": "valid" }, { "context": " :email-address \"valid@email.com\"})\n p/follow-redirect\n ", "end": 6348, "score": 0.9999198913574219, "start": 6333, "tag": "EMAIL", "value": "valid@email.com" }, { "context": "hy\" \"clj-name-length-error\"\n \"Peter Profile\" \"\" \"", "end": 12544, "score": 0.8384515047073364, "start": 12539, "tag": "NAME", "value": "Peter" }, { "context": " \"clj-biog-empty-error\"\n \"Peter Profile\" (ih/string-of-length 5001) \"", "end": 12633, "score": 0.8615509867668152, "start": 12628, "tag": "NAME", "value": "Peter" }, { "context": "hy\" \"clj-name-length-error\"\n \"Peter Profile\" \"\" \"", "end": 14297, "score": 0.7527406215667725, "start": 14292, "tag": "NAME", "value": "Peter" }, { "context": " \"clj-biog-empty-error\"\n \"Peter Profile\" (ih/string-of-length 5001) \"", "end": 14386, "score": 0.6333805322647095, "start": 14381, "tag": "NAME", "value": "Peter" }, { "context": "sage\n \"\" \"a@b.com\" \"a reason\" \"clj-wri", "end": 22705, "score": 0.9998832941055298, "start": 22698, "tag": "EMAIL", "value": "a@b.com" }, { "context": "ror\"\n (ih/string-of-length 51) \"a@b.com\" \"a reason\" \"clj-wri", "end": 22829, "score": 0.9998478889465332, "start": 22822, "tag": "EMAIL", "value": "a@b.com" }, { "context": " \"clj-writer-name-length-error\"\n \"Jenny\" \"\" \"a reas", "end": 22919, "score": 0.9997467994689941, "start": 22914, "tag": "NAME", "value": "Jenny" }, { "context": " \"clj-writer-email-empty-error\"\n \"Jenny\" \"invalid-email\" \"a reas", "end": 23044, "score": 0.9997789263725281, "start": 23039, "tag": "NAME", "value": "Jenny" }, { "context": " \"clj-writer-email-invalid-error\"\n \"Jenny\" \"a@b.com\" \"\" ", "end": 23171, "score": 0.9997783303260803, "start": 23166, "tag": "NAME", "value": "Jenny" }, { "context": "ror\"\n \"Jenny\" \"a@b.com\" \"\" \"clj-wri", "end": 23206, "score": 0.9998859167098999, "start": 23199, "tag": "EMAIL", "value": "a@b.com" }, { "context": " \"clj-writer-reason-empty-error\"\n \"Jenny\" \"a@b.com\" (ih/str", "end": 23297, "score": 0.9997847676277161, "start": 23292, "tag": "NAME", "value": "Jenny" }, { "context": "ror\"\n \"Jenny\" \"a@b.com\" (ih/string-of-length 5001) \"clj-wri", "end": 23332, "score": 0.9999001622200012, "start": 23325, "tag": "EMAIL", "value": "a@b.com" } ]
test/objective8/integration/front_end/validations.clj
d-cent/objective8
23
(ns objective8.integration.front-end.validations (:require [midje.sweet :refer :all] [peridot.core :as p] [oauth.client :as oauth] [objective8.front-end.api.http :as http-api] [objective8.integration.integration-helpers :as ih] [objective8.config :as config] [objective8.utils :as utils] [objective8.front-end.workflows.facebook :as facebook] [cheshire.core :as json])) (def USER_ID 1) (def OBJECTIVE_ID 2) (def OBJECTIVE_ID_AS_STRING (str OBJECTIVE_ID)) (def QUESTION_ID 3) (def DRAFT_ID 4) (def DRAFT_ID_AS_STRING (str DRAFT_ID)) (def INVITATION_ID 5) (def INVITATION_UUID "SOME_UUID") (def SECTION_LABEL "abcdef12") (def TWITTER_ID "twitter-123456") (def participant {:_id USER_ID :username "username" :writer-records []}) (def writer-for-objective {:_id USER_ID :username "username" :writer-records [{:objective-id OBJECTIVE_ID}]}) (def the-objective {:_id OBJECTIVE_ID :meta {:drafts-count 0 :comments-count 0}}) (def question {:_id QUESTION_ID :objective-id OBJECTIVE_ID :question "Why?" :meta {:answers-count 0}}) (def draft {:_id DRAFT_ID :objective-id OBJECTIVE_ID :_created_at "2015-02-12T16:46:18.838Z" :meta {:comments-count 0}}) (def draft-section {:section '() :uri (str "/objective/" OBJECTIVE_ID "/drafts/" DRAFT_ID "/sections/" SECTION_LABEL)}) (def the-invitation {:uuid INVITATION_UUID :objective-id OBJECTIVE_ID :invitation-id INVITATION_ID :status "active"}) (def ^:dynamic the-user participant) (def ^:dynamic find-user-by-auth-provider-user-id-result {:status ::http-api/success :result the-user}) (background ;; Sign-in background (oauth/access-token anything anything anything) => {:user_id TWITTER_ID} (http-api/find-user-by-auth-provider-user-id anything) => find-user-by-auth-provider-user-id-result (http-api/get-user anything) => {:status ::http-api/success :result the-user} ;; Test data background (http-api/get-objective OBJECTIVE_ID_AS_STRING) => {:status ::http-api/success :result the-objective} (http-api/get-objective OBJECTIVE_ID) => {:status ::http-api/success :result the-objective} (http-api/get-objective OBJECTIVE_ID anything) => {:status ::http-api/success :result the-objective} (http-api/get-question OBJECTIVE_ID QUESTION_ID) => {:status ::http-api/success :result question} (http-api/retrieve-answers anything anything) => {:status ::http-api/success :result []} (http-api/get-comments anything) => {:status ::http-api/success :result {:comments []}} (http-api/get-comments anything anything) => {:status ::http-api/success :result {:comments []}} (http-api/retrieve-invitation-by-uuid INVITATION_UUID) => {:status ::http-api/success :result the-invitation} (http-api/retrieve-writers OBJECTIVE_ID) => {:status ::http-api/success :result []} (http-api/retrieve-writers OBJECTIVE_ID_AS_STRING) => {:status ::http-api/success :result []} (http-api/retrieve-questions OBJECTIVE_ID) => {:status ::http-api/success :result []} (http-api/get-draft OBJECTIVE_ID_AS_STRING DRAFT_ID_AS_STRING) => {:status ::http-api/success :result draft} (http-api/get-draft OBJECTIVE_ID DRAFT_ID) => {:status ::http-api/success :result draft} (http-api/get-draft-section anything) => {:status ::http-api/success :result draft-section}) (def twitter-callback-url (str utils/host-url "/twitter-callback?oauth_verifier=VERIFICATION_TOKEN")) (def facebook-callback-url (str utils/host-url "/facebook-callback?code=1234455r6ftgyhu")) (def sign-up-url (str utils/host-url "/sign-up")) (def user-session (ih/front-end-context)) (facts "about the sign-up form" (binding [config/enable-csrf false find-user-by-auth-provider-user-id-result {:status ::http-api/not-found}] (tabular (fact "validation errors are reported" (-> user-session (p/request twitter-callback-url) (p/request sign-up-url :request-method :post :params {:username ?username :email-address ?email-address}) p/follow-redirect :response :body) => (contains ?error-tag)) ?username ?email-address ?error-tag "" "abc@def.com" "clj-username-invalid-error" "valid" "" "clj-email-empty-error" "valid" "invalid" "clj-email-invalid-error") (tabular (fact "auth validation error is reported" (against-background (facebook/get-access-token anything) => {:body (json/generate-string {:access_token "access-token-123"})} (facebook/get-token-info "access-token-123" anything) => {:body (json/generate-string {:data {:user_id "123"}})} (facebook/token-info-valid? {:user_id "123"} anything) => true (facebook/get-user-email "123") => {:body (json/generate-string {:email ?fb-email-address})}) (-> user-session (p/request facebook-callback-url) p/follow-redirect :response :body) => (contains "clj-auth-email-invalid-error")) ?fb-email-address "invalid" "") (fact "error is reported if username is not unique" (against-background (http-api/create-user anything) => {:status ::http-api/invalid-input}) (-> user-session (p/request twitter-callback-url) (p/request sign-up-url :request-method :post :params {:username "valid" :email-address "valid@email.com"}) p/follow-redirect :response :body) => (contains "clj-username-duplicated-error")) (tabular (fact "validation errors are hidden by default" (-> user-session (p/request twitter-callback-url) (p/request sign-up-url) :response :body) =not=> (contains ?error-tag)) ?error-tag "clj-username-invalid-error" "clj-username-duplicated-error" "clj-email-empty-error" "clj-email-invalid-error" "clj-auth-email-invalid-error"))) (facts "about the create objective form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-objective-form-post) :request-method :post :params {:title ?title :description ?description}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?title ?description ?expected-error-message "12" "A description" "clj-title-length-error" (ih/string-of-length 121) "A description" "clj-title-length-error" "A valid title" "" "clj-description-empty-error" "A valid title" (ih/string-of-length 5001) "clj-description-length-error") (tabular (fact "validation errors are hidden by default" (let [objective-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-objective-form)) :response :body)] objective-form-html =not=> (contains ?error-tag))) ?error-tag "clj-title-length-error" "clj-description-length-error" "clj-description-empty-error"))) (facts "about the add question form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-question-form-post :id OBJECTIVE_ID) :request-method :post :params {:question ?question}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?question ?expected-error-message (ih/string-of-length 9) "clj-question-length-error" (ih/string-of-length 501) "clj-question-length-error") (tabular (fact "validation errors are hidden by default" (let [question-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-a-question :id OBJECTIVE_ID)) :response :body)] question-form-html =not=> (contains ?error-tag))) ?error-tag "clj-question-length-error"))) (facts "about the add answer form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-answer-form-post :id OBJECTIVE_ID :q-id QUESTION_ID) :request-method :post :params {:answer ?answer}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?answer ?expected-error-message "" "clj-answer-empty-error" (ih/string-of-length 501) "clj-answer-length-error") (tabular (fact "validation errors are hidden by default" (let [answer-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/question :id OBJECTIVE_ID :q-id QUESTION_ID)) :response :body)] answer-form-html =not=> (contains ?error-tag))) ?error-tag "clj-answer-length-error" "clj-answer-empty-error"))) (facts "about the create profile form" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/writer-invitation :uuid INVITATION_UUID)) (p/request (utils/path-for :fe/create-profile-post) :request-method :post :params {:name ?name :biog ?biog}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?name ?biog ?expected-error-message "" "valid biography" "clj-name-empty-error" (ih/string-of-length 51) "valid biography" "clj-name-length-error" "Peter Profile" "" "clj-biog-empty-error" "Peter Profile" (ih/string-of-length 5001) "clj-biog-length-error") (tabular (fact "validation errors are hidden by default" (let [create-profile-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-profile-get)) :response :body)] create-profile-form-html =not=> (contains ?error-tag))) ?error-tag "clj-name-empty-error" "clj-name-length-error" "clj-biog-empty-error" "clj-biog-length-error"))) (facts "about the edit profile form" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/edit-profile-post) :request-method :post :params {:name ?name :biog ?biog}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?name ?biog ?expected-error-message "" "valid biography" "clj-name-empty-error" (ih/string-of-length 51) "valid biography" "clj-name-length-error" "Peter Profile" "" "clj-biog-empty-error" "Peter Profile" (ih/string-of-length 5001) "clj-biog-length-error") (tabular (fact "validation errors are hidden by default" (let [edit-profile-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/edit-profile-get)) :response :body)] edit-profile-form-html =not=> (contains ?error-tag))) ?error-tag "clj-name-empty-error" "clj-name-length-error" "clj-biog-empty-error" "clj-biog-length-error"))) (tabular (facts "about creating comments" (binding [config/enable-csrf false] (fact "validation errors are reported when posting a comment from the objective details page" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-comment) :request-method :post :params {:comment ?comment :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/objective :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on the objective detail page" (let [objective-details-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/objective :id OBJECTIVE_ID)) :response :body)] objective-details-html =not=> (contains ?error-tag))) (fact "validation errors are reported when posting a comment on a draft" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-comment) :request-method :post :params {:comment ?comment :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/draft :id OBJECTIVE_ID :d-id DRAFT_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on draft view pages" (let [draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/draft :id OBJECTIVE_ID :d-id DRAFT_ID)) :response :body)] draft-html =not=> (contains ?error-tag))) (fact "validation errors are reported when posting a comment on a draft section" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-annotation :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL) :request-method :post :params {:comment ?comment :reason "general" :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/draft-section :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on draft section pages" (let [draft-section-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/draft-section :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL)) :response :body)] draft-section-html =not=> (contains ?error-tag))))) ?comment ?error-tag "" "clj-comment-empty-error" (ih/string-of-length 501) "clj-comment-length-error") (facts "about importing drafts" (binding [config/enable-csrf false the-user writer-for-objective] (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/import-draft-post :id OBJECTIVE_ID) :request-method :post :params {:google-doc-html-content ""}) p/follow-redirect :response :body) => (contains "clj-draft-content-empty-error")) (fact "validation errors are hidden by default" (let [import-draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/import-draft-get :id OBJECTIVE_ID)) :response :body)] import-draft-html =not=> (contains "clj-draft-content-empty-error"))))) (facts "about adding drafts" (binding [config/enable-csrf false the-user writer-for-objective] (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-draft-post :id OBJECTIVE_ID) :request-method :post :params {:content ""}) p/follow-redirect :response :body) => (contains "clj-draft-empty-error")) (fact "validation errors are hidden by default" (let [add-draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-draft-get :id OBJECTIVE_ID)) :response :body)] add-draft-html =not=> (contains "clj-draft-empty-error"))))) (facts "about inviting writers" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/invitation-form-post :id OBJECTIVE_ID) :request-method :post :params {:writer-name ?writer-name :writer-email ?writer-email :reason ?reason}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?writer-name ?writer-email ?reason ?expected-error-message "" "a@b.com" "a reason" "clj-writer-name-empty-error" (ih/string-of-length 51) "a@b.com" "a reason" "clj-writer-name-length-error" "Jenny" "" "a reason" "clj-writer-email-empty-error" "Jenny" "invalid-email" "a reason" "clj-writer-email-invalid-error" "Jenny" "a@b.com" "" "clj-writer-reason-empty-error" "Jenny" "a@b.com" (ih/string-of-length 5001) "clj-writer-reason-length-error") (tabular (fact "validation errors are hidden by default" (let [invitation-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/invite-writer :id OBJECTIVE_ID)) :response :body)] invitation-form-html =not=> (contains ?error-tag))) ?error-tag "clj-writer-name-empty-error" "clj-writer-name-length-error" "clj-writer-email-empty-error" "clj-writer-email-invalid-error" "clj-writer-reason-empty-error" "clj-writer-reason-length-error"))) (tabular (facts "about writer notes" (binding [config/enable-csrf false the-user writer-for-objective] (facts "on the questions dashboard" (against-background (http-api/retrieve-questions OBJECTIVE_ID anything) => {:status ::http-api/success :result [{}]} (http-api/retrieve-answers anything anything) => {:status ::http-api/success :result [{:uri "/answer/uri"}]}) (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-writer-note) :request-method :post :params {:note ?note :note-on-uri "/answer/uri" :refer (utils/local-path-for :fe/dashboard-questions :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "validation errors are hidden by default" (let [dashboard-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/dashboard-questions :id OBJECTIVE_ID)) :response :body)] dashboard-html =not=> (contains ?error-tag)))) (facts "on the comments dashboard" (against-background (http-api/get-all-drafts anything) => {:status ::http-api/success :result [{:_created_at "2015-04-04T12:00:00.000Z"}]} (http-api/get-comments anything anything) => {:status ::http-api/success :result {:comments [{:uri "/comment/uri" :_created_at "2015-01-01T01:01:00.000Z"}]}}) (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-writer-note) :request-method :post :params {:note ?note :note-on-uri "/comment/uri" :refer (utils/local-path-for :fe/dashboard-comments :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "validation errors are hidden by default" (let [dashboard-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/dashboard-comments :id OBJECTIVE_ID)) :response :body)] dashboard-html =not=> (contains ?error-tag)))))) ?note ?error-tag "" "clj-writer-note-empty-error" (ih/string-of-length 501) "clj-writer-note-length-error")
65018
(ns objective8.integration.front-end.validations (:require [midje.sweet :refer :all] [peridot.core :as p] [oauth.client :as oauth] [objective8.front-end.api.http :as http-api] [objective8.integration.integration-helpers :as ih] [objective8.config :as config] [objective8.utils :as utils] [objective8.front-end.workflows.facebook :as facebook] [cheshire.core :as json])) (def USER_ID 1) (def OBJECTIVE_ID 2) (def OBJECTIVE_ID_AS_STRING (str OBJECTIVE_ID)) (def QUESTION_ID 3) (def DRAFT_ID 4) (def DRAFT_ID_AS_STRING (str DRAFT_ID)) (def INVITATION_ID 5) (def INVITATION_UUID "SOME_UUID") (def SECTION_LABEL "abcdef12") (def TWITTER_ID "twitter-123456") (def participant {:_id USER_ID :username "username" :writer-records []}) (def writer-for-objective {:_id USER_ID :username "username" :writer-records [{:objective-id OBJECTIVE_ID}]}) (def the-objective {:_id OBJECTIVE_ID :meta {:drafts-count 0 :comments-count 0}}) (def question {:_id QUESTION_ID :objective-id OBJECTIVE_ID :question "Why?" :meta {:answers-count 0}}) (def draft {:_id DRAFT_ID :objective-id OBJECTIVE_ID :_created_at "2015-02-12T16:46:18.838Z" :meta {:comments-count 0}}) (def draft-section {:section '() :uri (str "/objective/" OBJECTIVE_ID "/drafts/" DRAFT_ID "/sections/" SECTION_LABEL)}) (def the-invitation {:uuid INVITATION_UUID :objective-id OBJECTIVE_ID :invitation-id INVITATION_ID :status "active"}) (def ^:dynamic the-user participant) (def ^:dynamic find-user-by-auth-provider-user-id-result {:status ::http-api/success :result the-user}) (background ;; Sign-in background (oauth/access-token anything anything anything) => {:user_id TWITTER_ID} (http-api/find-user-by-auth-provider-user-id anything) => find-user-by-auth-provider-user-id-result (http-api/get-user anything) => {:status ::http-api/success :result the-user} ;; Test data background (http-api/get-objective OBJECTIVE_ID_AS_STRING) => {:status ::http-api/success :result the-objective} (http-api/get-objective OBJECTIVE_ID) => {:status ::http-api/success :result the-objective} (http-api/get-objective OBJECTIVE_ID anything) => {:status ::http-api/success :result the-objective} (http-api/get-question OBJECTIVE_ID QUESTION_ID) => {:status ::http-api/success :result question} (http-api/retrieve-answers anything anything) => {:status ::http-api/success :result []} (http-api/get-comments anything) => {:status ::http-api/success :result {:comments []}} (http-api/get-comments anything anything) => {:status ::http-api/success :result {:comments []}} (http-api/retrieve-invitation-by-uuid INVITATION_UUID) => {:status ::http-api/success :result the-invitation} (http-api/retrieve-writers OBJECTIVE_ID) => {:status ::http-api/success :result []} (http-api/retrieve-writers OBJECTIVE_ID_AS_STRING) => {:status ::http-api/success :result []} (http-api/retrieve-questions OBJECTIVE_ID) => {:status ::http-api/success :result []} (http-api/get-draft OBJECTIVE_ID_AS_STRING DRAFT_ID_AS_STRING) => {:status ::http-api/success :result draft} (http-api/get-draft OBJECTIVE_ID DRAFT_ID) => {:status ::http-api/success :result draft} (http-api/get-draft-section anything) => {:status ::http-api/success :result draft-section}) (def twitter-callback-url (str utils/host-url "/twitter-callback?oauth_verifier=VERIFICATION_TOKEN")) (def facebook-callback-url (str utils/host-url "/facebook-callback?code=1234455r6ftgyhu")) (def sign-up-url (str utils/host-url "/sign-up")) (def user-session (ih/front-end-context)) (facts "about the sign-up form" (binding [config/enable-csrf false find-user-by-auth-provider-user-id-result {:status ::http-api/not-found}] (tabular (fact "validation errors are reported" (-> user-session (p/request twitter-callback-url) (p/request sign-up-url :request-method :post :params {:username ?username :email-address ?email-address}) p/follow-redirect :response :body) => (contains ?error-tag)) ?username ?email-address ?error-tag "" "<EMAIL>" "clj-username-invalid-error" "valid" "" "clj-email-empty-error" "valid" "invalid" "clj-email-invalid-error") (tabular (fact "auth validation error is reported" (against-background (facebook/get-access-token anything) => {:body (json/generate-string {:access_token "access-<KEY>"})} (facebook/get-token-info "access-token-123" anything) => {:body (json/generate-string {:data {:user_id "123"}})} (facebook/token-info-valid? {:user_id "123"} anything) => true (facebook/get-user-email "123") => {:body (json/generate-string {:email ?fb-email-address})}) (-> user-session (p/request facebook-callback-url) p/follow-redirect :response :body) => (contains "clj-auth-email-invalid-error")) ?fb-email-address "invalid" "") (fact "error is reported if username is not unique" (against-background (http-api/create-user anything) => {:status ::http-api/invalid-input}) (-> user-session (p/request twitter-callback-url) (p/request sign-up-url :request-method :post :params {:username "valid" :email-address "<EMAIL>"}) p/follow-redirect :response :body) => (contains "clj-username-duplicated-error")) (tabular (fact "validation errors are hidden by default" (-> user-session (p/request twitter-callback-url) (p/request sign-up-url) :response :body) =not=> (contains ?error-tag)) ?error-tag "clj-username-invalid-error" "clj-username-duplicated-error" "clj-email-empty-error" "clj-email-invalid-error" "clj-auth-email-invalid-error"))) (facts "about the create objective form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-objective-form-post) :request-method :post :params {:title ?title :description ?description}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?title ?description ?expected-error-message "12" "A description" "clj-title-length-error" (ih/string-of-length 121) "A description" "clj-title-length-error" "A valid title" "" "clj-description-empty-error" "A valid title" (ih/string-of-length 5001) "clj-description-length-error") (tabular (fact "validation errors are hidden by default" (let [objective-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-objective-form)) :response :body)] objective-form-html =not=> (contains ?error-tag))) ?error-tag "clj-title-length-error" "clj-description-length-error" "clj-description-empty-error"))) (facts "about the add question form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-question-form-post :id OBJECTIVE_ID) :request-method :post :params {:question ?question}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?question ?expected-error-message (ih/string-of-length 9) "clj-question-length-error" (ih/string-of-length 501) "clj-question-length-error") (tabular (fact "validation errors are hidden by default" (let [question-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-a-question :id OBJECTIVE_ID)) :response :body)] question-form-html =not=> (contains ?error-tag))) ?error-tag "clj-question-length-error"))) (facts "about the add answer form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-answer-form-post :id OBJECTIVE_ID :q-id QUESTION_ID) :request-method :post :params {:answer ?answer}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?answer ?expected-error-message "" "clj-answer-empty-error" (ih/string-of-length 501) "clj-answer-length-error") (tabular (fact "validation errors are hidden by default" (let [answer-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/question :id OBJECTIVE_ID :q-id QUESTION_ID)) :response :body)] answer-form-html =not=> (contains ?error-tag))) ?error-tag "clj-answer-length-error" "clj-answer-empty-error"))) (facts "about the create profile form" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/writer-invitation :uuid INVITATION_UUID)) (p/request (utils/path-for :fe/create-profile-post) :request-method :post :params {:name ?name :biog ?biog}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?name ?biog ?expected-error-message "" "valid biography" "clj-name-empty-error" (ih/string-of-length 51) "valid biography" "clj-name-length-error" "<NAME> Profile" "" "clj-biog-empty-error" "<NAME> Profile" (ih/string-of-length 5001) "clj-biog-length-error") (tabular (fact "validation errors are hidden by default" (let [create-profile-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-profile-get)) :response :body)] create-profile-form-html =not=> (contains ?error-tag))) ?error-tag "clj-name-empty-error" "clj-name-length-error" "clj-biog-empty-error" "clj-biog-length-error"))) (facts "about the edit profile form" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/edit-profile-post) :request-method :post :params {:name ?name :biog ?biog}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?name ?biog ?expected-error-message "" "valid biography" "clj-name-empty-error" (ih/string-of-length 51) "valid biography" "clj-name-length-error" "<NAME> Profile" "" "clj-biog-empty-error" "<NAME> Profile" (ih/string-of-length 5001) "clj-biog-length-error") (tabular (fact "validation errors are hidden by default" (let [edit-profile-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/edit-profile-get)) :response :body)] edit-profile-form-html =not=> (contains ?error-tag))) ?error-tag "clj-name-empty-error" "clj-name-length-error" "clj-biog-empty-error" "clj-biog-length-error"))) (tabular (facts "about creating comments" (binding [config/enable-csrf false] (fact "validation errors are reported when posting a comment from the objective details page" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-comment) :request-method :post :params {:comment ?comment :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/objective :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on the objective detail page" (let [objective-details-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/objective :id OBJECTIVE_ID)) :response :body)] objective-details-html =not=> (contains ?error-tag))) (fact "validation errors are reported when posting a comment on a draft" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-comment) :request-method :post :params {:comment ?comment :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/draft :id OBJECTIVE_ID :d-id DRAFT_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on draft view pages" (let [draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/draft :id OBJECTIVE_ID :d-id DRAFT_ID)) :response :body)] draft-html =not=> (contains ?error-tag))) (fact "validation errors are reported when posting a comment on a draft section" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-annotation :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL) :request-method :post :params {:comment ?comment :reason "general" :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/draft-section :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on draft section pages" (let [draft-section-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/draft-section :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL)) :response :body)] draft-section-html =not=> (contains ?error-tag))))) ?comment ?error-tag "" "clj-comment-empty-error" (ih/string-of-length 501) "clj-comment-length-error") (facts "about importing drafts" (binding [config/enable-csrf false the-user writer-for-objective] (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/import-draft-post :id OBJECTIVE_ID) :request-method :post :params {:google-doc-html-content ""}) p/follow-redirect :response :body) => (contains "clj-draft-content-empty-error")) (fact "validation errors are hidden by default" (let [import-draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/import-draft-get :id OBJECTIVE_ID)) :response :body)] import-draft-html =not=> (contains "clj-draft-content-empty-error"))))) (facts "about adding drafts" (binding [config/enable-csrf false the-user writer-for-objective] (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-draft-post :id OBJECTIVE_ID) :request-method :post :params {:content ""}) p/follow-redirect :response :body) => (contains "clj-draft-empty-error")) (fact "validation errors are hidden by default" (let [add-draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-draft-get :id OBJECTIVE_ID)) :response :body)] add-draft-html =not=> (contains "clj-draft-empty-error"))))) (facts "about inviting writers" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/invitation-form-post :id OBJECTIVE_ID) :request-method :post :params {:writer-name ?writer-name :writer-email ?writer-email :reason ?reason}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?writer-name ?writer-email ?reason ?expected-error-message "" "<EMAIL>" "a reason" "clj-writer-name-empty-error" (ih/string-of-length 51) "<EMAIL>" "a reason" "clj-writer-name-length-error" "<NAME>" "" "a reason" "clj-writer-email-empty-error" "<NAME>" "invalid-email" "a reason" "clj-writer-email-invalid-error" "<NAME>" "<EMAIL>" "" "clj-writer-reason-empty-error" "<NAME>" "<EMAIL>" (ih/string-of-length 5001) "clj-writer-reason-length-error") (tabular (fact "validation errors are hidden by default" (let [invitation-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/invite-writer :id OBJECTIVE_ID)) :response :body)] invitation-form-html =not=> (contains ?error-tag))) ?error-tag "clj-writer-name-empty-error" "clj-writer-name-length-error" "clj-writer-email-empty-error" "clj-writer-email-invalid-error" "clj-writer-reason-empty-error" "clj-writer-reason-length-error"))) (tabular (facts "about writer notes" (binding [config/enable-csrf false the-user writer-for-objective] (facts "on the questions dashboard" (against-background (http-api/retrieve-questions OBJECTIVE_ID anything) => {:status ::http-api/success :result [{}]} (http-api/retrieve-answers anything anything) => {:status ::http-api/success :result [{:uri "/answer/uri"}]}) (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-writer-note) :request-method :post :params {:note ?note :note-on-uri "/answer/uri" :refer (utils/local-path-for :fe/dashboard-questions :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "validation errors are hidden by default" (let [dashboard-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/dashboard-questions :id OBJECTIVE_ID)) :response :body)] dashboard-html =not=> (contains ?error-tag)))) (facts "on the comments dashboard" (against-background (http-api/get-all-drafts anything) => {:status ::http-api/success :result [{:_created_at "2015-04-04T12:00:00.000Z"}]} (http-api/get-comments anything anything) => {:status ::http-api/success :result {:comments [{:uri "/comment/uri" :_created_at "2015-01-01T01:01:00.000Z"}]}}) (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-writer-note) :request-method :post :params {:note ?note :note-on-uri "/comment/uri" :refer (utils/local-path-for :fe/dashboard-comments :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "validation errors are hidden by default" (let [dashboard-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/dashboard-comments :id OBJECTIVE_ID)) :response :body)] dashboard-html =not=> (contains ?error-tag)))))) ?note ?error-tag "" "clj-writer-note-empty-error" (ih/string-of-length 501) "clj-writer-note-length-error")
true
(ns objective8.integration.front-end.validations (:require [midje.sweet :refer :all] [peridot.core :as p] [oauth.client :as oauth] [objective8.front-end.api.http :as http-api] [objective8.integration.integration-helpers :as ih] [objective8.config :as config] [objective8.utils :as utils] [objective8.front-end.workflows.facebook :as facebook] [cheshire.core :as json])) (def USER_ID 1) (def OBJECTIVE_ID 2) (def OBJECTIVE_ID_AS_STRING (str OBJECTIVE_ID)) (def QUESTION_ID 3) (def DRAFT_ID 4) (def DRAFT_ID_AS_STRING (str DRAFT_ID)) (def INVITATION_ID 5) (def INVITATION_UUID "SOME_UUID") (def SECTION_LABEL "abcdef12") (def TWITTER_ID "twitter-123456") (def participant {:_id USER_ID :username "username" :writer-records []}) (def writer-for-objective {:_id USER_ID :username "username" :writer-records [{:objective-id OBJECTIVE_ID}]}) (def the-objective {:_id OBJECTIVE_ID :meta {:drafts-count 0 :comments-count 0}}) (def question {:_id QUESTION_ID :objective-id OBJECTIVE_ID :question "Why?" :meta {:answers-count 0}}) (def draft {:_id DRAFT_ID :objective-id OBJECTIVE_ID :_created_at "2015-02-12T16:46:18.838Z" :meta {:comments-count 0}}) (def draft-section {:section '() :uri (str "/objective/" OBJECTIVE_ID "/drafts/" DRAFT_ID "/sections/" SECTION_LABEL)}) (def the-invitation {:uuid INVITATION_UUID :objective-id OBJECTIVE_ID :invitation-id INVITATION_ID :status "active"}) (def ^:dynamic the-user participant) (def ^:dynamic find-user-by-auth-provider-user-id-result {:status ::http-api/success :result the-user}) (background ;; Sign-in background (oauth/access-token anything anything anything) => {:user_id TWITTER_ID} (http-api/find-user-by-auth-provider-user-id anything) => find-user-by-auth-provider-user-id-result (http-api/get-user anything) => {:status ::http-api/success :result the-user} ;; Test data background (http-api/get-objective OBJECTIVE_ID_AS_STRING) => {:status ::http-api/success :result the-objective} (http-api/get-objective OBJECTIVE_ID) => {:status ::http-api/success :result the-objective} (http-api/get-objective OBJECTIVE_ID anything) => {:status ::http-api/success :result the-objective} (http-api/get-question OBJECTIVE_ID QUESTION_ID) => {:status ::http-api/success :result question} (http-api/retrieve-answers anything anything) => {:status ::http-api/success :result []} (http-api/get-comments anything) => {:status ::http-api/success :result {:comments []}} (http-api/get-comments anything anything) => {:status ::http-api/success :result {:comments []}} (http-api/retrieve-invitation-by-uuid INVITATION_UUID) => {:status ::http-api/success :result the-invitation} (http-api/retrieve-writers OBJECTIVE_ID) => {:status ::http-api/success :result []} (http-api/retrieve-writers OBJECTIVE_ID_AS_STRING) => {:status ::http-api/success :result []} (http-api/retrieve-questions OBJECTIVE_ID) => {:status ::http-api/success :result []} (http-api/get-draft OBJECTIVE_ID_AS_STRING DRAFT_ID_AS_STRING) => {:status ::http-api/success :result draft} (http-api/get-draft OBJECTIVE_ID DRAFT_ID) => {:status ::http-api/success :result draft} (http-api/get-draft-section anything) => {:status ::http-api/success :result draft-section}) (def twitter-callback-url (str utils/host-url "/twitter-callback?oauth_verifier=VERIFICATION_TOKEN")) (def facebook-callback-url (str utils/host-url "/facebook-callback?code=1234455r6ftgyhu")) (def sign-up-url (str utils/host-url "/sign-up")) (def user-session (ih/front-end-context)) (facts "about the sign-up form" (binding [config/enable-csrf false find-user-by-auth-provider-user-id-result {:status ::http-api/not-found}] (tabular (fact "validation errors are reported" (-> user-session (p/request twitter-callback-url) (p/request sign-up-url :request-method :post :params {:username ?username :email-address ?email-address}) p/follow-redirect :response :body) => (contains ?error-tag)) ?username ?email-address ?error-tag "" "PI:EMAIL:<EMAIL>END_PI" "clj-username-invalid-error" "valid" "" "clj-email-empty-error" "valid" "invalid" "clj-email-invalid-error") (tabular (fact "auth validation error is reported" (against-background (facebook/get-access-token anything) => {:body (json/generate-string {:access_token "access-PI:KEY:<KEY>END_PI"})} (facebook/get-token-info "access-token-123" anything) => {:body (json/generate-string {:data {:user_id "123"}})} (facebook/token-info-valid? {:user_id "123"} anything) => true (facebook/get-user-email "123") => {:body (json/generate-string {:email ?fb-email-address})}) (-> user-session (p/request facebook-callback-url) p/follow-redirect :response :body) => (contains "clj-auth-email-invalid-error")) ?fb-email-address "invalid" "") (fact "error is reported if username is not unique" (against-background (http-api/create-user anything) => {:status ::http-api/invalid-input}) (-> user-session (p/request twitter-callback-url) (p/request sign-up-url :request-method :post :params {:username "valid" :email-address "PI:EMAIL:<EMAIL>END_PI"}) p/follow-redirect :response :body) => (contains "clj-username-duplicated-error")) (tabular (fact "validation errors are hidden by default" (-> user-session (p/request twitter-callback-url) (p/request sign-up-url) :response :body) =not=> (contains ?error-tag)) ?error-tag "clj-username-invalid-error" "clj-username-duplicated-error" "clj-email-empty-error" "clj-email-invalid-error" "clj-auth-email-invalid-error"))) (facts "about the create objective form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-objective-form-post) :request-method :post :params {:title ?title :description ?description}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?title ?description ?expected-error-message "12" "A description" "clj-title-length-error" (ih/string-of-length 121) "A description" "clj-title-length-error" "A valid title" "" "clj-description-empty-error" "A valid title" (ih/string-of-length 5001) "clj-description-length-error") (tabular (fact "validation errors are hidden by default" (let [objective-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-objective-form)) :response :body)] objective-form-html =not=> (contains ?error-tag))) ?error-tag "clj-title-length-error" "clj-description-length-error" "clj-description-empty-error"))) (facts "about the add question form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-question-form-post :id OBJECTIVE_ID) :request-method :post :params {:question ?question}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?question ?expected-error-message (ih/string-of-length 9) "clj-question-length-error" (ih/string-of-length 501) "clj-question-length-error") (tabular (fact "validation errors are hidden by default" (let [question-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-a-question :id OBJECTIVE_ID)) :response :body)] question-form-html =not=> (contains ?error-tag))) ?error-tag "clj-question-length-error"))) (facts "about the add answer form" (binding [config/enable-csrf false] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-answer-form-post :id OBJECTIVE_ID :q-id QUESTION_ID) :request-method :post :params {:answer ?answer}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?answer ?expected-error-message "" "clj-answer-empty-error" (ih/string-of-length 501) "clj-answer-length-error") (tabular (fact "validation errors are hidden by default" (let [answer-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/question :id OBJECTIVE_ID :q-id QUESTION_ID)) :response :body)] answer-form-html =not=> (contains ?error-tag))) ?error-tag "clj-answer-length-error" "clj-answer-empty-error"))) (facts "about the create profile form" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/writer-invitation :uuid INVITATION_UUID)) (p/request (utils/path-for :fe/create-profile-post) :request-method :post :params {:name ?name :biog ?biog}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?name ?biog ?expected-error-message "" "valid biography" "clj-name-empty-error" (ih/string-of-length 51) "valid biography" "clj-name-length-error" "PI:NAME:<NAME>END_PI Profile" "" "clj-biog-empty-error" "PI:NAME:<NAME>END_PI Profile" (ih/string-of-length 5001) "clj-biog-length-error") (tabular (fact "validation errors are hidden by default" (let [create-profile-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/create-profile-get)) :response :body)] create-profile-form-html =not=> (contains ?error-tag))) ?error-tag "clj-name-empty-error" "clj-name-length-error" "clj-biog-empty-error" "clj-biog-length-error"))) (facts "about the edit profile form" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/edit-profile-post) :request-method :post :params {:name ?name :biog ?biog}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?name ?biog ?expected-error-message "" "valid biography" "clj-name-empty-error" (ih/string-of-length 51) "valid biography" "clj-name-length-error" "PI:NAME:<NAME>END_PI Profile" "" "clj-biog-empty-error" "PI:NAME:<NAME>END_PI Profile" (ih/string-of-length 5001) "clj-biog-length-error") (tabular (fact "validation errors are hidden by default" (let [edit-profile-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/edit-profile-get)) :response :body)] edit-profile-form-html =not=> (contains ?error-tag))) ?error-tag "clj-name-empty-error" "clj-name-length-error" "clj-biog-empty-error" "clj-biog-length-error"))) (tabular (facts "about creating comments" (binding [config/enable-csrf false] (fact "validation errors are reported when posting a comment from the objective details page" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-comment) :request-method :post :params {:comment ?comment :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/objective :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on the objective detail page" (let [objective-details-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/objective :id OBJECTIVE_ID)) :response :body)] objective-details-html =not=> (contains ?error-tag))) (fact "validation errors are reported when posting a comment on a draft" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-comment) :request-method :post :params {:comment ?comment :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/draft :id OBJECTIVE_ID :d-id DRAFT_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on draft view pages" (let [draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/draft :id OBJECTIVE_ID :d-id DRAFT_ID)) :response :body)] draft-html =not=> (contains ?error-tag))) (fact "validation errors are reported when posting a comment on a draft section" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-annotation :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL) :request-method :post :params {:comment ?comment :reason "general" :comment-on-uri "/thing/to/comment/on" :refer (utils/local-path-for :fe/draft-section :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "comment validation errors are hidden by default on draft section pages" (let [draft-section-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/draft-section :id OBJECTIVE_ID :d-id DRAFT_ID :section-label SECTION_LABEL)) :response :body)] draft-section-html =not=> (contains ?error-tag))))) ?comment ?error-tag "" "clj-comment-empty-error" (ih/string-of-length 501) "clj-comment-length-error") (facts "about importing drafts" (binding [config/enable-csrf false the-user writer-for-objective] (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/import-draft-post :id OBJECTIVE_ID) :request-method :post :params {:google-doc-html-content ""}) p/follow-redirect :response :body) => (contains "clj-draft-content-empty-error")) (fact "validation errors are hidden by default" (let [import-draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/import-draft-get :id OBJECTIVE_ID)) :response :body)] import-draft-html =not=> (contains "clj-draft-content-empty-error"))))) (facts "about adding drafts" (binding [config/enable-csrf false the-user writer-for-objective] (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-draft-post :id OBJECTIVE_ID) :request-method :post :params {:content ""}) p/follow-redirect :response :body) => (contains "clj-draft-empty-error")) (fact "validation errors are hidden by default" (let [add-draft-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/add-draft-get :id OBJECTIVE_ID)) :response :body)] add-draft-html =not=> (contains "clj-draft-empty-error"))))) (facts "about inviting writers" (binding [config/enable-csrf false the-user writer-for-objective] (tabular (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/invitation-form-post :id OBJECTIVE_ID) :request-method :post :params {:writer-name ?writer-name :writer-email ?writer-email :reason ?reason}) p/follow-redirect :response :body) => (contains ?expected-error-message)) ?writer-name ?writer-email ?reason ?expected-error-message "" "PI:EMAIL:<EMAIL>END_PI" "a reason" "clj-writer-name-empty-error" (ih/string-of-length 51) "PI:EMAIL:<EMAIL>END_PI" "a reason" "clj-writer-name-length-error" "PI:NAME:<NAME>END_PI" "" "a reason" "clj-writer-email-empty-error" "PI:NAME:<NAME>END_PI" "invalid-email" "a reason" "clj-writer-email-invalid-error" "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "" "clj-writer-reason-empty-error" "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" (ih/string-of-length 5001) "clj-writer-reason-length-error") (tabular (fact "validation errors are hidden by default" (let [invitation-form-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/invite-writer :id OBJECTIVE_ID)) :response :body)] invitation-form-html =not=> (contains ?error-tag))) ?error-tag "clj-writer-name-empty-error" "clj-writer-name-length-error" "clj-writer-email-empty-error" "clj-writer-email-invalid-error" "clj-writer-reason-empty-error" "clj-writer-reason-length-error"))) (tabular (facts "about writer notes" (binding [config/enable-csrf false the-user writer-for-objective] (facts "on the questions dashboard" (against-background (http-api/retrieve-questions OBJECTIVE_ID anything) => {:status ::http-api/success :result [{}]} (http-api/retrieve-answers anything anything) => {:status ::http-api/success :result [{:uri "/answer/uri"}]}) (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-writer-note) :request-method :post :params {:note ?note :note-on-uri "/answer/uri" :refer (utils/local-path-for :fe/dashboard-questions :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "validation errors are hidden by default" (let [dashboard-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/dashboard-questions :id OBJECTIVE_ID)) :response :body)] dashboard-html =not=> (contains ?error-tag)))) (facts "on the comments dashboard" (against-background (http-api/get-all-drafts anything) => {:status ::http-api/success :result [{:_created_at "2015-04-04T12:00:00.000Z"}]} (http-api/get-comments anything anything) => {:status ::http-api/success :result {:comments [{:uri "/comment/uri" :_created_at "2015-01-01T01:01:00.000Z"}]}}) (fact "validation errors are reported" (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/post-writer-note) :request-method :post :params {:note ?note :note-on-uri "/comment/uri" :refer (utils/local-path-for :fe/dashboard-comments :id OBJECTIVE_ID)}) p/follow-redirect :response :body) => (contains ?error-tag)) (fact "validation errors are hidden by default" (let [dashboard-html (-> user-session ih/sign-in-as-existing-user (p/request (utils/path-for :fe/dashboard-comments :id OBJECTIVE_ID)) :response :body)] dashboard-html =not=> (contains ?error-tag)))))) ?note ?error-tag "" "clj-writer-note-empty-error" (ih/string-of-length 501) "clj-writer-note-length-error")
[ { "context": "/app {:health-handler ::invalid}})\n :key := :blaze.handler/app\n :reason := ::ig/build-failed-spec\n [:e", "end": 1573, "score": 0.9664848446846008, "start": 1556, "tag": "KEY", "value": "blaze.handler/app" } ]
test/blaze/handler/app_test.clj
samply/blaze
50
(ns blaze.handler.app-test (:require [blaze.async.comp :as ac] [blaze.handler.app] [blaze.test-util :refer [given-thrown with-system]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest testing]] [integrant.core :as ig] [juxt.iota :refer [given]] [ring.util.response :as ring] [taoensso.timbre :as log])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.handler/app nil}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing config" (given-thrown (ig/init {:blaze.handler/app {}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rest-api)) [:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :health-handler)))) (testing "invalid rest-api" (given-thrown (ig/init {:blaze.handler/app {:rest-api ::invalid}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :health-handler)) [:explain ::s/problems 1 :pred] := `fn? [:explain ::s/problems 1 :val] := ::invalid)) (testing "invalid health" (given-thrown (ig/init {:blaze.handler/app {:health-handler ::invalid}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rest-api)) [:explain ::s/problems 1 :pred] := `fn? [:explain ::s/problems 1 :val] := ::invalid))) (defn- rest-api [_] (ac/completed-future (ring/response ::rest-api))) (defn- health-handler [_] (ac/completed-future (ring/response ::health-handler))) (def system {:blaze.handler/app {:rest-api rest-api :health-handler health-handler}}) (deftest handler-test (testing "rest-api" (with-system [{handler :blaze.handler/app} system] @(handler {:uri "/" :request-method :get} (fn [response] (given response :status := 200 :body := ::rest-api)) identity))) (testing "health-handler" (with-system [{handler :blaze.handler/app} system] @(handler {:uri "/health" :request-method :get} (fn [response] (given response :status := 200 :body := ::health-handler)) identity))))
108692
(ns blaze.handler.app-test (:require [blaze.async.comp :as ac] [blaze.handler.app] [blaze.test-util :refer [given-thrown with-system]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest testing]] [integrant.core :as ig] [juxt.iota :refer [given]] [ring.util.response :as ring] [taoensso.timbre :as log])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.handler/app nil}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing config" (given-thrown (ig/init {:blaze.handler/app {}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rest-api)) [:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :health-handler)))) (testing "invalid rest-api" (given-thrown (ig/init {:blaze.handler/app {:rest-api ::invalid}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :health-handler)) [:explain ::s/problems 1 :pred] := `fn? [:explain ::s/problems 1 :val] := ::invalid)) (testing "invalid health" (given-thrown (ig/init {:blaze.handler/app {:health-handler ::invalid}}) :key := :<KEY> :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rest-api)) [:explain ::s/problems 1 :pred] := `fn? [:explain ::s/problems 1 :val] := ::invalid))) (defn- rest-api [_] (ac/completed-future (ring/response ::rest-api))) (defn- health-handler [_] (ac/completed-future (ring/response ::health-handler))) (def system {:blaze.handler/app {:rest-api rest-api :health-handler health-handler}}) (deftest handler-test (testing "rest-api" (with-system [{handler :blaze.handler/app} system] @(handler {:uri "/" :request-method :get} (fn [response] (given response :status := 200 :body := ::rest-api)) identity))) (testing "health-handler" (with-system [{handler :blaze.handler/app} system] @(handler {:uri "/health" :request-method :get} (fn [response] (given response :status := 200 :body := ::health-handler)) identity))))
true
(ns blaze.handler.app-test (:require [blaze.async.comp :as ac] [blaze.handler.app] [blaze.test-util :refer [given-thrown with-system]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest testing]] [integrant.core :as ig] [juxt.iota :refer [given]] [ring.util.response :as ring] [taoensso.timbre :as log])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.handler/app nil}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing config" (given-thrown (ig/init {:blaze.handler/app {}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rest-api)) [:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :health-handler)))) (testing "invalid rest-api" (given-thrown (ig/init {:blaze.handler/app {:rest-api ::invalid}}) :key := :blaze.handler/app :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :health-handler)) [:explain ::s/problems 1 :pred] := `fn? [:explain ::s/problems 1 :val] := ::invalid)) (testing "invalid health" (given-thrown (ig/init {:blaze.handler/app {:health-handler ::invalid}}) :key := :PI:KEY:<KEY>END_PI :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rest-api)) [:explain ::s/problems 1 :pred] := `fn? [:explain ::s/problems 1 :val] := ::invalid))) (defn- rest-api [_] (ac/completed-future (ring/response ::rest-api))) (defn- health-handler [_] (ac/completed-future (ring/response ::health-handler))) (def system {:blaze.handler/app {:rest-api rest-api :health-handler health-handler}}) (deftest handler-test (testing "rest-api" (with-system [{handler :blaze.handler/app} system] @(handler {:uri "/" :request-method :get} (fn [response] (given response :status := 200 :body := ::rest-api)) identity))) (testing "health-handler" (with-system [{handler :blaze.handler/app} system] @(handler {:uri "/health" :request-method :get} (fn [response] (given response :status := 200 :body := ::health-handler)) identity))))
[ { "context": " (is (= (f/transform-stream-item [:insert {:name \"John\"}]) {:event-type :insert :new {:name \"John\"}}))\n ", "end": 297, "score": 0.9997923970222473, "start": 293, "tag": "NAME", "value": "John" }, { "context": ":name \"John\"}]) {:event-type :insert :new {:name \"John\"}}))\n (is (= (f/transform-stream-item [:modify", "end": 340, "score": 0.9997974038124084, "start": 336, "tag": "NAME", "value": "John" }, { "context": " (is (= (f/transform-stream-item [:modify {:name \"John\"} {:name \"John\" :age 31}])\n {:event-type", "end": 403, "score": 0.9997894167900085, "start": 399, "tag": "NAME", "value": "John" }, { "context": "sform-stream-item [:modify {:name \"John\"} {:name \"John\" :age 31}])\n {:event-type :modify :old {", "end": 418, "score": 0.9997864365577698, "start": 414, "tag": "NAME", "value": "John" }, { "context": "31}])\n {:event-type :modify :old {:name \"John\"} :new {:name \"John\" :age 31}}))\n (is (= (f/tr", "end": 479, "score": 0.9997563362121582, "start": 475, "tag": "NAME", "value": "John" }, { "context": "ent-type :modify :old {:name \"John\"} :new {:name \"John\" :age 31}}))\n (is (= (f/transform-stream-item ", "end": 499, "score": 0.9997729659080505, "start": 495, "tag": "NAME", "value": "John" }, { "context": " (is (= (f/transform-stream-item [:delete {:name \"John\"}]) {:event-type :delete :deleted {:name \"John\"}}", "end": 570, "score": 0.9997885823249817, "start": 566, "tag": "NAME", "value": "John" }, { "context": "e \"John\"}]) {:event-type :delete :deleted {:name \"John\"}}))))\n\n", "end": 617, "score": 0.9997891783714294, "start": 613, "tag": "NAME", "value": "John" } ]
data/train/clojure/cd15bd9d1e013544bbef556fcb034bba264cf531functions_test.clj
harshp8l/deep-learning-lang-detection
84
(ns onyx.plugin.functions-test (:require [clojure.test :refer [deftest is testing]] [onyx.plugin.functions :as f])) (deftest test-cases-for-stream-transducer (testing "Given an insert payload resembling a dynamodb stream" (is (= (f/transform-stream-item [:insert {:name "John"}]) {:event-type :insert :new {:name "John"}})) (is (= (f/transform-stream-item [:modify {:name "John"} {:name "John" :age 31}]) {:event-type :modify :old {:name "John"} :new {:name "John" :age 31}})) (is (= (f/transform-stream-item [:delete {:name "John"}]) {:event-type :delete :deleted {:name "John"}}))))
20511
(ns onyx.plugin.functions-test (:require [clojure.test :refer [deftest is testing]] [onyx.plugin.functions :as f])) (deftest test-cases-for-stream-transducer (testing "Given an insert payload resembling a dynamodb stream" (is (= (f/transform-stream-item [:insert {:name "<NAME>"}]) {:event-type :insert :new {:name "<NAME>"}})) (is (= (f/transform-stream-item [:modify {:name "<NAME>"} {:name "<NAME>" :age 31}]) {:event-type :modify :old {:name "<NAME>"} :new {:name "<NAME>" :age 31}})) (is (= (f/transform-stream-item [:delete {:name "<NAME>"}]) {:event-type :delete :deleted {:name "<NAME>"}}))))
true
(ns onyx.plugin.functions-test (:require [clojure.test :refer [deftest is testing]] [onyx.plugin.functions :as f])) (deftest test-cases-for-stream-transducer (testing "Given an insert payload resembling a dynamodb stream" (is (= (f/transform-stream-item [:insert {:name "PI:NAME:<NAME>END_PI"}]) {:event-type :insert :new {:name "PI:NAME:<NAME>END_PI"}})) (is (= (f/transform-stream-item [:modify {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI" :age 31}]) {:event-type :modify :old {:name "PI:NAME:<NAME>END_PI"} :new {:name "PI:NAME:<NAME>END_PI" :age 31}})) (is (= (f/transform-stream-item [:delete {:name "PI:NAME:<NAME>END_PI"}]) {:event-type :delete :deleted {:name "PI:NAME:<NAME>END_PI"}}))))
[ { "context": "ook chapter))\n\n(defroute \"/\" [] (dispatch-verses \"Matthew\" 1))\n\n(defn mount-root []\n (re-frame/clear-s", "end": 914, "score": 0.9636551141738892, "start": 911, "tag": "NAME", "value": "Mat" }, { "context": " chapter))\n\n(defroute \"/\" [] (dispatch-verses \"Matthew\" 1))\n\n(defn mount-root []\n (re-frame/clear-subsc", "end": 918, "score": 0.4735129773616791, "start": 914, "tag": "NAME", "value": "thew" } ]
data/test/clojure/87f3b9ffcfb150fcc9b64d0e72bbb043c56fcea4core.cljs
harshp8l/deep-learning-lang-detection
84
(ns ad-fontes.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-frisk.core :refer [enable-re-frisk!]] [secretary.core :as secretary :refer-macros [defroute]] [ad-fontes.events] [ad-fontes.subs] [ad-fontes.views :as views] [ad-fontes.config :as config])) (defn dev-setup [] (when config/debug? (enable-console-print!) (enable-re-frisk!) (println "dev mode"))) ;; TODO: Replace this with cljs-ajax or cljs-http code (defn dispatch-verses [book chapter] (let [promise (js/fetch (str "/api/" book "/" chapter))] (.then promise (fn [res] (let [promise2 (.text res)] (.then promise2 (fn [text] (re-frame/dispatch [:update-text text])))))))) (defroute "/:book/:chapter" [book chapter] (dispatch-verses book chapter)) (defroute "/" [] (dispatch-verses "Matthew" 1)) (defn mount-root [] (re-frame/clear-subscription-cache!) (reagent/render [views/main-panel] (.getElementById js/document "app"))) (defn ^:export init [] (re-frame/dispatch-sync [:initialize-db]) (dev-setup) (secretary/dispatch! js/window.location.pathname) (mount-root))
121215
(ns ad-fontes.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-frisk.core :refer [enable-re-frisk!]] [secretary.core :as secretary :refer-macros [defroute]] [ad-fontes.events] [ad-fontes.subs] [ad-fontes.views :as views] [ad-fontes.config :as config])) (defn dev-setup [] (when config/debug? (enable-console-print!) (enable-re-frisk!) (println "dev mode"))) ;; TODO: Replace this with cljs-ajax or cljs-http code (defn dispatch-verses [book chapter] (let [promise (js/fetch (str "/api/" book "/" chapter))] (.then promise (fn [res] (let [promise2 (.text res)] (.then promise2 (fn [text] (re-frame/dispatch [:update-text text])))))))) (defroute "/:book/:chapter" [book chapter] (dispatch-verses book chapter)) (defroute "/" [] (dispatch-verses "<NAME> <NAME>" 1)) (defn mount-root [] (re-frame/clear-subscription-cache!) (reagent/render [views/main-panel] (.getElementById js/document "app"))) (defn ^:export init [] (re-frame/dispatch-sync [:initialize-db]) (dev-setup) (secretary/dispatch! js/window.location.pathname) (mount-root))
true
(ns ad-fontes.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-frisk.core :refer [enable-re-frisk!]] [secretary.core :as secretary :refer-macros [defroute]] [ad-fontes.events] [ad-fontes.subs] [ad-fontes.views :as views] [ad-fontes.config :as config])) (defn dev-setup [] (when config/debug? (enable-console-print!) (enable-re-frisk!) (println "dev mode"))) ;; TODO: Replace this with cljs-ajax or cljs-http code (defn dispatch-verses [book chapter] (let [promise (js/fetch (str "/api/" book "/" chapter))] (.then promise (fn [res] (let [promise2 (.text res)] (.then promise2 (fn [text] (re-frame/dispatch [:update-text text])))))))) (defroute "/:book/:chapter" [book chapter] (dispatch-verses book chapter)) (defroute "/" [] (dispatch-verses "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" 1)) (defn mount-root [] (re-frame/clear-subscription-cache!) (reagent/render [views/main-panel] (.getElementById js/document "app"))) (defn ^:export init [] (re-frame/dispatch-sync [:initialize-db]) (dev-setup) (secretary/dispatch! js/window.location.pathname) (mount-root))
[ { "context": "rams {:id \"foo\"\n :name \"bar\"\n :url \"baz\"}\n ", "end": 604, "score": 0.518403172492981, "start": 601, "tag": "NAME", "value": "bar" }, { "context": ":id \"foo\"\n :name \"bar\"\n :url \"baz\"}))))", "end": 983, "score": 0.6230924725532532, "start": 980, "tag": "NAME", "value": "bar" }, { "context": "ey\n {:id \"1\"\n :name \"bar\"\n :url \"baz\"}]\n (let ", "end": 1180, "score": 0.7636536359786987, "start": 1177, "tag": "NAME", "value": "bar" } ]
test/bob/handlers/build_repo_handler_test.clj
lyeung/bob-clj
0
(ns bob.handlers.build-repo-handler-test (:require [bob.db.build-repo :as build-repo] [bob.handlers.build-repo-handler :as h] [bob.mock :refer [defmocktest mocking stubbing verify-call-times-for verify-first-call-args-for verify-nth-call-args-for]] [clojure.test :refer :all] [ring.util.http-response :as response])) (defmocktest save-build-repo (testing "save build-repo" (mocking [build-repo/save] (let [params {:id "foo" :name "bar" :url "baz"} req {:params params} result (h/save-build-repo req)] (is (= (response/ok) result)) (verify-call-times-for build-repo/save 1) (verify-first-call-args-for build-repo/save {:id "foo" :name "bar" :url "baz"}))))) (defmocktest get-build-repo (testing "get build-repo" (stubbing [build-repo/find-by-key {:id "1" :name "bar" :url "baz"}] (let [resp (h/get-build-repo "build-repo:1")] (is (= 200 (:status resp))) (is (= {:id "1" :name "bar" :url "baz"} (:body resp)))))))
78175
(ns bob.handlers.build-repo-handler-test (:require [bob.db.build-repo :as build-repo] [bob.handlers.build-repo-handler :as h] [bob.mock :refer [defmocktest mocking stubbing verify-call-times-for verify-first-call-args-for verify-nth-call-args-for]] [clojure.test :refer :all] [ring.util.http-response :as response])) (defmocktest save-build-repo (testing "save build-repo" (mocking [build-repo/save] (let [params {:id "foo" :name "<NAME>" :url "baz"} req {:params params} result (h/save-build-repo req)] (is (= (response/ok) result)) (verify-call-times-for build-repo/save 1) (verify-first-call-args-for build-repo/save {:id "foo" :name "<NAME>" :url "baz"}))))) (defmocktest get-build-repo (testing "get build-repo" (stubbing [build-repo/find-by-key {:id "1" :name "<NAME>" :url "baz"}] (let [resp (h/get-build-repo "build-repo:1")] (is (= 200 (:status resp))) (is (= {:id "1" :name "bar" :url "baz"} (:body resp)))))))
true
(ns bob.handlers.build-repo-handler-test (:require [bob.db.build-repo :as build-repo] [bob.handlers.build-repo-handler :as h] [bob.mock :refer [defmocktest mocking stubbing verify-call-times-for verify-first-call-args-for verify-nth-call-args-for]] [clojure.test :refer :all] [ring.util.http-response :as response])) (defmocktest save-build-repo (testing "save build-repo" (mocking [build-repo/save] (let [params {:id "foo" :name "PI:NAME:<NAME>END_PI" :url "baz"} req {:params params} result (h/save-build-repo req)] (is (= (response/ok) result)) (verify-call-times-for build-repo/save 1) (verify-first-call-args-for build-repo/save {:id "foo" :name "PI:NAME:<NAME>END_PI" :url "baz"}))))) (defmocktest get-build-repo (testing "get build-repo" (stubbing [build-repo/find-by-key {:id "1" :name "PI:NAME:<NAME>END_PI" :url "baz"}] (let [resp (h/get-build-repo "build-repo:1")] (is (= 200 (:status resp))) (is (= {:id "1" :name "bar" :url "baz"} (:body resp)))))))
[ { "context": "st test-application-api-session\n (let [username \"alice\"\n cookie (login-with-cookies username)\n ", "end": 2608, "score": 0.9729512929916382, "start": 2603, "tag": "USERNAME", "value": "alice" }, { "context": "eftest test-application-commands\n (let [user-id \"alice\"\n handler-id \"developer\"\n reviewer-", "end": 5448, "score": 0.9987573027610779, "start": 5443, "tag": "USERNAME", "value": "alice" }, { "context": " handler-id \"developer\"\n reviewer-id \"carl\"\n decider-id \"elsa\"\n license-id1 (t", "end": 5506, "score": 0.9867832660675049, "start": 5502, "tag": "USERNAME", "value": "carl" }, { "context": "r\"\n reviewer-id \"carl\"\n decider-id \"elsa\"\n license-id1 (test-helpers/create-license", "end": 5532, "score": 0.8806861042976379, "start": 5528, "tag": "USERNAME", "value": "elsa" }, { "context": "\n\n(deftest test-approve-with-end\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"devel", "end": 23716, "score": 0.9964996576309204, "start": 23714, "tag": "KEY", "value": "42" }, { "context": "-with-end\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"developer\"]\n (testing \"json\"", "end": 23742, "score": 0.914406955242157, "start": 23737, "tag": "USERNAME", "value": "alice" }, { "context": "(deftest test-application-create\n (let [api-key \"42\"\n user-id \"alice\"\n cat-id (test-hel", "end": 25480, "score": 0.9988583326339722, "start": 25478, "tag": "KEY", "value": "42" }, { "context": "tion-create\n (let [api-key \"42\"\n user-id \"alice\"\n cat-id (test-helpers/create-catalogue-it", "end": 25504, "score": 0.9676344394683838, "start": 25499, "tag": "USERNAME", "value": "alice" }, { "context": "on for disabled catalogue item\"\n (with-user \"owner\"\n (catalogue/set-catalogue-item-enabled! {", "end": 27643, "score": 0.9826928377151489, "start": 27638, "tag": "USERNAME", "value": "owner" }, { "context": "(deftest test-application-delete\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"devel", "end": 28109, "score": 0.9968148469924927, "start": 28107, "tag": "KEY", "value": "42" }, { "context": "on-delete\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"developer\"]\n (let [app-id (t", "end": 28135, "score": 0.9925958514213562, "start": 28130, "tag": "USERNAME", "value": "alice" }, { "context": "\n(deftest test-application-close\n (let [user-id \"alice\"\n application-id (test-helpers/create-appl", "end": 30043, "score": 0.9995391964912415, "start": 30038, "tag": "USERNAME", "value": "alice" }, { "context": "\n\n(deftest test-application-submit\n (let [owner \"owner\"\n user-id \"alice\"\n form-id (test-he", "end": 30686, "score": 0.9716259837150574, "start": 30681, "tag": "USERNAME", "value": "owner" }, { "context": "ion-submit\n (let [owner \"owner\"\n user-id \"alice\"\n form-id (test-helpers/create-form! {})\n ", "end": 30710, "score": 0.999255895614624, "start": 30705, "tag": "USERNAME", "value": "alice" }, { "context": "est test-application-invitations\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"devel", "end": 32381, "score": 0.9957393407821655, "start": 32379, "tag": "KEY", "value": "42" }, { "context": "vitations\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"developer\"\n app-id (test", "end": 32407, "score": 0.491723895072937, "start": 32402, "tag": "USERNAME", "value": "alice" }, { "context": " :member {:name \"Member 1\" :email \"member1@example.com\"}}))))\n (testin", "end": 32788, "score": 0.38834741711616516, "start": 32782, "tag": "NAME", "value": "Member" }, { "context": " :member {:name \"Member 1\" :email \"member1@example.com\"}}))))\n (testing ", "end": 32790, "score": 0.738075852394104, "start": 32789, "tag": "USERNAME", "value": "1" }, { "context": " :member {:name \"Member 1\" :email \"member1@example.com\"}}))))\n (testing \"accept member invitation for", "end": 32819, "score": 0.999911367893219, "start": 32800, "tag": "EMAIL", "value": "member1@example.com" }, { "context": " :invitation/token)\n member \"member1\"]\n (is token)\n (is (= {:success tru", "end": 33091, "score": 0.9594832062721252, "start": 33084, "tag": "USERNAME", "value": "member1" }, { "context": " :reviewer {:name \"Member 2\" :email \"member2@example.com\"}}))))\n (testing ", "end": 34079, "score": 0.8217698931694031, "start": 34071, "tag": "USERNAME", "value": "Member 2" }, { "context": " :reviewer {:name \"Member 2\" :email \"member2@example.com\"}}))))\n (testing \"accept handler invitation\"\n ", "end": 34108, "score": 0.9999151825904846, "start": 34089, "tag": "EMAIL", "value": "member2@example.com" }, { "context": " :invitation/token)\n reviewer \"reviewer1\"]\n (is token)\n (is (= {:success tru", "end": 34375, "score": 0.9909951686859131, "start": 34366, "tag": "USERNAME", "value": "reviewer1" }, { "context": " :decider {:name \"Member 3\" :email \"member3@example.com\"}}))))\n (testing ", "end": 35188, "score": 0.8070482611656189, "start": 35180, "tag": "NAME", "value": "Member 3" }, { "context": " :decider {:name \"Member 3\" :email \"member3@example.com\"}}))))\n (testing \"accept handler invitation\"\n ", "end": 35217, "score": 0.9999153017997742, "start": 35198, "tag": "EMAIL", "value": "member3@example.com" }, { "context": "test test-application-validation\n (let [user-id \"alice\"\n form-id (test-helpers/create-form! {:for", "end": 36181, "score": 0.9990967512130737, "start": 36176, "tag": "USERNAME", "value": "alice" }, { "context": "alogue-item! {:form-id form-id})\n user-id \"alice\"\n app-id (test-helpers/create-application!", "end": 49017, "score": 0.9477877616882324, "start": 49012, "tag": "USERNAME", "value": "alice" }, { "context": "(deftest test-decider-workflow\n (let [applicant \"alice\"\n handler \"handler\"\n decider \"carl\"", "end": 54700, "score": 0.5525465607643127, "start": 54695, "tag": "NAME", "value": "alice" }, { "context": "alice\"\n handler \"handler\"\n decider \"carl\"\n wf-id (test-helpers/create-workflow! {:t", "end": 54749, "score": 0.9436219930648804, "start": 54745, "tag": "NAME", "value": "carl" }, { "context": ")))))\n\n(deftest test-revoke\n (let [applicant-id \"alice\"\n member-id \"malice\"\n handler-id \"h", "end": 57934, "score": 0.9921982884407043, "start": 57929, "tag": "USERNAME", "value": "alice" }, { "context": "e\n (let [applicant-id \"alice\"\n member-id \"malice\"\n handler-id \"handler\"\n wfid (test-", "end": 57961, "score": 0.9985134601593018, "start": 57955, "tag": "USERNAME", "value": "malice" }, { "context": "iding-sensitive-information\n (let [applicant-id \"alice\"\n member-id \"developer\"\n handler-id", "end": 60700, "score": 0.9966378808021545, "start": 60695, "tag": "USERNAME", "value": "alice" }, { "context": "n\n (let [applicant-id \"alice\"\n member-id \"developer\"\n handler-id \"handler\"\n api-key \"42", "end": 60730, "score": 0.9839420318603516, "start": 60721, "tag": "USERNAME", "value": "developer" }, { "context": "er\"\n handler-id \"handler\"\n api-key \"42\"\n wfid (test-helpers/create-workflow! {:ha", "end": 60780, "score": 0.9988613724708557, "start": 60778, "tag": "KEY", "value": "42" }, { "context": " api-key handler-id)]\n (is (= {:userid \"alice\"\n :name \"Alice Applicant\"\n ", "end": 61962, "score": 0.9970858693122864, "start": 61957, "tag": "USERNAME", "value": "alice" }, { "context": " (is (= {:userid \"alice\"\n :name \"Alice Applicant\"\n :email \"alice@example.com\"\n ", "end": 62002, "score": 0.9997668266296387, "start": 61987, "tag": "NAME", "value": "Alice Applicant" }, { "context": " :name \"Alice Applicant\"\n :email \"alice@example.com\"\n :organizations [{:organization/i", "end": 62045, "score": 0.9999210238456726, "start": 62028, "tag": "EMAIL", "value": "alice@example.com" }, { "context": "ent/actor-attributes])))\n (is (= {:userid \"developer\"\n :name \"Developer\"\n ", "end": 62367, "score": 0.983252227306366, "start": 62358, "tag": "USERNAME", "value": "developer" }, { "context": "is (= {:userid \"developer\"\n :name \"Developer\"\n :email \"developer@example.com\"\n ", "end": 62401, "score": 0.9988478422164917, "start": 62392, "tag": "NAME", "value": "Developer" }, { "context": " :name \"Developer\"\n :email \"developer@example.com\"\n :nickname \"The Dev\"}\n ", "end": 62448, "score": 0.9999210238456726, "start": 62427, "tag": "EMAIL", "value": "developer@example.com" }, { "context": " api-key user)]\n (is (= {:userid \"alice\"\n :name \"Alice Applicant\"\n ", "end": 62895, "score": 0.9958996176719666, "start": 62890, "tag": "USERNAME", "value": "alice" }, { "context": " (is (= {:userid \"alice\"\n :name \"Alice Applicant\"\n :email \"alice@example.com\"\n ", "end": 62937, "score": 0.9997734427452087, "start": 62922, "tag": "NAME", "value": "Alice Applicant" }, { "context": ":name \"Alice Applicant\"\n :email \"alice@example.com\"\n :organizations [{:organization", "end": 62982, "score": 0.9999202489852905, "start": 62965, "tag": "EMAIL", "value": "alice@example.com" }, { "context": "t/actor-attributes])))\n (is (= {:userid \"developer\"\n :name \"Developer\"\n ", "end": 63227, "score": 0.9747951030731201, "start": 63218, "tag": "USERNAME", "value": "developer" }, { "context": " (= {:userid \"developer\"\n :name \"Developer\"\n :email \"developer@example.com\"", "end": 63263, "score": 0.9982661604881287, "start": 63254, "tag": "NAME", "value": "Developer" }, { "context": " :name \"Developer\"\n :email \"developer@example.com\"}\n (first (:application/members a", "end": 63312, "score": 0.9999213218688965, "start": 63291, "tag": "EMAIL", "value": "developer@example.com" }, { "context": "eftest test-application-export\n (let [applicant \"alice\"\n handler \"handler\"\n reporter \"repo", "end": 63522, "score": 0.9942903518676758, "start": 63517, "tag": "USERNAME", "value": "alice" }, { "context": "lice\"\n handler \"handler\"\n reporter \"reporter\"\n api-key \"42\"\n wf-id (test-helpers", "end": 63576, "score": 0.9993243217468262, "start": 63568, "tag": "USERNAME", "value": "reporter" }, { "context": "ler\"\n reporter \"reporter\"\n api-key \"42\"\n wf-id (test-helpers/create-workflow! {:t", "end": 63597, "score": 0.9987503290176392, "start": 63595, "tag": "KEY", "value": "42" }, { "context": "test-application-api-attachments\n (let [api-key \"42\"\n user-id \"alice\"\n handler-id \"deve", "end": 66901, "score": 0.9710321426391602, "start": 66899, "tag": "KEY", "value": "42" }, { "context": "attachments\n (let [api-key \"42\"\n user-id \"alice\"\n handler-id \"developer\" ;; developer is t", "end": 66925, "score": 0.9865884184837341, "start": 66920, "tag": "USERNAME", "value": "alice" }, { "context": " (authenticate api-key \"carl\")\n handler)]\n ", "end": 70696, "score": 0.9432898759841919, "start": 70692, "tag": "NAME", "value": "carl" }, { "context": ")\n (authenticate api-key \"carl\")\n handler)]\n (is ", "end": 74378, "score": 0.6653623580932617, "start": 74374, "tag": "NAME", "value": "carl" }, { "context": ")\n (authenticate api-key \"carl\")\n handler)]\n (is ", "end": 75596, "score": 0.7263385653495789, "start": 75592, "tag": "NAME", "value": "carl" }, { "context": "-application-comment-attachments\n (let [api-key \"42\"\n applicant-id \"alice\"\n handler-id ", "end": 75751, "score": 0.9991586804389954, "start": 75749, "tag": "KEY", "value": "42" }, { "context": "hments\n (let [api-key \"42\"\n applicant-id \"alice\"\n handler-id \"developer\"\n reviewer-", "end": 75780, "score": 0.5372468829154968, "start": 75775, "tag": "NAME", "value": "alice" }, { "context": " handler-id \"developer\"\n reviewer-id \"carl\"\n file #(assoc filecontent :filename %)\n ", "end": 75837, "score": 0.6632649302482605, "start": 75834, "tag": "USERNAME", "value": "car" }, { "context": " handler-id \"developer\"\n reviewer-id \"carl\"\n file #(assoc filecontent :filename %)\n ", "end": 75838, "score": 0.7492548823356628, "start": 75837, "tag": "NAME", "value": "l" }, { "context": " test-application-attachment-zip\n (let [api-key \"42\"\n applicant-id \"alice\"\n handler-id ", "end": 85237, "score": 0.9987058639526367, "start": 85235, "tag": "KEY", "value": "42" }, { "context": "nt-zip\n (let [api-key \"42\"\n applicant-id \"alice\"\n handler-id \"handler\"\n reporter-id", "end": 85266, "score": 0.912733256816864, "start": 85261, "tag": "USERNAME", "value": "alice" }, { "context": "lication-api-license-attachments\n (let [api-key \"42\"\n applicant \"alice\"\n non-applicant ", "end": 90998, "score": 0.9991121888160706, "start": 90996, "tag": "KEY", "value": "42" }, { "context": "tachments\n (let [api-key \"42\"\n applicant \"alice\"\n non-applicant \"bob\"\n owner \"owner", "end": 91024, "score": 0.8948773741722107, "start": 91019, "tag": "NAME", "value": "alice" }, { "context": "\n applicant \"alice\"\n non-applicant \"bob\"\n owner \"owner\"\n handler-user \"deve", "end": 91052, "score": 0.9500125646591187, "start": 91049, "tag": "NAME", "value": "bob" }, { "context": "alice\"\n non-applicant \"bob\"\n owner \"owner\"\n handler-user \"developer\"\n cat-id ", "end": 91074, "score": 0.8984671831130981, "start": 91069, "tag": "USERNAME", "value": "owner" }, { "context": "\"bob\"\n owner \"owner\"\n handler-user \"developer\"\n cat-id (test-helpers/create-catalogue-it", "end": 91107, "score": 0.9857410192489624, "start": 91098, "tag": "USERNAME", "value": "developer" }, { "context": "t test-applications-api-security\n (let [api-key \"42\"\n applicant \"alice\"\n cat-id (test-h", "end": 95479, "score": 0.9983317852020264, "start": 95477, "tag": "KEY", "value": "42" }, { "context": "-security\n (let [api-key \"42\"\n applicant \"alice\"\n cat-id (test-helpers/create-catalogue-it", "end": 95505, "score": 0.9964725375175476, "start": 95500, "tag": "USERNAME", "value": "alice" }, { "context": "\"})))))))\n\n(deftest test-todos\n (let [applicant \"alice\"\n handler \"developer\"\n reviewer \"re", "end": 99847, "score": 0.9887292981147766, "start": 99842, "tag": "USERNAME", "value": "alice" }, { "context": "ce\"\n handler \"developer\"\n reviewer \"reviewer\"\n decider \"decider\"\n app-id (test-h", "end": 99903, "score": 0.7905981540679932, "start": 99895, "tag": "USERNAME", "value": "reviewer" }, { "context": ")\n\n(deftest test-application-raw\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"handl", "end": 103392, "score": 0.9989213943481445, "start": 103390, "tag": "KEY", "value": "42" }, { "context": "ation-raw\n (let [api-key \"42\"\n applicant \"alice\"\n handler \"handler\"\n reporter \"repo", "end": 103418, "score": 0.9952344298362732, "start": 103413, "tag": "USERNAME", "value": "alice" }, { "context": "lice\"\n handler \"handler\"\n reporter \"reporter\"\n form-id (test-helpers/create-form! {:for", "end": 103472, "score": 0.9944107532501221, "start": 103464, "tag": "USERNAME", "value": "reporter" }, { "context": "rs\n [{:email \"handler@example.com\" :userid \"handler\" :name \"Hannah Handler\"}]}\n ", "end": 106965, "score": 0.9999227523803711, "start": 106946, "tag": "EMAIL", "value": "handler@example.com" }, { "context": " [{:email \"handler@example.com\" :userid \"handler\" :name \"Hannah Handler\"}]}\n :applica", "end": 106983, "score": 0.9744660258293152, "start": 106976, "tag": "USERNAME", "value": "handler" }, { "context": "il \"handler@example.com\" :userid \"handler\" :name \"Hannah Handler\"}]}\n :application/blacklist []\n ", "end": 107006, "score": 0.9997466802597046, "start": 106992, "tag": "NAME", "value": "Hannah Handler" }, { "context": "nil\n :application/applicant {:email \"alice@example.com\" :userid \"alice\" :name \"Alice Applicant\" :nicknam", "end": 107187, "score": 0.9999227523803711, "start": 107170, "tag": "EMAIL", "value": "alice@example.com" }, { "context": "on/applicant {:email \"alice@example.com\" :userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland", "end": 107203, "score": 0.9739612936973572, "start": 107198, "tag": "USERNAME", "value": "alice" }, { "context": ":email \"alice@example.com\" :userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland\" :organizations [{:orga", "end": 107227, "score": 0.999169647693634, "start": 107212, "tag": "NAME", "value": "Alice Applicant" }, { "context": " :event/actor-attributes {:userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland", "end": 109344, "score": 0.9992319941520691, "start": 109339, "tag": "USERNAME", "value": "alice" }, { "context": " :event/actor-attributes {:userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland\" :email \"alice@example.", "end": 109368, "score": 0.9990999102592468, "start": 109353, "tag": "NAME", "value": "Alice Applicant" }, { "context": "lice Applicant\" :nickname \"In Wonderland\" :email \"alice@example.com\" :organizations [{:organization/id \"default\"}] :r", "end": 109421, "score": 0.999911904335022, "start": 109404, "tag": "EMAIL", "value": "alice@example.com" }, { "context": " :event/actor \"alice\"\n :event/type ", "end": 110006, "score": 0.9892141222953796, "start": 110001, "tag": "NAME", "value": "alice" }, { "context": " :event/actor \"alice\"\n :application", "end": 110456, "score": 0.9866666197776794, "start": 110451, "tag": "NAME", "value": "alice" }, { "context": " :event/actor-attributes {:userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland", "end": 110592, "score": 0.9992885589599609, "start": 110587, "tag": "USERNAME", "value": "alice" }, { "context": " :event/actor-attributes {:userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland\" :email \"alice@example.", "end": 110616, "score": 0.9992838501930237, "start": 110601, "tag": "NAME", "value": "Alice Applicant" }, { "context": "lice Applicant\" :nickname \"In Wonderland\" :email \"alice@example.com\" :organizations [{:organization/id \"default\"}] :r", "end": 110669, "score": 0.9999109506607056, "start": 110652, "tag": "EMAIL", "value": "alice@example.com" }, { "context": " :event/actor \"alice\"\n :application", "end": 111127, "score": 0.869916558265686, "start": 111122, "tag": "NAME", "value": "alice" }, { "context": " :event/actor-attributes {:userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland", "end": 111263, "score": 0.9987372159957886, "start": 111258, "tag": "USERNAME", "value": "alice" }, { "context": " :event/actor-attributes {:userid \"alice\" :name \"Alice Applicant\" :nickname \"In Wonderland\" :email \"alice@example.", "end": 111287, "score": 0.9973306655883789, "start": 111272, "tag": "NAME", "value": "Alice Applicant" }, { "context": "lice Applicant\" :nickname \"In Wonderland\" :email \"alice@example.com\" :organizations [{:organization/id \"default\"}] :r", "end": 111340, "score": 0.9999168515205383, "start": 111323, "tag": "EMAIL", "value": "alice@example.com" } ]
test/clj/rems/api/test_applications.clj
dycons/rems
0
(ns ^:integration rems.api.test-applications (:require [clj-time.core :as time] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [rems.api.services.catalogue :as catalogue] [rems.api.testing :refer :all] [rems.db.applications] [rems.db.blacklist :as blacklist] [rems.db.core :as db] [rems.db.test-data :as test-data] [rems.db.test-data-helpers :as test-helpers] [rems.handler :refer [handler]] [rems.json] [rems.testing-util :refer [with-user]] [ring.mock.request :refer :all]) (:import java.io.ByteArrayOutputStream java.util.zip.ZipInputStream)) (use-fixtures :each api-fixture ;; TODO should this fixture have a name? (fn [f] (test-data/create-test-api-key!) (test-data/create-test-users-and-roles!) (f))) ;;; shared helpers (defn- send-command [actor cmd] (-> (request :post (str "/api/applications/" (name (:type cmd)))) (authenticate "42" actor) (json-body (dissoc cmd :type)) handler read-body)) (defn- send-command-transit [actor cmd] (-> (request :post (str "/api/applications/" (name (:type cmd)))) (authenticate "42" actor) (transit-body (dissoc cmd :type)) handler read-body)) (defn- get-ids [applications] (set (map :application/id applications))) (defn- license-ids-for-application [application] (set (map :license/id (:application/licenses application)))) (defn- catalogue-item-ids-for-application [application] (set (map :catalogue-item/id (:application/resources application)))) (defn- get-my-applications [user-id & [params]] (-> (request :get "/api/my-applications" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-all-applications [user-id & [params]] (-> (request :get "/api/applications" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-application-for-user [app-id user-id] (-> (request :get (str "/api/applications/" app-id)) (authenticate "42" user-id) handler read-ok-body)) (defn- get-todos [user-id & [params]] (-> (request :get "/api/applications/todo" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-handled-todos [user-id & [params]] (-> (request :get "/api/applications/handled" params) (authenticate "42" user-id) handler read-ok-body)) ;;; tests (deftest test-application-api-session (let [username "alice" cookie (login-with-cookies username) csrf (get-csrf-token cookie) cat-id (test-helpers/create-catalogue-item! {})] (testing "save with session" (let [body (-> (request :post "/api/applications/create") (header "Cookie" cookie) (header "x-csrf-token" csrf) (json-body {:catalogue-item-ids [cat-id]}) handler assert-response-is-ok read-body)] (is (:success body)))) (testing "save with session but without csrf" (let [response (-> (request :post "/api/applications/create") (header "Cookie" cookie) (json-body {:catalogue-item-ids [cat-id]}) handler)] (is (response-is-unauthorized? response)))) (testing "save with session and csrf and wrong api-key" (let [body (-> (request :post "/api/applications/create") (header "Cookie" cookie) (header "x-csrf-token" csrf) (header "x-rems-api-key" "WRONG") (json-body {:catalogue-item-ids [cat-id]}) handler assert-response-is-ok read-body)] (is (:success body)))))) (deftest pdf-smoke-test (testing "not found" (let [response (-> (request :get "/api/applications/9999999/pdf") (authenticate "42" "developer") handler)] (is (response-is-not-found? response)))) (let [cat-id (test-helpers/create-catalogue-item! {:title {:fi "Fi title" :en "En title"}}) application-id (test-helpers/create-application! {:actor "alice" :catalogue-item-ids [cat-id]})] (test-helpers/command! {:type :application.command/submit :application-id application-id :actor "alice"}) (testing "forbidden" (let [response (-> (request :get (str "/api/applications/" application-id "/pdf")) (authenticate "42" "bob") handler)] (is (response-is-forbidden? response)))) (testing "success" (let [response (-> (request :get (str "/api/applications/" application-id "/pdf")) (authenticate "42" "developer") handler assert-response-is-ok)] (is (= "application/pdf" (get-in response [:headers "Content-Type"]))) (is (= (str "filename=\"" application-id ".pdf\"") (get-in response [:headers "Content-Disposition"]))) (is (.startsWith (slurp (:body response)) "%PDF-1.")))))) (deftest test-application-commands (let [user-id "alice" handler-id "developer" reviewer-id "carl" decider-id "elsa" license-id1 (test-helpers/create-license! {}) license-id2 (test-helpers/create-license! {}) license-id3 (test-helpers/create-license! {}) license-id4 (test-helpers/create-license! {}) form-id (test-helpers/create-form! {}) workflow-id (test-helpers/create-workflow! {:type :workflow/master :handlers [handler-id]}) cat-item-id1 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id1 license-id2]}) :form-id form-id :workflow-id workflow-id}) cat-item-id2 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id1 license-id2]}) :form-id form-id :workflow-id workflow-id}) cat-item-id3 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id3]}) :form-id form-id :workflow-id workflow-id}) application-id (test-helpers/create-application! {:catalogue-item-ids [cat-item-id1] :actor user-id})] (testing "accept licenses" (is (= {:success true} (send-command user-id {:type :application.command/accept-licenses :application-id application-id :accepted-licenses [license-id1 license-id2]}))) (testing "with invalid application id" (is (= {:success false :errors [{:type "application-not-found"}]} (send-command user-id {:type :application.command/accept-licenses :application-id 9999999999 :accepted-licenses [license-id1 license-id2]}))))) (testing "save draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id application-id :field-values []})))) (testing "submit" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id})))) (testing "getting application as applicant" (let [application (get-application-for-user application-id user-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted"] (map :event/type (get application :application/events)))) (is (= #{"application.command/remove-member" "application.command/uninvite-member" "application.command/accept-licenses" "application.command/copy-as-new"} (set (get application :application/permissions)))))) (testing "getting application as handler" (let [application (get-application-for-user application-id handler-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= #{"application.command/request-review" "application.command/request-decision" "application.command/remark" "application.command/reject" "application.command/approve" "application.command/return" "application.command/add-licenses" "application.command/add-member" "application.command/remove-member" "application.command/invite-member" "application.command/invite-decider" "application.command/invite-reviewer" "application.command/uninvite-member" "application.command/change-resources" "application.command/close" "application.command/assign-external-id" "see-everything"} (set (get application :application/permissions)))))) (testing "disabling a command" (with-redefs [rems.config/env (assoc rems.config/env :disable-commands [:application.command/remark])] (testing "handler doesn't see hidden command" (let [application (get-application-for-user application-id handler-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= #{"application.command/request-review" "application.command/request-decision" "application.command/reject" "application.command/approve" "application.command/return" "application.command/add-licenses" "application.command/add-member" "application.command/remove-member" "application.command/invite-member" "application.command/invite-decider" "application.command/invite-reviewer" "application.command/uninvite-member" "application.command/change-resources" "application.command/close" "application.command/assign-external-id" "see-everything"} (set (get application :application/permissions)))))) (testing "disabled command fails" (is (= {:success false :errors [{:type "forbidden"}]} (send-command handler-id {:type :application.command/remark :application-id application-id :public false :comment "this is a remark"})))))) (testing "send command without user" (is (= {:success false :errors [{:type "forbidden"}]} (send-command "" {:type :application.command/approve :application-id application-id :comment ""})) "user should be forbidden to send command")) (testing "send command with a user that is not a handler" (is (= {:success false :errors [{:type "forbidden"}]} (send-command user-id {:type :application.command/approve :application-id application-id :comment ""})) "user should be forbidden to send command")) (testing "assing external id" (is (= {:success true} (send-command handler-id {:type :application.command/assign-external-id :application-id application-id :external-id "abc123"}))) (let [application (get-application-for-user application-id handler-id)] (is (= "abc123" (:application/external-id application))))) (testing "application can be returned" (is (= {:success true} (send-command handler-id {:type :application.command/return :application-id application-id :comment "Please check again"})))) (testing "changing resources as applicant" (is (= {:success true} (send-command user-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id2]})))) (testing "submitting again" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id})))) (testing "send commands with authorized user" (testing "even handler cannot review without request" (is (= {:errors [{:type "forbidden"}], :success false} (send-command handler-id {:type :application.command/review :application-id application-id :comment "What am I commenting on?"})))) (testing "review with request" (let [eventcount (count (get (get-application-for-user application-id handler-id) :events))] (testing "requesting review" (is (= {:success true} (send-command handler-id {:type :application.command/request-review :application-id application-id :reviewers [decider-id reviewer-id] :comment "What say you?"})))) (testing "reviewer can now review" (is (= {:success true} (send-command reviewer-id {:type :application.command/review :application-id application-id :comment "Yeah, I dunno"})))) (testing "review was linked to request" (let [application (get-application-for-user application-id handler-id) request-event (get-in application [:application/events eventcount]) review-event (get-in application [:application/events (inc eventcount)])] (is (= (:application/request-id request-event) (:application/request-id review-event))))))) (testing "adding and then accepting additional licenses" (testing "add licenses" (let [application (get-application-for-user application-id user-id)] (is (= #{license-id1 license-id2} (license-ids-for-application application))) (is (= {:success true} (send-command handler-id {:type :application.command/add-licenses :application-id application-id :licenses [license-id4] :comment "Please approve these new terms"}))) (let [application (get-application-for-user application-id user-id)] (is (= #{license-id1 license-id2 license-id4} (license-ids-for-application application)))))) (testing "applicant accepts the additional licenses" (is (= {:success true} (send-command user-id {:type :application.command/accept-licenses :application-id application-id :accepted-licenses [license-id4]}))))) (testing "changing resources as handler" (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id2} (catalogue-item-ids-for-application application))) (is (= #{license-id1 license-id2 license-id4} (license-ids-for-application application))) (is (= {:success true} (send-command handler-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id3] :comment "Here are the correct resources"}))) (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id3} (catalogue-item-ids-for-application application))) ;; TODO: The previously added licenses should probably be retained in the licenses after changing resources. (is (= #{license-id3} (license-ids-for-application application)))))) (testing "changing resources back as handler" (is (= {:success true} (send-command handler-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id2]}))) (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id2} (catalogue-item-ids-for-application application))) (is (= #{license-id1 license-id2} (license-ids-for-application application))))) (testing "request-decision" (is (= {:success true} (send-command handler-id {:type :application.command/request-decision :application-id application-id :deciders [decider-id] :comment ""})))) (testing "decide" (is (= {:success true} (send-command decider-id {:type :application.command/decide :application-id application-id :decision :approved :comment ""})))) (testing "hidden remark" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "" :public false})))) (testing "public remark with" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "" :public true})))) (testing "approve" (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id application-id :comment ""}))) (let [handler-data (get-application-for-user application-id handler-id) handler-event-types (map :event/type (get handler-data :application/events)) applicant-data (get-application-for-user application-id user-id) applicant-event-types (map :event/type (get applicant-data :application/events))] (testing "handler can see all events" (is (= {:application/id application-id :application/state "application.state/approved"} (select-keys handler-data [:application/id :application/state]))) (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted" "application.event/external-id-assigned" "application.event/returned" "application.event/resources-changed" "application.event/submitted" "application.event/review-requested" "application.event/reviewed" "application.event/licenses-added" "application.event/licenses-accepted" "application.event/resources-changed" "application.event/resources-changed" "application.event/decision-requested" "application.event/decided" "application.event/remarked" "application.event/remarked" "application.event/approved"] handler-event-types))) (testing "applicant cannot see all events" (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted" "application.event/external-id-assigned" "application.event/returned" "application.event/resources-changed" "application.event/submitted" "application.event/licenses-added" "application.event/licenses-accepted" "application.event/resources-changed" "application.event/resources-changed" "application.event/remarked" "application.event/approved"] applicant-event-types))))) (testing "copy as new" (let [result (send-command user-id {:type :application.command/copy-as-new :application-id application-id})] (is (:success result) {:result result}) (is (:application-id result) {:result result}) (is (not= application-id (:application-id result)) "should create a new application")))))) (deftest test-approve-with-end (let [api-key "42" applicant "alice" handler "developer"] (testing "json" (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:type :application.command/submit :application-id app-id :actor applicant}) (is (= {:success true} (send-command handler {:type :application.command/approve :application-id app-id :comment "" :entitlement-end "2100-01-01T00:00:00.000Z"}))) (let [app (get-application-for-user app-id applicant)] (is (= "application.state/approved" (:application/state app))) (is (= "2100-01-01T00:00:00.000Z" (:entitlement/end app)))))) (testing "transit" (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:type :application.command/submit :application-id app-id :actor applicant}) (is (= {:success true} (send-command-transit handler {:type :application.command/approve :application-id app-id :comment "" :entitlement-end (time/date-time 2100 01 01)}))) (let [app (get-application-for-user app-id applicant)] (is (= "application.state/approved" (:application/state app))) (is (= "2100-01-01T00:00:00.000Z" (:entitlement/end app)))))))) (deftest test-application-create (let [api-key "42" user-id "alice" cat-id (test-helpers/create-catalogue-item! {}) application-id (:application-id (api-call :post "/api/applications/create" {:catalogue-item-ids [cat-id]} "42" user-id))] (testing "creating" (is (some? application-id)) (let [created (get-application-for-user application-id user-id)] (is (= "application.state/draft" (get created :application/state))))) (testing "seeing draft is forbidden" (testing "as unrelated user" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "bob")))) (testing "as reporter" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "reporter")))) (testing "as handler" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "developer"))))) (testing "modifying application as other user is forbidden" (is (= {:success false :errors [{:type "forbidden"}]} (send-command "bob" {:type :application.command/save-draft :application-id application-id :field-values []})))) (testing "submitting" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id}))) (let [submitted (get-application-for-user application-id user-id)] (is (= "application.state/submitted" (get submitted :application/state))) (is (= ["application.event/created" "application.event/submitted"] (map :event/type (get submitted :application/events)))))) (testing "seeing submitted application as reporter is allowed" (is (response-is-ok? (-> (request :get (str "/api/applications/" application-id)) (authenticate api-key "reporter") handler)))) (testing "can't create application for disabled catalogue item" (with-user "owner" (catalogue/set-catalogue-item-enabled! {:id cat-id :enabled false})) (rems.db.applications/reload-cache!) (is (= {:success false :errors [{:type "disabled-catalogue-item" :catalogue-item-id cat-id}]} (api-call :post "/api/applications/create" {:catalogue-item-ids [cat-id]} "42" user-id)))))) (deftest test-application-delete (let [api-key "42" applicant "alice" handler "developer"] (let [app-id (test-helpers/create-application! {:actor applicant})] (testing "can't delete draft as other user" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key handler)))) (testing "can delete draft as applicant" (is (contains? (-> (get-application-for-user app-id applicant) :application/permissions set) "application.command/delete")) (is (= {:success true} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant)))) (testing "deleted application is gone" (is (response-is-not-found? (api-response :get (str "/api/applications/" app-id) nil api-key applicant))))) (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:application-id app-id :type :application.command/submit :actor applicant}) (testing "can't delete submitted application" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant)))) (test-helpers/command! {:application-id app-id :type :application.command/return :actor handler}) (testing "can't delete returned application" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant))))))) (deftest test-application-close (let [user-id "alice" application-id (test-helpers/create-application! {:actor user-id})] (test-helpers/command! {:application-id application-id :type :application.command/submit :actor user-id}) (is (= {:success true} (send-command "developer" {:type :application.command/close :application-id application-id :comment ""}))) (is (= "application.state/closed" (:application/state (get-application-for-user application-id user-id)))))) (deftest test-application-submit (let [owner "owner" user-id "alice" form-id (test-helpers/create-form! {}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) enable-catalogue-item! #(with-user owner (catalogue/set-catalogue-item-enabled! {:id cat-id :enabled %})) archive-catalogue-item! #(with-user owner (catalogue/set-catalogue-item-archived! {:id cat-id :archived %}))] (testing "submit with archived & disabled catalogue item succeeds" ;; draft needs to be created before disabling & archiving (let [app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (is (:success (enable-catalogue-item! false))) (is (:success (archive-catalogue-item! true))) (rems.db.applications/reload-cache!) (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id}))))) (testing "submit with normal catalogue item succeeds" (is (:success (enable-catalogue-item! true))) (is (:success (archive-catalogue-item! false))) (rems.db.applications/reload-cache!) (let [app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id}))))))) (deftest test-application-invitations (let [api-key "42" applicant "alice" handler "developer" app-id (test-helpers/create-application! {:actor applicant})] (testing "invite member for draft as applicant" (is (= {:success true} (send-command applicant {:type :application.command/invite-member :application-id app-id :member {:name "Member 1" :email "member1@example.com"}})))) (testing "accept member invitation for draft" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) member "member1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key member))) (testing ", member is able to fetch application and see themselves" (is (= #{member} (->> (get-application-for-user app-id member) :application/members (mapv :userid) set)))))) (testing "submit application" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "invite reviewer as handler" (is (= {:success true} (send-command handler {:type :application.command/invite-reviewer :application-id app-id :reviewer {:name "Member 2" :email "member2@example.com"}})))) (testing "accept handler invitation" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) reviewer "reviewer1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key reviewer))) (testing ", reviewer is able to fetch application and can submit a review" (is (= ["see-everything" "application.command/review" "application.command/remark"] (:application/permissions (get-application-for-user app-id reviewer))))))) (testing "invite decider as handler" (is (= {:success true} (send-command handler {:type :application.command/invite-decider :application-id app-id :decider {:name "Member 3" :email "member3@example.com"}})))) (testing "accept handler invitation" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) decider "decider1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key decider))) (testing ", decider is able to fetch application and can submit a review" (is (= ["see-everything" "application.command/reject" "application.command/decide" "application.command/remark" "application.command/approve"] (:application/permissions (get-application-for-user app-id decider))))))))) (deftest test-application-validation (let [user-id "alice" form-id (test-helpers/create-form! {:form/fields [{:field/id "req1" :field/title {:en "req" :fi "pak" :sv "obl"} :field/type :text :field/optional false} {:field/id "opt1" :field/title {:en "opt" :fi "val" :sv "fri"} :field/type :text :field/optional true}]}) form-id2 (test-helpers/create-form! {:form/fields [{:field/id "req2" :field/title {:en "req" :fi "pak" :sv "obl"} :field/type :text :field/optional false} {:field/id "opt2" :field/title {:en "opt" :fi "val" :sv "fri"} :field/type :text :field/optional true} {:field/id "table" :field/type :table :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}]} {:field/id "optionlist" :field/title {:en "Option list." :fi "Valintalista." :sv "Välj"} :field/type :option :field/options [{:key "Option1" :label {:en "First" :fi "Ensimmäinen" :sv "Först"}} {:key "Option2" :label {:en "Second" :fi "Toinen" :sv "Den andra"}} {:key "Option3" :label {:en "Third" :fi "Kolmas" :sv "Tredje"}}] :field/optional true}]}) wf-id (test-helpers/create-workflow! {}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id :workflow-id wf-id}) cat-id2 (test-helpers/create-catalogue-item! {:form-id form-id2 :workflow-id wf-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id cat-id2] :actor user-id})] (testing "set value of optional field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"}]}) (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id2 :field "opt2" :value "opt"}]})))) (testing "can't submit without required field" (is (= {:success false :errors [{:form-id form-id :field-id "req1" :type "t.form.validation/required"} {:form-id form-id2 :field-id "req2" :type "t.form.validation/required"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "set value of required field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"}]})))) (testing "can't set value of text field to JSON" (is (= {:success false :errors [{:form-id form-id :field-id "req1" :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "req1" :value [[{:column "foo" :value "bar"}]]}]})))) (testing "can set value of table field to JSON" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "table" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "col2" :value "bar"}]]}]}))) (is (= [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "col2" :value "bar"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 1 :form/fields 2 :field/value])))) (testing "column name validation for table fields" (is (= {:success false :errors [{:type "t.form.validation/invalid-value", :form-id form-id2, :field-id "table"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "table" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "colx" :value "bar"}]]}]})))) (testing "save-draft fails with non-existing value of option list" (is (= {:success false :errors [{:field-id "optionlist", :form-id form-id2, :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "optionlist" :value "foobar"}]})))) (testing "set existing value of option list" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "optionlist" :value "Option2"}]})))) (testing "can submit with required field" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))))) (deftest test-table ;; Adding the table field required changes to many API schemas since ;; the table values aren't just plain strings (like the values for ;; other fields). This test is mostly here to verify table values ;; work everywhere in the API. ;; ;; Table validations are mostly tested in test-application-validation (let [form-id (test-helpers/create-form! {:form/fields [{:field/id "opt" :field/type :table :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}]} {:field/id "req" :field/type :table :field/title {:en "required table" :fi "table" :sv "table"} :field/optional false :field/columns [{:key "foo" :label {:en "foo" :fi "foo" :sv "foo"}} {:key "bar" :label {:en "bar" :fi "bar" :sv "bar"}} {:key "xyz" :label {:en "xyz" :fi "xyz" :sv "xyz"}}]}]}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) user-id "alice" app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (testing "default values" (let [app (get-application-for-user app-id user-id)] (is (= [] (get-in app [:application/forms 0 :form/fields 0 :field/value]))) (is (= [] (get-in app [:application/forms 0 :form/fields 1 :field/value]))))) (testing "save a draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value []}]}))) (is (= [{:field/id "opt" :field/type "table" :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/visible true :field/private false :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}] :field/value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:field/id "req" :field/type "table" :field/title {:en "required table" :fi "table" :sv "table"} :field/optional false :field/visible true :field/private false :field/columns [{:key "foo" :label {:en "foo" :fi "foo" :sv "foo"}} {:key "bar" :label {:en "bar" :fi "bar" :sv "bar"}} {:key "xyz" :label {:en "xyz" :fi "xyz" :sv "xyz"}}] :field/value []}] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields])))) (testing "can't submit no rows in required table" (is (= {:success false :errors [{:type "t.form.validation/required" :form-id form-id :field-id "req"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "save a new draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value ""} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]]}]}))) (is (= [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/value])))) (testing "can't submit with empty column values" (is (= {:success false :errors [{:type "t.form.validation/column-values-missing" :form-id form-id :field-id "opt"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "can submit with all columns set" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]]}]}))) (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "can return" (is (= {:success true} (send-command "developer" {:type :application.command/return :application-id app-id}))) (is (= [[{:value "f" :column "foo"} {:value "b" :column "bar"} {:value "x" :column "xyz"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/value]))) (is (= [[{:value "f" :column "foo"} {:value "b" :column "bar"} {:value "x" :column "xyz"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/previous-value])))))) (deftest test-decider-workflow (let [applicant "alice" handler "handler" decider "carl" wf-id (test-helpers/create-workflow! {:type :workflow/decider :handlers [handler]}) cat-id (test-helpers/create-catalogue-item! {:workflow-id wf-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant})] (testing "applicant's commands for draft" (is (= #{"application.command/accept-licenses" "application.command/change-resources" "application.command/copy-as-new" "application.command/delete" "application.command/invite-member" "application.command/remove-member" "application.command/save-draft" "application.command/submit" "application.command/uninvite-member"} (set (:application/permissions (get-application-for-user app-id applicant)))))) (testing "submit" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "applicant's commands after submit" (is (= #{"application.command/accept-licenses" "application.command/copy-as-new" "application.command/remove-member" "application.command/uninvite-member"} (set (:application/permissions (get-application-for-user app-id applicant)))))) (testing "handler's commands" (is (= #{"application.command/add-licenses" "application.command/add-member" "application.command/assign-external-id" "application.command/change-resources" "application.command/close" "application.command/invite-reviewer" "application.command/invite-member" "application.command/remark" "application.command/remove-member" "application.command/request-decision" "application.command/request-review" "application.command/return" "application.command/uninvite-member" "see-everything"} (set (:application/permissions (get-application-for-user app-id handler)))))) (testing "request decision" (is (= {:success true} (send-command handler {:type :application.command/request-decision :application-id app-id :deciders [decider] :comment ""})))) (testing "decider's commands" (is (= #{"application.command/approve" "application.command/reject" "application.command/remark" "see-everything"} (set (:application/permissions (get-application-for-user app-id decider)))))) (testing "approve" (is (= {:success true} (send-command decider {:type :application.command/approve :application-id app-id :comment ""})))))) (deftest test-revoke (let [applicant-id "alice" member-id "malice" handler-id "handler" wfid (test-helpers/create-workflow! {:handlers [handler-id]}) formid (test-helpers/create-form! {}) ext1 "revoke-test-resource-1" ext2 "revoke-test-resource-2" res1 (test-helpers/create-resource! {:resource-ext-id ext1}) res2 (test-helpers/create-resource! {:resource-ext-id ext2}) cat1 (test-helpers/create-catalogue-item! {:workflow-id wfid :form-id formid :resource-id res1}) cat2 (test-helpers/create-catalogue-item! {:workflow-id wfid :form-id formid :resource-id res2}) app-id (test-helpers/create-application! {:actor applicant-id :catalogue-item-ids [cat1 cat2]})] (testing "set up application with multiple resources and members" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id}))) (is (= {:success true} (send-command handler-id {:type :application.command/add-member :application-id app-id :member {:userid member-id}}))) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id app-id :comment ""})))) (testing "entitlements are present" (is (= #{{:end nil :resid ext1 :userid applicant-id} {:end nil :resid ext2 :userid applicant-id} {:end nil :resid ext1 :userid member-id} {:end nil :resid ext2 :userid member-id}} (set (map #(select-keys % [:end :resid :userid]) (db/get-entitlements {:application app-id})))))) (testing "users are not blacklisted" (is (not (blacklist/blacklisted? applicant-id ext1))) (is (not (blacklist/blacklisted? applicant-id ext2))) (is (not (blacklist/blacklisted? member-id ext1))) (is (not (blacklist/blacklisted? member-id ext2)))) (testing "revoke application" (is (= {:success true} (send-command handler-id {:type :application.command/revoke :application-id app-id :comment "bad"})))) (testing "entitlements end" (is (every? :end (db/get-entitlements {:application app-id})))) (testing "users are blacklisted" (is (blacklist/blacklisted? applicant-id ext1)) (is (blacklist/blacklisted? applicant-id ext2)) (is (blacklist/blacklisted? member-id ext1)) (is (blacklist/blacklisted? member-id ext2))))) (deftest test-hiding-sensitive-information (let [applicant-id "alice" member-id "developer" handler-id "handler" api-key "42" wfid (test-helpers/create-workflow! {:handlers [handler-id]}) cat1 (test-helpers/create-catalogue-item! {:workflow-id wfid}) ;; TODO blacklist? app-id (test-helpers/create-application! {:actor applicant-id :catalogue-item-ids [cat1]})] (testing "set up approved application with multiple members" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id}))) (is (= {:success true} (send-command handler-id {:type :application.command/add-member :application-id app-id :member {:userid member-id}}))) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id app-id :comment ""})))) (testing "handler can see extra user attributes" (let [application (api-call :get (str "/api/applications/" app-id) nil api-key handler-id)] (is (= {:userid "alice" :name "Alice Applicant" :email "alice@example.com" :organizations [{:organization/id "default"}] :nickname "In Wonderland" :researcher-status-by "so"} (:application/applicant application) (get-in application [:application/events 0 :event/actor-attributes]))) (is (= {:userid "developer" :name "Developer" :email "developer@example.com" :nickname "The Dev"} (first (:application/members application)) (get-in application [:application/events 2 :application/member]))))) (doseq [user [applicant-id member-id]] (testing (str user " can't see extra user attributes") (let [application (api-call :get (str "/api/applications/" app-id) nil api-key user)] (is (= {:userid "alice" :name "Alice Applicant" :email "alice@example.com" :organizations [{:organization/id "default"}]} (:application/applicant application) (get-in application [:application/events 0 :event/actor-attributes]))) (is (= {:userid "developer" :name "Developer" :email "developer@example.com"} (first (:application/members application)) (get-in application [:application/events 2 :application/member])))))))) (deftest test-application-export (let [applicant "alice" handler "handler" reporter "reporter" api-key "42" wf-id (test-helpers/create-workflow! {:type :workflow/default :handlers [handler]}) form-id (test-helpers/create-form! {:form/fields [{:field/id "fld1" :field/type :text :field/title {:en "Field 1" :fi "Field 1" :sv "Field 1"} :field/optional false}]}) form-2-id (test-helpers/create-form! {:form/fields [{:field/id "fld2" :field/type :text :field/title {:en "HIDDEN" :fi "HIDDEN" :sv "HIDDEN"} :field/optional false}]}) cat-id (test-helpers/create-catalogue-item! {:title {:en "Item1"} :workflow-id wf-id :form-id form-id}) cat-2-id (test-helpers/create-catalogue-item! {:title {:en "Item2"} :workflow-id wf-id :form-id form-2-id}) app-id (test-helpers/create-draft! applicant [cat-id] "Answer1") _draft-app-id (test-helpers/create-draft! applicant [cat-id] "DraftAnswer") app-2-id (test-helpers/create-draft! applicant [cat-id cat-2-id] "Answer2")] (send-command applicant {:type :application.command/submit :application-id app-id}) (send-command applicant {:type :application.command/submit :application-id app-2-id}) (testing "reporter can export" (let [exported (api-call :get (str "/api/applications/export?form-id=" form-id) nil api-key reporter) [_header & lines] (str/split-lines exported)] (is (str/includes? exported "Field 1") exported) (is (not (str/includes? exported "HIDDEN")) exported) (testing "drafts are not visible" (is (not (str/includes? exported "DraftAnswer")))) (testing "submitted applications are visible" (is (= 2 (count lines))) (is (some #(str/includes? % "\"Item1\",\"Answer1\"") lines) lines) (is (some #(str/includes? % "\"Item1, Item2\",\"Answer2\"") lines) lines)))) (testing "handler can't export" (is (response-is-forbidden? (api-response :get (str "/api/applications/export?form-id=" form-id) nil api-key handler)))))) (def testfile (io/file "./test-data/test.txt")) (def malicious-file (io/file "./test-data/malicious_test.html")) (def filecontent {:tempfile testfile :content-type "text/plain" :filename "test.txt" :size (.length testfile)}) (def malicious-content {:tempfile malicious-file :content-type "text/html" :filename "malicious_test.html" :size (.length malicious-file)}) (deftest test-application-api-attachments (let [api-key "42" user-id "alice" handler-id "developer" ;; developer is the default handler in test-helpers form-id (test-helpers/create-form! {:form/fields [{:field/id "attach" :field/title {:en "some attachment" :fi "joku liite" :sv "bilaga"} :field/type :attachment :field/optional true}]}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id}) upload-request (fn [file] (-> (request :post (str "/api/applications/add-attachment?application-id=" app-id)) (assoc :params {"file" file}) (assoc :multipart-params {"file" file}))) read-request #(request :get (str "/api/applications/attachment/" %))] (testing "uploading malicious file for a draft" (let [response (-> (upload-request malicious-content) (authenticate api-key user-id) handler)] (is (response-is-unsupported-media-type? response)))) (testing "uploading attachment for a draft as handler" (let [response (-> (upload-request filecontent) (authenticate api-key handler-id) handler)] (is (response-is-forbidden? response)))) (testing "invalid value for attachment field" (is (= {:success false :errors [{:form-id form-id :field-id "attach" :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach" :value "1,a"}]})))) (testing "uploading attachment for a draft" (let [body (-> (upload-request filecontent) (authenticate api-key user-id) handler read-ok-body) id (:id body)] (is (:success body)) (is (number? id)) (testing "and retrieving it as the applicant" (let [response (-> (read-request id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))) (testing "and uploading an attachment with the same name" (let [id (-> (upload-request filecontent) (authenticate api-key user-id) handler read-ok-body :id)] (is (number? id)) (testing "and retrieving it" (let [response (-> (read-request id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test (1).txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))))) (testing "and retrieving it as non-applicant" (let [response (-> (read-request id) (authenticate api-key "carl") handler)] (is (response-is-forbidden? response)))) (testing "and uploading a second attachment" (let [body2 (-> (upload-request (assoc filecontent :filename "second.txt")) (authenticate api-key user-id) handler read-ok-body) id2 (:id body2)] (is (:success body2)) (is (number? id2)) (testing "and using them in a field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach" :value (str id "," id2)}]})))) (testing "and submitting" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "and accessing the attachments as handler" (let [response (-> (read-request id) (authenticate api-key handler-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))) (let [response (-> (read-request id2) (authenticate api-key handler-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"second.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))) (testing "and copying the application" (let [response (send-command user-id {:type :application.command/copy-as-new :application-id app-id}) new-app-id (:application-id response)] (is (:success response)) (is (number? new-app-id)) (testing "and fetching the copied attachent" (let [new-app (get-application-for-user new-app-id user-id) [new-id new-id2] (mapv :attachment/id (get new-app :application/attachments))] (is (number? new-id)) (is (number? new-id2)) (is (not= #{id id2} #{new-id new-id2})) (let [response (-> (read-request new-id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))) (let [response (-> (read-request new-id2) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"second.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))))))))))) (testing "retrieving nonexistent attachment" (let [response (-> (read-request 999999999999999) (authenticate api-key "carl") handler)] (is (response-is-not-found? response)))) (testing "uploading attachment for nonexistent application" (let [response (-> (request :post "/api/applications/add-attachment?application-id=99999999") (assoc :params {"file" filecontent}) (assoc :multipart-params {"file" filecontent}) (authenticate api-key user-id) handler)] (is (response-is-forbidden? response)))) (testing "uploading attachment without authentication" (let [response (-> (upload-request filecontent) handler)] (is (response-is-unauthorized? response)))) (testing "uploading attachment with wrong API key" (let [response (-> (upload-request filecontent) (authenticate api-key user-id) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler)] (is (response-is-unauthorized? response)))) (testing "uploading attachment as non-applicant" (let [response (-> (upload-request filecontent) (authenticate api-key "carl") handler)] (is (response-is-forbidden? response)))))) (deftest test-application-comment-attachments (let [api-key "42" applicant-id "alice" handler-id "developer" reviewer-id "carl" file #(assoc filecontent :filename %) workflow-id (test-helpers/create-workflow! {:type :workflow/master :handlers [handler-id]}) cat-item-id (test-helpers/create-catalogue-item! {:workflow-id workflow-id}) application-id (test-helpers/create-application! {:catalogue-item-ids [cat-item-id] :actor applicant-id}) add-attachment #(-> (request :post (str "/api/applications/add-attachment?application-id=" application-id)) (authenticate api-key %1) (assoc :params {"file" %2}) (assoc :multipart-params {"file" %2}) handler read-ok-body :id)] (testing "submit" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id application-id})))) (testing "unrelated user can't upload attachment" (is (response-is-forbidden? (-> (request :post (str "/api/applications/add-attachment?application-id=" application-id)) (authenticate api-key reviewer-id) (assoc :params {"file" filecontent}) (assoc :multipart-params {"file" filecontent}) handler)))) (testing "invite reviewer" (is (= {:success true} (send-command handler-id {:type :application.command/request-review :application-id application-id :reviewers [reviewer-id] :comment "please"})))) (testing "handler uploads an attachment" (let [attachment-id (add-attachment handler-id (file "handler-public-remark.txt"))] (is (number? attachment-id)) (testing "and attaches it to a public remark" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "see attachment" :public true :attachments [{:attachment/id attachment-id}]})))))) (testing "applicant can see attachment" (let [app (get-application-for-user application-id applicant-id) remark-event (last (:application/events app)) attachment-id (:attachment/id (first (:event/attachments remark-event)))] (is (number? attachment-id)) (testing "and fetch it" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id) assert-response-is-ok :body slurp)))))) (testing "reviewer uploads an attachment" (let [attachment-id (add-attachment reviewer-id (file "reviewer-review.txt"))] (is (number? attachment-id)) (testing ", handler can't use the attachment" (is (= {:success false :errors [{:type "invalid-attachments" :attachments [attachment-id]}]} (send-command handler-id {:type :application.command/remark :public false :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]})))) (testing ", attaches it to a review" (is (= {:success true} (send-command reviewer-id {:type :application.command/review :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))) (testing ", handler can fetch attachment" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key handler-id) assert-response-is-ok :body slurp)))) (testing ", applicant can't fetch attachment" (is (response-is-forbidden? (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id))))))) (testing "handler makes a private remark" (let [attachment-id (add-attachment handler-id (file "handler-private-remark.txt"))] (is (number? attachment-id)) (is (= {:success true} (send-command handler-id {:type :application.command/remark :public false :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))) (testing ", handler can fetch attachment" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key handler-id) assert-response-is-ok :body slurp)))) (testing ", applicant can't fetch attachment" (is (response-is-forbidden? (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id)))))) (testing "handler approves with attachment" (let [attachment-id (add-attachment handler-id (file "handler-approve.txt"))] (is (number? attachment-id)) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))))) (testing "handler closes with two attachments (with the same name)" (let [id1 (add-attachment handler-id (file "handler-close.txt")) id2 (add-attachment handler-id (file "handler-close.txt"))] (is (number? id1)) (is (number? id2)) (is (= {:success true} (send-command handler-id {:type :application.command/close :application-id application-id :comment "see attachment" :attachments [{:attachment/id id1} {:attachment/id id2}]}))))) (testing "applicant can see the three new attachments" (let [app (get-application-for-user application-id applicant-id) [close-event approve-event] (reverse (:application/events app)) [close-id1 close-id2] (map :attachment/id (:event/attachments close-event)) [approve-id] (map :attachment/id (:event/attachments approve-event))] (is (= "application.event/closed" (:event/type close-event))) (is (= "application.event/approved" (:event/type approve-event))) (is (number? close-id1)) (is (number? close-id2)) (is (number? approve-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" close-id1) nil api-key handler-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" close-id2) nil api-key handler-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" approve-id) nil api-key handler-id)))) (testing ":application/attachments" (testing "applicant" (is (= ["handler-public-remark.txt" "handler-approve.txt" "handler-close.txt" "handler-close (1).txt"] (mapv :attachment/filename (:application/attachments (get-application-for-user application-id applicant-id)))))) (testing "handler" (is (= ["handler-public-remark.txt" "reviewer-review.txt" "handler-private-remark.txt" "handler-approve.txt" "handler-close.txt" "handler-close (1).txt"] (mapv :attachment/filename (:application/attachments (get-application-for-user application-id handler-id))))))))) (deftest test-application-attachment-zip (let [api-key "42" applicant-id "alice" handler-id "handler" reporter-id "reporter" workflow-id (test-helpers/create-workflow! {:handlers [handler-id]}) form-id (test-helpers/create-form! {:form/fields [{:field/id "attach1" :field/title {:en "some attachment" :fi "joku liite" :sv "bilaga"} :field/type :attachment :field/optional true} {:field/id "attach2" :field/title {:en "another attachment" :fi "toinen liite" :sv "annan bilaga"} :field/type :attachment :field/optional true}]}) cat-id (test-helpers/create-catalogue-item! {:workflow-id workflow-id :form-id form-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant-id}) add-attachment (fn [user file] (-> (request :post (str "/api/applications/add-attachment?application-id=" app-id)) (authenticate api-key user) (assoc :params {"file" file}) (assoc :multipart-params {"file" file}) handler read-ok-body :id)) file #(assoc filecontent :filename %) fetch-zip (fn [user-id] (with-open [zip (-> (api-response :get (str "/api/applications/" app-id "/attachments") nil api-key user-id) :body ZipInputStream.)] (loop [files {}] (if-let [entry (.getNextEntry zip)] (let [buf (ByteArrayOutputStream.)] (io/copy zip buf) (recur (assoc files (.getName entry) (.toString buf "UTF-8")))) files))))] (testing "save a draft" (let [id (add-attachment applicant-id (file "invisible.txt"))] (is (= {:success true} (send-command applicant-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach1" :value (str id)}]}))))) (testing "save a new draft" (let [blue-id (add-attachment applicant-id (file "blue.txt")) green-id (add-attachment applicant-id (file "green.txt")) red-id (add-attachment applicant-id (file "red.txt"))] (is (= {:success true} (send-command applicant-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach1" :value (str blue-id "," green-id)} {:form form-id :field "attach2" :value (str red-id)}]}))))) (testing "fetch zip as applicant" (is (= {"blue.txt" (slurp testfile) "red.txt" (slurp testfile) "green.txt" (slurp testfile)} (fetch-zip applicant-id)))) (testing "submit" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id})))) (testing "remark with attachments" (let [blue-comment-id (add-attachment handler-id (file "blue.txt")) yellow-comment-id (add-attachment handler-id (file "yellow.txt"))] (is (= {:success true} (send-command handler-id {:type :application.command/remark :public true :application-id app-id :comment "see attachment" :attachments [{:attachment/id blue-comment-id} {:attachment/id yellow-comment-id}]})))) (testing "fetch zip as applicant, handler and reporter" (is (= {"blue.txt" (slurp testfile) "red.txt" (slurp testfile) "green.txt" (slurp testfile) "blue (1).txt" (slurp testfile) "yellow.txt" (slurp testfile)} (fetch-zip applicant-id) (fetch-zip handler-id) (fetch-zip reporter-id)))) (testing "fetch zip as third party" (is (response-is-forbidden? (api-response :get (str "/api/applications/" app-id "/attachments") nil api-key "malice")))) (testing "fetch zip for nonexisting application" (is (response-is-not-found? (api-response :get "/api/applications/99999999/attachments" nil api-key "malice"))))))) (deftest test-application-api-license-attachments (let [api-key "42" applicant "alice" non-applicant "bob" owner "owner" handler-user "developer" cat-id (test-helpers/create-catalogue-item! {}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant}) file-en (clojure.java.io/file "./test-data/test.txt") filecontent-en {:tempfile file-en :content-type "text/plain" :filename "test.txt" :size (.length file-en)} en-attachment-id (-> (request :post "/api/licenses/add_attachment") (assoc :params {"file" filecontent-en}) (assoc :multipart-params {"file" filecontent-en}) (authenticate api-key owner) handler read-ok-body :id) file-fi (clojure.java.io/file "./test-data/test-fi.txt") filecontent-fi {:tempfile file-fi :content-type "text/plain" :filename "test.txt" :size (.length file-fi)} fi-attachment-id (-> (request :post "/api/licenses/add_attachment") (assoc :params {"file" filecontent-fi}) (assoc :multipart-params {"file" filecontent-fi}) (authenticate api-key owner) handler read-ok-body :id) license-id (-> (request :post "/api/licenses/create") (authenticate api-key owner) (json-body {:licensetype "attachment" :organization {:organization/id "abc"} ;; TODO different content for different languages :localizations {:en {:title "en title" :textcontent "en text" :attachment-id en-attachment-id} :fi {:title "fi title" :textcontent "fi text" :attachment-id fi-attachment-id}}}) handler read-ok-body :id)] (testing "submit application" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "attach license to application" (is (= {:success true} (send-command handler-user {:type :application.command/add-licenses :application-id app-id :comment "" :licenses [license-id]})))) (testing "access license" (testing "as applicant" (is (= "hello from file\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key applicant) handler assert-response-is-ok :body slurp))) (testing "in finnish" (is (= "tervehdys tiedostosta\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/fi")) (authenticate api-key applicant) handler assert-response-is-ok :body slurp))))) (testing "as handler" (is (= "hello from file\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key handler-user) handler assert-response-is-ok :body slurp)))) (testing "as non-applicant" (is (response-is-forbidden? (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key non-applicant) handler))))))) (deftest test-applications-api-security (let [api-key "42" applicant "alice" cat-id (test-helpers/create-catalogue-item! {}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant})] (testing "fetch application without authentication" (let [req (request :get (str "/api/applications/" app-id))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "fetch nonexistent application" (let [response (-> (request :get "/api/applications/9999999999") (authenticate api-key applicant) handler)] (is (response-is-not-found? response)) (is (= "application/json" (get-in response [:headers "Content-Type"]))) (is (= {:error "not found"} (read-body response))))) (testing "fetch deciders without authentication or as non-handler" (let [req (request :get "/api/applications/deciders")] (assert-response-is-ok (-> req (authenticate api-key "developer") handler)) (is (response-is-forbidden? (-> req (authenticate api-key applicant) handler))) (is (response-is-unauthorized? (-> req handler))))) (testing "create without authentication" (let [req (-> (request :post "/api/applications/create") (json-body {:catalogue-item-ids [cat-id]}))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "create with wrong API key" (let [req (-> (request :post "/api/applications/create") (authenticate api-key applicant) (json-body {:catalogue-item-ids [cat-id]}))] (assert-response-is-ok (-> req handler)) (is (response-is-unauthorized? (-> req (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler))))) (testing "send command without authentication" (let [req (-> (request :post "/api/applications/submit") (json-body {:application-id app-id}))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "send command with wrong API key" (let [req (-> (request :post "/api/applications/submit") (authenticate api-key applicant) (json-body {:application-id app-id}))] (assert-response-is-ok (-> req handler)) (is (response-is-unauthorized? (-> req (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler))))))) (deftest test-application-listing (let [app-id (test-helpers/create-application! {:actor "alice"})] (testing "list user applications" (is (contains? (get-ids (get-my-applications "alice")) app-id))) (testing "search user applications" (is (contains? (get-ids (get-my-applications "alice" {:query "applicant:alice"})) app-id)) (is (empty? (get-ids (get-my-applications "alice" {:query "applicant:no-such-user"}))))) (testing "list all applications" (is (contains? (get-ids (get-all-applications "alice")) app-id))) (testing "search all applications" (is (contains? (get-ids (get-all-applications "alice" {:query "applicant:alice"})) app-id)) (is (empty? (get-ids (get-all-applications "alice" {:query "applicant:no-such-user"}))))))) (deftest test-todos (let [applicant "alice" handler "developer" reviewer "reviewer" decider "decider" app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/create-user! {:eppn reviewer}) (test-helpers/create-user! {:eppn decider}) (testing "does not list drafts" (is (not (contains? (get-ids (get-todos handler)) app-id)))) (testing "lists submitted in todos" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id}))) (is (contains? (get-ids (get-todos handler)) app-id)) (is (not (contains? (get-ids (get-handled-todos handler)) app-id)))) (testing "search todos" (is (contains? (get-ids (get-todos handler {:query (str "applicant:" applicant)})) app-id)) (is (empty? (get-ids (get-todos handler {:query "applicant:no-such-user"}))))) (testing "reviewer sees application in todos" (is (not (contains? (get-ids (get-todos reviewer)) app-id))) (is (= {:success true} (send-command handler {:type :application.command/request-review :application-id app-id :reviewers [reviewer] :comment "x"}))) (is (contains? (get-ids (get-todos reviewer)) app-id)) (is (not (contains? (get-ids (get-handled-todos reviewer)) app-id)))) (testing "decider sees application in todos" (is (not (contains? (get-ids (get-todos decider)) app-id))) (is (= {:success true} (send-command handler {:type :application.command/request-decision :application-id app-id :deciders [decider] :comment "x"}))) (is (contains? (get-ids (get-todos decider)) app-id)) (is (not (contains? (get-ids (get-handled-todos decider)) app-id)))) (testing "lists handled in handled" (is (= {:success true} (send-command handler {:type :application.command/approve :application-id app-id :comment ""}))) (is (not (contains? (get-ids (get-todos handler)) app-id))) (is (contains? (get-ids (get-handled-todos handler)) app-id))) (testing "search handled todos" (is (contains? (get-ids (get-handled-todos handler {:query (str "applicant:" applicant)})) app-id)) (is (empty? (get-ids (get-handled-todos handler {:query "applicant:no-such-user"}))))) (testing "reviewer sees accepted application in handled todos" (is (not (contains? (get-ids (get-todos reviewer)) app-id))) (is (contains? (get-ids (get-handled-todos reviewer)) app-id))) (testing "decider sees accepted application in handled todos" (is (not (contains? (get-ids (get-todos decider)) app-id))) (is (contains? (get-ids (get-handled-todos decider)) app-id))))) (deftest test-application-raw (let [api-key "42" applicant "alice" handler "handler" reporter "reporter" form-id (test-helpers/create-form! {:form/internal-name "notifications" :form/external-title {:en "Notifications EN" :fi "Notifications FI" :sv "Notifications SV"} :form/fields [{:field/type :text :field/id "field-1" :field/title {:en "text field" :fi "text field" :sv "text field"} :field/optional false}]}) workflow-id (test-helpers/create-workflow! {:title "wf" :handlers [handler] :type :workflow/default}) ext-id "resres" res-id (test-helpers/create-resource! {:resource-ext-id ext-id}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id :resource-id res-id :workflow-id workflow-id}) app-id (test-helpers/create-draft! applicant [cat-id] "raw test" (time/date-time 2010))] (testing "applicant can't get raw application" (is (response-is-forbidden? (api-response :get (str "/api/applications/" app-id "/raw") nil api-key applicant)))) (testing "reporter can get raw application" (is (= {:application/description "" :application/invited-members [] :application/last-activity "2010-01-01T00:00:00.000Z" :application/attachments [] :application/licenses [] :application/created "2010-01-01T00:00:00.000Z" :application/state "application.state/draft" :application/role-permissions {:everyone-else ["application.command/accept-invitation"] :member ["application.command/copy-as-new" "application.command/accept-licenses"] :reporter ["see-everything"] :applicant ["application.command/copy-as-new" "application.command/invite-member" "application.command/submit" "application.command/remove-member" "application.command/accept-licenses" "application.command/uninvite-member" "application.command/delete" "application.command/save-draft" "application.command/change-resources"]} :application/modified "2010-01-01T00:00:00.000Z" :application/user-roles {:alice ["applicant"] :handler ["handler"] :reporter ["reporter"]} :application/external-id "2010/1" :application/generated-external-id "2010/1" :application/workflow {:workflow/type "workflow/default" :workflow/id workflow-id :workflow.dynamic/handlers [{:email "handler@example.com" :userid "handler" :name "Hannah Handler"}]} :application/blacklist [] :application/id app-id :application/todo nil :application/applicant {:email "alice@example.com" :userid "alice" :name "Alice Applicant" :nickname "In Wonderland" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/members [] :application/resources [{:catalogue-item/start "REDACTED" :catalogue-item/end nil :catalogue-item/expired false :catalogue-item/enabled true :resource/id res-id :catalogue-item/title {} :catalogue-item/infourl {} :resource/ext-id ext-id :catalogue-item/archived false :catalogue-item/id cat-id}] :application/accepted-licenses {:alice []} :application/forms [{:form/fields [{:field/value "raw test" :field/type "text" :field/title {:en "text field" :fi "text field" :sv "text field"} :field/id "field-1" :field/optional false :field/visible true :field/private false}] :form/title "notifications" ; deprecated :form/internal-name "notifications" :form/external-title {:en "Notifications EN" :fi "Notifications FI" :sv "Notifications SV"} :form/id form-id}] :application/events [{:application/external-id "2010/1" :event/actor-attributes {:userid "alice" :name "Alice Applicant" :nickname "In Wonderland" :email "alice@example.com" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/id app-id :event/time "2010-01-01T00:00:00.000Z" :workflow/type "workflow/default" :application/resources [{:catalogue-item/id cat-id :resource/ext-id ext-id}] :application/forms [{:form/id form-id}] :workflow/id workflow-id :event/actor "alice" :event/type "application.event/created" :event/id 100 :application/licenses []} {:event/id 100 :event/type "application.event/draft-saved" :event/time "2010-01-01T00:00:00.000Z" :event/actor "alice" :application/id app-id :event/actor-attributes {:userid "alice" :name "Alice Applicant" :nickname "In Wonderland" :email "alice@example.com" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/field-values [{:form form-id :field "field-1" :value "raw test"}]} {:event/id 100 :event/type "application.event/licenses-accepted" :event/time "2010-01-01T00:00:00.000Z" :event/actor "alice" :application/id app-id :event/actor-attributes {:userid "alice" :name "Alice Applicant" :nickname "In Wonderland" :email "alice@example.com" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/accepted-licenses []}]} (-> (api-call :get (str "/api/applications/" app-id "/raw") nil api-key reporter) ;; start is set by the db not easy to mock (assoc-in [:application/resources 0 :catalogue-item/start] "REDACTED") ;; event ids are unpredictable (update :application/events (partial map #(update % :event/id (constantly 100))))))))))
87360
(ns ^:integration rems.api.test-applications (:require [clj-time.core :as time] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [rems.api.services.catalogue :as catalogue] [rems.api.testing :refer :all] [rems.db.applications] [rems.db.blacklist :as blacklist] [rems.db.core :as db] [rems.db.test-data :as test-data] [rems.db.test-data-helpers :as test-helpers] [rems.handler :refer [handler]] [rems.json] [rems.testing-util :refer [with-user]] [ring.mock.request :refer :all]) (:import java.io.ByteArrayOutputStream java.util.zip.ZipInputStream)) (use-fixtures :each api-fixture ;; TODO should this fixture have a name? (fn [f] (test-data/create-test-api-key!) (test-data/create-test-users-and-roles!) (f))) ;;; shared helpers (defn- send-command [actor cmd] (-> (request :post (str "/api/applications/" (name (:type cmd)))) (authenticate "42" actor) (json-body (dissoc cmd :type)) handler read-body)) (defn- send-command-transit [actor cmd] (-> (request :post (str "/api/applications/" (name (:type cmd)))) (authenticate "42" actor) (transit-body (dissoc cmd :type)) handler read-body)) (defn- get-ids [applications] (set (map :application/id applications))) (defn- license-ids-for-application [application] (set (map :license/id (:application/licenses application)))) (defn- catalogue-item-ids-for-application [application] (set (map :catalogue-item/id (:application/resources application)))) (defn- get-my-applications [user-id & [params]] (-> (request :get "/api/my-applications" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-all-applications [user-id & [params]] (-> (request :get "/api/applications" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-application-for-user [app-id user-id] (-> (request :get (str "/api/applications/" app-id)) (authenticate "42" user-id) handler read-ok-body)) (defn- get-todos [user-id & [params]] (-> (request :get "/api/applications/todo" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-handled-todos [user-id & [params]] (-> (request :get "/api/applications/handled" params) (authenticate "42" user-id) handler read-ok-body)) ;;; tests (deftest test-application-api-session (let [username "alice" cookie (login-with-cookies username) csrf (get-csrf-token cookie) cat-id (test-helpers/create-catalogue-item! {})] (testing "save with session" (let [body (-> (request :post "/api/applications/create") (header "Cookie" cookie) (header "x-csrf-token" csrf) (json-body {:catalogue-item-ids [cat-id]}) handler assert-response-is-ok read-body)] (is (:success body)))) (testing "save with session but without csrf" (let [response (-> (request :post "/api/applications/create") (header "Cookie" cookie) (json-body {:catalogue-item-ids [cat-id]}) handler)] (is (response-is-unauthorized? response)))) (testing "save with session and csrf and wrong api-key" (let [body (-> (request :post "/api/applications/create") (header "Cookie" cookie) (header "x-csrf-token" csrf) (header "x-rems-api-key" "WRONG") (json-body {:catalogue-item-ids [cat-id]}) handler assert-response-is-ok read-body)] (is (:success body)))))) (deftest pdf-smoke-test (testing "not found" (let [response (-> (request :get "/api/applications/9999999/pdf") (authenticate "42" "developer") handler)] (is (response-is-not-found? response)))) (let [cat-id (test-helpers/create-catalogue-item! {:title {:fi "Fi title" :en "En title"}}) application-id (test-helpers/create-application! {:actor "alice" :catalogue-item-ids [cat-id]})] (test-helpers/command! {:type :application.command/submit :application-id application-id :actor "alice"}) (testing "forbidden" (let [response (-> (request :get (str "/api/applications/" application-id "/pdf")) (authenticate "42" "bob") handler)] (is (response-is-forbidden? response)))) (testing "success" (let [response (-> (request :get (str "/api/applications/" application-id "/pdf")) (authenticate "42" "developer") handler assert-response-is-ok)] (is (= "application/pdf" (get-in response [:headers "Content-Type"]))) (is (= (str "filename=\"" application-id ".pdf\"") (get-in response [:headers "Content-Disposition"]))) (is (.startsWith (slurp (:body response)) "%PDF-1.")))))) (deftest test-application-commands (let [user-id "alice" handler-id "developer" reviewer-id "carl" decider-id "elsa" license-id1 (test-helpers/create-license! {}) license-id2 (test-helpers/create-license! {}) license-id3 (test-helpers/create-license! {}) license-id4 (test-helpers/create-license! {}) form-id (test-helpers/create-form! {}) workflow-id (test-helpers/create-workflow! {:type :workflow/master :handlers [handler-id]}) cat-item-id1 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id1 license-id2]}) :form-id form-id :workflow-id workflow-id}) cat-item-id2 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id1 license-id2]}) :form-id form-id :workflow-id workflow-id}) cat-item-id3 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id3]}) :form-id form-id :workflow-id workflow-id}) application-id (test-helpers/create-application! {:catalogue-item-ids [cat-item-id1] :actor user-id})] (testing "accept licenses" (is (= {:success true} (send-command user-id {:type :application.command/accept-licenses :application-id application-id :accepted-licenses [license-id1 license-id2]}))) (testing "with invalid application id" (is (= {:success false :errors [{:type "application-not-found"}]} (send-command user-id {:type :application.command/accept-licenses :application-id 9999999999 :accepted-licenses [license-id1 license-id2]}))))) (testing "save draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id application-id :field-values []})))) (testing "submit" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id})))) (testing "getting application as applicant" (let [application (get-application-for-user application-id user-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted"] (map :event/type (get application :application/events)))) (is (= #{"application.command/remove-member" "application.command/uninvite-member" "application.command/accept-licenses" "application.command/copy-as-new"} (set (get application :application/permissions)))))) (testing "getting application as handler" (let [application (get-application-for-user application-id handler-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= #{"application.command/request-review" "application.command/request-decision" "application.command/remark" "application.command/reject" "application.command/approve" "application.command/return" "application.command/add-licenses" "application.command/add-member" "application.command/remove-member" "application.command/invite-member" "application.command/invite-decider" "application.command/invite-reviewer" "application.command/uninvite-member" "application.command/change-resources" "application.command/close" "application.command/assign-external-id" "see-everything"} (set (get application :application/permissions)))))) (testing "disabling a command" (with-redefs [rems.config/env (assoc rems.config/env :disable-commands [:application.command/remark])] (testing "handler doesn't see hidden command" (let [application (get-application-for-user application-id handler-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= #{"application.command/request-review" "application.command/request-decision" "application.command/reject" "application.command/approve" "application.command/return" "application.command/add-licenses" "application.command/add-member" "application.command/remove-member" "application.command/invite-member" "application.command/invite-decider" "application.command/invite-reviewer" "application.command/uninvite-member" "application.command/change-resources" "application.command/close" "application.command/assign-external-id" "see-everything"} (set (get application :application/permissions)))))) (testing "disabled command fails" (is (= {:success false :errors [{:type "forbidden"}]} (send-command handler-id {:type :application.command/remark :application-id application-id :public false :comment "this is a remark"})))))) (testing "send command without user" (is (= {:success false :errors [{:type "forbidden"}]} (send-command "" {:type :application.command/approve :application-id application-id :comment ""})) "user should be forbidden to send command")) (testing "send command with a user that is not a handler" (is (= {:success false :errors [{:type "forbidden"}]} (send-command user-id {:type :application.command/approve :application-id application-id :comment ""})) "user should be forbidden to send command")) (testing "assing external id" (is (= {:success true} (send-command handler-id {:type :application.command/assign-external-id :application-id application-id :external-id "abc123"}))) (let [application (get-application-for-user application-id handler-id)] (is (= "abc123" (:application/external-id application))))) (testing "application can be returned" (is (= {:success true} (send-command handler-id {:type :application.command/return :application-id application-id :comment "Please check again"})))) (testing "changing resources as applicant" (is (= {:success true} (send-command user-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id2]})))) (testing "submitting again" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id})))) (testing "send commands with authorized user" (testing "even handler cannot review without request" (is (= {:errors [{:type "forbidden"}], :success false} (send-command handler-id {:type :application.command/review :application-id application-id :comment "What am I commenting on?"})))) (testing "review with request" (let [eventcount (count (get (get-application-for-user application-id handler-id) :events))] (testing "requesting review" (is (= {:success true} (send-command handler-id {:type :application.command/request-review :application-id application-id :reviewers [decider-id reviewer-id] :comment "What say you?"})))) (testing "reviewer can now review" (is (= {:success true} (send-command reviewer-id {:type :application.command/review :application-id application-id :comment "Yeah, I dunno"})))) (testing "review was linked to request" (let [application (get-application-for-user application-id handler-id) request-event (get-in application [:application/events eventcount]) review-event (get-in application [:application/events (inc eventcount)])] (is (= (:application/request-id request-event) (:application/request-id review-event))))))) (testing "adding and then accepting additional licenses" (testing "add licenses" (let [application (get-application-for-user application-id user-id)] (is (= #{license-id1 license-id2} (license-ids-for-application application))) (is (= {:success true} (send-command handler-id {:type :application.command/add-licenses :application-id application-id :licenses [license-id4] :comment "Please approve these new terms"}))) (let [application (get-application-for-user application-id user-id)] (is (= #{license-id1 license-id2 license-id4} (license-ids-for-application application)))))) (testing "applicant accepts the additional licenses" (is (= {:success true} (send-command user-id {:type :application.command/accept-licenses :application-id application-id :accepted-licenses [license-id4]}))))) (testing "changing resources as handler" (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id2} (catalogue-item-ids-for-application application))) (is (= #{license-id1 license-id2 license-id4} (license-ids-for-application application))) (is (= {:success true} (send-command handler-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id3] :comment "Here are the correct resources"}))) (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id3} (catalogue-item-ids-for-application application))) ;; TODO: The previously added licenses should probably be retained in the licenses after changing resources. (is (= #{license-id3} (license-ids-for-application application)))))) (testing "changing resources back as handler" (is (= {:success true} (send-command handler-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id2]}))) (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id2} (catalogue-item-ids-for-application application))) (is (= #{license-id1 license-id2} (license-ids-for-application application))))) (testing "request-decision" (is (= {:success true} (send-command handler-id {:type :application.command/request-decision :application-id application-id :deciders [decider-id] :comment ""})))) (testing "decide" (is (= {:success true} (send-command decider-id {:type :application.command/decide :application-id application-id :decision :approved :comment ""})))) (testing "hidden remark" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "" :public false})))) (testing "public remark with" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "" :public true})))) (testing "approve" (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id application-id :comment ""}))) (let [handler-data (get-application-for-user application-id handler-id) handler-event-types (map :event/type (get handler-data :application/events)) applicant-data (get-application-for-user application-id user-id) applicant-event-types (map :event/type (get applicant-data :application/events))] (testing "handler can see all events" (is (= {:application/id application-id :application/state "application.state/approved"} (select-keys handler-data [:application/id :application/state]))) (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted" "application.event/external-id-assigned" "application.event/returned" "application.event/resources-changed" "application.event/submitted" "application.event/review-requested" "application.event/reviewed" "application.event/licenses-added" "application.event/licenses-accepted" "application.event/resources-changed" "application.event/resources-changed" "application.event/decision-requested" "application.event/decided" "application.event/remarked" "application.event/remarked" "application.event/approved"] handler-event-types))) (testing "applicant cannot see all events" (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted" "application.event/external-id-assigned" "application.event/returned" "application.event/resources-changed" "application.event/submitted" "application.event/licenses-added" "application.event/licenses-accepted" "application.event/resources-changed" "application.event/resources-changed" "application.event/remarked" "application.event/approved"] applicant-event-types))))) (testing "copy as new" (let [result (send-command user-id {:type :application.command/copy-as-new :application-id application-id})] (is (:success result) {:result result}) (is (:application-id result) {:result result}) (is (not= application-id (:application-id result)) "should create a new application")))))) (deftest test-approve-with-end (let [api-key "<KEY>" applicant "alice" handler "developer"] (testing "json" (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:type :application.command/submit :application-id app-id :actor applicant}) (is (= {:success true} (send-command handler {:type :application.command/approve :application-id app-id :comment "" :entitlement-end "2100-01-01T00:00:00.000Z"}))) (let [app (get-application-for-user app-id applicant)] (is (= "application.state/approved" (:application/state app))) (is (= "2100-01-01T00:00:00.000Z" (:entitlement/end app)))))) (testing "transit" (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:type :application.command/submit :application-id app-id :actor applicant}) (is (= {:success true} (send-command-transit handler {:type :application.command/approve :application-id app-id :comment "" :entitlement-end (time/date-time 2100 01 01)}))) (let [app (get-application-for-user app-id applicant)] (is (= "application.state/approved" (:application/state app))) (is (= "2100-01-01T00:00:00.000Z" (:entitlement/end app)))))))) (deftest test-application-create (let [api-key "<KEY>" user-id "alice" cat-id (test-helpers/create-catalogue-item! {}) application-id (:application-id (api-call :post "/api/applications/create" {:catalogue-item-ids [cat-id]} "42" user-id))] (testing "creating" (is (some? application-id)) (let [created (get-application-for-user application-id user-id)] (is (= "application.state/draft" (get created :application/state))))) (testing "seeing draft is forbidden" (testing "as unrelated user" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "bob")))) (testing "as reporter" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "reporter")))) (testing "as handler" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "developer"))))) (testing "modifying application as other user is forbidden" (is (= {:success false :errors [{:type "forbidden"}]} (send-command "bob" {:type :application.command/save-draft :application-id application-id :field-values []})))) (testing "submitting" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id}))) (let [submitted (get-application-for-user application-id user-id)] (is (= "application.state/submitted" (get submitted :application/state))) (is (= ["application.event/created" "application.event/submitted"] (map :event/type (get submitted :application/events)))))) (testing "seeing submitted application as reporter is allowed" (is (response-is-ok? (-> (request :get (str "/api/applications/" application-id)) (authenticate api-key "reporter") handler)))) (testing "can't create application for disabled catalogue item" (with-user "owner" (catalogue/set-catalogue-item-enabled! {:id cat-id :enabled false})) (rems.db.applications/reload-cache!) (is (= {:success false :errors [{:type "disabled-catalogue-item" :catalogue-item-id cat-id}]} (api-call :post "/api/applications/create" {:catalogue-item-ids [cat-id]} "42" user-id)))))) (deftest test-application-delete (let [api-key "<KEY>" applicant "alice" handler "developer"] (let [app-id (test-helpers/create-application! {:actor applicant})] (testing "can't delete draft as other user" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key handler)))) (testing "can delete draft as applicant" (is (contains? (-> (get-application-for-user app-id applicant) :application/permissions set) "application.command/delete")) (is (= {:success true} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant)))) (testing "deleted application is gone" (is (response-is-not-found? (api-response :get (str "/api/applications/" app-id) nil api-key applicant))))) (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:application-id app-id :type :application.command/submit :actor applicant}) (testing "can't delete submitted application" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant)))) (test-helpers/command! {:application-id app-id :type :application.command/return :actor handler}) (testing "can't delete returned application" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant))))))) (deftest test-application-close (let [user-id "alice" application-id (test-helpers/create-application! {:actor user-id})] (test-helpers/command! {:application-id application-id :type :application.command/submit :actor user-id}) (is (= {:success true} (send-command "developer" {:type :application.command/close :application-id application-id :comment ""}))) (is (= "application.state/closed" (:application/state (get-application-for-user application-id user-id)))))) (deftest test-application-submit (let [owner "owner" user-id "alice" form-id (test-helpers/create-form! {}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) enable-catalogue-item! #(with-user owner (catalogue/set-catalogue-item-enabled! {:id cat-id :enabled %})) archive-catalogue-item! #(with-user owner (catalogue/set-catalogue-item-archived! {:id cat-id :archived %}))] (testing "submit with archived & disabled catalogue item succeeds" ;; draft needs to be created before disabling & archiving (let [app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (is (:success (enable-catalogue-item! false))) (is (:success (archive-catalogue-item! true))) (rems.db.applications/reload-cache!) (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id}))))) (testing "submit with normal catalogue item succeeds" (is (:success (enable-catalogue-item! true))) (is (:success (archive-catalogue-item! false))) (rems.db.applications/reload-cache!) (let [app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id}))))))) (deftest test-application-invitations (let [api-key "<KEY>" applicant "alice" handler "developer" app-id (test-helpers/create-application! {:actor applicant})] (testing "invite member for draft as applicant" (is (= {:success true} (send-command applicant {:type :application.command/invite-member :application-id app-id :member {:name "<NAME> 1" :email "<EMAIL>"}})))) (testing "accept member invitation for draft" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) member "member1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key member))) (testing ", member is able to fetch application and see themselves" (is (= #{member} (->> (get-application-for-user app-id member) :application/members (mapv :userid) set)))))) (testing "submit application" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "invite reviewer as handler" (is (= {:success true} (send-command handler {:type :application.command/invite-reviewer :application-id app-id :reviewer {:name "Member 2" :email "<EMAIL>"}})))) (testing "accept handler invitation" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) reviewer "reviewer1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key reviewer))) (testing ", reviewer is able to fetch application and can submit a review" (is (= ["see-everything" "application.command/review" "application.command/remark"] (:application/permissions (get-application-for-user app-id reviewer))))))) (testing "invite decider as handler" (is (= {:success true} (send-command handler {:type :application.command/invite-decider :application-id app-id :decider {:name "<NAME>" :email "<EMAIL>"}})))) (testing "accept handler invitation" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) decider "decider1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key decider))) (testing ", decider is able to fetch application and can submit a review" (is (= ["see-everything" "application.command/reject" "application.command/decide" "application.command/remark" "application.command/approve"] (:application/permissions (get-application-for-user app-id decider))))))))) (deftest test-application-validation (let [user-id "alice" form-id (test-helpers/create-form! {:form/fields [{:field/id "req1" :field/title {:en "req" :fi "pak" :sv "obl"} :field/type :text :field/optional false} {:field/id "opt1" :field/title {:en "opt" :fi "val" :sv "fri"} :field/type :text :field/optional true}]}) form-id2 (test-helpers/create-form! {:form/fields [{:field/id "req2" :field/title {:en "req" :fi "pak" :sv "obl"} :field/type :text :field/optional false} {:field/id "opt2" :field/title {:en "opt" :fi "val" :sv "fri"} :field/type :text :field/optional true} {:field/id "table" :field/type :table :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}]} {:field/id "optionlist" :field/title {:en "Option list." :fi "Valintalista." :sv "Välj"} :field/type :option :field/options [{:key "Option1" :label {:en "First" :fi "Ensimmäinen" :sv "Först"}} {:key "Option2" :label {:en "Second" :fi "Toinen" :sv "Den andra"}} {:key "Option3" :label {:en "Third" :fi "Kolmas" :sv "Tredje"}}] :field/optional true}]}) wf-id (test-helpers/create-workflow! {}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id :workflow-id wf-id}) cat-id2 (test-helpers/create-catalogue-item! {:form-id form-id2 :workflow-id wf-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id cat-id2] :actor user-id})] (testing "set value of optional field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"}]}) (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id2 :field "opt2" :value "opt"}]})))) (testing "can't submit without required field" (is (= {:success false :errors [{:form-id form-id :field-id "req1" :type "t.form.validation/required"} {:form-id form-id2 :field-id "req2" :type "t.form.validation/required"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "set value of required field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"}]})))) (testing "can't set value of text field to JSON" (is (= {:success false :errors [{:form-id form-id :field-id "req1" :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "req1" :value [[{:column "foo" :value "bar"}]]}]})))) (testing "can set value of table field to JSON" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "table" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "col2" :value "bar"}]]}]}))) (is (= [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "col2" :value "bar"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 1 :form/fields 2 :field/value])))) (testing "column name validation for table fields" (is (= {:success false :errors [{:type "t.form.validation/invalid-value", :form-id form-id2, :field-id "table"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "table" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "colx" :value "bar"}]]}]})))) (testing "save-draft fails with non-existing value of option list" (is (= {:success false :errors [{:field-id "optionlist", :form-id form-id2, :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "optionlist" :value "foobar"}]})))) (testing "set existing value of option list" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "optionlist" :value "Option2"}]})))) (testing "can submit with required field" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))))) (deftest test-table ;; Adding the table field required changes to many API schemas since ;; the table values aren't just plain strings (like the values for ;; other fields). This test is mostly here to verify table values ;; work everywhere in the API. ;; ;; Table validations are mostly tested in test-application-validation (let [form-id (test-helpers/create-form! {:form/fields [{:field/id "opt" :field/type :table :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}]} {:field/id "req" :field/type :table :field/title {:en "required table" :fi "table" :sv "table"} :field/optional false :field/columns [{:key "foo" :label {:en "foo" :fi "foo" :sv "foo"}} {:key "bar" :label {:en "bar" :fi "bar" :sv "bar"}} {:key "xyz" :label {:en "xyz" :fi "xyz" :sv "xyz"}}]}]}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) user-id "alice" app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (testing "default values" (let [app (get-application-for-user app-id user-id)] (is (= [] (get-in app [:application/forms 0 :form/fields 0 :field/value]))) (is (= [] (get-in app [:application/forms 0 :form/fields 1 :field/value]))))) (testing "save a draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value []}]}))) (is (= [{:field/id "opt" :field/type "table" :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/visible true :field/private false :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}] :field/value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:field/id "req" :field/type "table" :field/title {:en "required table" :fi "table" :sv "table"} :field/optional false :field/visible true :field/private false :field/columns [{:key "foo" :label {:en "foo" :fi "foo" :sv "foo"}} {:key "bar" :label {:en "bar" :fi "bar" :sv "bar"}} {:key "xyz" :label {:en "xyz" :fi "xyz" :sv "xyz"}}] :field/value []}] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields])))) (testing "can't submit no rows in required table" (is (= {:success false :errors [{:type "t.form.validation/required" :form-id form-id :field-id "req"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "save a new draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value ""} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]]}]}))) (is (= [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/value])))) (testing "can't submit with empty column values" (is (= {:success false :errors [{:type "t.form.validation/column-values-missing" :form-id form-id :field-id "opt"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "can submit with all columns set" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]]}]}))) (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "can return" (is (= {:success true} (send-command "developer" {:type :application.command/return :application-id app-id}))) (is (= [[{:value "f" :column "foo"} {:value "b" :column "bar"} {:value "x" :column "xyz"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/value]))) (is (= [[{:value "f" :column "foo"} {:value "b" :column "bar"} {:value "x" :column "xyz"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/previous-value])))))) (deftest test-decider-workflow (let [applicant "<NAME>" handler "handler" decider "<NAME>" wf-id (test-helpers/create-workflow! {:type :workflow/decider :handlers [handler]}) cat-id (test-helpers/create-catalogue-item! {:workflow-id wf-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant})] (testing "applicant's commands for draft" (is (= #{"application.command/accept-licenses" "application.command/change-resources" "application.command/copy-as-new" "application.command/delete" "application.command/invite-member" "application.command/remove-member" "application.command/save-draft" "application.command/submit" "application.command/uninvite-member"} (set (:application/permissions (get-application-for-user app-id applicant)))))) (testing "submit" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "applicant's commands after submit" (is (= #{"application.command/accept-licenses" "application.command/copy-as-new" "application.command/remove-member" "application.command/uninvite-member"} (set (:application/permissions (get-application-for-user app-id applicant)))))) (testing "handler's commands" (is (= #{"application.command/add-licenses" "application.command/add-member" "application.command/assign-external-id" "application.command/change-resources" "application.command/close" "application.command/invite-reviewer" "application.command/invite-member" "application.command/remark" "application.command/remove-member" "application.command/request-decision" "application.command/request-review" "application.command/return" "application.command/uninvite-member" "see-everything"} (set (:application/permissions (get-application-for-user app-id handler)))))) (testing "request decision" (is (= {:success true} (send-command handler {:type :application.command/request-decision :application-id app-id :deciders [decider] :comment ""})))) (testing "decider's commands" (is (= #{"application.command/approve" "application.command/reject" "application.command/remark" "see-everything"} (set (:application/permissions (get-application-for-user app-id decider)))))) (testing "approve" (is (= {:success true} (send-command decider {:type :application.command/approve :application-id app-id :comment ""})))))) (deftest test-revoke (let [applicant-id "alice" member-id "malice" handler-id "handler" wfid (test-helpers/create-workflow! {:handlers [handler-id]}) formid (test-helpers/create-form! {}) ext1 "revoke-test-resource-1" ext2 "revoke-test-resource-2" res1 (test-helpers/create-resource! {:resource-ext-id ext1}) res2 (test-helpers/create-resource! {:resource-ext-id ext2}) cat1 (test-helpers/create-catalogue-item! {:workflow-id wfid :form-id formid :resource-id res1}) cat2 (test-helpers/create-catalogue-item! {:workflow-id wfid :form-id formid :resource-id res2}) app-id (test-helpers/create-application! {:actor applicant-id :catalogue-item-ids [cat1 cat2]})] (testing "set up application with multiple resources and members" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id}))) (is (= {:success true} (send-command handler-id {:type :application.command/add-member :application-id app-id :member {:userid member-id}}))) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id app-id :comment ""})))) (testing "entitlements are present" (is (= #{{:end nil :resid ext1 :userid applicant-id} {:end nil :resid ext2 :userid applicant-id} {:end nil :resid ext1 :userid member-id} {:end nil :resid ext2 :userid member-id}} (set (map #(select-keys % [:end :resid :userid]) (db/get-entitlements {:application app-id})))))) (testing "users are not blacklisted" (is (not (blacklist/blacklisted? applicant-id ext1))) (is (not (blacklist/blacklisted? applicant-id ext2))) (is (not (blacklist/blacklisted? member-id ext1))) (is (not (blacklist/blacklisted? member-id ext2)))) (testing "revoke application" (is (= {:success true} (send-command handler-id {:type :application.command/revoke :application-id app-id :comment "bad"})))) (testing "entitlements end" (is (every? :end (db/get-entitlements {:application app-id})))) (testing "users are blacklisted" (is (blacklist/blacklisted? applicant-id ext1)) (is (blacklist/blacklisted? applicant-id ext2)) (is (blacklist/blacklisted? member-id ext1)) (is (blacklist/blacklisted? member-id ext2))))) (deftest test-hiding-sensitive-information (let [applicant-id "alice" member-id "developer" handler-id "handler" api-key "<KEY>" wfid (test-helpers/create-workflow! {:handlers [handler-id]}) cat1 (test-helpers/create-catalogue-item! {:workflow-id wfid}) ;; TODO blacklist? app-id (test-helpers/create-application! {:actor applicant-id :catalogue-item-ids [cat1]})] (testing "set up approved application with multiple members" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id}))) (is (= {:success true} (send-command handler-id {:type :application.command/add-member :application-id app-id :member {:userid member-id}}))) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id app-id :comment ""})))) (testing "handler can see extra user attributes" (let [application (api-call :get (str "/api/applications/" app-id) nil api-key handler-id)] (is (= {:userid "alice" :name "<NAME>" :email "<EMAIL>" :organizations [{:organization/id "default"}] :nickname "In Wonderland" :researcher-status-by "so"} (:application/applicant application) (get-in application [:application/events 0 :event/actor-attributes]))) (is (= {:userid "developer" :name "<NAME>" :email "<EMAIL>" :nickname "The Dev"} (first (:application/members application)) (get-in application [:application/events 2 :application/member]))))) (doseq [user [applicant-id member-id]] (testing (str user " can't see extra user attributes") (let [application (api-call :get (str "/api/applications/" app-id) nil api-key user)] (is (= {:userid "alice" :name "<NAME>" :email "<EMAIL>" :organizations [{:organization/id "default"}]} (:application/applicant application) (get-in application [:application/events 0 :event/actor-attributes]))) (is (= {:userid "developer" :name "<NAME>" :email "<EMAIL>"} (first (:application/members application)) (get-in application [:application/events 2 :application/member])))))))) (deftest test-application-export (let [applicant "alice" handler "handler" reporter "reporter" api-key "<KEY>" wf-id (test-helpers/create-workflow! {:type :workflow/default :handlers [handler]}) form-id (test-helpers/create-form! {:form/fields [{:field/id "fld1" :field/type :text :field/title {:en "Field 1" :fi "Field 1" :sv "Field 1"} :field/optional false}]}) form-2-id (test-helpers/create-form! {:form/fields [{:field/id "fld2" :field/type :text :field/title {:en "HIDDEN" :fi "HIDDEN" :sv "HIDDEN"} :field/optional false}]}) cat-id (test-helpers/create-catalogue-item! {:title {:en "Item1"} :workflow-id wf-id :form-id form-id}) cat-2-id (test-helpers/create-catalogue-item! {:title {:en "Item2"} :workflow-id wf-id :form-id form-2-id}) app-id (test-helpers/create-draft! applicant [cat-id] "Answer1") _draft-app-id (test-helpers/create-draft! applicant [cat-id] "DraftAnswer") app-2-id (test-helpers/create-draft! applicant [cat-id cat-2-id] "Answer2")] (send-command applicant {:type :application.command/submit :application-id app-id}) (send-command applicant {:type :application.command/submit :application-id app-2-id}) (testing "reporter can export" (let [exported (api-call :get (str "/api/applications/export?form-id=" form-id) nil api-key reporter) [_header & lines] (str/split-lines exported)] (is (str/includes? exported "Field 1") exported) (is (not (str/includes? exported "HIDDEN")) exported) (testing "drafts are not visible" (is (not (str/includes? exported "DraftAnswer")))) (testing "submitted applications are visible" (is (= 2 (count lines))) (is (some #(str/includes? % "\"Item1\",\"Answer1\"") lines) lines) (is (some #(str/includes? % "\"Item1, Item2\",\"Answer2\"") lines) lines)))) (testing "handler can't export" (is (response-is-forbidden? (api-response :get (str "/api/applications/export?form-id=" form-id) nil api-key handler)))))) (def testfile (io/file "./test-data/test.txt")) (def malicious-file (io/file "./test-data/malicious_test.html")) (def filecontent {:tempfile testfile :content-type "text/plain" :filename "test.txt" :size (.length testfile)}) (def malicious-content {:tempfile malicious-file :content-type "text/html" :filename "malicious_test.html" :size (.length malicious-file)}) (deftest test-application-api-attachments (let [api-key "<KEY>" user-id "alice" handler-id "developer" ;; developer is the default handler in test-helpers form-id (test-helpers/create-form! {:form/fields [{:field/id "attach" :field/title {:en "some attachment" :fi "joku liite" :sv "bilaga"} :field/type :attachment :field/optional true}]}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id}) upload-request (fn [file] (-> (request :post (str "/api/applications/add-attachment?application-id=" app-id)) (assoc :params {"file" file}) (assoc :multipart-params {"file" file}))) read-request #(request :get (str "/api/applications/attachment/" %))] (testing "uploading malicious file for a draft" (let [response (-> (upload-request malicious-content) (authenticate api-key user-id) handler)] (is (response-is-unsupported-media-type? response)))) (testing "uploading attachment for a draft as handler" (let [response (-> (upload-request filecontent) (authenticate api-key handler-id) handler)] (is (response-is-forbidden? response)))) (testing "invalid value for attachment field" (is (= {:success false :errors [{:form-id form-id :field-id "attach" :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach" :value "1,a"}]})))) (testing "uploading attachment for a draft" (let [body (-> (upload-request filecontent) (authenticate api-key user-id) handler read-ok-body) id (:id body)] (is (:success body)) (is (number? id)) (testing "and retrieving it as the applicant" (let [response (-> (read-request id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))) (testing "and uploading an attachment with the same name" (let [id (-> (upload-request filecontent) (authenticate api-key user-id) handler read-ok-body :id)] (is (number? id)) (testing "and retrieving it" (let [response (-> (read-request id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test (1).txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))))) (testing "and retrieving it as non-applicant" (let [response (-> (read-request id) (authenticate api-key "<NAME>") handler)] (is (response-is-forbidden? response)))) (testing "and uploading a second attachment" (let [body2 (-> (upload-request (assoc filecontent :filename "second.txt")) (authenticate api-key user-id) handler read-ok-body) id2 (:id body2)] (is (:success body2)) (is (number? id2)) (testing "and using them in a field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach" :value (str id "," id2)}]})))) (testing "and submitting" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "and accessing the attachments as handler" (let [response (-> (read-request id) (authenticate api-key handler-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))) (let [response (-> (read-request id2) (authenticate api-key handler-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"second.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))) (testing "and copying the application" (let [response (send-command user-id {:type :application.command/copy-as-new :application-id app-id}) new-app-id (:application-id response)] (is (:success response)) (is (number? new-app-id)) (testing "and fetching the copied attachent" (let [new-app (get-application-for-user new-app-id user-id) [new-id new-id2] (mapv :attachment/id (get new-app :application/attachments))] (is (number? new-id)) (is (number? new-id2)) (is (not= #{id id2} #{new-id new-id2})) (let [response (-> (read-request new-id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))) (let [response (-> (read-request new-id2) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"second.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))))))))))) (testing "retrieving nonexistent attachment" (let [response (-> (read-request 999999999999999) (authenticate api-key "<NAME>") handler)] (is (response-is-not-found? response)))) (testing "uploading attachment for nonexistent application" (let [response (-> (request :post "/api/applications/add-attachment?application-id=99999999") (assoc :params {"file" filecontent}) (assoc :multipart-params {"file" filecontent}) (authenticate api-key user-id) handler)] (is (response-is-forbidden? response)))) (testing "uploading attachment without authentication" (let [response (-> (upload-request filecontent) handler)] (is (response-is-unauthorized? response)))) (testing "uploading attachment with wrong API key" (let [response (-> (upload-request filecontent) (authenticate api-key user-id) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler)] (is (response-is-unauthorized? response)))) (testing "uploading attachment as non-applicant" (let [response (-> (upload-request filecontent) (authenticate api-key "<NAME>") handler)] (is (response-is-forbidden? response)))))) (deftest test-application-comment-attachments (let [api-key "<KEY>" applicant-id "<NAME>" handler-id "developer" reviewer-id "car<NAME>" file #(assoc filecontent :filename %) workflow-id (test-helpers/create-workflow! {:type :workflow/master :handlers [handler-id]}) cat-item-id (test-helpers/create-catalogue-item! {:workflow-id workflow-id}) application-id (test-helpers/create-application! {:catalogue-item-ids [cat-item-id] :actor applicant-id}) add-attachment #(-> (request :post (str "/api/applications/add-attachment?application-id=" application-id)) (authenticate api-key %1) (assoc :params {"file" %2}) (assoc :multipart-params {"file" %2}) handler read-ok-body :id)] (testing "submit" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id application-id})))) (testing "unrelated user can't upload attachment" (is (response-is-forbidden? (-> (request :post (str "/api/applications/add-attachment?application-id=" application-id)) (authenticate api-key reviewer-id) (assoc :params {"file" filecontent}) (assoc :multipart-params {"file" filecontent}) handler)))) (testing "invite reviewer" (is (= {:success true} (send-command handler-id {:type :application.command/request-review :application-id application-id :reviewers [reviewer-id] :comment "please"})))) (testing "handler uploads an attachment" (let [attachment-id (add-attachment handler-id (file "handler-public-remark.txt"))] (is (number? attachment-id)) (testing "and attaches it to a public remark" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "see attachment" :public true :attachments [{:attachment/id attachment-id}]})))))) (testing "applicant can see attachment" (let [app (get-application-for-user application-id applicant-id) remark-event (last (:application/events app)) attachment-id (:attachment/id (first (:event/attachments remark-event)))] (is (number? attachment-id)) (testing "and fetch it" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id) assert-response-is-ok :body slurp)))))) (testing "reviewer uploads an attachment" (let [attachment-id (add-attachment reviewer-id (file "reviewer-review.txt"))] (is (number? attachment-id)) (testing ", handler can't use the attachment" (is (= {:success false :errors [{:type "invalid-attachments" :attachments [attachment-id]}]} (send-command handler-id {:type :application.command/remark :public false :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]})))) (testing ", attaches it to a review" (is (= {:success true} (send-command reviewer-id {:type :application.command/review :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))) (testing ", handler can fetch attachment" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key handler-id) assert-response-is-ok :body slurp)))) (testing ", applicant can't fetch attachment" (is (response-is-forbidden? (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id))))))) (testing "handler makes a private remark" (let [attachment-id (add-attachment handler-id (file "handler-private-remark.txt"))] (is (number? attachment-id)) (is (= {:success true} (send-command handler-id {:type :application.command/remark :public false :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))) (testing ", handler can fetch attachment" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key handler-id) assert-response-is-ok :body slurp)))) (testing ", applicant can't fetch attachment" (is (response-is-forbidden? (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id)))))) (testing "handler approves with attachment" (let [attachment-id (add-attachment handler-id (file "handler-approve.txt"))] (is (number? attachment-id)) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))))) (testing "handler closes with two attachments (with the same name)" (let [id1 (add-attachment handler-id (file "handler-close.txt")) id2 (add-attachment handler-id (file "handler-close.txt"))] (is (number? id1)) (is (number? id2)) (is (= {:success true} (send-command handler-id {:type :application.command/close :application-id application-id :comment "see attachment" :attachments [{:attachment/id id1} {:attachment/id id2}]}))))) (testing "applicant can see the three new attachments" (let [app (get-application-for-user application-id applicant-id) [close-event approve-event] (reverse (:application/events app)) [close-id1 close-id2] (map :attachment/id (:event/attachments close-event)) [approve-id] (map :attachment/id (:event/attachments approve-event))] (is (= "application.event/closed" (:event/type close-event))) (is (= "application.event/approved" (:event/type approve-event))) (is (number? close-id1)) (is (number? close-id2)) (is (number? approve-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" close-id1) nil api-key handler-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" close-id2) nil api-key handler-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" approve-id) nil api-key handler-id)))) (testing ":application/attachments" (testing "applicant" (is (= ["handler-public-remark.txt" "handler-approve.txt" "handler-close.txt" "handler-close (1).txt"] (mapv :attachment/filename (:application/attachments (get-application-for-user application-id applicant-id)))))) (testing "handler" (is (= ["handler-public-remark.txt" "reviewer-review.txt" "handler-private-remark.txt" "handler-approve.txt" "handler-close.txt" "handler-close (1).txt"] (mapv :attachment/filename (:application/attachments (get-application-for-user application-id handler-id))))))))) (deftest test-application-attachment-zip (let [api-key "<KEY>" applicant-id "alice" handler-id "handler" reporter-id "reporter" workflow-id (test-helpers/create-workflow! {:handlers [handler-id]}) form-id (test-helpers/create-form! {:form/fields [{:field/id "attach1" :field/title {:en "some attachment" :fi "joku liite" :sv "bilaga"} :field/type :attachment :field/optional true} {:field/id "attach2" :field/title {:en "another attachment" :fi "toinen liite" :sv "annan bilaga"} :field/type :attachment :field/optional true}]}) cat-id (test-helpers/create-catalogue-item! {:workflow-id workflow-id :form-id form-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant-id}) add-attachment (fn [user file] (-> (request :post (str "/api/applications/add-attachment?application-id=" app-id)) (authenticate api-key user) (assoc :params {"file" file}) (assoc :multipart-params {"file" file}) handler read-ok-body :id)) file #(assoc filecontent :filename %) fetch-zip (fn [user-id] (with-open [zip (-> (api-response :get (str "/api/applications/" app-id "/attachments") nil api-key user-id) :body ZipInputStream.)] (loop [files {}] (if-let [entry (.getNextEntry zip)] (let [buf (ByteArrayOutputStream.)] (io/copy zip buf) (recur (assoc files (.getName entry) (.toString buf "UTF-8")))) files))))] (testing "save a draft" (let [id (add-attachment applicant-id (file "invisible.txt"))] (is (= {:success true} (send-command applicant-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach1" :value (str id)}]}))))) (testing "save a new draft" (let [blue-id (add-attachment applicant-id (file "blue.txt")) green-id (add-attachment applicant-id (file "green.txt")) red-id (add-attachment applicant-id (file "red.txt"))] (is (= {:success true} (send-command applicant-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach1" :value (str blue-id "," green-id)} {:form form-id :field "attach2" :value (str red-id)}]}))))) (testing "fetch zip as applicant" (is (= {"blue.txt" (slurp testfile) "red.txt" (slurp testfile) "green.txt" (slurp testfile)} (fetch-zip applicant-id)))) (testing "submit" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id})))) (testing "remark with attachments" (let [blue-comment-id (add-attachment handler-id (file "blue.txt")) yellow-comment-id (add-attachment handler-id (file "yellow.txt"))] (is (= {:success true} (send-command handler-id {:type :application.command/remark :public true :application-id app-id :comment "see attachment" :attachments [{:attachment/id blue-comment-id} {:attachment/id yellow-comment-id}]})))) (testing "fetch zip as applicant, handler and reporter" (is (= {"blue.txt" (slurp testfile) "red.txt" (slurp testfile) "green.txt" (slurp testfile) "blue (1).txt" (slurp testfile) "yellow.txt" (slurp testfile)} (fetch-zip applicant-id) (fetch-zip handler-id) (fetch-zip reporter-id)))) (testing "fetch zip as third party" (is (response-is-forbidden? (api-response :get (str "/api/applications/" app-id "/attachments") nil api-key "malice")))) (testing "fetch zip for nonexisting application" (is (response-is-not-found? (api-response :get "/api/applications/99999999/attachments" nil api-key "malice"))))))) (deftest test-application-api-license-attachments (let [api-key "<KEY>" applicant "<NAME>" non-applicant "<NAME>" owner "owner" handler-user "developer" cat-id (test-helpers/create-catalogue-item! {}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant}) file-en (clojure.java.io/file "./test-data/test.txt") filecontent-en {:tempfile file-en :content-type "text/plain" :filename "test.txt" :size (.length file-en)} en-attachment-id (-> (request :post "/api/licenses/add_attachment") (assoc :params {"file" filecontent-en}) (assoc :multipart-params {"file" filecontent-en}) (authenticate api-key owner) handler read-ok-body :id) file-fi (clojure.java.io/file "./test-data/test-fi.txt") filecontent-fi {:tempfile file-fi :content-type "text/plain" :filename "test.txt" :size (.length file-fi)} fi-attachment-id (-> (request :post "/api/licenses/add_attachment") (assoc :params {"file" filecontent-fi}) (assoc :multipart-params {"file" filecontent-fi}) (authenticate api-key owner) handler read-ok-body :id) license-id (-> (request :post "/api/licenses/create") (authenticate api-key owner) (json-body {:licensetype "attachment" :organization {:organization/id "abc"} ;; TODO different content for different languages :localizations {:en {:title "en title" :textcontent "en text" :attachment-id en-attachment-id} :fi {:title "fi title" :textcontent "fi text" :attachment-id fi-attachment-id}}}) handler read-ok-body :id)] (testing "submit application" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "attach license to application" (is (= {:success true} (send-command handler-user {:type :application.command/add-licenses :application-id app-id :comment "" :licenses [license-id]})))) (testing "access license" (testing "as applicant" (is (= "hello from file\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key applicant) handler assert-response-is-ok :body slurp))) (testing "in finnish" (is (= "tervehdys tiedostosta\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/fi")) (authenticate api-key applicant) handler assert-response-is-ok :body slurp))))) (testing "as handler" (is (= "hello from file\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key handler-user) handler assert-response-is-ok :body slurp)))) (testing "as non-applicant" (is (response-is-forbidden? (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key non-applicant) handler))))))) (deftest test-applications-api-security (let [api-key "<KEY>" applicant "alice" cat-id (test-helpers/create-catalogue-item! {}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant})] (testing "fetch application without authentication" (let [req (request :get (str "/api/applications/" app-id))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "fetch nonexistent application" (let [response (-> (request :get "/api/applications/9999999999") (authenticate api-key applicant) handler)] (is (response-is-not-found? response)) (is (= "application/json" (get-in response [:headers "Content-Type"]))) (is (= {:error "not found"} (read-body response))))) (testing "fetch deciders without authentication or as non-handler" (let [req (request :get "/api/applications/deciders")] (assert-response-is-ok (-> req (authenticate api-key "developer") handler)) (is (response-is-forbidden? (-> req (authenticate api-key applicant) handler))) (is (response-is-unauthorized? (-> req handler))))) (testing "create without authentication" (let [req (-> (request :post "/api/applications/create") (json-body {:catalogue-item-ids [cat-id]}))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "create with wrong API key" (let [req (-> (request :post "/api/applications/create") (authenticate api-key applicant) (json-body {:catalogue-item-ids [cat-id]}))] (assert-response-is-ok (-> req handler)) (is (response-is-unauthorized? (-> req (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler))))) (testing "send command without authentication" (let [req (-> (request :post "/api/applications/submit") (json-body {:application-id app-id}))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "send command with wrong API key" (let [req (-> (request :post "/api/applications/submit") (authenticate api-key applicant) (json-body {:application-id app-id}))] (assert-response-is-ok (-> req handler)) (is (response-is-unauthorized? (-> req (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler))))))) (deftest test-application-listing (let [app-id (test-helpers/create-application! {:actor "alice"})] (testing "list user applications" (is (contains? (get-ids (get-my-applications "alice")) app-id))) (testing "search user applications" (is (contains? (get-ids (get-my-applications "alice" {:query "applicant:alice"})) app-id)) (is (empty? (get-ids (get-my-applications "alice" {:query "applicant:no-such-user"}))))) (testing "list all applications" (is (contains? (get-ids (get-all-applications "alice")) app-id))) (testing "search all applications" (is (contains? (get-ids (get-all-applications "alice" {:query "applicant:alice"})) app-id)) (is (empty? (get-ids (get-all-applications "alice" {:query "applicant:no-such-user"}))))))) (deftest test-todos (let [applicant "alice" handler "developer" reviewer "reviewer" decider "decider" app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/create-user! {:eppn reviewer}) (test-helpers/create-user! {:eppn decider}) (testing "does not list drafts" (is (not (contains? (get-ids (get-todos handler)) app-id)))) (testing "lists submitted in todos" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id}))) (is (contains? (get-ids (get-todos handler)) app-id)) (is (not (contains? (get-ids (get-handled-todos handler)) app-id)))) (testing "search todos" (is (contains? (get-ids (get-todos handler {:query (str "applicant:" applicant)})) app-id)) (is (empty? (get-ids (get-todos handler {:query "applicant:no-such-user"}))))) (testing "reviewer sees application in todos" (is (not (contains? (get-ids (get-todos reviewer)) app-id))) (is (= {:success true} (send-command handler {:type :application.command/request-review :application-id app-id :reviewers [reviewer] :comment "x"}))) (is (contains? (get-ids (get-todos reviewer)) app-id)) (is (not (contains? (get-ids (get-handled-todos reviewer)) app-id)))) (testing "decider sees application in todos" (is (not (contains? (get-ids (get-todos decider)) app-id))) (is (= {:success true} (send-command handler {:type :application.command/request-decision :application-id app-id :deciders [decider] :comment "x"}))) (is (contains? (get-ids (get-todos decider)) app-id)) (is (not (contains? (get-ids (get-handled-todos decider)) app-id)))) (testing "lists handled in handled" (is (= {:success true} (send-command handler {:type :application.command/approve :application-id app-id :comment ""}))) (is (not (contains? (get-ids (get-todos handler)) app-id))) (is (contains? (get-ids (get-handled-todos handler)) app-id))) (testing "search handled todos" (is (contains? (get-ids (get-handled-todos handler {:query (str "applicant:" applicant)})) app-id)) (is (empty? (get-ids (get-handled-todos handler {:query "applicant:no-such-user"}))))) (testing "reviewer sees accepted application in handled todos" (is (not (contains? (get-ids (get-todos reviewer)) app-id))) (is (contains? (get-ids (get-handled-todos reviewer)) app-id))) (testing "decider sees accepted application in handled todos" (is (not (contains? (get-ids (get-todos decider)) app-id))) (is (contains? (get-ids (get-handled-todos decider)) app-id))))) (deftest test-application-raw (let [api-key "<KEY>" applicant "alice" handler "handler" reporter "reporter" form-id (test-helpers/create-form! {:form/internal-name "notifications" :form/external-title {:en "Notifications EN" :fi "Notifications FI" :sv "Notifications SV"} :form/fields [{:field/type :text :field/id "field-1" :field/title {:en "text field" :fi "text field" :sv "text field"} :field/optional false}]}) workflow-id (test-helpers/create-workflow! {:title "wf" :handlers [handler] :type :workflow/default}) ext-id "resres" res-id (test-helpers/create-resource! {:resource-ext-id ext-id}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id :resource-id res-id :workflow-id workflow-id}) app-id (test-helpers/create-draft! applicant [cat-id] "raw test" (time/date-time 2010))] (testing "applicant can't get raw application" (is (response-is-forbidden? (api-response :get (str "/api/applications/" app-id "/raw") nil api-key applicant)))) (testing "reporter can get raw application" (is (= {:application/description "" :application/invited-members [] :application/last-activity "2010-01-01T00:00:00.000Z" :application/attachments [] :application/licenses [] :application/created "2010-01-01T00:00:00.000Z" :application/state "application.state/draft" :application/role-permissions {:everyone-else ["application.command/accept-invitation"] :member ["application.command/copy-as-new" "application.command/accept-licenses"] :reporter ["see-everything"] :applicant ["application.command/copy-as-new" "application.command/invite-member" "application.command/submit" "application.command/remove-member" "application.command/accept-licenses" "application.command/uninvite-member" "application.command/delete" "application.command/save-draft" "application.command/change-resources"]} :application/modified "2010-01-01T00:00:00.000Z" :application/user-roles {:alice ["applicant"] :handler ["handler"] :reporter ["reporter"]} :application/external-id "2010/1" :application/generated-external-id "2010/1" :application/workflow {:workflow/type "workflow/default" :workflow/id workflow-id :workflow.dynamic/handlers [{:email "<EMAIL>" :userid "handler" :name "<NAME>"}]} :application/blacklist [] :application/id app-id :application/todo nil :application/applicant {:email "<EMAIL>" :userid "alice" :name "<NAME>" :nickname "In Wonderland" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/members [] :application/resources [{:catalogue-item/start "REDACTED" :catalogue-item/end nil :catalogue-item/expired false :catalogue-item/enabled true :resource/id res-id :catalogue-item/title {} :catalogue-item/infourl {} :resource/ext-id ext-id :catalogue-item/archived false :catalogue-item/id cat-id}] :application/accepted-licenses {:alice []} :application/forms [{:form/fields [{:field/value "raw test" :field/type "text" :field/title {:en "text field" :fi "text field" :sv "text field"} :field/id "field-1" :field/optional false :field/visible true :field/private false}] :form/title "notifications" ; deprecated :form/internal-name "notifications" :form/external-title {:en "Notifications EN" :fi "Notifications FI" :sv "Notifications SV"} :form/id form-id}] :application/events [{:application/external-id "2010/1" :event/actor-attributes {:userid "alice" :name "<NAME>" :nickname "In Wonderland" :email "<EMAIL>" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/id app-id :event/time "2010-01-01T00:00:00.000Z" :workflow/type "workflow/default" :application/resources [{:catalogue-item/id cat-id :resource/ext-id ext-id}] :application/forms [{:form/id form-id}] :workflow/id workflow-id :event/actor "<NAME>" :event/type "application.event/created" :event/id 100 :application/licenses []} {:event/id 100 :event/type "application.event/draft-saved" :event/time "2010-01-01T00:00:00.000Z" :event/actor "<NAME>" :application/id app-id :event/actor-attributes {:userid "alice" :name "<NAME>" :nickname "In Wonderland" :email "<EMAIL>" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/field-values [{:form form-id :field "field-1" :value "raw test"}]} {:event/id 100 :event/type "application.event/licenses-accepted" :event/time "2010-01-01T00:00:00.000Z" :event/actor "<NAME>" :application/id app-id :event/actor-attributes {:userid "alice" :name "<NAME>" :nickname "In Wonderland" :email "<EMAIL>" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/accepted-licenses []}]} (-> (api-call :get (str "/api/applications/" app-id "/raw") nil api-key reporter) ;; start is set by the db not easy to mock (assoc-in [:application/resources 0 :catalogue-item/start] "REDACTED") ;; event ids are unpredictable (update :application/events (partial map #(update % :event/id (constantly 100))))))))))
true
(ns ^:integration rems.api.test-applications (:require [clj-time.core :as time] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [rems.api.services.catalogue :as catalogue] [rems.api.testing :refer :all] [rems.db.applications] [rems.db.blacklist :as blacklist] [rems.db.core :as db] [rems.db.test-data :as test-data] [rems.db.test-data-helpers :as test-helpers] [rems.handler :refer [handler]] [rems.json] [rems.testing-util :refer [with-user]] [ring.mock.request :refer :all]) (:import java.io.ByteArrayOutputStream java.util.zip.ZipInputStream)) (use-fixtures :each api-fixture ;; TODO should this fixture have a name? (fn [f] (test-data/create-test-api-key!) (test-data/create-test-users-and-roles!) (f))) ;;; shared helpers (defn- send-command [actor cmd] (-> (request :post (str "/api/applications/" (name (:type cmd)))) (authenticate "42" actor) (json-body (dissoc cmd :type)) handler read-body)) (defn- send-command-transit [actor cmd] (-> (request :post (str "/api/applications/" (name (:type cmd)))) (authenticate "42" actor) (transit-body (dissoc cmd :type)) handler read-body)) (defn- get-ids [applications] (set (map :application/id applications))) (defn- license-ids-for-application [application] (set (map :license/id (:application/licenses application)))) (defn- catalogue-item-ids-for-application [application] (set (map :catalogue-item/id (:application/resources application)))) (defn- get-my-applications [user-id & [params]] (-> (request :get "/api/my-applications" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-all-applications [user-id & [params]] (-> (request :get "/api/applications" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-application-for-user [app-id user-id] (-> (request :get (str "/api/applications/" app-id)) (authenticate "42" user-id) handler read-ok-body)) (defn- get-todos [user-id & [params]] (-> (request :get "/api/applications/todo" params) (authenticate "42" user-id) handler read-ok-body)) (defn- get-handled-todos [user-id & [params]] (-> (request :get "/api/applications/handled" params) (authenticate "42" user-id) handler read-ok-body)) ;;; tests (deftest test-application-api-session (let [username "alice" cookie (login-with-cookies username) csrf (get-csrf-token cookie) cat-id (test-helpers/create-catalogue-item! {})] (testing "save with session" (let [body (-> (request :post "/api/applications/create") (header "Cookie" cookie) (header "x-csrf-token" csrf) (json-body {:catalogue-item-ids [cat-id]}) handler assert-response-is-ok read-body)] (is (:success body)))) (testing "save with session but without csrf" (let [response (-> (request :post "/api/applications/create") (header "Cookie" cookie) (json-body {:catalogue-item-ids [cat-id]}) handler)] (is (response-is-unauthorized? response)))) (testing "save with session and csrf and wrong api-key" (let [body (-> (request :post "/api/applications/create") (header "Cookie" cookie) (header "x-csrf-token" csrf) (header "x-rems-api-key" "WRONG") (json-body {:catalogue-item-ids [cat-id]}) handler assert-response-is-ok read-body)] (is (:success body)))))) (deftest pdf-smoke-test (testing "not found" (let [response (-> (request :get "/api/applications/9999999/pdf") (authenticate "42" "developer") handler)] (is (response-is-not-found? response)))) (let [cat-id (test-helpers/create-catalogue-item! {:title {:fi "Fi title" :en "En title"}}) application-id (test-helpers/create-application! {:actor "alice" :catalogue-item-ids [cat-id]})] (test-helpers/command! {:type :application.command/submit :application-id application-id :actor "alice"}) (testing "forbidden" (let [response (-> (request :get (str "/api/applications/" application-id "/pdf")) (authenticate "42" "bob") handler)] (is (response-is-forbidden? response)))) (testing "success" (let [response (-> (request :get (str "/api/applications/" application-id "/pdf")) (authenticate "42" "developer") handler assert-response-is-ok)] (is (= "application/pdf" (get-in response [:headers "Content-Type"]))) (is (= (str "filename=\"" application-id ".pdf\"") (get-in response [:headers "Content-Disposition"]))) (is (.startsWith (slurp (:body response)) "%PDF-1.")))))) (deftest test-application-commands (let [user-id "alice" handler-id "developer" reviewer-id "carl" decider-id "elsa" license-id1 (test-helpers/create-license! {}) license-id2 (test-helpers/create-license! {}) license-id3 (test-helpers/create-license! {}) license-id4 (test-helpers/create-license! {}) form-id (test-helpers/create-form! {}) workflow-id (test-helpers/create-workflow! {:type :workflow/master :handlers [handler-id]}) cat-item-id1 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id1 license-id2]}) :form-id form-id :workflow-id workflow-id}) cat-item-id2 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id1 license-id2]}) :form-id form-id :workflow-id workflow-id}) cat-item-id3 (test-helpers/create-catalogue-item! {:resource-id (test-helpers/create-resource! {:license-ids [license-id3]}) :form-id form-id :workflow-id workflow-id}) application-id (test-helpers/create-application! {:catalogue-item-ids [cat-item-id1] :actor user-id})] (testing "accept licenses" (is (= {:success true} (send-command user-id {:type :application.command/accept-licenses :application-id application-id :accepted-licenses [license-id1 license-id2]}))) (testing "with invalid application id" (is (= {:success false :errors [{:type "application-not-found"}]} (send-command user-id {:type :application.command/accept-licenses :application-id 9999999999 :accepted-licenses [license-id1 license-id2]}))))) (testing "save draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id application-id :field-values []})))) (testing "submit" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id})))) (testing "getting application as applicant" (let [application (get-application-for-user application-id user-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted"] (map :event/type (get application :application/events)))) (is (= #{"application.command/remove-member" "application.command/uninvite-member" "application.command/accept-licenses" "application.command/copy-as-new"} (set (get application :application/permissions)))))) (testing "getting application as handler" (let [application (get-application-for-user application-id handler-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= #{"application.command/request-review" "application.command/request-decision" "application.command/remark" "application.command/reject" "application.command/approve" "application.command/return" "application.command/add-licenses" "application.command/add-member" "application.command/remove-member" "application.command/invite-member" "application.command/invite-decider" "application.command/invite-reviewer" "application.command/uninvite-member" "application.command/change-resources" "application.command/close" "application.command/assign-external-id" "see-everything"} (set (get application :application/permissions)))))) (testing "disabling a command" (with-redefs [rems.config/env (assoc rems.config/env :disable-commands [:application.command/remark])] (testing "handler doesn't see hidden command" (let [application (get-application-for-user application-id handler-id)] (is (= "workflow/master" (get-in application [:application/workflow :workflow/type]))) (is (= #{"application.command/request-review" "application.command/request-decision" "application.command/reject" "application.command/approve" "application.command/return" "application.command/add-licenses" "application.command/add-member" "application.command/remove-member" "application.command/invite-member" "application.command/invite-decider" "application.command/invite-reviewer" "application.command/uninvite-member" "application.command/change-resources" "application.command/close" "application.command/assign-external-id" "see-everything"} (set (get application :application/permissions)))))) (testing "disabled command fails" (is (= {:success false :errors [{:type "forbidden"}]} (send-command handler-id {:type :application.command/remark :application-id application-id :public false :comment "this is a remark"})))))) (testing "send command without user" (is (= {:success false :errors [{:type "forbidden"}]} (send-command "" {:type :application.command/approve :application-id application-id :comment ""})) "user should be forbidden to send command")) (testing "send command with a user that is not a handler" (is (= {:success false :errors [{:type "forbidden"}]} (send-command user-id {:type :application.command/approve :application-id application-id :comment ""})) "user should be forbidden to send command")) (testing "assing external id" (is (= {:success true} (send-command handler-id {:type :application.command/assign-external-id :application-id application-id :external-id "abc123"}))) (let [application (get-application-for-user application-id handler-id)] (is (= "abc123" (:application/external-id application))))) (testing "application can be returned" (is (= {:success true} (send-command handler-id {:type :application.command/return :application-id application-id :comment "Please check again"})))) (testing "changing resources as applicant" (is (= {:success true} (send-command user-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id2]})))) (testing "submitting again" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id})))) (testing "send commands with authorized user" (testing "even handler cannot review without request" (is (= {:errors [{:type "forbidden"}], :success false} (send-command handler-id {:type :application.command/review :application-id application-id :comment "What am I commenting on?"})))) (testing "review with request" (let [eventcount (count (get (get-application-for-user application-id handler-id) :events))] (testing "requesting review" (is (= {:success true} (send-command handler-id {:type :application.command/request-review :application-id application-id :reviewers [decider-id reviewer-id] :comment "What say you?"})))) (testing "reviewer can now review" (is (= {:success true} (send-command reviewer-id {:type :application.command/review :application-id application-id :comment "Yeah, I dunno"})))) (testing "review was linked to request" (let [application (get-application-for-user application-id handler-id) request-event (get-in application [:application/events eventcount]) review-event (get-in application [:application/events (inc eventcount)])] (is (= (:application/request-id request-event) (:application/request-id review-event))))))) (testing "adding and then accepting additional licenses" (testing "add licenses" (let [application (get-application-for-user application-id user-id)] (is (= #{license-id1 license-id2} (license-ids-for-application application))) (is (= {:success true} (send-command handler-id {:type :application.command/add-licenses :application-id application-id :licenses [license-id4] :comment "Please approve these new terms"}))) (let [application (get-application-for-user application-id user-id)] (is (= #{license-id1 license-id2 license-id4} (license-ids-for-application application)))))) (testing "applicant accepts the additional licenses" (is (= {:success true} (send-command user-id {:type :application.command/accept-licenses :application-id application-id :accepted-licenses [license-id4]}))))) (testing "changing resources as handler" (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id2} (catalogue-item-ids-for-application application))) (is (= #{license-id1 license-id2 license-id4} (license-ids-for-application application))) (is (= {:success true} (send-command handler-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id3] :comment "Here are the correct resources"}))) (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id3} (catalogue-item-ids-for-application application))) ;; TODO: The previously added licenses should probably be retained in the licenses after changing resources. (is (= #{license-id3} (license-ids-for-application application)))))) (testing "changing resources back as handler" (is (= {:success true} (send-command handler-id {:type :application.command/change-resources :application-id application-id :catalogue-item-ids [cat-item-id2]}))) (let [application (get-application-for-user application-id user-id)] (is (= #{cat-item-id2} (catalogue-item-ids-for-application application))) (is (= #{license-id1 license-id2} (license-ids-for-application application))))) (testing "request-decision" (is (= {:success true} (send-command handler-id {:type :application.command/request-decision :application-id application-id :deciders [decider-id] :comment ""})))) (testing "decide" (is (= {:success true} (send-command decider-id {:type :application.command/decide :application-id application-id :decision :approved :comment ""})))) (testing "hidden remark" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "" :public false})))) (testing "public remark with" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "" :public true})))) (testing "approve" (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id application-id :comment ""}))) (let [handler-data (get-application-for-user application-id handler-id) handler-event-types (map :event/type (get handler-data :application/events)) applicant-data (get-application-for-user application-id user-id) applicant-event-types (map :event/type (get applicant-data :application/events))] (testing "handler can see all events" (is (= {:application/id application-id :application/state "application.state/approved"} (select-keys handler-data [:application/id :application/state]))) (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted" "application.event/external-id-assigned" "application.event/returned" "application.event/resources-changed" "application.event/submitted" "application.event/review-requested" "application.event/reviewed" "application.event/licenses-added" "application.event/licenses-accepted" "application.event/resources-changed" "application.event/resources-changed" "application.event/decision-requested" "application.event/decided" "application.event/remarked" "application.event/remarked" "application.event/approved"] handler-event-types))) (testing "applicant cannot see all events" (is (= ["application.event/created" "application.event/licenses-accepted" "application.event/draft-saved" "application.event/submitted" "application.event/external-id-assigned" "application.event/returned" "application.event/resources-changed" "application.event/submitted" "application.event/licenses-added" "application.event/licenses-accepted" "application.event/resources-changed" "application.event/resources-changed" "application.event/remarked" "application.event/approved"] applicant-event-types))))) (testing "copy as new" (let [result (send-command user-id {:type :application.command/copy-as-new :application-id application-id})] (is (:success result) {:result result}) (is (:application-id result) {:result result}) (is (not= application-id (:application-id result)) "should create a new application")))))) (deftest test-approve-with-end (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" handler "developer"] (testing "json" (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:type :application.command/submit :application-id app-id :actor applicant}) (is (= {:success true} (send-command handler {:type :application.command/approve :application-id app-id :comment "" :entitlement-end "2100-01-01T00:00:00.000Z"}))) (let [app (get-application-for-user app-id applicant)] (is (= "application.state/approved" (:application/state app))) (is (= "2100-01-01T00:00:00.000Z" (:entitlement/end app)))))) (testing "transit" (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:type :application.command/submit :application-id app-id :actor applicant}) (is (= {:success true} (send-command-transit handler {:type :application.command/approve :application-id app-id :comment "" :entitlement-end (time/date-time 2100 01 01)}))) (let [app (get-application-for-user app-id applicant)] (is (= "application.state/approved" (:application/state app))) (is (= "2100-01-01T00:00:00.000Z" (:entitlement/end app)))))))) (deftest test-application-create (let [api-key "PI:KEY:<KEY>END_PI" user-id "alice" cat-id (test-helpers/create-catalogue-item! {}) application-id (:application-id (api-call :post "/api/applications/create" {:catalogue-item-ids [cat-id]} "42" user-id))] (testing "creating" (is (some? application-id)) (let [created (get-application-for-user application-id user-id)] (is (= "application.state/draft" (get created :application/state))))) (testing "seeing draft is forbidden" (testing "as unrelated user" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "bob")))) (testing "as reporter" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "reporter")))) (testing "as handler" (is (response-is-forbidden? (api-response :get (str "/api/applications/" application-id) nil api-key "developer"))))) (testing "modifying application as other user is forbidden" (is (= {:success false :errors [{:type "forbidden"}]} (send-command "bob" {:type :application.command/save-draft :application-id application-id :field-values []})))) (testing "submitting" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id application-id}))) (let [submitted (get-application-for-user application-id user-id)] (is (= "application.state/submitted" (get submitted :application/state))) (is (= ["application.event/created" "application.event/submitted"] (map :event/type (get submitted :application/events)))))) (testing "seeing submitted application as reporter is allowed" (is (response-is-ok? (-> (request :get (str "/api/applications/" application-id)) (authenticate api-key "reporter") handler)))) (testing "can't create application for disabled catalogue item" (with-user "owner" (catalogue/set-catalogue-item-enabled! {:id cat-id :enabled false})) (rems.db.applications/reload-cache!) (is (= {:success false :errors [{:type "disabled-catalogue-item" :catalogue-item-id cat-id}]} (api-call :post "/api/applications/create" {:catalogue-item-ids [cat-id]} "42" user-id)))))) (deftest test-application-delete (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" handler "developer"] (let [app-id (test-helpers/create-application! {:actor applicant})] (testing "can't delete draft as other user" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key handler)))) (testing "can delete draft as applicant" (is (contains? (-> (get-application-for-user app-id applicant) :application/permissions set) "application.command/delete")) (is (= {:success true} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant)))) (testing "deleted application is gone" (is (response-is-not-found? (api-response :get (str "/api/applications/" app-id) nil api-key applicant))))) (let [app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/command! {:application-id app-id :type :application.command/submit :actor applicant}) (testing "can't delete submitted application" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant)))) (test-helpers/command! {:application-id app-id :type :application.command/return :actor handler}) (testing "can't delete returned application" (is (= {:errors [{:type "forbidden"}] :success false} (api-call :post "/api/applications/delete" {:application-id app-id} api-key applicant))))))) (deftest test-application-close (let [user-id "alice" application-id (test-helpers/create-application! {:actor user-id})] (test-helpers/command! {:application-id application-id :type :application.command/submit :actor user-id}) (is (= {:success true} (send-command "developer" {:type :application.command/close :application-id application-id :comment ""}))) (is (= "application.state/closed" (:application/state (get-application-for-user application-id user-id)))))) (deftest test-application-submit (let [owner "owner" user-id "alice" form-id (test-helpers/create-form! {}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) enable-catalogue-item! #(with-user owner (catalogue/set-catalogue-item-enabled! {:id cat-id :enabled %})) archive-catalogue-item! #(with-user owner (catalogue/set-catalogue-item-archived! {:id cat-id :archived %}))] (testing "submit with archived & disabled catalogue item succeeds" ;; draft needs to be created before disabling & archiving (let [app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (is (:success (enable-catalogue-item! false))) (is (:success (archive-catalogue-item! true))) (rems.db.applications/reload-cache!) (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id}))))) (testing "submit with normal catalogue item succeeds" (is (:success (enable-catalogue-item! true))) (is (:success (archive-catalogue-item! false))) (rems.db.applications/reload-cache!) (let [app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id}))))))) (deftest test-application-invitations (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" handler "developer" app-id (test-helpers/create-application! {:actor applicant})] (testing "invite member for draft as applicant" (is (= {:success true} (send-command applicant {:type :application.command/invite-member :application-id app-id :member {:name "PI:NAME:<NAME>END_PI 1" :email "PI:EMAIL:<EMAIL>END_PI"}})))) (testing "accept member invitation for draft" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) member "member1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key member))) (testing ", member is able to fetch application and see themselves" (is (= #{member} (->> (get-application-for-user app-id member) :application/members (mapv :userid) set)))))) (testing "submit application" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "invite reviewer as handler" (is (= {:success true} (send-command handler {:type :application.command/invite-reviewer :application-id app-id :reviewer {:name "Member 2" :email "PI:EMAIL:<EMAIL>END_PI"}})))) (testing "accept handler invitation" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) reviewer "reviewer1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key reviewer))) (testing ", reviewer is able to fetch application and can submit a review" (is (= ["see-everything" "application.command/review" "application.command/remark"] (:application/permissions (get-application-for-user app-id reviewer))))))) (testing "invite decider as handler" (is (= {:success true} (send-command handler {:type :application.command/invite-decider :application-id app-id :decider {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}})))) (testing "accept handler invitation" (let [token (-> (rems.db.applications/get-application-internal app-id) :application/events last :invitation/token) decider "decider1"] (is token) (is (= {:success true :application-id app-id} (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key decider))) (testing ", decider is able to fetch application and can submit a review" (is (= ["see-everything" "application.command/reject" "application.command/decide" "application.command/remark" "application.command/approve"] (:application/permissions (get-application-for-user app-id decider))))))))) (deftest test-application-validation (let [user-id "alice" form-id (test-helpers/create-form! {:form/fields [{:field/id "req1" :field/title {:en "req" :fi "pak" :sv "obl"} :field/type :text :field/optional false} {:field/id "opt1" :field/title {:en "opt" :fi "val" :sv "fri"} :field/type :text :field/optional true}]}) form-id2 (test-helpers/create-form! {:form/fields [{:field/id "req2" :field/title {:en "req" :fi "pak" :sv "obl"} :field/type :text :field/optional false} {:field/id "opt2" :field/title {:en "opt" :fi "val" :sv "fri"} :field/type :text :field/optional true} {:field/id "table" :field/type :table :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}]} {:field/id "optionlist" :field/title {:en "Option list." :fi "Valintalista." :sv "Välj"} :field/type :option :field/options [{:key "Option1" :label {:en "First" :fi "Ensimmäinen" :sv "Först"}} {:key "Option2" :label {:en "Second" :fi "Toinen" :sv "Den andra"}} {:key "Option3" :label {:en "Third" :fi "Kolmas" :sv "Tredje"}}] :field/optional true}]}) wf-id (test-helpers/create-workflow! {}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id :workflow-id wf-id}) cat-id2 (test-helpers/create-catalogue-item! {:form-id form-id2 :workflow-id wf-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id cat-id2] :actor user-id})] (testing "set value of optional field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"}]}) (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id2 :field "opt2" :value "opt"}]})))) (testing "can't submit without required field" (is (= {:success false :errors [{:form-id form-id :field-id "req1" :type "t.form.validation/required"} {:form-id form-id2 :field-id "req2" :type "t.form.validation/required"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "set value of required field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"}]})))) (testing "can't set value of text field to JSON" (is (= {:success false :errors [{:form-id form-id :field-id "req1" :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "req1" :value [[{:column "foo" :value "bar"}]]}]})))) (testing "can set value of table field to JSON" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "table" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "col2" :value "bar"}]]}]}))) (is (= [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "col2" :value "bar"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 1 :form/fields 2 :field/value])))) (testing "column name validation for table fields" (is (= {:success false :errors [{:type "t.form.validation/invalid-value", :form-id form-id2, :field-id "table"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "table" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "foo"} {:column "colx" :value "bar"}]]}]})))) (testing "save-draft fails with non-existing value of option list" (is (= {:success false :errors [{:field-id "optionlist", :form-id form-id2, :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "optionlist" :value "foobar"}]})))) (testing "set existing value of option list" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt1" :value "opt"} {:form form-id :field "req1" :value "req"} {:form form-id2 :field "opt2" :value "opt"} {:form form-id2 :field "req2" :value "req"} {:form form-id2 :field "optionlist" :value "Option2"}]})))) (testing "can submit with required field" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))))) (deftest test-table ;; Adding the table field required changes to many API schemas since ;; the table values aren't just plain strings (like the values for ;; other fields). This test is mostly here to verify table values ;; work everywhere in the API. ;; ;; Table validations are mostly tested in test-application-validation (let [form-id (test-helpers/create-form! {:form/fields [{:field/id "opt" :field/type :table :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}]} {:field/id "req" :field/type :table :field/title {:en "required table" :fi "table" :sv "table"} :field/optional false :field/columns [{:key "foo" :label {:en "foo" :fi "foo" :sv "foo"}} {:key "bar" :label {:en "bar" :fi "bar" :sv "bar"}} {:key "xyz" :label {:en "xyz" :fi "xyz" :sv "xyz"}}]}]}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) user-id "alice" app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id})] (testing "default values" (let [app (get-application-for-user app-id user-id)] (is (= [] (get-in app [:application/forms 0 :form/fields 0 :field/value]))) (is (= [] (get-in app [:application/forms 0 :form/fields 1 :field/value]))))) (testing "save a draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value []}]}))) (is (= [{:field/id "opt" :field/type "table" :field/title {:en "table" :fi "table" :sv "table"} :field/optional true :field/visible true :field/private false :field/columns [{:key "col1" :label {:en "col1" :fi "col1" :sv "col1"}} {:key "col2" :label {:en "col2" :fi "col2" :sv "col2"}}] :field/value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:field/id "req" :field/type "table" :field/title {:en "required table" :fi "table" :sv "table"} :field/optional false :field/visible true :field/private false :field/columns [{:key "foo" :label {:en "foo" :fi "foo" :sv "foo"}} {:key "bar" :label {:en "bar" :fi "bar" :sv "bar"}} {:key "xyz" :label {:en "xyz" :fi "xyz" :sv "xyz"}}] :field/value []}] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields])))) (testing "can't submit no rows in required table" (is (= {:success false :errors [{:type "t.form.validation/required" :form-id form-id :field-id "req"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "save a new draft" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value ""} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]]}]}))) (is (= [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/value])))) (testing "can't submit with empty column values" (is (= {:success false :errors [{:type "t.form.validation/column-values-missing" :form-id form-id :field-id "opt"}]} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "can submit with all columns set" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "opt" :value [[{:column "col1" :value "1"} {:column "col2" :value "2"}] [{:column "col1" :value "1"} {:column "col2" :value "2"}]]} {:form form-id :field "req" :value [[{:column "foo" :value "f"} {:column "bar" :value "b"} {:column "xyz" :value "x"}]]}]}))) (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "can return" (is (= {:success true} (send-command "developer" {:type :application.command/return :application-id app-id}))) (is (= [[{:value "f" :column "foo"} {:value "b" :column "bar"} {:value "x" :column "xyz"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/value]))) (is (= [[{:value "f" :column "foo"} {:value "b" :column "bar"} {:value "x" :column "xyz"}]] (get-in (get-application-for-user app-id user-id) [:application/forms 0 :form/fields 1 :field/previous-value])))))) (deftest test-decider-workflow (let [applicant "PI:NAME:<NAME>END_PI" handler "handler" decider "PI:NAME:<NAME>END_PI" wf-id (test-helpers/create-workflow! {:type :workflow/decider :handlers [handler]}) cat-id (test-helpers/create-catalogue-item! {:workflow-id wf-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant})] (testing "applicant's commands for draft" (is (= #{"application.command/accept-licenses" "application.command/change-resources" "application.command/copy-as-new" "application.command/delete" "application.command/invite-member" "application.command/remove-member" "application.command/save-draft" "application.command/submit" "application.command/uninvite-member"} (set (:application/permissions (get-application-for-user app-id applicant)))))) (testing "submit" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "applicant's commands after submit" (is (= #{"application.command/accept-licenses" "application.command/copy-as-new" "application.command/remove-member" "application.command/uninvite-member"} (set (:application/permissions (get-application-for-user app-id applicant)))))) (testing "handler's commands" (is (= #{"application.command/add-licenses" "application.command/add-member" "application.command/assign-external-id" "application.command/change-resources" "application.command/close" "application.command/invite-reviewer" "application.command/invite-member" "application.command/remark" "application.command/remove-member" "application.command/request-decision" "application.command/request-review" "application.command/return" "application.command/uninvite-member" "see-everything"} (set (:application/permissions (get-application-for-user app-id handler)))))) (testing "request decision" (is (= {:success true} (send-command handler {:type :application.command/request-decision :application-id app-id :deciders [decider] :comment ""})))) (testing "decider's commands" (is (= #{"application.command/approve" "application.command/reject" "application.command/remark" "see-everything"} (set (:application/permissions (get-application-for-user app-id decider)))))) (testing "approve" (is (= {:success true} (send-command decider {:type :application.command/approve :application-id app-id :comment ""})))))) (deftest test-revoke (let [applicant-id "alice" member-id "malice" handler-id "handler" wfid (test-helpers/create-workflow! {:handlers [handler-id]}) formid (test-helpers/create-form! {}) ext1 "revoke-test-resource-1" ext2 "revoke-test-resource-2" res1 (test-helpers/create-resource! {:resource-ext-id ext1}) res2 (test-helpers/create-resource! {:resource-ext-id ext2}) cat1 (test-helpers/create-catalogue-item! {:workflow-id wfid :form-id formid :resource-id res1}) cat2 (test-helpers/create-catalogue-item! {:workflow-id wfid :form-id formid :resource-id res2}) app-id (test-helpers/create-application! {:actor applicant-id :catalogue-item-ids [cat1 cat2]})] (testing "set up application with multiple resources and members" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id}))) (is (= {:success true} (send-command handler-id {:type :application.command/add-member :application-id app-id :member {:userid member-id}}))) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id app-id :comment ""})))) (testing "entitlements are present" (is (= #{{:end nil :resid ext1 :userid applicant-id} {:end nil :resid ext2 :userid applicant-id} {:end nil :resid ext1 :userid member-id} {:end nil :resid ext2 :userid member-id}} (set (map #(select-keys % [:end :resid :userid]) (db/get-entitlements {:application app-id})))))) (testing "users are not blacklisted" (is (not (blacklist/blacklisted? applicant-id ext1))) (is (not (blacklist/blacklisted? applicant-id ext2))) (is (not (blacklist/blacklisted? member-id ext1))) (is (not (blacklist/blacklisted? member-id ext2)))) (testing "revoke application" (is (= {:success true} (send-command handler-id {:type :application.command/revoke :application-id app-id :comment "bad"})))) (testing "entitlements end" (is (every? :end (db/get-entitlements {:application app-id})))) (testing "users are blacklisted" (is (blacklist/blacklisted? applicant-id ext1)) (is (blacklist/blacklisted? applicant-id ext2)) (is (blacklist/blacklisted? member-id ext1)) (is (blacklist/blacklisted? member-id ext2))))) (deftest test-hiding-sensitive-information (let [applicant-id "alice" member-id "developer" handler-id "handler" api-key "PI:KEY:<KEY>END_PI" wfid (test-helpers/create-workflow! {:handlers [handler-id]}) cat1 (test-helpers/create-catalogue-item! {:workflow-id wfid}) ;; TODO blacklist? app-id (test-helpers/create-application! {:actor applicant-id :catalogue-item-ids [cat1]})] (testing "set up approved application with multiple members" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id}))) (is (= {:success true} (send-command handler-id {:type :application.command/add-member :application-id app-id :member {:userid member-id}}))) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id app-id :comment ""})))) (testing "handler can see extra user attributes" (let [application (api-call :get (str "/api/applications/" app-id) nil api-key handler-id)] (is (= {:userid "alice" :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :organizations [{:organization/id "default"}] :nickname "In Wonderland" :researcher-status-by "so"} (:application/applicant application) (get-in application [:application/events 0 :event/actor-attributes]))) (is (= {:userid "developer" :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :nickname "The Dev"} (first (:application/members application)) (get-in application [:application/events 2 :application/member]))))) (doseq [user [applicant-id member-id]] (testing (str user " can't see extra user attributes") (let [application (api-call :get (str "/api/applications/" app-id) nil api-key user)] (is (= {:userid "alice" :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :organizations [{:organization/id "default"}]} (:application/applicant application) (get-in application [:application/events 0 :event/actor-attributes]))) (is (= {:userid "developer" :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} (first (:application/members application)) (get-in application [:application/events 2 :application/member])))))))) (deftest test-application-export (let [applicant "alice" handler "handler" reporter "reporter" api-key "PI:KEY:<KEY>END_PI" wf-id (test-helpers/create-workflow! {:type :workflow/default :handlers [handler]}) form-id (test-helpers/create-form! {:form/fields [{:field/id "fld1" :field/type :text :field/title {:en "Field 1" :fi "Field 1" :sv "Field 1"} :field/optional false}]}) form-2-id (test-helpers/create-form! {:form/fields [{:field/id "fld2" :field/type :text :field/title {:en "HIDDEN" :fi "HIDDEN" :sv "HIDDEN"} :field/optional false}]}) cat-id (test-helpers/create-catalogue-item! {:title {:en "Item1"} :workflow-id wf-id :form-id form-id}) cat-2-id (test-helpers/create-catalogue-item! {:title {:en "Item2"} :workflow-id wf-id :form-id form-2-id}) app-id (test-helpers/create-draft! applicant [cat-id] "Answer1") _draft-app-id (test-helpers/create-draft! applicant [cat-id] "DraftAnswer") app-2-id (test-helpers/create-draft! applicant [cat-id cat-2-id] "Answer2")] (send-command applicant {:type :application.command/submit :application-id app-id}) (send-command applicant {:type :application.command/submit :application-id app-2-id}) (testing "reporter can export" (let [exported (api-call :get (str "/api/applications/export?form-id=" form-id) nil api-key reporter) [_header & lines] (str/split-lines exported)] (is (str/includes? exported "Field 1") exported) (is (not (str/includes? exported "HIDDEN")) exported) (testing "drafts are not visible" (is (not (str/includes? exported "DraftAnswer")))) (testing "submitted applications are visible" (is (= 2 (count lines))) (is (some #(str/includes? % "\"Item1\",\"Answer1\"") lines) lines) (is (some #(str/includes? % "\"Item1, Item2\",\"Answer2\"") lines) lines)))) (testing "handler can't export" (is (response-is-forbidden? (api-response :get (str "/api/applications/export?form-id=" form-id) nil api-key handler)))))) (def testfile (io/file "./test-data/test.txt")) (def malicious-file (io/file "./test-data/malicious_test.html")) (def filecontent {:tempfile testfile :content-type "text/plain" :filename "test.txt" :size (.length testfile)}) (def malicious-content {:tempfile malicious-file :content-type "text/html" :filename "malicious_test.html" :size (.length malicious-file)}) (deftest test-application-api-attachments (let [api-key "PI:KEY:<KEY>END_PI" user-id "alice" handler-id "developer" ;; developer is the default handler in test-helpers form-id (test-helpers/create-form! {:form/fields [{:field/id "attach" :field/title {:en "some attachment" :fi "joku liite" :sv "bilaga"} :field/type :attachment :field/optional true}]}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor user-id}) upload-request (fn [file] (-> (request :post (str "/api/applications/add-attachment?application-id=" app-id)) (assoc :params {"file" file}) (assoc :multipart-params {"file" file}))) read-request #(request :get (str "/api/applications/attachment/" %))] (testing "uploading malicious file for a draft" (let [response (-> (upload-request malicious-content) (authenticate api-key user-id) handler)] (is (response-is-unsupported-media-type? response)))) (testing "uploading attachment for a draft as handler" (let [response (-> (upload-request filecontent) (authenticate api-key handler-id) handler)] (is (response-is-forbidden? response)))) (testing "invalid value for attachment field" (is (= {:success false :errors [{:form-id form-id :field-id "attach" :type "t.form.validation/invalid-value"}]} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach" :value "1,a"}]})))) (testing "uploading attachment for a draft" (let [body (-> (upload-request filecontent) (authenticate api-key user-id) handler read-ok-body) id (:id body)] (is (:success body)) (is (number? id)) (testing "and retrieving it as the applicant" (let [response (-> (read-request id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))) (testing "and uploading an attachment with the same name" (let [id (-> (upload-request filecontent) (authenticate api-key user-id) handler read-ok-body :id)] (is (number? id)) (testing "and retrieving it" (let [response (-> (read-request id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test (1).txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))))) (testing "and retrieving it as non-applicant" (let [response (-> (read-request id) (authenticate api-key "PI:NAME:<NAME>END_PI") handler)] (is (response-is-forbidden? response)))) (testing "and uploading a second attachment" (let [body2 (-> (upload-request (assoc filecontent :filename "second.txt")) (authenticate api-key user-id) handler read-ok-body) id2 (:id body2)] (is (:success body2)) (is (number? id2)) (testing "and using them in a field" (is (= {:success true} (send-command user-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach" :value (str id "," id2)}]})))) (testing "and submitting" (is (= {:success true} (send-command user-id {:type :application.command/submit :application-id app-id})))) (testing "and accessing the attachments as handler" (let [response (-> (read-request id) (authenticate api-key handler-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))) (let [response (-> (read-request id2) (authenticate api-key handler-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"second.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response)))))) (testing "and copying the application" (let [response (send-command user-id {:type :application.command/copy-as-new :application-id app-id}) new-app-id (:application-id response)] (is (:success response)) (is (number? new-app-id)) (testing "and fetching the copied attachent" (let [new-app (get-application-for-user new-app-id user-id) [new-id new-id2] (mapv :attachment/id (get new-app :application/attachments))] (is (number? new-id)) (is (number? new-id2)) (is (not= #{id id2} #{new-id new-id2})) (let [response (-> (read-request new-id) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"test.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))) (let [response (-> (read-request new-id2) (authenticate api-key user-id) handler assert-response-is-ok)] (is (= "attachment;filename=\"second.txt\"" (get-in response [:headers "Content-Disposition"]))) (is (= (slurp testfile) (slurp (:body response))))))))))))) (testing "retrieving nonexistent attachment" (let [response (-> (read-request 999999999999999) (authenticate api-key "PI:NAME:<NAME>END_PI") handler)] (is (response-is-not-found? response)))) (testing "uploading attachment for nonexistent application" (let [response (-> (request :post "/api/applications/add-attachment?application-id=99999999") (assoc :params {"file" filecontent}) (assoc :multipart-params {"file" filecontent}) (authenticate api-key user-id) handler)] (is (response-is-forbidden? response)))) (testing "uploading attachment without authentication" (let [response (-> (upload-request filecontent) handler)] (is (response-is-unauthorized? response)))) (testing "uploading attachment with wrong API key" (let [response (-> (upload-request filecontent) (authenticate api-key user-id) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler)] (is (response-is-unauthorized? response)))) (testing "uploading attachment as non-applicant" (let [response (-> (upload-request filecontent) (authenticate api-key "PI:NAME:<NAME>END_PI") handler)] (is (response-is-forbidden? response)))))) (deftest test-application-comment-attachments (let [api-key "PI:KEY:<KEY>END_PI" applicant-id "PI:NAME:<NAME>END_PI" handler-id "developer" reviewer-id "carPI:NAME:<NAME>END_PI" file #(assoc filecontent :filename %) workflow-id (test-helpers/create-workflow! {:type :workflow/master :handlers [handler-id]}) cat-item-id (test-helpers/create-catalogue-item! {:workflow-id workflow-id}) application-id (test-helpers/create-application! {:catalogue-item-ids [cat-item-id] :actor applicant-id}) add-attachment #(-> (request :post (str "/api/applications/add-attachment?application-id=" application-id)) (authenticate api-key %1) (assoc :params {"file" %2}) (assoc :multipart-params {"file" %2}) handler read-ok-body :id)] (testing "submit" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id application-id})))) (testing "unrelated user can't upload attachment" (is (response-is-forbidden? (-> (request :post (str "/api/applications/add-attachment?application-id=" application-id)) (authenticate api-key reviewer-id) (assoc :params {"file" filecontent}) (assoc :multipart-params {"file" filecontent}) handler)))) (testing "invite reviewer" (is (= {:success true} (send-command handler-id {:type :application.command/request-review :application-id application-id :reviewers [reviewer-id] :comment "please"})))) (testing "handler uploads an attachment" (let [attachment-id (add-attachment handler-id (file "handler-public-remark.txt"))] (is (number? attachment-id)) (testing "and attaches it to a public remark" (is (= {:success true} (send-command handler-id {:type :application.command/remark :application-id application-id :comment "see attachment" :public true :attachments [{:attachment/id attachment-id}]})))))) (testing "applicant can see attachment" (let [app (get-application-for-user application-id applicant-id) remark-event (last (:application/events app)) attachment-id (:attachment/id (first (:event/attachments remark-event)))] (is (number? attachment-id)) (testing "and fetch it" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id) assert-response-is-ok :body slurp)))))) (testing "reviewer uploads an attachment" (let [attachment-id (add-attachment reviewer-id (file "reviewer-review.txt"))] (is (number? attachment-id)) (testing ", handler can't use the attachment" (is (= {:success false :errors [{:type "invalid-attachments" :attachments [attachment-id]}]} (send-command handler-id {:type :application.command/remark :public false :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]})))) (testing ", attaches it to a review" (is (= {:success true} (send-command reviewer-id {:type :application.command/review :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))) (testing ", handler can fetch attachment" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key handler-id) assert-response-is-ok :body slurp)))) (testing ", applicant can't fetch attachment" (is (response-is-forbidden? (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id))))))) (testing "handler makes a private remark" (let [attachment-id (add-attachment handler-id (file "handler-private-remark.txt"))] (is (number? attachment-id)) (is (= {:success true} (send-command handler-id {:type :application.command/remark :public false :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))) (testing ", handler can fetch attachment" (is (= (slurp testfile) (-> (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key handler-id) assert-response-is-ok :body slurp)))) (testing ", applicant can't fetch attachment" (is (response-is-forbidden? (api-response :get (str "/api/applications/attachment/" attachment-id) nil api-key applicant-id)))))) (testing "handler approves with attachment" (let [attachment-id (add-attachment handler-id (file "handler-approve.txt"))] (is (number? attachment-id)) (is (= {:success true} (send-command handler-id {:type :application.command/approve :application-id application-id :comment "see attachment" :attachments [{:attachment/id attachment-id}]}))))) (testing "handler closes with two attachments (with the same name)" (let [id1 (add-attachment handler-id (file "handler-close.txt")) id2 (add-attachment handler-id (file "handler-close.txt"))] (is (number? id1)) (is (number? id2)) (is (= {:success true} (send-command handler-id {:type :application.command/close :application-id application-id :comment "see attachment" :attachments [{:attachment/id id1} {:attachment/id id2}]}))))) (testing "applicant can see the three new attachments" (let [app (get-application-for-user application-id applicant-id) [close-event approve-event] (reverse (:application/events app)) [close-id1 close-id2] (map :attachment/id (:event/attachments close-event)) [approve-id] (map :attachment/id (:event/attachments approve-event))] (is (= "application.event/closed" (:event/type close-event))) (is (= "application.event/approved" (:event/type approve-event))) (is (number? close-id1)) (is (number? close-id2)) (is (number? approve-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" close-id1) nil api-key handler-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" close-id2) nil api-key handler-id)) (assert-response-is-ok (api-response :get (str "/api/applications/attachment/" approve-id) nil api-key handler-id)))) (testing ":application/attachments" (testing "applicant" (is (= ["handler-public-remark.txt" "handler-approve.txt" "handler-close.txt" "handler-close (1).txt"] (mapv :attachment/filename (:application/attachments (get-application-for-user application-id applicant-id)))))) (testing "handler" (is (= ["handler-public-remark.txt" "reviewer-review.txt" "handler-private-remark.txt" "handler-approve.txt" "handler-close.txt" "handler-close (1).txt"] (mapv :attachment/filename (:application/attachments (get-application-for-user application-id handler-id))))))))) (deftest test-application-attachment-zip (let [api-key "PI:KEY:<KEY>END_PI" applicant-id "alice" handler-id "handler" reporter-id "reporter" workflow-id (test-helpers/create-workflow! {:handlers [handler-id]}) form-id (test-helpers/create-form! {:form/fields [{:field/id "attach1" :field/title {:en "some attachment" :fi "joku liite" :sv "bilaga"} :field/type :attachment :field/optional true} {:field/id "attach2" :field/title {:en "another attachment" :fi "toinen liite" :sv "annan bilaga"} :field/type :attachment :field/optional true}]}) cat-id (test-helpers/create-catalogue-item! {:workflow-id workflow-id :form-id form-id}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant-id}) add-attachment (fn [user file] (-> (request :post (str "/api/applications/add-attachment?application-id=" app-id)) (authenticate api-key user) (assoc :params {"file" file}) (assoc :multipart-params {"file" file}) handler read-ok-body :id)) file #(assoc filecontent :filename %) fetch-zip (fn [user-id] (with-open [zip (-> (api-response :get (str "/api/applications/" app-id "/attachments") nil api-key user-id) :body ZipInputStream.)] (loop [files {}] (if-let [entry (.getNextEntry zip)] (let [buf (ByteArrayOutputStream.)] (io/copy zip buf) (recur (assoc files (.getName entry) (.toString buf "UTF-8")))) files))))] (testing "save a draft" (let [id (add-attachment applicant-id (file "invisible.txt"))] (is (= {:success true} (send-command applicant-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach1" :value (str id)}]}))))) (testing "save a new draft" (let [blue-id (add-attachment applicant-id (file "blue.txt")) green-id (add-attachment applicant-id (file "green.txt")) red-id (add-attachment applicant-id (file "red.txt"))] (is (= {:success true} (send-command applicant-id {:type :application.command/save-draft :application-id app-id :field-values [{:form form-id :field "attach1" :value (str blue-id "," green-id)} {:form form-id :field "attach2" :value (str red-id)}]}))))) (testing "fetch zip as applicant" (is (= {"blue.txt" (slurp testfile) "red.txt" (slurp testfile) "green.txt" (slurp testfile)} (fetch-zip applicant-id)))) (testing "submit" (is (= {:success true} (send-command applicant-id {:type :application.command/submit :application-id app-id})))) (testing "remark with attachments" (let [blue-comment-id (add-attachment handler-id (file "blue.txt")) yellow-comment-id (add-attachment handler-id (file "yellow.txt"))] (is (= {:success true} (send-command handler-id {:type :application.command/remark :public true :application-id app-id :comment "see attachment" :attachments [{:attachment/id blue-comment-id} {:attachment/id yellow-comment-id}]})))) (testing "fetch zip as applicant, handler and reporter" (is (= {"blue.txt" (slurp testfile) "red.txt" (slurp testfile) "green.txt" (slurp testfile) "blue (1).txt" (slurp testfile) "yellow.txt" (slurp testfile)} (fetch-zip applicant-id) (fetch-zip handler-id) (fetch-zip reporter-id)))) (testing "fetch zip as third party" (is (response-is-forbidden? (api-response :get (str "/api/applications/" app-id "/attachments") nil api-key "malice")))) (testing "fetch zip for nonexisting application" (is (response-is-not-found? (api-response :get "/api/applications/99999999/attachments" nil api-key "malice"))))))) (deftest test-application-api-license-attachments (let [api-key "PI:KEY:<KEY>END_PI" applicant "PI:NAME:<NAME>END_PI" non-applicant "PI:NAME:<NAME>END_PI" owner "owner" handler-user "developer" cat-id (test-helpers/create-catalogue-item! {}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant}) file-en (clojure.java.io/file "./test-data/test.txt") filecontent-en {:tempfile file-en :content-type "text/plain" :filename "test.txt" :size (.length file-en)} en-attachment-id (-> (request :post "/api/licenses/add_attachment") (assoc :params {"file" filecontent-en}) (assoc :multipart-params {"file" filecontent-en}) (authenticate api-key owner) handler read-ok-body :id) file-fi (clojure.java.io/file "./test-data/test-fi.txt") filecontent-fi {:tempfile file-fi :content-type "text/plain" :filename "test.txt" :size (.length file-fi)} fi-attachment-id (-> (request :post "/api/licenses/add_attachment") (assoc :params {"file" filecontent-fi}) (assoc :multipart-params {"file" filecontent-fi}) (authenticate api-key owner) handler read-ok-body :id) license-id (-> (request :post "/api/licenses/create") (authenticate api-key owner) (json-body {:licensetype "attachment" :organization {:organization/id "abc"} ;; TODO different content for different languages :localizations {:en {:title "en title" :textcontent "en text" :attachment-id en-attachment-id} :fi {:title "fi title" :textcontent "fi text" :attachment-id fi-attachment-id}}}) handler read-ok-body :id)] (testing "submit application" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id})))) (testing "attach license to application" (is (= {:success true} (send-command handler-user {:type :application.command/add-licenses :application-id app-id :comment "" :licenses [license-id]})))) (testing "access license" (testing "as applicant" (is (= "hello from file\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key applicant) handler assert-response-is-ok :body slurp))) (testing "in finnish" (is (= "tervehdys tiedostosta\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/fi")) (authenticate api-key applicant) handler assert-response-is-ok :body slurp))))) (testing "as handler" (is (= "hello from file\n" (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key handler-user) handler assert-response-is-ok :body slurp)))) (testing "as non-applicant" (is (response-is-forbidden? (-> (request :get (str "/api/applications/" app-id "/license-attachment/" license-id "/en")) (authenticate api-key non-applicant) handler))))))) (deftest test-applications-api-security (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" cat-id (test-helpers/create-catalogue-item! {}) app-id (test-helpers/create-application! {:catalogue-item-ids [cat-id] :actor applicant})] (testing "fetch application without authentication" (let [req (request :get (str "/api/applications/" app-id))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "fetch nonexistent application" (let [response (-> (request :get "/api/applications/9999999999") (authenticate api-key applicant) handler)] (is (response-is-not-found? response)) (is (= "application/json" (get-in response [:headers "Content-Type"]))) (is (= {:error "not found"} (read-body response))))) (testing "fetch deciders without authentication or as non-handler" (let [req (request :get "/api/applications/deciders")] (assert-response-is-ok (-> req (authenticate api-key "developer") handler)) (is (response-is-forbidden? (-> req (authenticate api-key applicant) handler))) (is (response-is-unauthorized? (-> req handler))))) (testing "create without authentication" (let [req (-> (request :post "/api/applications/create") (json-body {:catalogue-item-ids [cat-id]}))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "create with wrong API key" (let [req (-> (request :post "/api/applications/create") (authenticate api-key applicant) (json-body {:catalogue-item-ids [cat-id]}))] (assert-response-is-ok (-> req handler)) (is (response-is-unauthorized? (-> req (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler))))) (testing "send command without authentication" (let [req (-> (request :post "/api/applications/submit") (json-body {:application-id app-id}))] (assert-response-is-ok (-> req (authenticate api-key applicant) handler)) (is (response-is-unauthorized? (-> req handler))))) (testing "send command with wrong API key" (let [req (-> (request :post "/api/applications/submit") (authenticate api-key applicant) (json-body {:application-id app-id}))] (assert-response-is-ok (-> req handler)) (is (response-is-unauthorized? (-> req (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") handler))))))) (deftest test-application-listing (let [app-id (test-helpers/create-application! {:actor "alice"})] (testing "list user applications" (is (contains? (get-ids (get-my-applications "alice")) app-id))) (testing "search user applications" (is (contains? (get-ids (get-my-applications "alice" {:query "applicant:alice"})) app-id)) (is (empty? (get-ids (get-my-applications "alice" {:query "applicant:no-such-user"}))))) (testing "list all applications" (is (contains? (get-ids (get-all-applications "alice")) app-id))) (testing "search all applications" (is (contains? (get-ids (get-all-applications "alice" {:query "applicant:alice"})) app-id)) (is (empty? (get-ids (get-all-applications "alice" {:query "applicant:no-such-user"}))))))) (deftest test-todos (let [applicant "alice" handler "developer" reviewer "reviewer" decider "decider" app-id (test-helpers/create-application! {:actor applicant})] (test-helpers/create-user! {:eppn reviewer}) (test-helpers/create-user! {:eppn decider}) (testing "does not list drafts" (is (not (contains? (get-ids (get-todos handler)) app-id)))) (testing "lists submitted in todos" (is (= {:success true} (send-command applicant {:type :application.command/submit :application-id app-id}))) (is (contains? (get-ids (get-todos handler)) app-id)) (is (not (contains? (get-ids (get-handled-todos handler)) app-id)))) (testing "search todos" (is (contains? (get-ids (get-todos handler {:query (str "applicant:" applicant)})) app-id)) (is (empty? (get-ids (get-todos handler {:query "applicant:no-such-user"}))))) (testing "reviewer sees application in todos" (is (not (contains? (get-ids (get-todos reviewer)) app-id))) (is (= {:success true} (send-command handler {:type :application.command/request-review :application-id app-id :reviewers [reviewer] :comment "x"}))) (is (contains? (get-ids (get-todos reviewer)) app-id)) (is (not (contains? (get-ids (get-handled-todos reviewer)) app-id)))) (testing "decider sees application in todos" (is (not (contains? (get-ids (get-todos decider)) app-id))) (is (= {:success true} (send-command handler {:type :application.command/request-decision :application-id app-id :deciders [decider] :comment "x"}))) (is (contains? (get-ids (get-todos decider)) app-id)) (is (not (contains? (get-ids (get-handled-todos decider)) app-id)))) (testing "lists handled in handled" (is (= {:success true} (send-command handler {:type :application.command/approve :application-id app-id :comment ""}))) (is (not (contains? (get-ids (get-todos handler)) app-id))) (is (contains? (get-ids (get-handled-todos handler)) app-id))) (testing "search handled todos" (is (contains? (get-ids (get-handled-todos handler {:query (str "applicant:" applicant)})) app-id)) (is (empty? (get-ids (get-handled-todos handler {:query "applicant:no-such-user"}))))) (testing "reviewer sees accepted application in handled todos" (is (not (contains? (get-ids (get-todos reviewer)) app-id))) (is (contains? (get-ids (get-handled-todos reviewer)) app-id))) (testing "decider sees accepted application in handled todos" (is (not (contains? (get-ids (get-todos decider)) app-id))) (is (contains? (get-ids (get-handled-todos decider)) app-id))))) (deftest test-application-raw (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" handler "handler" reporter "reporter" form-id (test-helpers/create-form! {:form/internal-name "notifications" :form/external-title {:en "Notifications EN" :fi "Notifications FI" :sv "Notifications SV"} :form/fields [{:field/type :text :field/id "field-1" :field/title {:en "text field" :fi "text field" :sv "text field"} :field/optional false}]}) workflow-id (test-helpers/create-workflow! {:title "wf" :handlers [handler] :type :workflow/default}) ext-id "resres" res-id (test-helpers/create-resource! {:resource-ext-id ext-id}) cat-id (test-helpers/create-catalogue-item! {:form-id form-id :resource-id res-id :workflow-id workflow-id}) app-id (test-helpers/create-draft! applicant [cat-id] "raw test" (time/date-time 2010))] (testing "applicant can't get raw application" (is (response-is-forbidden? (api-response :get (str "/api/applications/" app-id "/raw") nil api-key applicant)))) (testing "reporter can get raw application" (is (= {:application/description "" :application/invited-members [] :application/last-activity "2010-01-01T00:00:00.000Z" :application/attachments [] :application/licenses [] :application/created "2010-01-01T00:00:00.000Z" :application/state "application.state/draft" :application/role-permissions {:everyone-else ["application.command/accept-invitation"] :member ["application.command/copy-as-new" "application.command/accept-licenses"] :reporter ["see-everything"] :applicant ["application.command/copy-as-new" "application.command/invite-member" "application.command/submit" "application.command/remove-member" "application.command/accept-licenses" "application.command/uninvite-member" "application.command/delete" "application.command/save-draft" "application.command/change-resources"]} :application/modified "2010-01-01T00:00:00.000Z" :application/user-roles {:alice ["applicant"] :handler ["handler"] :reporter ["reporter"]} :application/external-id "2010/1" :application/generated-external-id "2010/1" :application/workflow {:workflow/type "workflow/default" :workflow/id workflow-id :workflow.dynamic/handlers [{:email "PI:EMAIL:<EMAIL>END_PI" :userid "handler" :name "PI:NAME:<NAME>END_PI"}]} :application/blacklist [] :application/id app-id :application/todo nil :application/applicant {:email "PI:EMAIL:<EMAIL>END_PI" :userid "alice" :name "PI:NAME:<NAME>END_PI" :nickname "In Wonderland" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/members [] :application/resources [{:catalogue-item/start "REDACTED" :catalogue-item/end nil :catalogue-item/expired false :catalogue-item/enabled true :resource/id res-id :catalogue-item/title {} :catalogue-item/infourl {} :resource/ext-id ext-id :catalogue-item/archived false :catalogue-item/id cat-id}] :application/accepted-licenses {:alice []} :application/forms [{:form/fields [{:field/value "raw test" :field/type "text" :field/title {:en "text field" :fi "text field" :sv "text field"} :field/id "field-1" :field/optional false :field/visible true :field/private false}] :form/title "notifications" ; deprecated :form/internal-name "notifications" :form/external-title {:en "Notifications EN" :fi "Notifications FI" :sv "Notifications SV"} :form/id form-id}] :application/events [{:application/external-id "2010/1" :event/actor-attributes {:userid "alice" :name "PI:NAME:<NAME>END_PI" :nickname "In Wonderland" :email "PI:EMAIL:<EMAIL>END_PI" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/id app-id :event/time "2010-01-01T00:00:00.000Z" :workflow/type "workflow/default" :application/resources [{:catalogue-item/id cat-id :resource/ext-id ext-id}] :application/forms [{:form/id form-id}] :workflow/id workflow-id :event/actor "PI:NAME:<NAME>END_PI" :event/type "application.event/created" :event/id 100 :application/licenses []} {:event/id 100 :event/type "application.event/draft-saved" :event/time "2010-01-01T00:00:00.000Z" :event/actor "PI:NAME:<NAME>END_PI" :application/id app-id :event/actor-attributes {:userid "alice" :name "PI:NAME:<NAME>END_PI" :nickname "In Wonderland" :email "PI:EMAIL:<EMAIL>END_PI" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/field-values [{:form form-id :field "field-1" :value "raw test"}]} {:event/id 100 :event/type "application.event/licenses-accepted" :event/time "2010-01-01T00:00:00.000Z" :event/actor "PI:NAME:<NAME>END_PI" :application/id app-id :event/actor-attributes {:userid "alice" :name "PI:NAME:<NAME>END_PI" :nickname "In Wonderland" :email "PI:EMAIL:<EMAIL>END_PI" :organizations [{:organization/id "default"}] :researcher-status-by "so"} :application/accepted-licenses []}]} (-> (api-call :get (str "/api/applications/" app-id "/raw") nil api-key reporter) ;; start is set by the db not easy to mock (assoc-in [:application/resources 0 :catalogue-item/start] "REDACTED") ;; event ids are unpredictable (update :application/events (partial map #(update % :event/id (constantly 100))))))))))
[ { "context": "urity tokens,\n and related secrets.\"\n {:author \"Isaak Uchakaev\"\n :last-update-date \"19-10-2021\"}\n (:import (o", "end": 241, "score": 0.9998928308486938, "start": 227, "tag": "NAME", "value": "Isaak Uchakaev" } ]
src/secrets/core.clj
lk-geimfari/secrets.clj
66
(ns secrets.core "The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets." {:author "Isaak Uchakaev" :last-update-date "19-10-2021"} (:import (org.apache.commons.codec.binary Base64 Hex) (java.security SecureRandom))) (def ^:private default-number-of-bytes 32) (def ^:private secure-random "Creates a secure random number generator (RNG)." (SecureRandom.)) (defn- get-random-bytes "Returns a random byte array of the specified size." [nbytes] (let [bytes (byte-array nbytes)] (.nextBytes secure-random bytes) bytes)) (defn token-bytes "Return a random byte string containing nbytes number of bytes. If nbytes is nil or not supplied, a reasonable default is used." ([] (get-random-bytes default-number-of-bytes)) ([nbytes] (get-random-bytes nbytes))) (defn token-hex "Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is nil or not supplied, a reasonable default is used ('default-nbytes')." ([] (token-hex default-number-of-bytes)) ([nbytes] (-> nbytes (get-random-bytes) (Hex/encodeHexString)))) (defn token-urlsafe "Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is nil or not supplied, a reasonable default is used ('default-nbytes')." ([] (token-urlsafe default-number-of-bytes)) ([nbytes] (-> nbytes (get-random-bytes) (Base64/encodeBase64URLSafeString)))) (defn randbelow "Return a random int in the range [0, n)." [n] (.nextInt secure-random n)) (defn choice "Return a randomly-chosen element from a non-empty coll." [collection] (when (empty? collection) (throw (Exception. "Cannot choose from an empty sequence"))) (nth collection (randbelow (count collection)))) (defn choices "Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises an exception." [population k] (repeatedly k #(choice population)))
99213
(ns secrets.core "The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets." {:author "<NAME>" :last-update-date "19-10-2021"} (:import (org.apache.commons.codec.binary Base64 Hex) (java.security SecureRandom))) (def ^:private default-number-of-bytes 32) (def ^:private secure-random "Creates a secure random number generator (RNG)." (SecureRandom.)) (defn- get-random-bytes "Returns a random byte array of the specified size." [nbytes] (let [bytes (byte-array nbytes)] (.nextBytes secure-random bytes) bytes)) (defn token-bytes "Return a random byte string containing nbytes number of bytes. If nbytes is nil or not supplied, a reasonable default is used." ([] (get-random-bytes default-number-of-bytes)) ([nbytes] (get-random-bytes nbytes))) (defn token-hex "Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is nil or not supplied, a reasonable default is used ('default-nbytes')." ([] (token-hex default-number-of-bytes)) ([nbytes] (-> nbytes (get-random-bytes) (Hex/encodeHexString)))) (defn token-urlsafe "Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is nil or not supplied, a reasonable default is used ('default-nbytes')." ([] (token-urlsafe default-number-of-bytes)) ([nbytes] (-> nbytes (get-random-bytes) (Base64/encodeBase64URLSafeString)))) (defn randbelow "Return a random int in the range [0, n)." [n] (.nextInt secure-random n)) (defn choice "Return a randomly-chosen element from a non-empty coll." [collection] (when (empty? collection) (throw (Exception. "Cannot choose from an empty sequence"))) (nth collection (randbelow (count collection)))) (defn choices "Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises an exception." [population k] (repeatedly k #(choice population)))
true
(ns secrets.core "The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets." {:author "PI:NAME:<NAME>END_PI" :last-update-date "19-10-2021"} (:import (org.apache.commons.codec.binary Base64 Hex) (java.security SecureRandom))) (def ^:private default-number-of-bytes 32) (def ^:private secure-random "Creates a secure random number generator (RNG)." (SecureRandom.)) (defn- get-random-bytes "Returns a random byte array of the specified size." [nbytes] (let [bytes (byte-array nbytes)] (.nextBytes secure-random bytes) bytes)) (defn token-bytes "Return a random byte string containing nbytes number of bytes. If nbytes is nil or not supplied, a reasonable default is used." ([] (get-random-bytes default-number-of-bytes)) ([nbytes] (get-random-bytes nbytes))) (defn token-hex "Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is nil or not supplied, a reasonable default is used ('default-nbytes')." ([] (token-hex default-number-of-bytes)) ([nbytes] (-> nbytes (get-random-bytes) (Hex/encodeHexString)))) (defn token-urlsafe "Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is nil or not supplied, a reasonable default is used ('default-nbytes')." ([] (token-urlsafe default-number-of-bytes)) ([nbytes] (-> nbytes (get-random-bytes) (Base64/encodeBase64URLSafeString)))) (defn randbelow "Return a random int in the range [0, n)." [n] (.nextInt secure-random n)) (defn choice "Return a randomly-chosen element from a non-empty coll." [collection] (when (empty? collection) (throw (Exception. "Cannot choose from an empty sequence"))) (nth collection (randbelow (count collection)))) (defn choices "Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises an exception." [population k] (repeatedly k #(choice population)))
[ { "context": "s/\" id \"/people\")\n {:params {:name name}\n :format :json\n :respon", "end": 426, "score": 0.9859796166419983, "start": 422, "tag": "NAME", "value": "name" } ]
src/cljs/avalon/pages/home.cljs
baritonehands/avalon
5
(ns avalon.pages.home (:require [ajax.core :refer [POST]] [reagent.core :as r] [avalon.utils :refer [row col show-error make-styles]] [avalon.pages.games :as games] [accountant.core :as route] [material-ui :as ui] [reagent.session :as session])) (defn join-game! [id name] (POST (str "/api/games/" id "/people") {:params {:name name} :format :json :response-format :json :keywords? true :handler (fn [resp] (session/put! :person-id (:id resp)) (games/get-game! id :force true) (route/navigate! (str "/games/" id "/play/" (:id resp)))) :error-handler (fn [{:keys [response]}] (show-error "Unable to join game" (-> response first second first)))})) (def use-styles (make-styles (fn [^Theme theme] {:header {:padding (.spacing theme 2)}}))) (defn header [] (let [classes (use-styles)] (r/as-element [:> ui/Typography {:variant "h5" :class (:header classes)} "Welcome to Avalon!"]))) (defn button [props & children] [:> ui/Grid {:item true :xs 8} (into [:> ui/Button (merge {:variant "contained" :color "secondary" :full-width true} props)] children)]) (defn text-field [props] [:> ui/Grid {:item true :xs 8} [:> ui/TextField (merge {:full-width true} props)]]) (defn home-page [] (let [state (r/atom {:joining false}) create! (fn [_] (POST "/api/games" {:response-format :json :keywords? true :handler (fn [resp] (session/put! :game resp) (swap! state assoc :joining true :code (:id resp)))}))] (fn [] [:> ui/Grid {:container true :spacing 2} [col {:container true :justify "center"} [:> header]] [col {:container true :justify "center" :spacing 2} (if-not (:joining @state) [:<> [button {:onClick create!} "Create Game"] [button {:onClick #(swap! state assoc :joining true)} "Join Game"]] [:<> [col {:container true :justify "center"} [text-field {:placeholder "Enter an access code" :label "Access Code" :full-width true :input-props {:auto-capitalize "none" :auto-correct "off"} :default-value (:code @state) :on-change #(swap! state assoc :code (-> % .-target .-value))}]] [col {:container true :justify "center"} [text-field {:placeholder "Enter your name" :label "Your Name" :full-width true :input-props {:auto-correct "off"} :default-value (:name @state) :on-change #(swap! state assoc :name (-> % .-target .-value))}]] [button {:on-click #(join-game! (:code @state) (:name @state))} "Join"] [button {:on-click #(swap! state assoc :joining false) :color "default"} "Back"]])]])))
51366
(ns avalon.pages.home (:require [ajax.core :refer [POST]] [reagent.core :as r] [avalon.utils :refer [row col show-error make-styles]] [avalon.pages.games :as games] [accountant.core :as route] [material-ui :as ui] [reagent.session :as session])) (defn join-game! [id name] (POST (str "/api/games/" id "/people") {:params {:name <NAME>} :format :json :response-format :json :keywords? true :handler (fn [resp] (session/put! :person-id (:id resp)) (games/get-game! id :force true) (route/navigate! (str "/games/" id "/play/" (:id resp)))) :error-handler (fn [{:keys [response]}] (show-error "Unable to join game" (-> response first second first)))})) (def use-styles (make-styles (fn [^Theme theme] {:header {:padding (.spacing theme 2)}}))) (defn header [] (let [classes (use-styles)] (r/as-element [:> ui/Typography {:variant "h5" :class (:header classes)} "Welcome to Avalon!"]))) (defn button [props & children] [:> ui/Grid {:item true :xs 8} (into [:> ui/Button (merge {:variant "contained" :color "secondary" :full-width true} props)] children)]) (defn text-field [props] [:> ui/Grid {:item true :xs 8} [:> ui/TextField (merge {:full-width true} props)]]) (defn home-page [] (let [state (r/atom {:joining false}) create! (fn [_] (POST "/api/games" {:response-format :json :keywords? true :handler (fn [resp] (session/put! :game resp) (swap! state assoc :joining true :code (:id resp)))}))] (fn [] [:> ui/Grid {:container true :spacing 2} [col {:container true :justify "center"} [:> header]] [col {:container true :justify "center" :spacing 2} (if-not (:joining @state) [:<> [button {:onClick create!} "Create Game"] [button {:onClick #(swap! state assoc :joining true)} "Join Game"]] [:<> [col {:container true :justify "center"} [text-field {:placeholder "Enter an access code" :label "Access Code" :full-width true :input-props {:auto-capitalize "none" :auto-correct "off"} :default-value (:code @state) :on-change #(swap! state assoc :code (-> % .-target .-value))}]] [col {:container true :justify "center"} [text-field {:placeholder "Enter your name" :label "Your Name" :full-width true :input-props {:auto-correct "off"} :default-value (:name @state) :on-change #(swap! state assoc :name (-> % .-target .-value))}]] [button {:on-click #(join-game! (:code @state) (:name @state))} "Join"] [button {:on-click #(swap! state assoc :joining false) :color "default"} "Back"]])]])))
true
(ns avalon.pages.home (:require [ajax.core :refer [POST]] [reagent.core :as r] [avalon.utils :refer [row col show-error make-styles]] [avalon.pages.games :as games] [accountant.core :as route] [material-ui :as ui] [reagent.session :as session])) (defn join-game! [id name] (POST (str "/api/games/" id "/people") {:params {:name PI:NAME:<NAME>END_PI} :format :json :response-format :json :keywords? true :handler (fn [resp] (session/put! :person-id (:id resp)) (games/get-game! id :force true) (route/navigate! (str "/games/" id "/play/" (:id resp)))) :error-handler (fn [{:keys [response]}] (show-error "Unable to join game" (-> response first second first)))})) (def use-styles (make-styles (fn [^Theme theme] {:header {:padding (.spacing theme 2)}}))) (defn header [] (let [classes (use-styles)] (r/as-element [:> ui/Typography {:variant "h5" :class (:header classes)} "Welcome to Avalon!"]))) (defn button [props & children] [:> ui/Grid {:item true :xs 8} (into [:> ui/Button (merge {:variant "contained" :color "secondary" :full-width true} props)] children)]) (defn text-field [props] [:> ui/Grid {:item true :xs 8} [:> ui/TextField (merge {:full-width true} props)]]) (defn home-page [] (let [state (r/atom {:joining false}) create! (fn [_] (POST "/api/games" {:response-format :json :keywords? true :handler (fn [resp] (session/put! :game resp) (swap! state assoc :joining true :code (:id resp)))}))] (fn [] [:> ui/Grid {:container true :spacing 2} [col {:container true :justify "center"} [:> header]] [col {:container true :justify "center" :spacing 2} (if-not (:joining @state) [:<> [button {:onClick create!} "Create Game"] [button {:onClick #(swap! state assoc :joining true)} "Join Game"]] [:<> [col {:container true :justify "center"} [text-field {:placeholder "Enter an access code" :label "Access Code" :full-width true :input-props {:auto-capitalize "none" :auto-correct "off"} :default-value (:code @state) :on-change #(swap! state assoc :code (-> % .-target .-value))}]] [col {:container true :justify "center"} [text-field {:placeholder "Enter your name" :label "Your Name" :full-width true :input-props {:auto-correct "off"} :default-value (:name @state) :on-change #(swap! state assoc :name (-> % .-target .-value))}]] [button {:on-click #(join-game! (:code @state) (:name @state))} "Join"] [button {:on-click #(swap! state assoc :joining false) :color "default"} "Back"]])]])))
[ { "context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache License", "end": 32, "score": 0.8192288875579834, "start": 25, "tag": "NAME", "value": "Netflix" } ]
src/main/clojure/pigpen/core.clj
magomimmo/PigPen
1
;; ;; ;; Copyright 2013 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.core "Contains the operators for PigPen." (:refer-clojure :exclude [load-string constantly map mapcat map-indexed sort sort-by filter remove distinct concat take group-by into reduce]) (:require [pigpen.raw :as raw] [pigpen.io] [pigpen.map] [pigpen.filter] [pigpen.set] [pigpen.join] [pigpen.exec])) (set! *warn-on-reflection* true) ;; ********** IO ********** (intern *ns* (with-meta 'load-pig (meta #'pigpen.io/load-pig)) @#'pigpen.io/load-pig) (intern *ns* (with-meta 'load-string (meta #'pigpen.io/load-string)) @#'pigpen.io/load-string) (intern *ns* (with-meta 'load-tsv (meta #'pigpen.io/load-tsv)) @#'pigpen.io/load-tsv) (intern *ns* (with-meta 'load-clj (meta #'pigpen.io/load-clj)) @#'pigpen.io/load-clj) (intern *ns* (with-meta 'load-json (meta #'pigpen.io/load-json)) @#'pigpen.io/load-json) (intern *ns* (with-meta 'load-lazy (meta #'pigpen.io/load-lazy)) @#'pigpen.io/load-lazy) (intern *ns* (with-meta 'store-pig (meta #'pigpen.io/store-pig)) @#'pigpen.io/store-pig) (intern *ns* (with-meta 'store-string (meta #'pigpen.io/store-string)) @#'pigpen.io/store-string) (intern *ns* (with-meta 'store-tsv (meta #'pigpen.io/store-tsv)) @#'pigpen.io/store-tsv) (intern *ns* (with-meta 'store-clj (meta #'pigpen.io/store-clj)) @#'pigpen.io/store-clj) (intern *ns* (with-meta 'store-json (meta #'pigpen.io/store-json)) @#'pigpen.io/store-json) (intern *ns* (with-meta 'constantly (meta #'pigpen.io/constantly)) @#'pigpen.io/constantly) (intern *ns* (with-meta 'return (meta #'pigpen.io/return)) @#'pigpen.io/return) ;; ********** Map ********** (intern *ns* (with-meta 'map (meta #'pigpen.map/map)) @#'pigpen.map/map) (intern *ns* (with-meta 'mapcat (meta #'pigpen.map/mapcat)) @#'pigpen.map/mapcat) (intern *ns* (with-meta 'map-indexed (meta #'pigpen.map/map-indexed)) @#'pigpen.map/map-indexed) (intern *ns* (with-meta 'sort (meta #'pigpen.map/sort)) @#'pigpen.map/sort) (intern *ns* (with-meta 'sort-by (meta #'pigpen.map/sort-by)) @#'pigpen.map/sort-by) ;; ********** Filter ********** (intern *ns* (with-meta 'filter (meta #'pigpen.filter/filter)) @#'pigpen.filter/filter) (intern *ns* (with-meta 'remove (meta #'pigpen.filter/remove)) @#'pigpen.filter/remove) (intern *ns* (with-meta 'take (meta #'pigpen.filter/take)) @#'pigpen.filter/take) (intern *ns* (with-meta 'sample (meta #'pigpen.filter/sample)) @#'pigpen.filter/sample) ;; ********** Set ********** (intern *ns* (with-meta 'distinct (meta #'pigpen.set/distinct)) @#'pigpen.set/distinct) (intern *ns* (with-meta 'union (meta #'pigpen.set/union)) @#'pigpen.set/union) (intern *ns* (with-meta 'concat (meta #'pigpen.set/concat)) @#'pigpen.set/concat) (intern *ns* (with-meta 'union-multiset (meta #'pigpen.set/union-multiset)) @#'pigpen.set/union-multiset) (intern *ns* (with-meta 'intersection (meta #'pigpen.set/intersection)) @#'pigpen.set/intersection) (intern *ns* (with-meta 'intersection-multiset (meta #'pigpen.set/intersection-multiset)) @#'pigpen.set/intersection-multiset) (intern *ns* (with-meta 'difference (meta #'pigpen.set/difference)) @#'pigpen.set/difference) (intern *ns* (with-meta 'difference-multiset (meta #'pigpen.set/difference-multiset)) @#'pigpen.set/difference-multiset) ;; ********** Join ********** (intern *ns* (with-meta 'group-by (meta #'pigpen.join/group-by)) @#'pigpen.join/group-by) (intern *ns* (with-meta 'into (meta #'pigpen.join/into)) @#'pigpen.join/into) (intern *ns* (with-meta 'reduce (meta #'pigpen.join/reduce)) @#'pigpen.join/reduce) (intern *ns* (with-meta 'cogroup (meta #'pigpen.join/cogroup)) @#'pigpen.join/cogroup) (intern *ns* (with-meta 'join (meta #'pigpen.join/join)) @#'pigpen.join/join) (intern *ns* (with-meta 'fold (meta #'pigpen.join/fold)) @#'pigpen.join/fold) (intern *ns* (with-meta 'filter-by (meta #'pigpen.join/filter-by)) @#'pigpen.join/filter-by) (intern *ns* (with-meta 'remove-by (meta #'pigpen.join/remove-by)) @#'pigpen.join/remove-by) ;; ********** Script ********** (defn script "Combines multiple store commands into a single script. This is not required if you have a single output. Example: (pig/script (pig/store-tsv \"foo.tsv\" foo) (pig/store-clj \"bar.clj\" bar)) Note: When run locally, this will merge the results of any source relations. " {:arglists '([outputs+]) :added "0.1.0"} [& outputs] (raw/script$ outputs)) (intern *ns* (with-meta 'generate-script (meta #'pigpen.exec/generate-script)) @#'pigpen.exec/generate-script) (intern *ns* (with-meta 'write-script (meta #'pigpen.exec/write-script)) @#'pigpen.exec/write-script) (intern *ns* (with-meta 'dump (meta #'pigpen.exec/dump)) @#'pigpen.exec/dump) (intern *ns* (with-meta 'show (meta #'pigpen.exec/show)) @#'pigpen.exec/show) (intern *ns* (with-meta 'show+ (meta #'pigpen.exec/show+)) @#'pigpen.exec/show+)
5609
;; ;; ;; Copyright 2013 <NAME>, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.core "Contains the operators for PigPen." (:refer-clojure :exclude [load-string constantly map mapcat map-indexed sort sort-by filter remove distinct concat take group-by into reduce]) (:require [pigpen.raw :as raw] [pigpen.io] [pigpen.map] [pigpen.filter] [pigpen.set] [pigpen.join] [pigpen.exec])) (set! *warn-on-reflection* true) ;; ********** IO ********** (intern *ns* (with-meta 'load-pig (meta #'pigpen.io/load-pig)) @#'pigpen.io/load-pig) (intern *ns* (with-meta 'load-string (meta #'pigpen.io/load-string)) @#'pigpen.io/load-string) (intern *ns* (with-meta 'load-tsv (meta #'pigpen.io/load-tsv)) @#'pigpen.io/load-tsv) (intern *ns* (with-meta 'load-clj (meta #'pigpen.io/load-clj)) @#'pigpen.io/load-clj) (intern *ns* (with-meta 'load-json (meta #'pigpen.io/load-json)) @#'pigpen.io/load-json) (intern *ns* (with-meta 'load-lazy (meta #'pigpen.io/load-lazy)) @#'pigpen.io/load-lazy) (intern *ns* (with-meta 'store-pig (meta #'pigpen.io/store-pig)) @#'pigpen.io/store-pig) (intern *ns* (with-meta 'store-string (meta #'pigpen.io/store-string)) @#'pigpen.io/store-string) (intern *ns* (with-meta 'store-tsv (meta #'pigpen.io/store-tsv)) @#'pigpen.io/store-tsv) (intern *ns* (with-meta 'store-clj (meta #'pigpen.io/store-clj)) @#'pigpen.io/store-clj) (intern *ns* (with-meta 'store-json (meta #'pigpen.io/store-json)) @#'pigpen.io/store-json) (intern *ns* (with-meta 'constantly (meta #'pigpen.io/constantly)) @#'pigpen.io/constantly) (intern *ns* (with-meta 'return (meta #'pigpen.io/return)) @#'pigpen.io/return) ;; ********** Map ********** (intern *ns* (with-meta 'map (meta #'pigpen.map/map)) @#'pigpen.map/map) (intern *ns* (with-meta 'mapcat (meta #'pigpen.map/mapcat)) @#'pigpen.map/mapcat) (intern *ns* (with-meta 'map-indexed (meta #'pigpen.map/map-indexed)) @#'pigpen.map/map-indexed) (intern *ns* (with-meta 'sort (meta #'pigpen.map/sort)) @#'pigpen.map/sort) (intern *ns* (with-meta 'sort-by (meta #'pigpen.map/sort-by)) @#'pigpen.map/sort-by) ;; ********** Filter ********** (intern *ns* (with-meta 'filter (meta #'pigpen.filter/filter)) @#'pigpen.filter/filter) (intern *ns* (with-meta 'remove (meta #'pigpen.filter/remove)) @#'pigpen.filter/remove) (intern *ns* (with-meta 'take (meta #'pigpen.filter/take)) @#'pigpen.filter/take) (intern *ns* (with-meta 'sample (meta #'pigpen.filter/sample)) @#'pigpen.filter/sample) ;; ********** Set ********** (intern *ns* (with-meta 'distinct (meta #'pigpen.set/distinct)) @#'pigpen.set/distinct) (intern *ns* (with-meta 'union (meta #'pigpen.set/union)) @#'pigpen.set/union) (intern *ns* (with-meta 'concat (meta #'pigpen.set/concat)) @#'pigpen.set/concat) (intern *ns* (with-meta 'union-multiset (meta #'pigpen.set/union-multiset)) @#'pigpen.set/union-multiset) (intern *ns* (with-meta 'intersection (meta #'pigpen.set/intersection)) @#'pigpen.set/intersection) (intern *ns* (with-meta 'intersection-multiset (meta #'pigpen.set/intersection-multiset)) @#'pigpen.set/intersection-multiset) (intern *ns* (with-meta 'difference (meta #'pigpen.set/difference)) @#'pigpen.set/difference) (intern *ns* (with-meta 'difference-multiset (meta #'pigpen.set/difference-multiset)) @#'pigpen.set/difference-multiset) ;; ********** Join ********** (intern *ns* (with-meta 'group-by (meta #'pigpen.join/group-by)) @#'pigpen.join/group-by) (intern *ns* (with-meta 'into (meta #'pigpen.join/into)) @#'pigpen.join/into) (intern *ns* (with-meta 'reduce (meta #'pigpen.join/reduce)) @#'pigpen.join/reduce) (intern *ns* (with-meta 'cogroup (meta #'pigpen.join/cogroup)) @#'pigpen.join/cogroup) (intern *ns* (with-meta 'join (meta #'pigpen.join/join)) @#'pigpen.join/join) (intern *ns* (with-meta 'fold (meta #'pigpen.join/fold)) @#'pigpen.join/fold) (intern *ns* (with-meta 'filter-by (meta #'pigpen.join/filter-by)) @#'pigpen.join/filter-by) (intern *ns* (with-meta 'remove-by (meta #'pigpen.join/remove-by)) @#'pigpen.join/remove-by) ;; ********** Script ********** (defn script "Combines multiple store commands into a single script. This is not required if you have a single output. Example: (pig/script (pig/store-tsv \"foo.tsv\" foo) (pig/store-clj \"bar.clj\" bar)) Note: When run locally, this will merge the results of any source relations. " {:arglists '([outputs+]) :added "0.1.0"} [& outputs] (raw/script$ outputs)) (intern *ns* (with-meta 'generate-script (meta #'pigpen.exec/generate-script)) @#'pigpen.exec/generate-script) (intern *ns* (with-meta 'write-script (meta #'pigpen.exec/write-script)) @#'pigpen.exec/write-script) (intern *ns* (with-meta 'dump (meta #'pigpen.exec/dump)) @#'pigpen.exec/dump) (intern *ns* (with-meta 'show (meta #'pigpen.exec/show)) @#'pigpen.exec/show) (intern *ns* (with-meta 'show+ (meta #'pigpen.exec/show+)) @#'pigpen.exec/show+)
true
;; ;; ;; Copyright 2013 PI:NAME:<NAME>END_PI, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.core "Contains the operators for PigPen." (:refer-clojure :exclude [load-string constantly map mapcat map-indexed sort sort-by filter remove distinct concat take group-by into reduce]) (:require [pigpen.raw :as raw] [pigpen.io] [pigpen.map] [pigpen.filter] [pigpen.set] [pigpen.join] [pigpen.exec])) (set! *warn-on-reflection* true) ;; ********** IO ********** (intern *ns* (with-meta 'load-pig (meta #'pigpen.io/load-pig)) @#'pigpen.io/load-pig) (intern *ns* (with-meta 'load-string (meta #'pigpen.io/load-string)) @#'pigpen.io/load-string) (intern *ns* (with-meta 'load-tsv (meta #'pigpen.io/load-tsv)) @#'pigpen.io/load-tsv) (intern *ns* (with-meta 'load-clj (meta #'pigpen.io/load-clj)) @#'pigpen.io/load-clj) (intern *ns* (with-meta 'load-json (meta #'pigpen.io/load-json)) @#'pigpen.io/load-json) (intern *ns* (with-meta 'load-lazy (meta #'pigpen.io/load-lazy)) @#'pigpen.io/load-lazy) (intern *ns* (with-meta 'store-pig (meta #'pigpen.io/store-pig)) @#'pigpen.io/store-pig) (intern *ns* (with-meta 'store-string (meta #'pigpen.io/store-string)) @#'pigpen.io/store-string) (intern *ns* (with-meta 'store-tsv (meta #'pigpen.io/store-tsv)) @#'pigpen.io/store-tsv) (intern *ns* (with-meta 'store-clj (meta #'pigpen.io/store-clj)) @#'pigpen.io/store-clj) (intern *ns* (with-meta 'store-json (meta #'pigpen.io/store-json)) @#'pigpen.io/store-json) (intern *ns* (with-meta 'constantly (meta #'pigpen.io/constantly)) @#'pigpen.io/constantly) (intern *ns* (with-meta 'return (meta #'pigpen.io/return)) @#'pigpen.io/return) ;; ********** Map ********** (intern *ns* (with-meta 'map (meta #'pigpen.map/map)) @#'pigpen.map/map) (intern *ns* (with-meta 'mapcat (meta #'pigpen.map/mapcat)) @#'pigpen.map/mapcat) (intern *ns* (with-meta 'map-indexed (meta #'pigpen.map/map-indexed)) @#'pigpen.map/map-indexed) (intern *ns* (with-meta 'sort (meta #'pigpen.map/sort)) @#'pigpen.map/sort) (intern *ns* (with-meta 'sort-by (meta #'pigpen.map/sort-by)) @#'pigpen.map/sort-by) ;; ********** Filter ********** (intern *ns* (with-meta 'filter (meta #'pigpen.filter/filter)) @#'pigpen.filter/filter) (intern *ns* (with-meta 'remove (meta #'pigpen.filter/remove)) @#'pigpen.filter/remove) (intern *ns* (with-meta 'take (meta #'pigpen.filter/take)) @#'pigpen.filter/take) (intern *ns* (with-meta 'sample (meta #'pigpen.filter/sample)) @#'pigpen.filter/sample) ;; ********** Set ********** (intern *ns* (with-meta 'distinct (meta #'pigpen.set/distinct)) @#'pigpen.set/distinct) (intern *ns* (with-meta 'union (meta #'pigpen.set/union)) @#'pigpen.set/union) (intern *ns* (with-meta 'concat (meta #'pigpen.set/concat)) @#'pigpen.set/concat) (intern *ns* (with-meta 'union-multiset (meta #'pigpen.set/union-multiset)) @#'pigpen.set/union-multiset) (intern *ns* (with-meta 'intersection (meta #'pigpen.set/intersection)) @#'pigpen.set/intersection) (intern *ns* (with-meta 'intersection-multiset (meta #'pigpen.set/intersection-multiset)) @#'pigpen.set/intersection-multiset) (intern *ns* (with-meta 'difference (meta #'pigpen.set/difference)) @#'pigpen.set/difference) (intern *ns* (with-meta 'difference-multiset (meta #'pigpen.set/difference-multiset)) @#'pigpen.set/difference-multiset) ;; ********** Join ********** (intern *ns* (with-meta 'group-by (meta #'pigpen.join/group-by)) @#'pigpen.join/group-by) (intern *ns* (with-meta 'into (meta #'pigpen.join/into)) @#'pigpen.join/into) (intern *ns* (with-meta 'reduce (meta #'pigpen.join/reduce)) @#'pigpen.join/reduce) (intern *ns* (with-meta 'cogroup (meta #'pigpen.join/cogroup)) @#'pigpen.join/cogroup) (intern *ns* (with-meta 'join (meta #'pigpen.join/join)) @#'pigpen.join/join) (intern *ns* (with-meta 'fold (meta #'pigpen.join/fold)) @#'pigpen.join/fold) (intern *ns* (with-meta 'filter-by (meta #'pigpen.join/filter-by)) @#'pigpen.join/filter-by) (intern *ns* (with-meta 'remove-by (meta #'pigpen.join/remove-by)) @#'pigpen.join/remove-by) ;; ********** Script ********** (defn script "Combines multiple store commands into a single script. This is not required if you have a single output. Example: (pig/script (pig/store-tsv \"foo.tsv\" foo) (pig/store-clj \"bar.clj\" bar)) Note: When run locally, this will merge the results of any source relations. " {:arglists '([outputs+]) :added "0.1.0"} [& outputs] (raw/script$ outputs)) (intern *ns* (with-meta 'generate-script (meta #'pigpen.exec/generate-script)) @#'pigpen.exec/generate-script) (intern *ns* (with-meta 'write-script (meta #'pigpen.exec/write-script)) @#'pigpen.exec/write-script) (intern *ns* (with-meta 'dump (meta #'pigpen.exec/dump)) @#'pigpen.exec/dump) (intern *ns* (with-meta 'show (meta #'pigpen.exec/show)) @#'pigpen.exec/show) (intern *ns* (with-meta 'show+ (meta #'pigpen.exec/show+)) @#'pigpen.exec/show+)